blob: 79d97b99b40e8a44730fac4f9e27be5cdabaa901 [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"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000032static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000033 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000034 const ObjCMethodDecl *Method,
35 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
39static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000040 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000041 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattner8fdf3282008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000047{
David Chisnall0d13f6f2010-01-23 02:40:42 +000048 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000052}
53
Patrick Beardeb382ec2012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
56/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000057///
Eric Christopher16098f32012-03-29 17:31:31 +000058llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Patrick Beardeb382ec2012-04-19 00:25:12 +000061 const Expr *SubExpr = E->getSubExpr();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Get the method.
Patrick Beardeb382ec2012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 assert(BoxingMethod && "BoxingMethod is null");
65 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
66 Selector Sel = BoxingMethod->getSelector();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000067
68 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-04-19 00:25:12 +000069 // Assumes that the method was introduced in the class that should be
70 // messaged (avoids pulling it out of the result type).
Ted Kremenekebcb57a2012-03-06 20:05:56 +000071 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000072 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCallbd7370a2013-02-28 19:01:20 +000073 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Patrick Beardeb382ec2012-04-19 00:25:12 +000074
75 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000076 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beardeb382ec2012-04-19 00:25:12 +000077 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000078 CallArgList Args;
79 Args.add(RV, ArgQT);
Patrick Beardeb382ec2012-04-19 00:25:12 +000080
Ted Kremenekebcb57a2012-03-06 20:05:56 +000081 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beardeb382ec2012-04-19 00:25:12 +000082 BoxingMethod->getResultType(), Sel, Receiver, Args,
83 ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000084 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86}
87
88llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
John McCall527842f2013-04-04 00:20:38 +0000112 // In ARC, we may need to do extra work to keep all the keys and
113 // values alive until after the call.
114 SmallVector<llvm::Value *, 16> NeededObjects;
115 bool TrackNeededObjects =
116 (getLangOpts().ObjCAutoRefCount &&
117 CGM.getCodeGenOpts().OptimizationLevel != 0);
118
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000119 // Perform the actual initialialization of the array(s).
120 for (uint64_t i = 0; i < NumElements; i++) {
121 if (ALE) {
John McCall527842f2013-04-04 00:20:38 +0000122 // Emit the element and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000123 const Expr *Rhs = ALE->getElement(i);
124 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
125 ElementType,
126 Context.getTypeAlignInChars(Rhs->getType()),
127 Context);
John McCall527842f2013-04-04 00:20:38 +0000128
129 llvm::Value *value = EmitScalarExpr(Rhs);
130 EmitStoreThroughLValue(RValue::get(value), LV, true);
131 if (TrackNeededObjects) {
132 NeededObjects.push_back(value);
133 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000134 } else {
John McCall527842f2013-04-04 00:20:38 +0000135 // Emit the key and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000136 const Expr *Key = DLE->getKeyValueElement(i).Key;
137 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
138 ElementType,
139 Context.getTypeAlignInChars(Key->getType()),
140 Context);
John McCall527842f2013-04-04 00:20:38 +0000141 llvm::Value *keyValue = EmitScalarExpr(Key);
142 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000143
John McCall527842f2013-04-04 00:20:38 +0000144 // Emit the value and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000145 const Expr *Value = DLE->getKeyValueElement(i).Value;
146 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
147 ElementType,
148 Context.getTypeAlignInChars(Value->getType()),
149 Context);
John McCall527842f2013-04-04 00:20:38 +0000150 llvm::Value *valueValue = EmitScalarExpr(Value);
151 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
152 if (TrackNeededObjects) {
153 NeededObjects.push_back(keyValue);
154 NeededObjects.push_back(valueValue);
155 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000156 }
157 }
158
159 // Generate the argument list.
160 CallArgList Args;
161 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
162 const ParmVarDecl *argDecl = *PI++;
163 QualType ArgQT = argDecl->getType().getUnqualifiedType();
164 Args.add(RValue::get(Objects), ArgQT);
165 if (DLE) {
166 argDecl = *PI++;
167 ArgQT = argDecl->getType().getUnqualifiedType();
168 Args.add(RValue::get(Keys), ArgQT);
169 }
170 argDecl = *PI;
171 ArgQT = argDecl->getType().getUnqualifiedType();
172 llvm::Value *Count =
173 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
174 Args.add(RValue::get(Count), ArgQT);
175
176 // Generate a reference to the class pointer, which will be the receiver.
177 Selector Sel = MethodWithObjects->getSelector();
178 QualType ResultType = E->getType();
179 const ObjCObjectPointerType *InterfacePointerType
180 = ResultType->getAsObjCInterfacePointerType();
181 ObjCInterfaceDecl *Class
182 = InterfacePointerType->getObjectType()->getInterface();
183 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +0000184 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000185
186 // Generate the message send.
Eric Christopher16098f32012-03-29 17:31:31 +0000187 RValue result
188 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
189 MethodWithObjects->getResultType(),
190 Sel,
191 Receiver, Args, Class,
192 MethodWithObjects);
John McCall527842f2013-04-04 00:20:38 +0000193
194 // The above message send needs these objects, but in ARC they are
195 // passed in a buffer that is essentially __unsafe_unretained.
196 // Therefore we must prevent the optimizer from releasing them until
197 // after the call.
198 if (TrackNeededObjects) {
199 EmitARCIntrinsicUse(NeededObjects);
200 }
201
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000202 return Builder.CreateBitCast(result.getScalarVal(),
203 ConvertType(E->getType()));
204}
205
206llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
207 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
208}
209
210llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
211 const ObjCDictionaryLiteral *E) {
212 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
213}
214
Chris Lattner8fdf3282008-06-24 17:04:18 +0000215/// Emit a selector.
216llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
217 // Untyped selector.
218 // Note that this implementation allows for non-constant strings to be passed
219 // as arguments to @selector(). Currently, the only thing preventing this
220 // behaviour is the type checking in the front end.
John McCallbd7370a2013-02-28 19:01:20 +0000221 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000222}
223
Daniel Dunbared7c6182008-08-20 00:28:19 +0000224llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
225 // FIXME: This should pass the Decl not the name.
John McCallbd7370a2013-02-28 19:01:20 +0000226 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbared7c6182008-08-20 00:28:19 +0000227}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000228
Douglas Gregor926df6c2011-06-11 01:09:30 +0000229/// \brief Adjust the type of the result of an Objective-C message send
230/// expression when the method has a related result type.
231static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000232 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000233 const ObjCMethodDecl *Method,
234 RValue Result) {
235 if (!Method)
236 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000237
Douglas Gregor926df6c2011-06-11 01:09:30 +0000238 if (!Method->hasRelatedResultType() ||
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000239 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor926df6c2011-06-11 01:09:30 +0000240 !Result.isScalar())
241 return Result;
242
243 // We have applied a related result type. Cast the rvalue appropriately.
244 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000245 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000246}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000247
John McCalldc7c5ad2011-07-22 08:53:00 +0000248/// Decide whether to extend the lifetime of the receiver of a
249/// returns-inner-pointer message.
250static bool
251shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
252 switch (message->getReceiverKind()) {
253
254 // For a normal instance message, we should extend unless the
255 // receiver is loaded from a variable with precise lifetime.
256 case ObjCMessageExpr::Instance: {
257 const Expr *receiver = message->getInstanceReceiver();
258 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
259 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
260 receiver = ice->getSubExpr()->IgnoreParens();
261
262 // Only __strong variables.
263 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
264 return true;
265
266 // All ivars and fields have precise lifetime.
267 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
268 return false;
269
270 // Otherwise, check for variables.
271 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
272 if (!declRef) return true;
273 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
274 if (!var) return true;
275
276 // All variables have precise lifetime except local variables with
277 // automatic storage duration that aren't specially marked.
278 return (var->hasLocalStorage() &&
279 !var->hasAttr<ObjCPreciseLifetimeAttr>());
280 }
281
282 case ObjCMessageExpr::Class:
283 case ObjCMessageExpr::SuperClass:
284 // It's never necessary for class objects.
285 return false;
286
287 case ObjCMessageExpr::SuperInstance:
288 // We generally assume that 'self' lives throughout a method call.
289 return false;
290 }
291
292 llvm_unreachable("invalid receiver kind");
293}
294
John McCallef072fd2010-05-22 01:48:05 +0000295RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
296 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000297 // Only the lookup mechanism and first two arguments of the method
298 // implementation vary between runtimes. We can get the receiver and
299 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000300
John McCallf85e1932011-06-15 23:02:42 +0000301 bool isDelegateInit = E->isDelegateInitCall();
302
John McCalldc7c5ad2011-07-22 08:53:00 +0000303 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000304
John McCallf85e1932011-06-15 23:02:42 +0000305 // We don't retain the receiver in delegate init calls, and this is
306 // safe because the receiver value is always loaded from 'self',
307 // which we zero out. We don't want to Block_copy block receivers,
308 // though.
309 bool retainSelf =
310 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000311 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000312 method &&
313 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000314
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000315 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000316 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000317 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000318 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000319 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000320 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000321 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000322 switch (E->getReceiverKind()) {
323 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000324 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000325 if (retainSelf) {
326 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
327 E->getInstanceReceiver());
328 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000329 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000330 } else
331 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000332 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000333
Douglas Gregor04badcf2010-04-21 00:45:42 +0000334 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000335 ReceiverType = E->getClassReceiver();
336 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000337 assert(ObjTy && "Invalid Objective-C class message send");
338 OID = ObjTy->getInterface();
339 assert(OID && "Invalid Objective-C class message send");
John McCallbd7370a2013-02-28 19:01:20 +0000340 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000341 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000342 break;
343 }
344
345 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000346 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000347 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000348 isSuperMessage = true;
349 break;
350
351 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000352 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000353 Receiver = LoadObjCSelf();
354 isSuperMessage = true;
355 isClassMessage = true;
356 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000357 }
358
John McCalldc7c5ad2011-07-22 08:53:00 +0000359 if (retainSelf)
360 Receiver = EmitARCRetainNonBlock(Receiver);
361
362 // In ARC, we sometimes want to "extend the lifetime"
363 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
364 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000365 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000366 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
367 shouldExtendReceiverForInnerPointerMessage(E))
368 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
369
John McCallf85e1932011-06-15 23:02:42 +0000370 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000371 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000372
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000373 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000374 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000375
John McCallf85e1932011-06-15 23:02:42 +0000376 // For delegate init calls in ARC, do an unsafe store of null into
377 // self. This represents the call taking direct ownership of that
378 // value. We have to do this after emitting the other call
379 // arguments because they might also reference self, but we don't
380 // have to worry about any of them modifying self because that would
381 // be an undefined read and write of an object in unordered
382 // expressions.
383 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000384 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000385 "delegate init calls should only be marked in ARC");
386
387 // Do an unsafe store of null into self.
388 llvm::Value *selfAddr =
389 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
390 assert(selfAddr && "no self entry for a delegate init call?");
391
392 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
393 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000394
Douglas Gregor926df6c2011-06-11 01:09:30 +0000395 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000396 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000397 // super is only valid in an Objective-C method
398 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000399 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000400 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
401 E->getSelector(),
402 OMD->getClassInterface(),
403 isCategoryImpl,
404 Receiver,
405 isClassMessage,
406 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000407 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000408 } else {
409 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
410 E->getSelector(),
411 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000412 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000413 }
John McCallf85e1932011-06-15 23:02:42 +0000414
415 // For delegate init calls in ARC, implicitly store the result of
416 // the call back into self. This takes ownership of the value.
417 if (isDelegateInit) {
418 llvm::Value *selfAddr =
419 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
420 llvm::Value *newSelf = result.getScalarVal();
421
422 // The delegate return type isn't necessarily a matching type; in
423 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000424 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000425 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
426 newSelf = Builder.CreateBitCast(newSelf, selfTy);
427
428 Builder.CreateStore(newSelf, selfAddr);
429 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000430
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000431 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000432}
433
John McCallf85e1932011-06-15 23:02:42 +0000434namespace {
435struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000436 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000437 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000438
439 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000440 const ObjCInterfaceDecl *iface = impl->getClassInterface();
441 if (!iface->getSuperClass()) return;
442
John McCall799d34e2011-07-13 18:26:47 +0000443 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
444
John McCallf85e1932011-06-15 23:02:42 +0000445 // Call [super dealloc] if we have a superclass.
446 llvm::Value *self = CGF.LoadObjCSelf();
447
448 CallArgList args;
449 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
450 CGF.getContext().VoidTy,
451 method->getSelector(),
452 iface,
John McCall799d34e2011-07-13 18:26:47 +0000453 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000454 self,
455 /*is class msg*/ false,
456 args,
457 method);
458 }
459};
460}
461
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000462/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
463/// the LLVM function and sets the other context used by
464/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000465void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000466 const ObjCContainerDecl *CD,
467 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000468 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000469 // Check if we should generate debug info for this method.
Alexey Samsonova240df22012-10-16 07:22:28 +0000470 if (!OMD->hasAttr<NoDebugAttr>())
471 maybeInitializeDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000472
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000473 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000474
John McCallde5d3c72012-02-17 03:33:10 +0000475 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000476 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000477
John McCalld26bc762011-03-09 04:27:21 +0000478 args.push_back(OMD->getSelfDecl());
479 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000480
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000481 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher16098f32012-03-29 17:31:31 +0000482 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000483 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000484
Peter Collingbourne14110472011-01-13 18:57:25 +0000485 CurGD = OMD;
486
Devang Patel8d3f8972011-05-19 23:37:41 +0000487 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000488
489 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000490 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000491 OMD->isInstanceMethod() &&
492 OMD->getSelector().isUnarySelector()) {
493 const IdentifierInfo *ident =
494 OMD->getSelector().getIdentifierInfoForSlot(0);
495 if (ident->isStr("dealloc"))
496 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
497 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000498}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000499
John McCallf85e1932011-06-15 23:02:42 +0000500static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
501 LValue lvalue, QualType type);
502
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000503/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000504/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000505void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000506 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000507 EmitStmt(OMD->getBody());
508 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000509}
510
John McCall41bdde92011-09-12 23:06:44 +0000511/// emitStructGetterCall - Call the runtime function to load a property
512/// into the return value slot.
513static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
514 bool isAtomic, bool hasStrong) {
515 ASTContext &Context = CGF.getContext();
516
517 llvm::Value *src =
518 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
519 ivar, 0).getAddress();
520
521 // objc_copyStruct (ReturnValue, &structIvar,
522 // sizeof (Type of Ivar), isAtomic, false);
523 CallArgList args;
524
525 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
526 args.add(RValue::get(dest), Context.VoidPtrTy);
527
528 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
529 args.add(RValue::get(src), Context.VoidPtrTy);
530
531 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
532 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
533 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
534 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
535
536 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000537 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
538 FunctionType::ExtInfo(),
539 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000540 fn, ReturnValueSlot(), args);
541}
542
John McCall1e1f4872011-09-13 03:34:09 +0000543/// Determine whether the given architecture supports unaligned atomic
544/// accesses. They don't have to be fast, just faster than a function
545/// call and a mutex.
546static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000547 // FIXME: Allow unaligned atomic load/store on x86. (It is not
548 // currently supported by the backend.)
549 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000550}
551
552/// Return the maximum size that permits atomic accesses for the given
553/// architecture.
554static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
555 llvm::Triple::ArchType arch) {
556 // ARM has 8-byte atomic accesses, but it's not clear whether we
557 // want to rely on them here.
558
559 // In the default case, just assume that any size up to a pointer is
560 // fine given adequate alignment.
561 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
562}
563
564namespace {
565 class PropertyImplStrategy {
566 public:
567 enum StrategyKind {
568 /// The 'native' strategy is to use the architecture's provided
569 /// reads and writes.
570 Native,
571
572 /// Use objc_setProperty and objc_getProperty.
573 GetSetProperty,
574
575 /// Use objc_setProperty for the setter, but use expression
576 /// evaluation for the getter.
577 SetPropertyAndExpressionGet,
578
579 /// Use objc_copyStruct.
580 CopyStruct,
581
582 /// The 'expression' strategy is to emit normal assignment or
583 /// lvalue-to-rvalue expressions.
584 Expression
585 };
586
587 StrategyKind getKind() const { return StrategyKind(Kind); }
588
589 bool hasStrongMember() const { return HasStrong; }
590 bool isAtomic() const { return IsAtomic; }
591 bool isCopy() const { return IsCopy; }
592
593 CharUnits getIvarSize() const { return IvarSize; }
594 CharUnits getIvarAlignment() const { return IvarAlignment; }
595
596 PropertyImplStrategy(CodeGenModule &CGM,
597 const ObjCPropertyImplDecl *propImpl);
598
599 private:
600 unsigned Kind : 8;
601 unsigned IsAtomic : 1;
602 unsigned IsCopy : 1;
603 unsigned HasStrong : 1;
604
605 CharUnits IvarSize;
606 CharUnits IvarAlignment;
607 };
608}
609
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000610/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000611PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
612 const ObjCPropertyImplDecl *propImpl) {
613 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000614 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000615
John McCall265941b2011-09-13 18:31:23 +0000616 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
617 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000618 HasStrong = false; // doesn't matter here.
619
620 // Evaluate the ivar's size and alignment.
621 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
622 QualType ivarType = ivar->getType();
623 llvm::tie(IvarSize, IvarAlignment)
624 = CGM.getContext().getTypeInfoInChars(ivarType);
625
626 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000627 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000628 if (IsCopy) {
629 Kind = GetSetProperty;
630 return;
631 }
632
John McCall265941b2011-09-13 18:31:23 +0000633 // Handle retain.
634 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000635 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000636 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000637 // fallthrough
638
639 // In ARC, if the property is non-atomic, use expression emission,
640 // which translates to objc_storeStrong. This isn't required, but
641 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000642 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld64c2eb2012-08-20 23:36:59 +0000643 // Using standard expression emission for the setter is only
644 // acceptable if the ivar is __strong, which won't be true if
645 // the property is annotated with __attribute__((NSObject)).
646 // TODO: falling all the way back to objc_setProperty here is
647 // just laziness, though; we could still use objc_storeStrong
648 // if we hacked it right.
649 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
650 Kind = Expression;
651 else
652 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000653 return;
654
655 // Otherwise, we need to at least use setProperty. However, if
656 // the property isn't atomic, we can use normal expression
657 // emission for the getter.
658 } else if (!IsAtomic) {
659 Kind = SetPropertyAndExpressionGet;
660 return;
661
662 // Otherwise, we have to use both setProperty and getProperty.
663 } else {
664 Kind = GetSetProperty;
665 return;
666 }
667 }
668
669 // If we're not atomic, just use expression accesses.
670 if (!IsAtomic) {
671 Kind = Expression;
672 return;
673 }
674
John McCall5889c602011-09-13 05:36:29 +0000675 // Properties on bitfield ivars need to be emitted using expression
676 // accesses even if they're nominally atomic.
677 if (ivar->isBitField()) {
678 Kind = Expression;
679 return;
680 }
681
John McCall1e1f4872011-09-13 03:34:09 +0000682 // GC-qualified or ARC-qualified ivars need to be emitted as
683 // expressions. This actually works out to being atomic anyway,
684 // except for ARC __strong, but that should trigger the above code.
685 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000686 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000687 CGM.getContext().getObjCGCAttrKind(ivarType))) {
688 Kind = Expression;
689 return;
690 }
691
692 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000693 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000694 if (const RecordType *recordType = ivarType->getAs<RecordType>())
695 HasStrong = recordType->getDecl()->hasObjectMember();
696
697 // We can never access structs with object members with a native
698 // access, because we need to use write barriers. This is what
699 // objc_copyStruct is for.
700 if (HasStrong) {
701 Kind = CopyStruct;
702 return;
703 }
704
705 // Otherwise, this is target-dependent and based on the size and
706 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000707
708 // If the size of the ivar is not a power of two, give up. We don't
709 // want to get into the business of doing compare-and-swaps.
710 if (!IvarSize.isPowerOfTwo()) {
711 Kind = CopyStruct;
712 return;
713 }
714
John McCall1e1f4872011-09-13 03:34:09 +0000715 llvm::Triple::ArchType arch =
716 CGM.getContext().getTargetInfo().getTriple().getArch();
717
718 // Most architectures require memory to fit within a single cache
719 // line, so the alignment has to be at least the size of the access.
720 // Otherwise we have to grab a lock.
721 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
722 Kind = CopyStruct;
723 return;
724 }
725
726 // If the ivar's size exceeds the architecture's maximum atomic
727 // access size, we have to use CopyStruct.
728 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
729 Kind = CopyStruct;
730 return;
731 }
732
733 // Otherwise, we can use native loads and stores.
734 Kind = Native;
735}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000736
James Dennett2ee5ba32012-06-15 22:10:14 +0000737/// \brief Generate an Objective-C property getter function.
738///
739/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000740/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000741void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
742 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000743 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000744 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000745 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
746 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
747 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000748 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000750 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000751
752 FinishFunction();
753}
754
John McCall6c11f0b2011-09-13 06:00:03 +0000755static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
756 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000757 if (!getter) return true;
758
759 // Sema only makes only of these when the ivar has a C++ class type,
760 // so the form is pretty constrained.
761
John McCall6c11f0b2011-09-13 06:00:03 +0000762 // If the property has a reference type, we might just be binding a
763 // reference, in which case the result will be a gl-value. We should
764 // treat this as a non-trivial operation.
765 if (getter->isGLValue())
766 return false;
767
John McCall1e1f4872011-09-13 03:34:09 +0000768 // If we selected a trivial copy-constructor, we're okay.
769 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
770 return (construct->getConstructor()->isTrivial());
771
772 // The constructor might require cleanups (in which case it's never
773 // trivial).
774 assert(isa<ExprWithCleanups>(getter));
775 return false;
776}
777
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000778/// emitCPPObjectAtomicGetterCall - Call the runtime function to
779/// copy the ivar into the resturn slot.
780static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
781 llvm::Value *returnAddr,
782 ObjCIvarDecl *ivar,
783 llvm::Constant *AtomicHelperFn) {
784 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
785 // AtomicHelperFn);
786 CallArgList args;
787
788 // The 1st argument is the return Slot.
789 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
790
791 // The 2nd argument is the address of the ivar.
792 llvm::Value *ivarAddr =
793 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
794 CGF.LoadObjCSelf(), ivar, 0).getAddress();
795 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
796 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
797
798 // Third argument is the helper function.
799 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
800
801 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +0000802 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000803 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
804 args,
805 FunctionType::ExtInfo(),
806 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000807 copyCppAtomicObjectFn, ReturnValueSlot(), args);
808}
809
John McCall1e1f4872011-09-13 03:34:09 +0000810void
811CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000812 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000813 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000814 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000815 // If there's a non-trivial 'get' expression, we just have to emit that.
816 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000817 if (!AtomicHelperFn) {
818 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
819 /*nrvo*/ 0);
820 EmitReturnStmt(ret);
821 }
822 else {
823 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
824 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
825 ivar, AtomicHelperFn);
826 }
John McCall1e1f4872011-09-13 03:34:09 +0000827 return;
828 }
829
830 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
831 QualType propType = prop->getType();
832 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
833
834 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
835
836 // Pick an implementation strategy.
837 PropertyImplStrategy strategy(CGM, propImpl);
838 switch (strategy.getKind()) {
839 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +0000840 // We don't need to do anything for a zero-size struct.
841 if (strategy.getIvarSize().isZero())
842 return;
843
John McCall1e1f4872011-09-13 03:34:09 +0000844 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
845
846 // Currently, all atomic accesses have to be through integer
847 // types, so there's no point in trying to pick a prettier type.
848 llvm::Type *bitcastType =
849 llvm::Type::getIntNTy(getLLVMContext(),
850 getContext().toBits(strategy.getIvarSize()));
851 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
852
853 // Perform an atomic load. This does not impose ordering constraints.
854 llvm::Value *ivarAddr = LV.getAddress();
855 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
856 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
857 load->setAlignment(strategy.getIvarAlignment().getQuantity());
858 load->setAtomic(llvm::Unordered);
859
860 // Store that value into the return address. Doing this with a
861 // bitcast is likely to produce some pretty ugly IR, but it's not
862 // the *most* terrible thing in the world.
863 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
864
865 // Make sure we don't do an autorelease.
866 AutoreleaseResult = false;
867 return;
868 }
869
870 case PropertyImplStrategy::GetSetProperty: {
871 llvm::Value *getPropertyFn =
872 CGM.getObjCRuntime().GetPropertyGetFunction();
873 if (!getPropertyFn) {
874 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000875 return;
876 }
877
878 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
879 // FIXME: Can't this be simpler? This might even be worse than the
880 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000881 llvm::Value *cmd =
882 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
883 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
884 llvm::Value *ivarOffset =
885 EmitIvarOffset(classImpl->getClassInterface(), ivar);
886
887 CallArgList args;
888 args.add(RValue::get(self), getContext().getObjCIdType());
889 args.add(RValue::get(cmd), getContext().getObjCSelType());
890 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000891 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
892 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000893
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000894 // FIXME: We shouldn't need to get the function info here, the
895 // runtime already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +0000896 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
897 FunctionType::ExtInfo(),
898 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000899 getPropertyFn, ReturnValueSlot(), args);
900
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000901 // We need to fix the type here. Ivars with copy & retain are
902 // always objects so we don't need to worry about complex or
903 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000904 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian52c18b02012-04-26 21:33:14 +0000905 getTypes().ConvertType(getterMethod->getResultType())));
John McCall1e1f4872011-09-13 03:34:09 +0000906
907 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000908
909 // objc_getProperty does an autorelease, so we should suppress ours.
910 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000911
John McCall1e1f4872011-09-13 03:34:09 +0000912 return;
913 }
914
915 case PropertyImplStrategy::CopyStruct:
916 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
917 strategy.hasStrongMember());
918 return;
919
920 case PropertyImplStrategy::Expression:
921 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
922 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
923
924 QualType ivarType = ivar->getType();
John McCall9d232c82013-03-07 21:37:08 +0000925 switch (getEvaluationKind(ivarType)) {
926 case TEK_Complex: {
927 ComplexPairTy pair = EmitLoadOfComplex(LV);
928 EmitStoreOfComplex(pair,
929 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
930 /*init*/ true);
931 return;
932 }
933 case TEK_Aggregate:
John McCall1e1f4872011-09-13 03:34:09 +0000934 // The return value slot is guaranteed to not be aliased, but
935 // that's not necessarily the same as "on the stack", so
936 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000937 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall9d232c82013-03-07 21:37:08 +0000938 return;
939 case TEK_Scalar: {
John McCallba3dd902011-07-22 05:23:13 +0000940 llvm::Value *value;
941 if (propType->isReferenceType()) {
942 value = LV.getAddress();
943 } else {
944 // We want to load and autoreleaseReturnValue ARC __weak ivars.
945 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000946 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000947
948 // Otherwise we want to do a simple load, suppressing the
949 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000950 } else {
John McCallba3dd902011-07-22 05:23:13 +0000951 value = EmitLoadOfLValue(LV).getScalarVal();
952 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000953 }
John McCallf85e1932011-06-15 23:02:42 +0000954
John McCallba3dd902011-07-22 05:23:13 +0000955 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000956 value = Builder.CreateBitCast(value,
957 ConvertType(GetterMethodDecl->getResultType()));
John McCallba3dd902011-07-22 05:23:13 +0000958 }
959
960 EmitReturnOfRValue(RValue::get(value), propType);
John McCall9d232c82013-03-07 21:37:08 +0000961 return;
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000962 }
John McCall9d232c82013-03-07 21:37:08 +0000963 }
964 llvm_unreachable("bad evaluation kind");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000965 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000966
John McCall1e1f4872011-09-13 03:34:09 +0000967 }
968 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000969}
970
John McCall41bdde92011-09-12 23:06:44 +0000971/// emitStructSetterCall - Call the runtime function to store the value
972/// from the first formal parameter into the given ivar.
973static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
974 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000975 // objc_copyStruct (&structIvar, &Arg,
976 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000977 CallArgList args;
978
979 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000980 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
981 CGF.LoadObjCSelf(), ivar, 0)
982 .getAddress();
983 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
984 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000985
986 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000987 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000988 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000989 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000990 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
991 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
992 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000993
994 // The third argument is the sizeof the type.
995 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000996 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
997 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000998
John McCall41bdde92011-09-12 23:06:44 +0000999 // The fourth argument is the 'isAtomic' flag.
1000 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +00001001
John McCall41bdde92011-09-12 23:06:44 +00001002 // The fifth argument is the 'hasStrong' flag.
1003 // FIXME: should this really always be false?
1004 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1005
1006 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001007 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1008 args,
1009 FunctionType::ExtInfo(),
1010 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +00001011 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +00001012}
1013
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001014/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1015/// the value from the first formal parameter into the given ivar, using
1016/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1017static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1018 ObjCMethodDecl *OMD,
1019 ObjCIvarDecl *ivar,
1020 llvm::Constant *AtomicHelperFn) {
1021 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1022 // AtomicHelperFn);
1023 CallArgList args;
1024
1025 // The first argument is the address of the ivar.
1026 llvm::Value *ivarAddr =
1027 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1028 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1029 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1030 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1031
1032 // The second argument is the address of the parameter variable.
1033 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001034 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001035 VK_LValue, SourceLocation());
1036 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1037 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1038 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1039
1040 // Third argument is the helper function.
1041 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1042
1043 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +00001044 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001045 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1046 args,
1047 FunctionType::ExtInfo(),
1048 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001049 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1050
1051
1052}
1053
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001054
John McCall1e1f4872011-09-13 03:34:09 +00001055static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1056 Expr *setter = PID->getSetterCXXAssignment();
1057 if (!setter) return true;
1058
1059 // Sema only makes only of these when the ivar has a C++ class type,
1060 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001061
1062 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001063 // This also implies that there's nothing non-trivial going on with
1064 // the arguments, because operator= can only be trivial if it's a
1065 // synthesized assignment operator and therefore both parameters are
1066 // references.
1067 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001068 if (const FunctionDecl *callee
1069 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1070 if (callee->isTrivial())
1071 return true;
1072 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001073 }
John McCall71c758d2011-09-10 09:17:20 +00001074
John McCall1e1f4872011-09-13 03:34:09 +00001075 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001076 return false;
1077}
1078
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001079static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001080 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001081 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001082 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001083}
1084
John McCall71c758d2011-09-10 09:17:20 +00001085void
1086CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001087 const ObjCPropertyImplDecl *propImpl,
1088 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001089 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001090 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001091 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001092
1093 // Just use the setter expression if Sema gave us one and it's
1094 // non-trivial.
1095 if (!hasTrivialSetExpr(propImpl)) {
1096 if (!AtomicHelperFn)
1097 // If non-atomic, assignment is called directly.
1098 EmitStmt(propImpl->getSetterCXXAssignment());
1099 else
1100 // If atomic, assignment is called via a locking api.
1101 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1102 AtomicHelperFn);
1103 return;
1104 }
John McCall71c758d2011-09-10 09:17:20 +00001105
John McCall1e1f4872011-09-13 03:34:09 +00001106 PropertyImplStrategy strategy(CGM, propImpl);
1107 switch (strategy.getKind()) {
1108 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +00001109 // We don't need to do anything for a zero-size struct.
1110 if (strategy.getIvarSize().isZero())
1111 return;
1112
John McCall1e1f4872011-09-13 03:34:09 +00001113 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001114
John McCall1e1f4872011-09-13 03:34:09 +00001115 LValue ivarLValue =
1116 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1117 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001118
John McCall1e1f4872011-09-13 03:34:09 +00001119 // Currently, all atomic accesses have to be through integer
1120 // types, so there's no point in trying to pick a prettier type.
1121 llvm::Type *bitcastType =
1122 llvm::Type::getIntNTy(getLLVMContext(),
1123 getContext().toBits(strategy.getIvarSize()));
1124 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1125
1126 // Cast both arguments to the chosen operation type.
1127 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1128 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1129
1130 // This bitcast load is likely to cause some nasty IR.
1131 llvm::Value *load = Builder.CreateLoad(argAddr);
1132
1133 // Perform an atomic store. There are no memory ordering requirements.
1134 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1135 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1136 store->setAtomic(llvm::Unordered);
1137 return;
1138 }
1139
1140 case PropertyImplStrategy::GetSetProperty:
1141 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001142
1143 llvm::Value *setOptimizedPropertyFn = 0;
1144 llvm::Value *setPropertyFn = 0;
1145 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001146 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001147 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001148 CGM.getObjCRuntime()
1149 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1150 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001151 if (!setOptimizedPropertyFn) {
1152 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1153 return;
1154 }
John McCall71c758d2011-09-10 09:17:20 +00001155 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001156 else {
1157 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1158 if (!setPropertyFn) {
1159 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1160 return;
1161 }
1162 }
1163
John McCall71c758d2011-09-10 09:17:20 +00001164 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1165 // <is-atomic>, <is-copy>).
1166 llvm::Value *cmd =
1167 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1168 llvm::Value *self =
1169 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1170 llvm::Value *ivarOffset =
1171 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1172 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1173 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1174
1175 CallArgList args;
1176 args.add(RValue::get(self), getContext().getObjCIdType());
1177 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001178 if (setOptimizedPropertyFn) {
1179 args.add(RValue::get(arg), getContext().getObjCIdType());
1180 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001181 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1182 FunctionType::ExtInfo(),
1183 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001184 setOptimizedPropertyFn, ReturnValueSlot(), args);
1185 } else {
1186 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1187 args.add(RValue::get(arg), getContext().getObjCIdType());
1188 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1189 getContext().BoolTy);
1190 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1191 getContext().BoolTy);
1192 // FIXME: We shouldn't need to get the function info here, the runtime
1193 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001194 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1195 FunctionType::ExtInfo(),
1196 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001197 setPropertyFn, ReturnValueSlot(), args);
1198 }
1199
John McCall71c758d2011-09-10 09:17:20 +00001200 return;
1201 }
1202
John McCall1e1f4872011-09-13 03:34:09 +00001203 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001204 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001205 return;
John McCall1e1f4872011-09-13 03:34:09 +00001206
1207 case PropertyImplStrategy::Expression:
1208 break;
John McCall71c758d2011-09-10 09:17:20 +00001209 }
1210
1211 // Otherwise, fake up some ASTs and emit a normal assignment.
1212 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001213 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1214 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001215 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1216 selfDecl->getType(), CK_LValueToRValue, &self,
1217 VK_RValue);
1218 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001219 SourceLocation(), SourceLocation(),
1220 &selfLoad, true, true);
John McCall71c758d2011-09-10 09:17:20 +00001221
1222 ParmVarDecl *argDecl = *setterMethod->param_begin();
1223 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001224 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001225 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1226 argType.getUnqualifiedType(), CK_LValueToRValue,
1227 &arg, VK_RValue);
1228
1229 // The property type can differ from the ivar type in some situations with
1230 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1231 // The following absurdity is just to ensure well-formed IR.
1232 CastKind argCK = CK_NoOp;
1233 if (ivarRef.getType()->isObjCObjectPointerType()) {
1234 if (argLoad.getType()->isObjCObjectPointerType())
1235 argCK = CK_BitCast;
1236 else if (argLoad.getType()->isBlockPointerType())
1237 argCK = CK_BlockPointerToObjCPointerCast;
1238 else
1239 argCK = CK_CPointerToObjCPointerCast;
1240 } else if (ivarRef.getType()->isBlockPointerType()) {
1241 if (argLoad.getType()->isBlockPointerType())
1242 argCK = CK_BitCast;
1243 else
1244 argCK = CK_AnyPointerToBlockPointerCast;
1245 } else if (ivarRef.getType()->isPointerType()) {
1246 argCK = CK_BitCast;
1247 }
1248 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1249 ivarRef.getType(), argCK, &argLoad,
1250 VK_RValue);
1251 Expr *finalArg = &argLoad;
1252 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1253 argLoad.getType()))
1254 finalArg = &argCast;
1255
1256
1257 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1258 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +00001259 SourceLocation(), false);
John McCall71c758d2011-09-10 09:17:20 +00001260 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001261}
1262
James Dennett2ee5ba32012-06-15 22:10:14 +00001263/// \brief Generate an Objective-C property setter function.
1264///
1265/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001266/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001267void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1268 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001269 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001270 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001271 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1272 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1273 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001274 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001275
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001276 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001277
1278 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001279}
1280
John McCalle81ac692011-03-22 07:05:39 +00001281namespace {
John McCall9928c482011-07-12 16:41:08 +00001282 struct DestroyIvar : EHScopeStack::Cleanup {
1283 private:
1284 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001285 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001286 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001287 bool useEHCleanupForArray;
1288 public:
1289 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1290 CodeGenFunction::Destroyer *destroyer,
1291 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001292 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001293 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001294
John McCallad346f42011-07-12 20:27:29 +00001295 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001296 LValue lvalue
1297 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1298 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001299 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001300 }
1301 };
1302}
1303
John McCall9928c482011-07-12 16:41:08 +00001304/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1305static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1306 llvm::Value *addr,
1307 QualType type) {
1308 llvm::Value *null = getNullForVariable(addr);
1309 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1310}
John McCallf85e1932011-06-15 23:02:42 +00001311
John McCalle81ac692011-03-22 07:05:39 +00001312static void emitCXXDestructMethod(CodeGenFunction &CGF,
1313 ObjCImplementationDecl *impl) {
1314 CodeGenFunction::RunCleanupsScope scope(CGF);
1315
1316 llvm::Value *self = CGF.LoadObjCSelf();
1317
Jordy Rosedb8264e2011-07-22 02:08:32 +00001318 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1319 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001320 ivar; ivar = ivar->getNextIvar()) {
1321 QualType type = ivar->getType();
1322
John McCalle81ac692011-03-22 07:05:39 +00001323 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001324 QualType::DestructionKind dtorKind = type.isDestructedType();
1325 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001326
John McCall9928c482011-07-12 16:41:08 +00001327 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001328
John McCall9928c482011-07-12 16:41:08 +00001329 // Use a call to objc_storeStrong to destroy strong ivars, for the
1330 // general benefit of the tools.
1331 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001332 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001333
John McCall9928c482011-07-12 16:41:08 +00001334 // Otherwise use the default for the destruction kind.
1335 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001336 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001337 }
John McCall9928c482011-07-12 16:41:08 +00001338
1339 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1340
1341 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1342 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001343 }
1344
1345 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1346}
1347
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001348void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1349 ObjCMethodDecl *MD,
1350 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001351 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001352 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001353
1354 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001355 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001356 // Suppress the final autorelease in ARC.
1357 AutoreleaseResult = false;
1358
Chris Lattner5f9e2722011-07-23 10:55:15 +00001359 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001360 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1361 E = IMP->init_end(); B != E; ++B) {
1362 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001363 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001364 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001365 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1366 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001367 EmitAggExpr(IvarInit->getInit(),
1368 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001369 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001370 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001371 }
1372 // constructor returns 'self'.
1373 CodeGenTypes &Types = CGM.getTypes();
1374 QualType IdTy(CGM.getContext().getObjCIdType());
1375 llvm::Value *SelfAsId =
1376 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1377 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001378
1379 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001380 } else {
John McCalle81ac692011-03-22 07:05:39 +00001381 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001382 }
1383 FinishFunction();
1384}
1385
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001386bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1387 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1388 it++; it++;
1389 const ABIArgInfo &AI = it->info;
1390 // FIXME. Is this sufficient check?
1391 return (AI.getKind() == ABIArgInfo::Indirect);
1392}
1393
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001394bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001395 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001396 return false;
1397 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1398 return FDTTy->getDecl()->hasObjectMember();
1399 return false;
1400}
1401
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001402llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001403 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1404 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001405}
1406
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001407QualType CodeGenFunction::TypeOfSelfObject() {
1408 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1409 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001410 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1411 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001412 return PTy->getPointeeType();
1413}
1414
Chris Lattner74391b42009-03-22 21:03:39 +00001415void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001416 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001417 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001419 if (!EnumerationMutationFn) {
1420 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1421 return;
1422 }
1423
Devang Patelbcbd03a2011-01-19 01:36:36 +00001424 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001425 if (DI)
1426 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001427
Devang Patel9d99f2d2011-06-13 23:15:32 +00001428 // The local variable comes into scope immediately.
1429 AutoVarEmission variable = AutoVarEmission::invalid();
1430 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1431 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1432
John McCalld88687f2011-01-07 01:49:06 +00001433 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Anders Carlssonf484c312008-08-31 02:33:12 +00001435 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001436 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001437 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001438 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Anders Carlssonf484c312008-08-31 02:33:12 +00001440 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001441 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001442
John McCalld88687f2011-01-07 01:49:06 +00001443 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001444 IdentifierInfo *II[] = {
1445 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1446 &CGM.getContext().Idents.get("objects"),
1447 &CGM.getContext().Idents.get("count")
1448 };
1449 Selector FastEnumSel =
1450 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001451
1452 QualType ItemsTy =
1453 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001454 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001455 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001456 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCall990567c2011-07-27 01:07:15 +00001458 // Emit the collection pointer. In ARC, we do a retain.
1459 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001460 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001461 Collection = EmitARCRetainScalarExpr(S.getCollection());
1462
1463 // Enter a cleanup to do the release.
1464 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1465 } else {
1466 Collection = EmitScalarExpr(S.getCollection());
1467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
John McCall4b302d32011-08-05 00:14:38 +00001469 // The 'continue' label needs to appear within the cleanup for the
1470 // collection object.
1471 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1472
John McCalld88687f2011-01-07 01:49:06 +00001473 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001474 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001475
1476 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001477 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001478
John McCalld88687f2011-01-07 01:49:06 +00001479 // The second argument is a temporary array with space for NumItems
1480 // pointers. We'll actually be loading elements from the array
1481 // pointer written into the control state; this buffer is so that
1482 // collections that *aren't* backed by arrays can still queue up
1483 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001484 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001485
John McCalld88687f2011-01-07 01:49:06 +00001486 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001487 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001488 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001489 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
John McCalld88687f2011-01-07 01:49:06 +00001491 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001492 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001493 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001494 getContext().UnsignedLongTy,
1495 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001496 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001497
John McCalld88687f2011-01-07 01:49:06 +00001498 // The initial number of objects that were returned in the buffer.
1499 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001500
John McCalld88687f2011-01-07 01:49:06 +00001501 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1502 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001503
John McCalld88687f2011-01-07 01:49:06 +00001504 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001505
John McCalld88687f2011-01-07 01:49:06 +00001506 // If the limit pointer was zero to begin with, the collection is
1507 // empty; skip all this.
1508 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1509 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001510
John McCalld88687f2011-01-07 01:49:06 +00001511 // Otherwise, initialize the loop.
1512 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001513
John McCalld88687f2011-01-07 01:49:06 +00001514 // Save the initial mutations value. This is the value at an
1515 // address that was written into the state object by
1516 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001517 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001518 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001519 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001520 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001521
John McCalld88687f2011-01-07 01:49:06 +00001522 llvm::Value *initialMutations =
1523 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001524
John McCalld88687f2011-01-07 01:49:06 +00001525 // Start looping. This is the point we return to whenever we have a
1526 // fresh, non-empty batch of objects.
1527 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1528 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001529
John McCalld88687f2011-01-07 01:49:06 +00001530 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001531 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001532 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001533
John McCalld88687f2011-01-07 01:49:06 +00001534 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001535 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001536 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001537
John McCalld88687f2011-01-07 01:49:06 +00001538 // Check whether the mutations value has changed from where it was
1539 // at start. StateMutationsPtr should actually be invariant between
1540 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001541 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001542 llvm::Value *currentMutations
1543 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001544
John McCalld88687f2011-01-07 01:49:06 +00001545 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001546 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001547
John McCalld88687f2011-01-07 01:49:06 +00001548 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1549 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
John McCalld88687f2011-01-07 01:49:06 +00001551 // If so, call the enumeration-mutation function.
1552 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001553 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001554 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001555 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001556 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001557 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001558 // FIXME: We shouldn't need to get the function info here, the runtime already
1559 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001560 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1561 FunctionType::ExtInfo(),
1562 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001563 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
John McCalld88687f2011-01-07 01:49:06 +00001565 // Otherwise, or if the mutation function returns, just continue.
1566 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001567
John McCalld88687f2011-01-07 01:49:06 +00001568 // Initialize the element variable.
1569 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001570 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001571 LValue elementLValue;
1572 QualType elementType;
1573 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001574 // Initialize the variable, in case it's a __block variable or something.
1575 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001576
John McCall57b3b6a2011-02-22 07:16:58 +00001577 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001578 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001579 VK_LValue, SourceLocation());
1580 elementLValue = EmitLValue(&tempDRE);
1581 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001582 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001583
1584 if (D->isARCPseudoStrong())
1585 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001586 } else {
1587 elementLValue = LValue(); // suppress warning
1588 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001589 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001590 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001591 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001592
1593 // Fetch the buffer out of the enumeration state.
1594 // TODO: this pointer should actually be invariant between
1595 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001596 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001597 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001598 llvm::Value *EnumStateItems =
1599 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001600
John McCalld88687f2011-01-07 01:49:06 +00001601 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001602 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001603 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1604 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
John McCalld88687f2011-01-07 01:49:06 +00001606 // Cast that value to the right type.
1607 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1608 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001609
John McCalld88687f2011-01-07 01:49:06 +00001610 // Make sure we have an l-value. Yes, this gets evaluated every
1611 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001612 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001613 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001614 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001615 } else {
1616 EmitScalarInit(CurrentItem, elementLValue);
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
John McCall57b3b6a2011-02-22 07:16:58 +00001619 // If we do have an element variable, this assignment is the end of
1620 // its initialization.
1621 if (elementIsVariable)
1622 EmitAutoVarCleanups(variable);
1623
John McCalld88687f2011-01-07 01:49:06 +00001624 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001625 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001626 {
1627 RunCleanupsScope Scope(*this);
1628 EmitStmt(S.getBody());
1629 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001630 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001631
John McCalld88687f2011-01-07 01:49:06 +00001632 // Destroy the element variable now.
1633 elementVariableScope.ForceCleanup();
1634
1635 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001636 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001637
John McCalld88687f2011-01-07 01:49:06 +00001638 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001639
John McCalld88687f2011-01-07 01:49:06 +00001640 // First we check in the local buffer.
1641 llvm::Value *indexPlusOne
1642 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001643
John McCalld88687f2011-01-07 01:49:06 +00001644 // If we haven't overrun the buffer yet, we can continue.
1645 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1646 LoopBodyBB, FetchMoreBB);
1647
1648 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1649 count->addIncoming(count, AfterBody.getBlock());
1650
1651 // Otherwise, we have to fetch more elements.
1652 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001653
1654 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001655 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001656 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001657 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001658 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
John McCalld88687f2011-01-07 01:49:06 +00001660 // If we got a zero count, we're done.
1661 llvm::Value *refetchCount = CountRV.getScalarVal();
1662
1663 // (note that the message send might split FetchMoreBB)
1664 index->addIncoming(zero, Builder.GetInsertBlock());
1665 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1666
1667 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1668 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Anders Carlssonf484c312008-08-31 02:33:12 +00001670 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001671 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001672
John McCall57b3b6a2011-02-22 07:16:58 +00001673 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001674 // If the element was not a declaration, set it to be null.
1675
John McCalld88687f2011-01-07 01:49:06 +00001676 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1677 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001678 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001679 }
1680
Eric Christopher73fb3502011-10-13 21:45:18 +00001681 if (DI)
1682 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001683
John McCall990567c2011-07-27 01:07:15 +00001684 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001685 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001686 PopCleanupBlock();
1687
John McCallff8e1152010-07-23 21:56:41 +00001688 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001689}
1690
Mike Stump1eb44332009-09-09 15:08:12 +00001691void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001692 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001693}
1694
Mike Stump1eb44332009-09-09 15:08:12 +00001695void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001696 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1697}
1698
Chris Lattner10cac6f2008-11-15 21:26:17 +00001699void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001700 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001701 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001702}
1703
John McCall33e56f32011-09-10 06:18:15 +00001704/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001705/// primitive retain.
1706llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1707 llvm::Value *value) {
1708 return EmitARCRetain(type, value);
1709}
1710
1711namespace {
1712 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001713 CallObjCRelease(llvm::Value *object) : object(object) {}
1714 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001715
John McCallad346f42011-07-12 20:27:29 +00001716 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001717 // Releases at the end of the full-expression are imprecise.
1718 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001719 }
1720 };
1721}
1722
John McCall33e56f32011-09-10 06:18:15 +00001723/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001724/// release at the end of the full-expression.
1725llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1726 llvm::Value *object) {
1727 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001728 // conditional.
1729 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001730 return object;
1731}
1732
1733llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1734 llvm::Value *value) {
1735 return EmitARCRetainAutorelease(type, value);
1736}
1737
John McCallb6a60792013-03-23 02:35:54 +00001738/// Given a number of pointers, inform the optimizer that they're
1739/// being intrinsically used up until this point in the program.
1740void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1741 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1742 if (!fn) {
1743 llvm::FunctionType *fnType =
1744 llvm::FunctionType::get(CGM.VoidTy, ArrayRef<llvm::Type*>(), true);
1745 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1746 }
1747
1748 // This isn't really a "runtime" function, but as an intrinsic it
1749 // doesn't really matter as long as we align things up.
1750 EmitNounwindRuntimeCall(fn, values);
1751}
1752
John McCallf85e1932011-06-15 23:02:42 +00001753
1754static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001755 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001756 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001757 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1758
Michael Gottesman554b07d2013-02-02 00:57:44 +00001759 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmancfe18a12013-02-02 01:05:06 +00001760 // If the target runtime doesn't naturally support ARC, emit weak
1761 // references to the runtime support library. We don't really
1762 // permit this to fail, but we need a particular relocation style.
Michael Gottesman554b07d2013-02-02 00:57:44 +00001763 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00001764 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesman554b07d2013-02-02 00:57:44 +00001765 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1766 // If we have Native ARC, set nonlazybind attribute for these APIs for
1767 // performance.
Bill Wendling72390b32012-12-20 19:27:06 +00001768 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmandb99e8b2013-02-02 01:03:01 +00001769 }
Michael Gottesman554b07d2013-02-02 00:57:44 +00001770 }
John McCallf85e1932011-06-15 23:02:42 +00001771
1772 return fn;
1773}
1774
1775/// Perform an operation having the signature
1776/// i8* (i8*)
1777/// where a null input causes a no-op and returns null.
1778static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1779 llvm::Value *value,
1780 llvm::Constant *&fn,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001781 StringRef fnName,
1782 bool isTailCall = false) {
John McCallf85e1932011-06-15 23:02:42 +00001783 if (isa<llvm::ConstantPointerNull>(value)) return value;
1784
1785 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001786 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001787 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001788 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1789 }
1790
1791 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001792 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001793 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1794
1795 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001796 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001797 if (isTailCall)
1798 call->setTailCall();
John McCallf85e1932011-06-15 23:02:42 +00001799
1800 // Cast the result back to the original type.
1801 return CGF.Builder.CreateBitCast(call, origType);
1802}
1803
1804/// Perform an operation having the following signature:
1805/// i8* (i8**)
1806static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1807 llvm::Value *addr,
1808 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001809 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001810 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001811 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001812 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001813 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1814 }
1815
1816 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001817 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001818 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1819
1820 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001821 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00001822
1823 // Cast the result back to a dereference of the original type.
John McCallf85e1932011-06-15 23:02:42 +00001824 if (origType != CGF.Int8PtrPtrTy)
1825 result = CGF.Builder.CreateBitCast(result,
1826 cast<llvm::PointerType>(origType)->getElementType());
1827
1828 return result;
1829}
1830
1831/// Perform an operation having the following signature:
1832/// i8* (i8**, i8*)
1833static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1834 llvm::Value *addr,
1835 llvm::Value *value,
1836 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001837 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001838 bool ignored) {
1839 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1840 == value->getType());
1841
1842 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001843 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001844
Chris Lattner2acc6e32011-07-18 04:24:23 +00001845 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001846 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1847 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1848 }
1849
Chris Lattner2acc6e32011-07-18 04:24:23 +00001850 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001851
John McCallbd7370a2013-02-28 19:01:20 +00001852 llvm::Value *args[] = {
1853 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1854 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1855 };
1856 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001857
1858 if (ignored) return 0;
1859
1860 return CGF.Builder.CreateBitCast(result, origType);
1861}
1862
1863/// Perform an operation having the following signature:
1864/// void (i8**, i8**)
1865static void emitARCCopyOperation(CodeGenFunction &CGF,
1866 llvm::Value *dst,
1867 llvm::Value *src,
1868 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001869 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001870 assert(dst->getType() == src->getType());
1871
1872 if (!fn) {
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001873 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1874
Chris Lattner2acc6e32011-07-18 04:24:23 +00001875 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001876 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1877 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1878 }
1879
John McCallbd7370a2013-02-28 19:01:20 +00001880 llvm::Value *args[] = {
1881 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1882 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1883 };
1884 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001885}
1886
1887/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001888/// call i8* \@objc_retain(i8* %value)
1889/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001890llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1891 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001892 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001893 else
1894 return EmitARCRetainNonBlock(value);
1895}
1896
1897/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001898/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001899llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1900 return emitARCValueOperation(*this, value,
1901 CGM.getARCEntrypoints().objc_retain,
1902 "objc_retain");
1903}
1904
1905/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001906/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001907///
1908/// \param mandatory - If false, emit the call with metadata
1909/// indicating that it's okay for the optimizer to eliminate this call
1910/// if it can prove that the block never escapes except down the stack.
1911llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1912 bool mandatory) {
1913 llvm::Value *result
1914 = emitARCValueOperation(*this, value,
1915 CGM.getARCEntrypoints().objc_retainBlock,
1916 "objc_retainBlock");
1917
1918 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1919 // tell the optimizer that it doesn't need to do this copy if the
1920 // block doesn't escape, where being passed as an argument doesn't
1921 // count as escaping.
1922 if (!mandatory && isa<llvm::Instruction>(result)) {
1923 llvm::CallInst *call
1924 = cast<llvm::CallInst>(result->stripPointerCasts());
1925 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1926
1927 SmallVector<llvm::Value*,1> args;
1928 call->setMetadata("clang.arc.copy_on_escape",
1929 llvm::MDNode::get(Builder.getContext(), args));
1930 }
1931
1932 return result;
John McCallf85e1932011-06-15 23:02:42 +00001933}
1934
1935/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001936/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001937///
1938/// Yes, this function name is one character away from a different
1939/// call with completely different semantics.
1940llvm::Value *
1941CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1942 // Fetch the void(void) inline asm which marks that we're going to
1943 // retain the autoreleased return value.
1944 llvm::InlineAsm *&marker
1945 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1946 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001947 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001948 = CGM.getTargetCodeGenInfo()
1949 .getARCRetainAutoreleasedReturnValueMarker();
1950
1951 // If we have an empty assembly string, there's nothing to do.
1952 if (assembly.empty()) {
1953
1954 // Otherwise, at -O0, build an inline asm that we're going to call
1955 // in a moment.
1956 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1957 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001958 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001959
1960 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1961
1962 // If we're at -O1 and above, we don't want to litter the code
1963 // with this marker yet, so leave a breadcrumb for the ARC
1964 // optimizer to pick up.
1965 } else {
1966 llvm::NamedMDNode *metadata =
1967 CGM.getModule().getOrInsertNamedMetadata(
1968 "clang.arc.retainAutoreleasedReturnValueMarker");
1969 assert(metadata->getNumOperands() <= 1);
1970 if (metadata->getNumOperands() == 0) {
1971 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001972 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001973 }
1974 }
1975 }
1976
1977 // Call the marker asm if we made one, which we do only at -O0.
1978 if (marker) Builder.CreateCall(marker);
1979
1980 return emitARCValueOperation(*this, value,
1981 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1982 "objc_retainAutoreleasedReturnValue");
1983}
1984
1985/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001986/// call void \@objc_release(i8* %value)
John McCall5b07e802013-03-13 03:10:54 +00001987void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1988 ARCPreciseLifetime_t precise) {
John McCallf85e1932011-06-15 23:02:42 +00001989 if (isa<llvm::ConstantPointerNull>(value)) return;
1990
1991 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1992 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001993 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001994 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001995 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1996 }
1997
1998 // Cast the argument to 'id'.
1999 value = Builder.CreateBitCast(value, Int8PtrTy);
2000
2001 // Call objc_release.
John McCallbd7370a2013-02-28 19:01:20 +00002002 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002003
John McCall5b07e802013-03-13 03:10:54 +00002004 if (precise == ARCImpreciseLifetime) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002005 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00002006 call->setMetadata("clang.imprecise_release",
2007 llvm::MDNode::get(Builder.getContext(), args));
2008 }
2009}
2010
John McCall015f33b2012-10-17 02:28:37 +00002011/// Destroy a __strong variable.
2012///
2013/// At -O0, emit a call to store 'null' into the address;
2014/// instrumenting tools prefer this because the address is exposed,
2015/// but it's relatively cumbersome to optimize.
2016///
2017/// At -O1 and above, just load and call objc_release.
2018///
2019/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall5b07e802013-03-13 03:10:54 +00002020void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2021 ARCPreciseLifetime_t precise) {
John McCall015f33b2012-10-17 02:28:37 +00002022 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2023 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2024 llvm::Value *null = llvm::ConstantPointerNull::get(
2025 cast<llvm::PointerType>(addrTy->getElementType()));
2026 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2027 return;
2028 }
2029
2030 llvm::Value *value = Builder.CreateLoad(addr);
2031 EmitARCRelease(value, precise);
2032}
2033
John McCallf85e1932011-06-15 23:02:42 +00002034/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002035/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002036llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2037 llvm::Value *value,
2038 bool ignored) {
2039 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2040 == value->getType());
2041
2042 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2043 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002044 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00002045 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00002046 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2047 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2048 }
2049
John McCallbd7370a2013-02-28 19:01:20 +00002050 llvm::Value *args[] = {
2051 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2052 Builder.CreateBitCast(value, Int8PtrTy)
2053 };
2054 EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00002055
2056 if (ignored) return 0;
2057 return value;
2058}
2059
2060/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002061/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002062/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00002063llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00002064 llvm::Value *newValue,
2065 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00002066 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00002067 bool isBlock = type->isBlockPointerType();
2068
2069 // Use a store barrier at -O0 unless this is a block type or the
2070 // lvalue is inadequately aligned.
2071 if (shouldUseFusedARCCalls() &&
2072 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00002073 (dst.getAlignment().isZero() ||
2074 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00002075 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2076 }
2077
2078 // Otherwise, split it out.
2079
2080 // Retain the new value.
2081 newValue = EmitARCRetain(type, newValue);
2082
2083 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00002084 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00002085
2086 // Store. We do this before the release so that any deallocs won't
2087 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002088 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002089
2090 // Finally, release the old value.
John McCall5b07e802013-03-13 03:10:54 +00002091 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002092
2093 return newValue;
2094}
2095
2096/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002097/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002098llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2099 return emitARCValueOperation(*this, value,
2100 CGM.getARCEntrypoints().objc_autorelease,
2101 "objc_autorelease");
2102}
2103
2104/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002105/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002106llvm::Value *
2107CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2108 return emitARCValueOperation(*this, value,
2109 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002110 "objc_autoreleaseReturnValue",
2111 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002112}
2113
2114/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002115/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002116llvm::Value *
2117CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2118 return emitARCValueOperation(*this, value,
2119 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002120 "objc_retainAutoreleaseReturnValue",
2121 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002122}
2123
2124/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002125/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002126/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002127/// %retain = call i8* \@objc_retainBlock(i8* %value)
2128/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002129llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2130 llvm::Value *value) {
2131 if (!type->isBlockPointerType())
2132 return EmitARCRetainAutoreleaseNonBlock(value);
2133
2134 if (isa<llvm::ConstantPointerNull>(value)) return value;
2135
Chris Lattner2acc6e32011-07-18 04:24:23 +00002136 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002137 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002138 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002139 value = EmitARCAutorelease(value);
2140 return Builder.CreateBitCast(value, origType);
2141}
2142
2143/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002144/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002145llvm::Value *
2146CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2147 return emitARCValueOperation(*this, value,
2148 CGM.getARCEntrypoints().objc_retainAutorelease,
2149 "objc_retainAutorelease");
2150}
2151
James Dennett9d96e9c2012-06-22 05:41:30 +00002152/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002153/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2154llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2155 return emitARCLoadOperation(*this, addr,
2156 CGM.getARCEntrypoints().objc_loadWeak,
2157 "objc_loadWeak");
2158}
2159
James Dennett9d96e9c2012-06-22 05:41:30 +00002160/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002161llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2162 return emitARCLoadOperation(*this, addr,
2163 CGM.getARCEntrypoints().objc_loadWeakRetained,
2164 "objc_loadWeakRetained");
2165}
2166
James Dennett9d96e9c2012-06-22 05:41:30 +00002167/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002168/// Returns %value.
2169llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2170 llvm::Value *value,
2171 bool ignored) {
2172 return emitARCStoreOperation(*this, addr, value,
2173 CGM.getARCEntrypoints().objc_storeWeak,
2174 "objc_storeWeak", ignored);
2175}
2176
James Dennett9d96e9c2012-06-22 05:41:30 +00002177/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002178/// Returns %value. %addr is known to not have a current weak entry.
2179/// Essentially equivalent to:
2180/// *addr = nil; objc_storeWeak(addr, value);
2181void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2182 // If we're initializing to null, just write null to memory; no need
2183 // to get the runtime involved. But don't do this if optimization
2184 // is enabled, because accounting for this would make the optimizer
2185 // much more complicated.
2186 if (isa<llvm::ConstantPointerNull>(value) &&
2187 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2188 Builder.CreateStore(value, addr);
2189 return;
2190 }
2191
2192 emitARCStoreOperation(*this, addr, value,
2193 CGM.getARCEntrypoints().objc_initWeak,
2194 "objc_initWeak", /*ignored*/ true);
2195}
2196
James Dennett9d96e9c2012-06-22 05:41:30 +00002197/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002198/// Essentially objc_storeWeak(addr, nil).
2199void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2200 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2201 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002202 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002203 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002204 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2205 }
2206
2207 // Cast the argument to 'id*'.
2208 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2209
John McCallbd7370a2013-02-28 19:01:20 +00002210 EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00002211}
2212
James Dennett9d96e9c2012-06-22 05:41:30 +00002213/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002214/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2215/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2216void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2217 emitARCCopyOperation(*this, dst, src,
2218 CGM.getARCEntrypoints().objc_moveWeak,
2219 "objc_moveWeak");
2220}
2221
James Dennett9d96e9c2012-06-22 05:41:30 +00002222/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002223/// Disregards the current value in %dest. Essentially
2224/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2225void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2226 emitARCCopyOperation(*this, dst, src,
2227 CGM.getARCEntrypoints().objc_copyWeak,
2228 "objc_copyWeak");
2229}
2230
2231/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002232/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002233llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2234 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2235 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002236 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002237 llvm::FunctionType::get(Int8PtrTy, false);
2238 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2239 }
2240
John McCallbd7370a2013-02-28 19:01:20 +00002241 return EmitNounwindRuntimeCall(fn);
John McCallf85e1932011-06-15 23:02:42 +00002242}
2243
2244/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002245/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002246void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2247 assert(value->getType() == Int8PtrTy);
2248
2249 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2250 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002251 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002252 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002253
2254 // We don't want to use a weak import here; instead we should not
2255 // fall into this path.
2256 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2257 }
2258
John McCallbd7370a2013-02-28 19:01:20 +00002259 EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002260}
2261
2262/// Produce the code to do an MRR version objc_autoreleasepool_push.
2263/// Which is: [[NSAutoreleasePool alloc] init];
2264/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2265/// init is declared as: - (id) init; in its NSObject super class.
2266///
2267llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2268 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +00002269 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCallf85e1932011-06-15 23:02:42 +00002270 // [NSAutoreleasePool alloc]
2271 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2272 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2273 CallArgList Args;
2274 RValue AllocRV =
2275 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2276 getContext().getObjCIdType(),
2277 AllocSel, Receiver, Args);
2278
2279 // [Receiver init]
2280 Receiver = AllocRV.getScalarVal();
2281 II = &CGM.getContext().Idents.get("init");
2282 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2283 RValue InitRV =
2284 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2285 getContext().getObjCIdType(),
2286 InitSel, Receiver, Args);
2287 return InitRV.getScalarVal();
2288}
2289
2290/// Produce the code to do a primitive release.
2291/// [tmp drain];
2292void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2293 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2294 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2295 CallArgList Args;
2296 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2297 getContext().VoidTy, DrainSel, Arg, Args);
2298}
2299
John McCallbdc4d802011-07-09 01:37:26 +00002300void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2301 llvm::Value *addr,
2302 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002303 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002304}
2305
2306void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2307 llvm::Value *addr,
2308 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002309 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002310}
2311
2312void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2313 llvm::Value *addr,
2314 QualType type) {
2315 CGF.EmitARCDestroyWeak(addr);
2316}
2317
John McCallf85e1932011-06-15 23:02:42 +00002318namespace {
John McCallf85e1932011-06-15 23:02:42 +00002319 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2320 llvm::Value *Token;
2321
2322 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2323
John McCallad346f42011-07-12 20:27:29 +00002324 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002325 CGF.EmitObjCAutoreleasePoolPop(Token);
2326 }
2327 };
2328 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2329 llvm::Value *Token;
2330
2331 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2332
John McCallad346f42011-07-12 20:27:29 +00002333 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002334 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2335 }
2336 };
2337}
2338
2339void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002340 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002341 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2342 else
2343 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2344}
2345
John McCallf85e1932011-06-15 23:02:42 +00002346static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2347 LValue lvalue,
2348 QualType type) {
2349 switch (type.getObjCLifetime()) {
2350 case Qualifiers::OCL_None:
2351 case Qualifiers::OCL_ExplicitNone:
2352 case Qualifiers::OCL_Strong:
2353 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002354 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002355 false);
2356
2357 case Qualifiers::OCL_Weak:
2358 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2359 true);
2360 }
2361
2362 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002363}
2364
2365static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2366 const Expr *e) {
2367 e = e->IgnoreParens();
2368 QualType type = e->getType();
2369
John McCall21480112011-08-30 00:57:29 +00002370 // If we're loading retained from a __strong xvalue, we can avoid
2371 // an extra retain/release pair by zeroing out the source of this
2372 // "move" operation.
2373 if (e->isXValue() &&
2374 !type.isConstQualified() &&
2375 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2376 // Emit the lvalue.
2377 LValue lv = CGF.EmitLValue(e);
2378
2379 // Load the object pointer.
2380 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2381
2382 // Set the source pointer to NULL.
2383 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2384
2385 return TryEmitResult(result, true);
2386 }
2387
John McCallf85e1932011-06-15 23:02:42 +00002388 // As a very special optimization, in ARC++, if the l-value is the
2389 // result of a non-volatile assignment, do a simple retain of the
2390 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002391 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002392 !type.isVolatileQualified() &&
2393 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2394 isa<BinaryOperator>(e) &&
2395 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2396 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2397
2398 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2399}
2400
2401static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2402 llvm::Value *value);
2403
2404/// Given that the given expression is some sort of call (which does
2405/// not return retained), emit a retain following it.
2406static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2407 llvm::Value *value = CGF.EmitScalarExpr(e);
2408 return emitARCRetainAfterCall(CGF, value);
2409}
2410
2411static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2412 llvm::Value *value) {
2413 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2414 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2415
2416 // Place the retain immediately following the call.
2417 CGF.Builder.SetInsertPoint(call->getParent(),
2418 ++llvm::BasicBlock::iterator(call));
2419 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2420
2421 CGF.Builder.restoreIP(ip);
2422 return value;
2423 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2424 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2425
2426 // Place the retain at the beginning of the normal destination block.
2427 llvm::BasicBlock *BB = invoke->getNormalDest();
2428 CGF.Builder.SetInsertPoint(BB, BB->begin());
2429 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2430
2431 CGF.Builder.restoreIP(ip);
2432 return value;
2433
2434 // Bitcasts can arise because of related-result returns. Rewrite
2435 // the operand.
2436 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2437 llvm::Value *operand = bitcast->getOperand(0);
2438 operand = emitARCRetainAfterCall(CGF, operand);
2439 bitcast->setOperand(0, operand);
2440 return bitcast;
2441
2442 // Generic fall-back case.
2443 } else {
2444 // Retain using the non-block variant: we never need to do a copy
2445 // of a block that's been returned to us.
2446 return CGF.EmitARCRetainNonBlock(value);
2447 }
2448}
2449
John McCalldc05b112011-09-10 01:16:55 +00002450/// Determine whether it might be important to emit a separate
2451/// objc_retain_block on the result of the given expression, or
2452/// whether it's okay to just emit it in a +1 context.
2453static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2454 assert(e->getType()->isBlockPointerType());
2455 e = e->IgnoreParens();
2456
2457 // For future goodness, emit block expressions directly in +1
2458 // contexts if we can.
2459 if (isa<BlockExpr>(e))
2460 return false;
2461
2462 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2463 switch (cast->getCastKind()) {
2464 // Emitting these operations in +1 contexts is goodness.
2465 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002466 case CK_ARCReclaimReturnedObject:
2467 case CK_ARCConsumeObject:
2468 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002469 return false;
2470
2471 // These operations preserve a block type.
2472 case CK_NoOp:
2473 case CK_BitCast:
2474 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2475
2476 // These operations are known to be bad (or haven't been considered).
2477 case CK_AnyPointerToBlockPointerCast:
2478 default:
2479 return true;
2480 }
2481 }
2482
2483 return true;
2484}
2485
John McCall4b9c2d22011-11-06 09:01:30 +00002486/// Try to emit a PseudoObjectExpr at +1.
2487///
2488/// This massively duplicates emitPseudoObjectRValue.
2489static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2490 const PseudoObjectExpr *E) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002491 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCall4b9c2d22011-11-06 09:01:30 +00002492
2493 // Find the result expression.
2494 const Expr *resultExpr = E->getResultExpr();
2495 assert(resultExpr);
2496 TryEmitResult result;
2497
2498 for (PseudoObjectExpr::const_semantics_iterator
2499 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2500 const Expr *semantic = *i;
2501
2502 // If this semantic expression is an opaque value, bind it
2503 // to the result of its source expression.
2504 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2505 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2506 OVMA opaqueData;
2507
2508 // If this semantic is the result of the pseudo-object
2509 // expression, try to evaluate the source as +1.
2510 if (ov == resultExpr) {
2511 assert(!OVMA::shouldBindAsLValue(ov));
2512 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2513 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2514
2515 // Otherwise, just bind it.
2516 } else {
2517 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2518 }
2519 opaques.push_back(opaqueData);
2520
2521 // Otherwise, if the expression is the result, evaluate it
2522 // and remember the result.
2523 } else if (semantic == resultExpr) {
2524 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2525
2526 // Otherwise, evaluate the expression in an ignored context.
2527 } else {
2528 CGF.EmitIgnoredExpr(semantic);
2529 }
2530 }
2531
2532 // Unbind all the opaques now.
2533 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2534 opaques[i].unbind(CGF);
2535
2536 return result;
2537}
2538
John McCallf85e1932011-06-15 23:02:42 +00002539static TryEmitResult
2540tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002541 // We should *never* see a nested full-expression here, because if
2542 // we fail to emit at +1, our caller must not retain after we close
2543 // out the full-expression.
2544 assert(!isa<ExprWithCleanups>(e));
John McCall990567c2011-07-27 01:07:15 +00002545
John McCallf85e1932011-06-15 23:02:42 +00002546 // The desired result type, if it differs from the type of the
2547 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002548 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002549
2550 while (true) {
2551 e = e->IgnoreParens();
2552
2553 // There's a break at the end of this if-chain; anything
2554 // that wants to keep looping has to explicitly continue.
2555 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2556 switch (ce->getCastKind()) {
2557 // No-op casts don't change the type, so we just ignore them.
2558 case CK_NoOp:
2559 e = ce->getSubExpr();
2560 continue;
2561
2562 case CK_LValueToRValue: {
2563 TryEmitResult loadResult
2564 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2565 if (resultType) {
2566 llvm::Value *value = loadResult.getPointer();
2567 value = CGF.Builder.CreateBitCast(value, resultType);
2568 loadResult.setPointer(value);
2569 }
2570 return loadResult;
2571 }
2572
2573 // These casts can change the type, so remember that and
2574 // soldier on. We only need to remember the outermost such
2575 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002576 case CK_CPointerToObjCPointerCast:
2577 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002578 case CK_AnyPointerToBlockPointerCast:
2579 case CK_BitCast:
2580 if (!resultType)
2581 resultType = CGF.ConvertType(ce->getType());
2582 e = ce->getSubExpr();
2583 assert(e->getType()->hasPointerRepresentation());
2584 continue;
2585
2586 // For consumptions, just emit the subexpression and thus elide
2587 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002588 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002589 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2590 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2591 return TryEmitResult(result, true);
2592 }
2593
John McCalldc05b112011-09-10 01:16:55 +00002594 // Block extends are net +0. Naively, we could just recurse on
2595 // the subexpression, but actually we need to ensure that the
2596 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002597 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002598 llvm::Value *result; // will be a +0 value
2599
2600 // If we can't safely assume the sub-expression will produce a
2601 // block-copied value, emit the sub-expression at +0.
2602 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2603 result = CGF.EmitScalarExpr(ce->getSubExpr());
2604
2605 // Otherwise, try to emit the sub-expression at +1 recursively.
2606 } else {
2607 TryEmitResult subresult
2608 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2609 result = subresult.getPointer();
2610
2611 // If that produced a retained value, just use that,
2612 // possibly casting down.
2613 if (subresult.getInt()) {
2614 if (resultType)
2615 result = CGF.Builder.CreateBitCast(result, resultType);
2616 return TryEmitResult(result, true);
2617 }
2618
2619 // Otherwise it's +0.
2620 }
2621
2622 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002623 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002624 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2625 return TryEmitResult(result, true);
2626 }
2627
John McCall7e5e5f42011-07-07 06:58:02 +00002628 // For reclaims, emit the subexpression as a retained call and
2629 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002630 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002631 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2632 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2633 return TryEmitResult(result, true);
2634 }
2635
John McCallf85e1932011-06-15 23:02:42 +00002636 default:
2637 break;
2638 }
2639
2640 // Skip __extension__.
2641 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2642 if (op->getOpcode() == UO_Extension) {
2643 e = op->getSubExpr();
2644 continue;
2645 }
2646
2647 // For calls and message sends, use the retained-call logic.
2648 // Delegate inits are a special case in that they're the only
2649 // returns-retained expression that *isn't* surrounded by
2650 // a consume.
2651 } else if (isa<CallExpr>(e) ||
2652 (isa<ObjCMessageExpr>(e) &&
2653 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2654 llvm::Value *result = emitARCRetainCall(CGF, e);
2655 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2656 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002657
2658 // Look through pseudo-object expressions.
2659 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2660 TryEmitResult result
2661 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2662 if (resultType) {
2663 llvm::Value *value = result.getPointer();
2664 value = CGF.Builder.CreateBitCast(value, resultType);
2665 result.setPointer(value);
2666 }
2667 return result;
John McCallf85e1932011-06-15 23:02:42 +00002668 }
2669
2670 // Conservatively halt the search at any other expression kind.
2671 break;
2672 }
2673
2674 // We didn't find an obvious production, so emit what we've got and
2675 // tell the caller that we didn't manage to retain.
2676 llvm::Value *result = CGF.EmitScalarExpr(e);
2677 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2678 return TryEmitResult(result, false);
2679}
2680
2681static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2682 LValue lvalue,
2683 QualType type) {
2684 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2685 llvm::Value *value = result.getPointer();
2686 if (!result.getInt())
2687 value = CGF.EmitARCRetain(type, value);
2688 return value;
2689}
2690
2691/// EmitARCRetainScalarExpr - Semantically equivalent to
2692/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2693/// best-effort attempt to peephole expressions that naturally produce
2694/// retained objects.
2695llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002696 // The retain needs to happen within the full-expression.
2697 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2698 enterFullExpression(cleanups);
2699 RunCleanupsScope scope(*this);
2700 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2701 }
2702
John McCallf85e1932011-06-15 23:02:42 +00002703 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2704 llvm::Value *value = result.getPointer();
2705 if (!result.getInt())
2706 value = EmitARCRetain(e->getType(), value);
2707 return value;
2708}
2709
2710llvm::Value *
2711CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002712 // The retain needs to happen within the full-expression.
2713 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2714 enterFullExpression(cleanups);
2715 RunCleanupsScope scope(*this);
2716 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2717 }
2718
John McCallf85e1932011-06-15 23:02:42 +00002719 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2720 llvm::Value *value = result.getPointer();
2721 if (result.getInt())
2722 value = EmitARCAutorelease(value);
2723 else
2724 value = EmitARCRetainAutorelease(e->getType(), value);
2725 return value;
2726}
2727
John McCall348f16f2011-10-04 06:23:45 +00002728llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2729 llvm::Value *result;
2730 bool doRetain;
2731
2732 if (shouldEmitSeparateBlockRetain(e)) {
2733 result = EmitScalarExpr(e);
2734 doRetain = true;
2735 } else {
2736 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2737 result = subresult.getPointer();
2738 doRetain = !subresult.getInt();
2739 }
2740
2741 if (doRetain)
2742 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2743 return EmitObjCConsumeObject(e->getType(), result);
2744}
2745
John McCall2b014d62011-10-01 10:32:24 +00002746llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2747 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002748 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002749 // Do so before running any cleanups for the full-expression.
John McCall72dcecc2013-02-12 00:25:08 +00002750 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall2b014d62011-10-01 10:32:24 +00002751 return EmitARCRetainAutoreleaseScalarExpr(expr);
2752 }
2753
2754 // Otherwise, use the normal scalar-expression emission. The
2755 // exception machinery doesn't do anything special with the
2756 // exception like retaining it, so there's no safety associated with
2757 // only running cleanups after the throw has started, and when it
2758 // matters it tends to be substantially inferior code.
2759 return EmitScalarExpr(expr);
2760}
2761
John McCallf85e1932011-06-15 23:02:42 +00002762std::pair<LValue,llvm::Value*>
2763CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2764 bool ignored) {
2765 // Evaluate the RHS first.
2766 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2767 llvm::Value *value = result.getPointer();
2768
John McCallfb720812011-07-28 07:23:35 +00002769 bool hasImmediateRetain = result.getInt();
2770
2771 // If we didn't emit a retained object, and the l-value is of block
2772 // type, then we need to emit the block-retain immediately in case
2773 // it invalidates the l-value.
2774 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002775 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002776 hasImmediateRetain = true;
2777 }
2778
John McCallf85e1932011-06-15 23:02:42 +00002779 LValue lvalue = EmitLValue(e->getLHS());
2780
2781 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002782 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002783 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002784 EmitLoadOfScalar(lvalue);
2785 EmitStoreOfScalar(value, lvalue);
John McCall5b07e802013-03-13 03:10:54 +00002786 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002787 } else {
John McCall545d9962011-06-25 02:11:03 +00002788 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002789 }
2790
2791 return std::pair<LValue,llvm::Value*>(lvalue, value);
2792}
2793
2794std::pair<LValue,llvm::Value*>
2795CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2796 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2797 LValue lvalue = EmitLValue(e->getLHS());
2798
Eli Friedman6da2c712011-12-03 04:14:32 +00002799 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002800
2801 return std::pair<LValue,llvm::Value*>(lvalue, value);
2802}
2803
2804void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002805 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002806 const Stmt *subStmt = ARPS.getSubStmt();
2807 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2808
2809 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002810 if (DI)
2811 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002812
2813 // Keep track of the current cleanup stack depth.
2814 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00002815 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002816 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2817 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2818 } else {
2819 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2820 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2821 }
2822
2823 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2824 E = S.body_end(); I != E; ++I)
2825 EmitStmt(*I);
2826
Eric Christopher73fb3502011-10-13 21:45:18 +00002827 if (DI)
2828 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002829}
John McCall0c24c802011-06-24 23:21:27 +00002830
2831/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2832/// make sure it survives garbage collection until this point.
2833void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2834 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002835 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002836 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002837 llvm::Value *extender
2838 = llvm::InlineAsm::get(extenderType,
2839 /* assembly */ "",
2840 /* constraints */ "r",
2841 /* side effects */ true);
2842
2843 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00002844 EmitNounwindRuntimeCall(extender, object);
John McCall0c24c802011-06-24 23:21:27 +00002845}
2846
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002847/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002848/// non-trivial copy assignment function, produce following helper function.
2849/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2850///
2851llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002852CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2853 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002854 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002855 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002856 return 0;
2857 QualType Ty = PID->getPropertyIvarDecl()->getType();
2858 if (!Ty->isRecordType())
2859 return 0;
2860 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002861 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002862 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002863 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002864 if (hasTrivialSetExpr(PID))
2865 return 0;
2866 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2867 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2868 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002869
2870 ASTContext &C = getContext();
2871 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002872 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002873 FunctionDecl *FD = FunctionDecl::Create(C,
2874 C.getTranslationUnitDecl(),
2875 SourceLocation(),
2876 SourceLocation(), II, C.VoidTy, 0,
2877 SC_Static,
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002878 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002879 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002880
2881 QualType DestTy = C.getPointerType(Ty);
2882 QualType SrcTy = Ty;
2883 SrcTy.addConst();
2884 SrcTy = C.getPointerType(SrcTy);
2885
2886 FunctionArgList args;
2887 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2888 args.push_back(&dstDecl);
2889 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2890 args.push_back(&srcDecl);
2891
2892 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002893 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2894 FunctionType::ExtInfo(),
2895 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002896
John McCallde5d3c72012-02-17 03:33:10 +00002897 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002898
2899 llvm::Function *Fn =
2900 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002901 "__assign_helper_atomic_property_",
2902 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002903
Alexey Samsonova240df22012-10-16 07:22:28 +00002904 // Initialize debug info if needed.
2905 maybeInitializeDebugInfo();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002906
2907 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2908
John McCallf4b88a42012-03-10 09:33:50 +00002909 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2910 VK_RValue, SourceLocation());
2911 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2912 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002913
John McCallf4b88a42012-03-10 09:33:50 +00002914 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2915 VK_RValue, SourceLocation());
2916 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2917 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002918
John McCallf4b88a42012-03-10 09:33:50 +00002919 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002920 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002921 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002922 Args, DestTy->getPointeeType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00002923 VK_LValue, SourceLocation(), false);
John McCallf4b88a42012-03-10 09:33:50 +00002924
2925 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002926
2927 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002928 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002929 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002930 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002931}
2932
2933llvm::Constant *
2934CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2935 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002936 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002937 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002938 return 0;
2939 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2940 QualType Ty = PD->getType();
2941 if (!Ty->isRecordType())
2942 return 0;
2943 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2944 return 0;
2945 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002946
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002947 if (hasTrivialGetExpr(PID))
2948 return 0;
2949 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2950 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2951 return HelperFn;
2952
2953
2954 ASTContext &C = getContext();
2955 IdentifierInfo *II
2956 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2957 FunctionDecl *FD = FunctionDecl::Create(C,
2958 C.getTranslationUnitDecl(),
2959 SourceLocation(),
2960 SourceLocation(), II, C.VoidTy, 0,
2961 SC_Static,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002962 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002963 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002964
2965 QualType DestTy = C.getPointerType(Ty);
2966 QualType SrcTy = Ty;
2967 SrcTy.addConst();
2968 SrcTy = C.getPointerType(SrcTy);
2969
2970 FunctionArgList args;
2971 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2972 args.push_back(&dstDecl);
2973 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2974 args.push_back(&srcDecl);
2975
2976 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002977 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2978 FunctionType::ExtInfo(),
2979 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002980
John McCallde5d3c72012-02-17 03:33:10 +00002981 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002982
2983 llvm::Function *Fn =
2984 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2985 "__copy_helper_atomic_property_", &CGM.getModule());
2986
Alexey Samsonova240df22012-10-16 07:22:28 +00002987 // Initialize debug info if needed.
2988 maybeInitializeDebugInfo();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002989
2990 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2991
John McCallf4b88a42012-03-10 09:33:50 +00002992 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002993 VK_RValue, SourceLocation());
2994
John McCallf4b88a42012-03-10 09:33:50 +00002995 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2996 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002997
2998 CXXConstructExpr *CXXConstExpr =
2999 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3000
3001 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00003002 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003003 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3004 ++A;
3005
3006 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3007 A != AEnd; ++A)
3008 ConstructorArgs.push_back(*A);
3009
3010 CXXConstructExpr *TheCXXConstructExpr =
3011 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3012 CXXConstExpr->getConstructor(),
3013 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003014 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003015 CXXConstExpr->hadMultipleCandidates(),
3016 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003017 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00003018 CXXConstExpr->getConstructionKind(),
3019 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003020
John McCallf4b88a42012-03-10 09:33:50 +00003021 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3022 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003023
John McCallf4b88a42012-03-10 09:33:50 +00003024 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00003025 CharUnits Alignment
3026 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003027 EmitAggExpr(TheCXXConstructExpr,
3028 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3029 AggValueSlot::IsDestructed,
3030 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00003031 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003032
3033 FinishFunction();
3034 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3035 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3036 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003037}
3038
Eli Friedmancae40c42012-02-28 01:08:45 +00003039llvm::Value *
3040CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3041 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003042 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3043 Selector CopySelector =
3044 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00003045 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3046 Selector AutoreleaseSelector =
3047 getContext().Selectors.getNullarySelector(AutoreleaseID);
3048
3049 // Emit calls to retain/autorelease.
3050 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3051 llvm::Value *Val = Block;
3052 RValue Result;
3053 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003054 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00003055 Val, CallArgList(), 0, 0);
3056 Val = Result.getScalarVal();
3057 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3058 Ty, AutoreleaseSelector,
3059 Val, CallArgList(), 0, 0);
3060 Val = Result.getScalarVal();
3061 return Val;
3062}
3063
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003064
Ted Kremenek2979ec72008-04-09 15:51:31 +00003065CGObjCRuntime::~CGObjCRuntime() {}