blob: 19f5ca258ffb24abcb1e48ae361bc00c3d5329ce [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"
Mark Lacey8b549992013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCallf85e1932011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000034static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000035 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000036 const ObjCMethodDecl *Method,
37 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000038
39/// Given the address of a variable of pointer type, find the correct
40/// null to store into it.
41static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000042 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000043 cast<llvm::PointerType>(addr->getType())->getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
Chris Lattner8fdf3282008-06-24 17:04:18 +000047/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000048llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000049{
David Chisnall0d13f6f2010-01-23 02:40:42 +000050 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000052 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000053 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000054}
55
Patrick Beardeb382ec2012-04-19 00:25:12 +000056/// EmitObjCBoxedExpr - This routine generates code to call
57/// the appropriate expression boxing method. This will either be
58/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000059///
Eric Christopher16098f32012-03-29 17:31:31 +000060llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000061CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Generate the correct selector for this literal's concrete type.
Ted Kremenekebcb57a2012-03-06 20:05:56 +000063 // Get the method.
Patrick Beardeb382ec2012-04-19 00:25:12 +000064 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
65 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-04-19 00:25:12 +000070 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
Ted Kremenekebcb57a2012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCallbd7370a2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070075
Ted Kremenekebcb57a2012-03-06 20:05:56 +000076 CallArgList Args;
Stephen Hines0e2c34f2015-03-23 12:09:02 -070077 EmitCallArgs(Args, BoxingMethod, E->arg_begin(), E->arg_end());
Stephen Hines651f13c2014-04-23 16:59:28 -070078
79 RValue result = Runtime.GenerateMessageSend(
80 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
81 Args, ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000082 return Builder.CreateBitCast(result.getScalarVal(),
83 ConvertType(E->getType()));
84}
85
86llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
87 const ObjCMethodDecl *MethodWithObjects) {
88 ASTContext &Context = CGM.getContext();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070089 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +000090 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
91 if (!ALE)
92 DLE = cast<ObjCDictionaryLiteral>(E);
93
94 // Compute the type of the array we're initializing.
95 uint64_t NumElements =
96 ALE ? ALE->getNumElements() : DLE->getNumElements();
97 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
98 NumElements);
99 QualType ElementType = Context.getObjCIdType().withConst();
100 QualType ElementArrayType
101 = Context.getConstantArrayType(ElementType, APNumElements,
102 ArrayType::Normal, /*IndexTypeQuals=*/0);
103
104 // Allocate the temporary array(s).
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700105 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
106 llvm::Value *Keys = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000107 if (DLE)
108 Keys = CreateMemTemp(ElementArrayType, "keys");
109
John McCall527842f2013-04-04 00:20:38 +0000110 // In ARC, we may need to do extra work to keep all the keys and
111 // values alive until after the call.
112 SmallVector<llvm::Value *, 16> NeededObjects;
113 bool TrackNeededObjects =
114 (getLangOpts().ObjCAutoRefCount &&
115 CGM.getCodeGenOpts().OptimizationLevel != 0);
116
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000117 // Perform the actual initialialization of the array(s).
118 for (uint64_t i = 0; i < NumElements; i++) {
119 if (ALE) {
John McCall527842f2013-04-04 00:20:38 +0000120 // Emit the element and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000121 const Expr *Rhs = ALE->getElement(i);
122 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
123 ElementType,
124 Context.getTypeAlignInChars(Rhs->getType()),
125 Context);
John McCall527842f2013-04-04 00:20:38 +0000126
127 llvm::Value *value = EmitScalarExpr(Rhs);
128 EmitStoreThroughLValue(RValue::get(value), LV, true);
129 if (TrackNeededObjects) {
130 NeededObjects.push_back(value);
131 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000132 } else {
John McCall527842f2013-04-04 00:20:38 +0000133 // Emit the key and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000134 const Expr *Key = DLE->getKeyValueElement(i).Key;
135 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
136 ElementType,
137 Context.getTypeAlignInChars(Key->getType()),
138 Context);
John McCall527842f2013-04-04 00:20:38 +0000139 llvm::Value *keyValue = EmitScalarExpr(Key);
140 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000141
John McCall527842f2013-04-04 00:20:38 +0000142 // Emit the value and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000143 const Expr *Value = DLE->getKeyValueElement(i).Value;
144 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
145 ElementType,
146 Context.getTypeAlignInChars(Value->getType()),
147 Context);
John McCall527842f2013-04-04 00:20:38 +0000148 llvm::Value *valueValue = EmitScalarExpr(Value);
149 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
150 if (TrackNeededObjects) {
151 NeededObjects.push_back(keyValue);
152 NeededObjects.push_back(valueValue);
153 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000154 }
155 }
156
157 // Generate the argument list.
158 CallArgList Args;
159 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
160 const ParmVarDecl *argDecl = *PI++;
161 QualType ArgQT = argDecl->getType().getUnqualifiedType();
162 Args.add(RValue::get(Objects), ArgQT);
163 if (DLE) {
164 argDecl = *PI++;
165 ArgQT = argDecl->getType().getUnqualifiedType();
166 Args.add(RValue::get(Keys), ArgQT);
167 }
168 argDecl = *PI;
169 ArgQT = argDecl->getType().getUnqualifiedType();
170 llvm::Value *Count =
171 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
172 Args.add(RValue::get(Count), ArgQT);
173
174 // Generate a reference to the class pointer, which will be the receiver.
175 Selector Sel = MethodWithObjects->getSelector();
176 QualType ResultType = E->getType();
177 const ObjCObjectPointerType *InterfacePointerType
178 = ResultType->getAsObjCInterfacePointerType();
179 ObjCInterfaceDecl *Class
180 = InterfacePointerType->getObjectType()->getInterface();
181 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +0000182 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000183
184 // Generate the message send.
Stephen Hines651f13c2014-04-23 16:59:28 -0700185 RValue result = Runtime.GenerateMessageSend(
186 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
187 Receiver, Args, Class, MethodWithObjects);
John McCall527842f2013-04-04 00:20:38 +0000188
189 // The above message send needs these objects, but in ARC they are
190 // passed in a buffer that is essentially __unsafe_unretained.
191 // Therefore we must prevent the optimizer from releasing them until
192 // after the call.
193 if (TrackNeededObjects) {
194 EmitARCIntrinsicUse(NeededObjects);
195 }
196
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000197 return Builder.CreateBitCast(result.getScalarVal(),
198 ConvertType(E->getType()));
199}
200
201llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
202 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
203}
204
205llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
206 const ObjCDictionaryLiteral *E) {
207 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
208}
209
Chris Lattner8fdf3282008-06-24 17:04:18 +0000210/// Emit a selector.
211llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
212 // Untyped selector.
213 // Note that this implementation allows for non-constant strings to be passed
214 // as arguments to @selector(). Currently, the only thing preventing this
215 // behaviour is the type checking in the front end.
John McCallbd7370a2013-02-28 19:01:20 +0000216 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000217}
218
Daniel Dunbared7c6182008-08-20 00:28:19 +0000219llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
220 // FIXME: This should pass the Decl not the name.
John McCallbd7370a2013-02-28 19:01:20 +0000221 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbared7c6182008-08-20 00:28:19 +0000222}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000223
Douglas Gregor926df6c2011-06-11 01:09:30 +0000224/// \brief Adjust the type of the result of an Objective-C message send
225/// expression when the method has a related result type.
226static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000227 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000228 const ObjCMethodDecl *Method,
229 RValue Result) {
230 if (!Method)
231 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000232
Douglas Gregor926df6c2011-06-11 01:09:30 +0000233 if (!Method->hasRelatedResultType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700234 CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
Douglas Gregor926df6c2011-06-11 01:09:30 +0000235 !Result.isScalar())
236 return Result;
237
238 // We have applied a related result type. Cast the rvalue appropriately.
239 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000240 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000241}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000242
John McCalldc7c5ad2011-07-22 08:53:00 +0000243/// Decide whether to extend the lifetime of the receiver of a
244/// returns-inner-pointer message.
245static bool
246shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
247 switch (message->getReceiverKind()) {
248
249 // For a normal instance message, we should extend unless the
250 // receiver is loaded from a variable with precise lifetime.
251 case ObjCMessageExpr::Instance: {
252 const Expr *receiver = message->getInstanceReceiver();
253 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
254 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
255 receiver = ice->getSubExpr()->IgnoreParens();
256
257 // Only __strong variables.
258 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
259 return true;
260
261 // All ivars and fields have precise lifetime.
262 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
263 return false;
264
265 // Otherwise, check for variables.
266 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
267 if (!declRef) return true;
268 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
269 if (!var) return true;
270
271 // All variables have precise lifetime except local variables with
272 // automatic storage duration that aren't specially marked.
273 return (var->hasLocalStorage() &&
274 !var->hasAttr<ObjCPreciseLifetimeAttr>());
275 }
276
277 case ObjCMessageExpr::Class:
278 case ObjCMessageExpr::SuperClass:
279 // It's never necessary for class objects.
280 return false;
281
282 case ObjCMessageExpr::SuperInstance:
283 // We generally assume that 'self' lives throughout a method call.
284 return false;
285 }
286
287 llvm_unreachable("invalid receiver kind");
288}
289
John McCallef072fd2010-05-22 01:48:05 +0000290RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
291 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000292 // Only the lookup mechanism and first two arguments of the method
293 // implementation vary between runtimes. We can get the receiver and
294 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000295
John McCallf85e1932011-06-15 23:02:42 +0000296 bool isDelegateInit = E->isDelegateInitCall();
297
John McCalldc7c5ad2011-07-22 08:53:00 +0000298 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000299
John McCallf85e1932011-06-15 23:02:42 +0000300 // We don't retain the receiver in delegate init calls, and this is
301 // safe because the receiver value is always loaded from 'self',
302 // which we zero out. We don't want to Block_copy block receivers,
303 // though.
304 bool retainSelf =
305 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000306 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000307 method &&
308 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000309
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000310 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000311 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000312 bool isClassMessage = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700313 ObjCInterfaceDecl *OID = nullptr;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000314 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000315 QualType ReceiverType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700316 llvm::Value *Receiver = nullptr;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000317 switch (E->getReceiverKind()) {
318 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000319 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000320 if (retainSelf) {
321 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
322 E->getInstanceReceiver());
323 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000324 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000325 } else
326 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000327 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000328
Douglas Gregor04badcf2010-04-21 00:45:42 +0000329 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000330 ReceiverType = E->getClassReceiver();
331 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000332 assert(ObjTy && "Invalid Objective-C class message send");
333 OID = ObjTy->getInterface();
334 assert(OID && "Invalid Objective-C class message send");
John McCallbd7370a2013-02-28 19:01:20 +0000335 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000336 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000337 break;
338 }
339
340 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000341 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000342 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000343 isSuperMessage = true;
344 break;
345
346 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000347 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000348 Receiver = LoadObjCSelf();
349 isSuperMessage = true;
350 isClassMessage = true;
351 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000352 }
353
John McCalldc7c5ad2011-07-22 08:53:00 +0000354 if (retainSelf)
355 Receiver = EmitARCRetainNonBlock(Receiver);
356
357 // In ARC, we sometimes want to "extend the lifetime"
358 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
359 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000360 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000361 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
362 shouldExtendReceiverForInnerPointerMessage(E))
363 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
364
Stephen Hines651f13c2014-04-23 16:59:28 -0700365 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000366
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000367 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000368 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000369
John McCallf85e1932011-06-15 23:02:42 +0000370 // For delegate init calls in ARC, do an unsafe store of null into
371 // self. This represents the call taking direct ownership of that
372 // value. We have to do this after emitting the other call
373 // arguments because they might also reference self, but we don't
374 // have to worry about any of them modifying self because that would
375 // be an undefined read and write of an object in unordered
376 // expressions.
377 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000378 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000379 "delegate init calls should only be marked in ARC");
380
381 // Do an unsafe store of null into self.
382 llvm::Value *selfAddr =
383 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
384 assert(selfAddr && "no self entry for a delegate init call?");
385
386 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
387 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000388
Douglas Gregor926df6c2011-06-11 01:09:30 +0000389 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000390 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000391 // super is only valid in an Objective-C method
392 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000393 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000394 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
395 E->getSelector(),
396 OMD->getClassInterface(),
397 isCategoryImpl,
398 Receiver,
399 isClassMessage,
400 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000401 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000402 } else {
403 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
404 E->getSelector(),
405 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000406 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000407 }
John McCallf85e1932011-06-15 23:02:42 +0000408
409 // For delegate init calls in ARC, implicitly store the result of
410 // the call back into self. This takes ownership of the value.
411 if (isDelegateInit) {
412 llvm::Value *selfAddr =
413 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
414 llvm::Value *newSelf = result.getScalarVal();
415
416 // The delegate return type isn't necessarily a matching type; in
417 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000418 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000419 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
420 newSelf = Builder.CreateBitCast(newSelf, selfTy);
421
422 Builder.CreateStore(newSelf, selfAddr);
423 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000424
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000425 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000426}
427
John McCallf85e1932011-06-15 23:02:42 +0000428namespace {
429struct FinishARCDealloc : EHScopeStack::Cleanup {
Stephen Hines651f13c2014-04-23 16:59:28 -0700430 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +0000431 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000432
433 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000434 const ObjCInterfaceDecl *iface = impl->getClassInterface();
435 if (!iface->getSuperClass()) return;
436
John McCall799d34e2011-07-13 18:26:47 +0000437 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
438
John McCallf85e1932011-06-15 23:02:42 +0000439 // Call [super dealloc] if we have a superclass.
440 llvm::Value *self = CGF.LoadObjCSelf();
441
442 CallArgList args;
443 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
444 CGF.getContext().VoidTy,
445 method->getSelector(),
446 iface,
John McCall799d34e2011-07-13 18:26:47 +0000447 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000448 self,
449 /*is class msg*/ false,
450 args,
451 method);
452 }
453};
454}
455
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000456/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
457/// the LLVM function and sets the other context used by
458/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000459void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700460 const ObjCContainerDecl *CD) {
461 SourceLocation StartLoc = OMD->getLocStart();
John McCalld26bc762011-03-09 04:27:21 +0000462 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000463 // Check if we should generate debug info for this method.
David Blaikiec3030bc2013-08-26 20:33:21 +0000464 if (OMD->hasAttr<NoDebugAttr>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700465 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patel4800ea62010-04-05 21:09:15 +0000466
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000467 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000468
John McCallde5d3c72012-02-17 03:33:10 +0000469 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000470 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000471
John McCalld26bc762011-03-09 04:27:21 +0000472 args.push_back(OMD->getSelfDecl());
473 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000474
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700475 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner41110242008-06-17 18:05:57 +0000476
Peter Collingbourne14110472011-01-13 18:57:25 +0000477 CurGD = OMD;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700478 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne14110472011-01-13 18:57:25 +0000479
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700480 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
481 OMD->getLocation(), StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000482
483 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000484 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000485 OMD->isInstanceMethod() &&
486 OMD->getSelector().isUnarySelector()) {
487 const IdentifierInfo *ident =
488 OMD->getSelector().getIdentifierInfoForSlot(0);
489 if (ident->isStr("dealloc"))
490 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
491 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000492}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000493
John McCallf85e1932011-06-15 23:02:42 +0000494static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
495 LValue lvalue, QualType type);
496
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000497/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000498/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000499void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700500 StartObjCMethod(OMD, OMD->getClassInterface());
Stephen Hines651f13c2014-04-23 16:59:28 -0700501 PGO.assignRegionCounters(OMD, CurFn);
502 assert(isa<CompoundStmt>(OMD->getBody()));
503 RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
504 Cnt.beginRegion(Builder);
505 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000506 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000507}
508
John McCall41bdde92011-09-12 23:06:44 +0000509/// emitStructGetterCall - Call the runtime function to load a property
510/// into the return value slot.
511static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
512 bool isAtomic, bool hasStrong) {
513 ASTContext &Context = CGF.getContext();
514
515 llvm::Value *src =
516 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
517 ivar, 0).getAddress();
518
519 // objc_copyStruct (ReturnValue, &structIvar,
520 // sizeof (Type of Ivar), isAtomic, false);
521 CallArgList args;
522
523 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
524 args.add(RValue::get(dest), Context.VoidPtrTy);
525
526 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
527 args.add(RValue::get(src), Context.VoidPtrTy);
528
529 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
530 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
531 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
532 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
533
534 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000535 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
536 FunctionType::ExtInfo(),
537 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000538 fn, ReturnValueSlot(), args);
539}
540
John McCall1e1f4872011-09-13 03:34:09 +0000541/// Determine whether the given architecture supports unaligned atomic
542/// accesses. They don't have to be fast, just faster than a function
543/// call and a mutex.
544static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000545 // FIXME: Allow unaligned atomic load/store on x86. (It is not
546 // currently supported by the backend.)
547 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000548}
549
550/// Return the maximum size that permits atomic accesses for the given
551/// architecture.
552static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
553 llvm::Triple::ArchType arch) {
554 // ARM has 8-byte atomic accesses, but it's not clear whether we
555 // want to rely on them here.
556
557 // In the default case, just assume that any size up to a pointer is
558 // fine given adequate alignment.
559 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
560}
561
562namespace {
563 class PropertyImplStrategy {
564 public:
565 enum StrategyKind {
566 /// The 'native' strategy is to use the architecture's provided
567 /// reads and writes.
568 Native,
569
570 /// Use objc_setProperty and objc_getProperty.
571 GetSetProperty,
572
573 /// Use objc_setProperty for the setter, but use expression
574 /// evaluation for the getter.
575 SetPropertyAndExpressionGet,
576
577 /// Use objc_copyStruct.
578 CopyStruct,
579
580 /// The 'expression' strategy is to emit normal assignment or
581 /// lvalue-to-rvalue expressions.
582 Expression
583 };
584
585 StrategyKind getKind() const { return StrategyKind(Kind); }
586
587 bool hasStrongMember() const { return HasStrong; }
588 bool isAtomic() const { return IsAtomic; }
589 bool isCopy() const { return IsCopy; }
590
591 CharUnits getIvarSize() const { return IvarSize; }
592 CharUnits getIvarAlignment() const { return IvarAlignment; }
593
594 PropertyImplStrategy(CodeGenModule &CGM,
595 const ObjCPropertyImplDecl *propImpl);
596
597 private:
598 unsigned Kind : 8;
599 unsigned IsAtomic : 1;
600 unsigned IsCopy : 1;
601 unsigned HasStrong : 1;
602
603 CharUnits IvarSize;
604 CharUnits IvarAlignment;
605 };
606}
607
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000608/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000609PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
610 const ObjCPropertyImplDecl *propImpl) {
611 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000612 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000613
John McCall265941b2011-09-13 18:31:23 +0000614 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
615 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000616 HasStrong = false; // doesn't matter here.
617
618 // Evaluate the ivar's size and alignment.
619 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
620 QualType ivarType = ivar->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700621 std::tie(IvarSize, IvarAlignment) =
622 CGM.getContext().getTypeInfoInChars(ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000623
624 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000625 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000626 if (IsCopy) {
627 Kind = GetSetProperty;
628 return;
629 }
630
John McCall265941b2011-09-13 18:31:23 +0000631 // Handle retain.
632 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000633 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000634 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000635 // fallthrough
636
637 // In ARC, if the property is non-atomic, use expression emission,
638 // which translates to objc_storeStrong. This isn't required, but
639 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000640 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld64c2eb2012-08-20 23:36:59 +0000641 // Using standard expression emission for the setter is only
642 // acceptable if the ivar is __strong, which won't be true if
643 // the property is annotated with __attribute__((NSObject)).
644 // TODO: falling all the way back to objc_setProperty here is
645 // just laziness, though; we could still use objc_storeStrong
646 // if we hacked it right.
647 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
648 Kind = Expression;
649 else
650 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000651 return;
652
653 // Otherwise, we need to at least use setProperty. However, if
654 // the property isn't atomic, we can use normal expression
655 // emission for the getter.
656 } else if (!IsAtomic) {
657 Kind = SetPropertyAndExpressionGet;
658 return;
659
660 // Otherwise, we have to use both setProperty and getProperty.
661 } else {
662 Kind = GetSetProperty;
663 return;
664 }
665 }
666
667 // If we're not atomic, just use expression accesses.
668 if (!IsAtomic) {
669 Kind = Expression;
670 return;
671 }
672
John McCall5889c602011-09-13 05:36:29 +0000673 // Properties on bitfield ivars need to be emitted using expression
674 // accesses even if they're nominally atomic.
675 if (ivar->isBitField()) {
676 Kind = Expression;
677 return;
678 }
679
John McCall1e1f4872011-09-13 03:34:09 +0000680 // GC-qualified or ARC-qualified ivars need to be emitted as
681 // expressions. This actually works out to being atomic anyway,
682 // except for ARC __strong, but that should trigger the above code.
683 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000684 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000685 CGM.getContext().getObjCGCAttrKind(ivarType))) {
686 Kind = Expression;
687 return;
688 }
689
690 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000691 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000692 if (const RecordType *recordType = ivarType->getAs<RecordType>())
693 HasStrong = recordType->getDecl()->hasObjectMember();
694
695 // We can never access structs with object members with a native
696 // access, because we need to use write barriers. This is what
697 // objc_copyStruct is for.
698 if (HasStrong) {
699 Kind = CopyStruct;
700 return;
701 }
702
703 // Otherwise, this is target-dependent and based on the size and
704 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000705
706 // If the size of the ivar is not a power of two, give up. We don't
707 // want to get into the business of doing compare-and-swaps.
708 if (!IvarSize.isPowerOfTwo()) {
709 Kind = CopyStruct;
710 return;
711 }
712
John McCall1e1f4872011-09-13 03:34:09 +0000713 llvm::Triple::ArchType arch =
John McCall64aa4b32013-04-16 22:48:15 +0000714 CGM.getTarget().getTriple().getArch();
John McCall1e1f4872011-09-13 03:34:09 +0000715
716 // Most architectures require memory to fit within a single cache
717 // line, so the alignment has to be at least the size of the access.
718 // Otherwise we have to grab a lock.
719 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
720 Kind = CopyStruct;
721 return;
722 }
723
724 // If the ivar's size exceeds the architecture's maximum atomic
725 // access size, we have to use CopyStruct.
726 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
727 Kind = CopyStruct;
728 return;
729 }
730
731 // Otherwise, we can use native loads and stores.
732 Kind = Native;
733}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000734
James Dennett2ee5ba32012-06-15 22:10:14 +0000735/// \brief Generate an Objective-C property getter function.
736///
737/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000738/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000739void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
740 const ObjCPropertyImplDecl *PID) {
Stephen Hines176edba2014-12-01 14:53:08 -0800741 llvm::Constant *AtomicHelperFn =
742 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000743 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
744 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
745 assert(OMD && "Invalid call to generate getter (empty method)");
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700746 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000748 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000749
750 FinishFunction();
751}
752
John McCall6c11f0b2011-09-13 06:00:03 +0000753static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
754 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000755 if (!getter) return true;
756
757 // Sema only makes only of these when the ivar has a C++ class type,
758 // so the form is pretty constrained.
759
John McCall6c11f0b2011-09-13 06:00:03 +0000760 // If the property has a reference type, we might just be binding a
761 // reference, in which case the result will be a gl-value. We should
762 // treat this as a non-trivial operation.
763 if (getter->isGLValue())
764 return false;
765
John McCall1e1f4872011-09-13 03:34:09 +0000766 // If we selected a trivial copy-constructor, we're okay.
767 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
768 return (construct->getConstructor()->isTrivial());
769
770 // The constructor might require cleanups (in which case it's never
771 // trivial).
772 assert(isa<ExprWithCleanups>(getter));
773 return false;
774}
775
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000776/// emitCPPObjectAtomicGetterCall - Call the runtime function to
777/// copy the ivar into the resturn slot.
778static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
779 llvm::Value *returnAddr,
780 ObjCIvarDecl *ivar,
781 llvm::Constant *AtomicHelperFn) {
782 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
783 // AtomicHelperFn);
784 CallArgList args;
785
786 // The 1st argument is the return Slot.
787 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
788
789 // The 2nd argument is the address of the ivar.
790 llvm::Value *ivarAddr =
791 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
792 CGF.LoadObjCSelf(), ivar, 0).getAddress();
793 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
794 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
795
796 // Third argument is the helper function.
797 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
798
799 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +0000800 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000801 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
802 args,
803 FunctionType::ExtInfo(),
804 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000805 copyCppAtomicObjectFn, ReturnValueSlot(), args);
806}
807
John McCall1e1f4872011-09-13 03:34:09 +0000808void
809CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000810 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000811 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000812 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000813 // If there's a non-trivial 'get' expression, we just have to emit that.
814 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000815 if (!AtomicHelperFn) {
816 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700817 /*nrvo*/ nullptr);
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000818 EmitReturnStmt(ret);
819 }
820 else {
821 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
822 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
823 ivar, AtomicHelperFn);
824 }
John McCall1e1f4872011-09-13 03:34:09 +0000825 return;
826 }
827
828 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
829 QualType propType = prop->getType();
830 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
831
832 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
833
834 // Pick an implementation strategy.
835 PropertyImplStrategy strategy(CGM, propImpl);
836 switch (strategy.getKind()) {
837 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +0000838 // We don't need to do anything for a zero-size struct.
839 if (strategy.getIvarSize().isZero())
840 return;
841
John McCall1e1f4872011-09-13 03:34:09 +0000842 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
843
844 // Currently, all atomic accesses have to be through integer
845 // types, so there's no point in trying to pick a prettier type.
846 llvm::Type *bitcastType =
847 llvm::Type::getIntNTy(getLLVMContext(),
848 getContext().toBits(strategy.getIvarSize()));
849 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
850
851 // Perform an atomic load. This does not impose ordering constraints.
852 llvm::Value *ivarAddr = LV.getAddress();
853 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
854 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
855 load->setAlignment(strategy.getIvarAlignment().getQuantity());
856 load->setAtomic(llvm::Unordered);
857
858 // Store that value into the return address. Doing this with a
859 // bitcast is likely to produce some pretty ugly IR, but it's not
860 // the *most* terrible thing in the world.
861 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
862
863 // Make sure we don't do an autorelease.
864 AutoreleaseResult = false;
865 return;
866 }
867
868 case PropertyImplStrategy::GetSetProperty: {
869 llvm::Value *getPropertyFn =
870 CGM.getObjCRuntime().GetPropertyGetFunction();
871 if (!getPropertyFn) {
872 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000873 return;
874 }
875
876 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
877 // FIXME: Can't this be simpler? This might even be worse than the
878 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000879 llvm::Value *cmd =
880 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
881 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
882 llvm::Value *ivarOffset =
883 EmitIvarOffset(classImpl->getClassInterface(), ivar);
884
885 CallArgList args;
886 args.add(RValue::get(self), getContext().getObjCIdType());
887 args.add(RValue::get(cmd), getContext().getObjCSelType());
888 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000889 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
890 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000891
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000892 // FIXME: We shouldn't need to get the function info here, the
893 // runtime already should have computed it to build the function.
Stephen Hines651f13c2014-04-23 16:59:28 -0700894 llvm::Instruction *CallInstruction;
John McCall0f3d0972012-07-07 06:41:13 +0000895 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
896 FunctionType::ExtInfo(),
897 RequiredArgs::All),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700898 getPropertyFn, ReturnValueSlot(), args, nullptr,
Stephen Hines651f13c2014-04-23 16:59:28 -0700899 &CallInstruction);
900 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
901 call->setTailCall();
John McCall1e1f4872011-09-13 03:34:09 +0000902
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000903 // We need to fix the type here. Ivars with copy & retain are
904 // always objects so we don't need to worry about complex or
905 // aggregates.
Stephen Hines651f13c2014-04-23 16:59:28 -0700906 RV = RValue::get(Builder.CreateBitCast(
907 RV.getScalarVal(),
908 getTypes().ConvertType(getterMethod->getReturnType())));
John McCall1e1f4872011-09-13 03:34:09 +0000909
910 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000911
912 // objc_getProperty does an autorelease, so we should suppress ours.
913 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000914
John McCall1e1f4872011-09-13 03:34:09 +0000915 return;
916 }
917
918 case PropertyImplStrategy::CopyStruct:
919 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
920 strategy.hasStrongMember());
921 return;
922
923 case PropertyImplStrategy::Expression:
924 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
925 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
926
927 QualType ivarType = ivar->getType();
John McCall9d232c82013-03-07 21:37:08 +0000928 switch (getEvaluationKind(ivarType)) {
929 case TEK_Complex: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000930 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall9d232c82013-03-07 21:37:08 +0000931 EmitStoreOfComplex(pair,
932 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
933 /*init*/ true);
934 return;
935 }
936 case TEK_Aggregate:
John McCall1e1f4872011-09-13 03:34:09 +0000937 // The return value slot is guaranteed to not be aliased, but
938 // that's not necessarily the same as "on the stack", so
939 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000940 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall9d232c82013-03-07 21:37:08 +0000941 return;
942 case TEK_Scalar: {
John McCallba3dd902011-07-22 05:23:13 +0000943 llvm::Value *value;
944 if (propType->isReferenceType()) {
945 value = LV.getAddress();
946 } else {
947 // We want to load and autoreleaseReturnValue ARC __weak ivars.
948 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000949 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000950
951 // Otherwise we want to do a simple load, suppressing the
952 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000953 } else {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000954 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCallba3dd902011-07-22 05:23:13 +0000955 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000956 }
John McCallf85e1932011-06-15 23:02:42 +0000957
John McCallba3dd902011-07-22 05:23:13 +0000958 value = Builder.CreateBitCast(value, ConvertType(propType));
Stephen Hines651f13c2014-04-23 16:59:28 -0700959 value = Builder.CreateBitCast(
960 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCallba3dd902011-07-22 05:23:13 +0000961 }
962
963 EmitReturnOfRValue(RValue::get(value), propType);
John McCall9d232c82013-03-07 21:37:08 +0000964 return;
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000965 }
John McCall9d232c82013-03-07 21:37:08 +0000966 }
967 llvm_unreachable("bad evaluation kind");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000968 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000969
John McCall1e1f4872011-09-13 03:34:09 +0000970 }
971 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000972}
973
John McCall41bdde92011-09-12 23:06:44 +0000974/// emitStructSetterCall - Call the runtime function to store the value
975/// from the first formal parameter into the given ivar.
976static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
977 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000978 // objc_copyStruct (&structIvar, &Arg,
979 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000980 CallArgList args;
981
982 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000983 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
984 CGF.LoadObjCSelf(), ivar, 0)
985 .getAddress();
986 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
987 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000988
989 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000990 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000991 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000992 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000993 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
994 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
995 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000996
997 // The third argument is the sizeof the type.
998 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000999 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1000 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +00001001
John McCall41bdde92011-09-12 23:06:44 +00001002 // The fourth argument is the 'isAtomic' flag.
1003 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +00001004
John McCall41bdde92011-09-12 23:06:44 +00001005 // The fifth argument is the 'hasStrong' flag.
1006 // FIXME: should this really always be false?
1007 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1008
1009 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001010 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1011 args,
1012 FunctionType::ExtInfo(),
1013 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +00001014 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +00001015}
1016
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001017/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1018/// the value from the first formal parameter into the given ivar, using
1019/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1020static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1021 ObjCMethodDecl *OMD,
1022 ObjCIvarDecl *ivar,
1023 llvm::Constant *AtomicHelperFn) {
1024 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1025 // AtomicHelperFn);
1026 CallArgList args;
1027
1028 // The first argument is the address of the ivar.
1029 llvm::Value *ivarAddr =
1030 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1031 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1032 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1033 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1034
1035 // The second argument is the address of the parameter variable.
1036 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001037 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001038 VK_LValue, SourceLocation());
1039 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1040 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1041 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1042
1043 // Third argument is the helper function.
1044 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1045
1046 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +00001047 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001048 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1049 args,
1050 FunctionType::ExtInfo(),
1051 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001052 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001053}
1054
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001055
John McCall1e1f4872011-09-13 03:34:09 +00001056static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1057 Expr *setter = PID->getSetterCXXAssignment();
1058 if (!setter) return true;
1059
1060 // Sema only makes only of these when the ivar has a C++ class type,
1061 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001062
1063 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001064 // This also implies that there's nothing non-trivial going on with
1065 // the arguments, because operator= can only be trivial if it's a
1066 // synthesized assignment operator and therefore both parameters are
1067 // references.
1068 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001069 if (const FunctionDecl *callee
1070 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1071 if (callee->isTrivial())
1072 return true;
1073 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001074 }
John McCall71c758d2011-09-10 09:17:20 +00001075
John McCall1e1f4872011-09-13 03:34:09 +00001076 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001077 return false;
1078}
1079
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001080static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001081 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001082 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001083 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001084}
1085
John McCall71c758d2011-09-10 09:17:20 +00001086void
1087CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001088 const ObjCPropertyImplDecl *propImpl,
1089 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001090 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001091 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001092 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001093
1094 // Just use the setter expression if Sema gave us one and it's
1095 // non-trivial.
1096 if (!hasTrivialSetExpr(propImpl)) {
1097 if (!AtomicHelperFn)
1098 // If non-atomic, assignment is called directly.
1099 EmitStmt(propImpl->getSetterCXXAssignment());
1100 else
1101 // If atomic, assignment is called via a locking api.
1102 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1103 AtomicHelperFn);
1104 return;
1105 }
John McCall71c758d2011-09-10 09:17:20 +00001106
John McCall1e1f4872011-09-13 03:34:09 +00001107 PropertyImplStrategy strategy(CGM, propImpl);
1108 switch (strategy.getKind()) {
1109 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +00001110 // We don't need to do anything for a zero-size struct.
1111 if (strategy.getIvarSize().isZero())
1112 return;
1113
John McCall1e1f4872011-09-13 03:34:09 +00001114 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001115
John McCall1e1f4872011-09-13 03:34:09 +00001116 LValue ivarLValue =
1117 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1118 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001119
John McCall1e1f4872011-09-13 03:34:09 +00001120 // Currently, all atomic accesses have to be through integer
1121 // types, so there's no point in trying to pick a prettier type.
1122 llvm::Type *bitcastType =
1123 llvm::Type::getIntNTy(getLLVMContext(),
1124 getContext().toBits(strategy.getIvarSize()));
1125 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1126
1127 // Cast both arguments to the chosen operation type.
1128 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1129 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1130
1131 // This bitcast load is likely to cause some nasty IR.
1132 llvm::Value *load = Builder.CreateLoad(argAddr);
1133
1134 // Perform an atomic store. There are no memory ordering requirements.
1135 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1136 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1137 store->setAtomic(llvm::Unordered);
1138 return;
1139 }
1140
1141 case PropertyImplStrategy::GetSetProperty:
1142 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001143
1144 llvm::Value *setOptimizedPropertyFn = nullptr;
1145 llvm::Value *setPropertyFn = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001146 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001147 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001148 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001149 CGM.getObjCRuntime()
1150 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1151 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001152 if (!setOptimizedPropertyFn) {
1153 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1154 return;
1155 }
John McCall71c758d2011-09-10 09:17:20 +00001156 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001157 else {
1158 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1159 if (!setPropertyFn) {
1160 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1161 return;
1162 }
1163 }
1164
John McCall71c758d2011-09-10 09:17:20 +00001165 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1166 // <is-atomic>, <is-copy>).
1167 llvm::Value *cmd =
1168 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1169 llvm::Value *self =
1170 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1171 llvm::Value *ivarOffset =
1172 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1173 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1174 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1175
1176 CallArgList args;
1177 args.add(RValue::get(self), getContext().getObjCIdType());
1178 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001179 if (setOptimizedPropertyFn) {
1180 args.add(RValue::get(arg), getContext().getObjCIdType());
1181 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001182 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1183 FunctionType::ExtInfo(),
1184 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001185 setOptimizedPropertyFn, ReturnValueSlot(), args);
1186 } else {
1187 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1188 args.add(RValue::get(arg), getContext().getObjCIdType());
1189 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1190 getContext().BoolTy);
1191 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1192 getContext().BoolTy);
1193 // FIXME: We shouldn't need to get the function info here, the runtime
1194 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001195 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1196 FunctionType::ExtInfo(),
1197 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001198 setPropertyFn, ReturnValueSlot(), args);
1199 }
1200
John McCall71c758d2011-09-10 09:17:20 +00001201 return;
1202 }
1203
John McCall1e1f4872011-09-13 03:34:09 +00001204 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001205 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001206 return;
John McCall1e1f4872011-09-13 03:34:09 +00001207
1208 case PropertyImplStrategy::Expression:
1209 break;
John McCall71c758d2011-09-10 09:17:20 +00001210 }
1211
1212 // Otherwise, fake up some ASTs and emit a normal assignment.
1213 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001214 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1215 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001216 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1217 selfDecl->getType(), CK_LValueToRValue, &self,
1218 VK_RValue);
1219 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001220 SourceLocation(), SourceLocation(),
1221 &selfLoad, true, true);
John McCall71c758d2011-09-10 09:17:20 +00001222
1223 ParmVarDecl *argDecl = *setterMethod->param_begin();
1224 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001225 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001226 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1227 argType.getUnqualifiedType(), CK_LValueToRValue,
1228 &arg, VK_RValue);
1229
1230 // The property type can differ from the ivar type in some situations with
1231 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1232 // The following absurdity is just to ensure well-formed IR.
1233 CastKind argCK = CK_NoOp;
1234 if (ivarRef.getType()->isObjCObjectPointerType()) {
1235 if (argLoad.getType()->isObjCObjectPointerType())
1236 argCK = CK_BitCast;
1237 else if (argLoad.getType()->isBlockPointerType())
1238 argCK = CK_BlockPointerToObjCPointerCast;
1239 else
1240 argCK = CK_CPointerToObjCPointerCast;
1241 } else if (ivarRef.getType()->isBlockPointerType()) {
1242 if (argLoad.getType()->isBlockPointerType())
1243 argCK = CK_BitCast;
1244 else
1245 argCK = CK_AnyPointerToBlockPointerCast;
1246 } else if (ivarRef.getType()->isPointerType()) {
1247 argCK = CK_BitCast;
1248 }
1249 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1250 ivarRef.getType(), argCK, &argLoad,
1251 VK_RValue);
1252 Expr *finalArg = &argLoad;
1253 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1254 argLoad.getType()))
1255 finalArg = &argCast;
1256
1257
1258 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1259 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +00001260 SourceLocation(), false);
John McCall71c758d2011-09-10 09:17:20 +00001261 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001262}
1263
James Dennett2ee5ba32012-06-15 22:10:14 +00001264/// \brief Generate an Objective-C property setter function.
1265///
1266/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001267/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001268void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1269 const ObjCPropertyImplDecl *PID) {
Stephen Hines176edba2014-12-01 14:53:08 -08001270 llvm::Constant *AtomicHelperFn =
1271 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001272 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1273 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1274 assert(OMD && "Invalid call to generate setter (empty method)");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001275 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001276
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001277 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001278
1279 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001280}
1281
John McCalle81ac692011-03-22 07:05:39 +00001282namespace {
John McCall9928c482011-07-12 16:41:08 +00001283 struct DestroyIvar : EHScopeStack::Cleanup {
1284 private:
1285 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001286 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001287 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001288 bool useEHCleanupForArray;
1289 public:
1290 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1291 CodeGenFunction::Destroyer *destroyer,
1292 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001293 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001294 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001295
Stephen Hines651f13c2014-04-23 16:59:28 -07001296 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall9928c482011-07-12 16:41:08 +00001297 LValue lvalue
1298 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1299 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001300 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001301 }
1302 };
1303}
1304
John McCall9928c482011-07-12 16:41:08 +00001305/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1306static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1307 llvm::Value *addr,
1308 QualType type) {
1309 llvm::Value *null = getNullForVariable(addr);
1310 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1311}
John McCallf85e1932011-06-15 23:02:42 +00001312
John McCalle81ac692011-03-22 07:05:39 +00001313static void emitCXXDestructMethod(CodeGenFunction &CGF,
1314 ObjCImplementationDecl *impl) {
1315 CodeGenFunction::RunCleanupsScope scope(CGF);
1316
1317 llvm::Value *self = CGF.LoadObjCSelf();
1318
Jordy Rosedb8264e2011-07-22 02:08:32 +00001319 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1320 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001321 ivar; ivar = ivar->getNextIvar()) {
1322 QualType type = ivar->getType();
1323
John McCalle81ac692011-03-22 07:05:39 +00001324 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001325 QualType::DestructionKind dtorKind = type.isDestructedType();
1326 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001327
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001328 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCalle81ac692011-03-22 07:05:39 +00001329
John McCall9928c482011-07-12 16:41:08 +00001330 // Use a call to objc_storeStrong to destroy strong ivars, for the
1331 // general benefit of the tools.
1332 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001333 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001334
John McCall9928c482011-07-12 16:41:08 +00001335 // Otherwise use the default for the destruction kind.
1336 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001337 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001338 }
John McCall9928c482011-07-12 16:41:08 +00001339
1340 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1341
1342 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1343 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001344 }
1345
1346 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1347}
1348
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001349void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1350 ObjCMethodDecl *MD,
1351 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001352 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001353 StartObjCMethod(MD, IMP->getClassInterface());
John McCalle81ac692011-03-22 07:05:39 +00001354
1355 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001356 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001357 // Suppress the final autorelease in ARC.
1358 AutoreleaseResult = false;
1359
Stephen Hines651f13c2014-04-23 16:59:28 -07001360 for (const auto *IvarInit : IMP->inits()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001361 FieldDecl *Field = IvarInit->getAnyMember();
Stephen Hines651f13c2014-04-23 16:59:28 -07001362 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001363 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1364 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001365 EmitAggExpr(IvarInit->getInit(),
1366 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001367 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001368 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001369 }
1370 // constructor returns 'self'.
1371 CodeGenTypes &Types = CGM.getTypes();
1372 QualType IdTy(CGM.getContext().getObjCIdType());
1373 llvm::Value *SelfAsId =
1374 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1375 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001376
1377 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001378 } else {
John McCalle81ac692011-03-22 07:05:39 +00001379 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001380 }
1381 FinishFunction();
1382}
1383
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001384bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1385 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1386 it++; it++;
1387 const ABIArgInfo &AI = it->info;
1388 // FIXME. Is this sufficient check?
1389 return (AI.getKind() == ABIArgInfo::Indirect);
1390}
1391
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001392bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001393 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001394 return false;
1395 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1396 return FDTTy->getDecl()->hasObjectMember();
1397 return false;
1398}
1399
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001400llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCallf5ebf9b2013-05-03 07:33:41 +00001401 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1402 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1403 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001404 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
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
Stephen Hines651f13c2014-04-23 16:59:28 -07001507 // empty; skip all this. Set the branch weight assuming this has the same
1508 // probability of exiting the loop as any other loop exit.
1509 uint64_t EntryCount = PGO.getCurrentRegionCount();
1510 RegionCounter Cnt = getPGORegionCounter(&S);
John McCalld88687f2011-01-07 01:49:06 +00001511 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
Stephen Hines651f13c2014-04-23 16:59:28 -07001512 EmptyBB, LoopInitBB,
1513 PGO.createBranchWeights(EntryCount, Cnt.getCount()));
Anders Carlssonf484c312008-08-31 02:33:12 +00001514
John McCalld88687f2011-01-07 01:49:06 +00001515 // Otherwise, initialize the loop.
1516 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
John McCalld88687f2011-01-07 01:49:06 +00001518 // Save the initial mutations value. This is the value at an
1519 // address that was written into the state object by
1520 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001521 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001522 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001523 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001524 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001525
John McCalld88687f2011-01-07 01:49:06 +00001526 llvm::Value *initialMutations =
1527 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001528
John McCalld88687f2011-01-07 01:49:06 +00001529 // Start looping. This is the point we return to whenever we have a
1530 // fresh, non-empty batch of objects.
1531 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1532 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
John McCalld88687f2011-01-07 01:49:06 +00001534 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001535 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001536 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001537
John McCalld88687f2011-01-07 01:49:06 +00001538 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001539 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001540 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Stephen Hines651f13c2014-04-23 16:59:28 -07001542 Cnt.beginRegion(Builder);
1543
John McCalld88687f2011-01-07 01:49:06 +00001544 // Check whether the mutations value has changed from where it was
1545 // at start. StateMutationsPtr should actually be invariant between
1546 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001547 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001548 llvm::Value *currentMutations
1549 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001550
John McCalld88687f2011-01-07 01:49:06 +00001551 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001552 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCalld88687f2011-01-07 01:49:06 +00001554 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1555 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
John McCalld88687f2011-01-07 01:49:06 +00001557 // If so, call the enumeration-mutation function.
1558 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001559 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001560 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001561 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001562 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001563 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001564 // FIXME: We shouldn't need to get the function info here, the runtime already
1565 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001566 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1567 FunctionType::ExtInfo(),
1568 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001569 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001570
John McCalld88687f2011-01-07 01:49:06 +00001571 // Otherwise, or if the mutation function returns, just continue.
1572 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
John McCalld88687f2011-01-07 01:49:06 +00001574 // Initialize the element variable.
1575 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001576 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001577 LValue elementLValue;
1578 QualType elementType;
1579 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001580 // Initialize the variable, in case it's a __block variable or something.
1581 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001582
John McCall57b3b6a2011-02-22 07:16:58 +00001583 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001584 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001585 VK_LValue, SourceLocation());
1586 elementLValue = EmitLValue(&tempDRE);
1587 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001588 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001589
1590 if (D->isARCPseudoStrong())
1591 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001592 } else {
1593 elementLValue = LValue(); // suppress warning
1594 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001595 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001596 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001597 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001598
1599 // Fetch the buffer out of the enumeration state.
1600 // TODO: this pointer should actually be invariant between
1601 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001602 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001603 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001604 llvm::Value *EnumStateItems =
1605 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001606
John McCalld88687f2011-01-07 01:49:06 +00001607 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001608 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001609 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1610 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
John McCalld88687f2011-01-07 01:49:06 +00001612 // Cast that value to the right type.
1613 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1614 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001615
John McCalld88687f2011-01-07 01:49:06 +00001616 // Make sure we have an l-value. Yes, this gets evaluated every
1617 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001618 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001619 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001620 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001621 } else {
1622 EmitScalarInit(CurrentItem, elementLValue);
1623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
John McCall57b3b6a2011-02-22 07:16:58 +00001625 // If we do have an element variable, this assignment is the end of
1626 // its initialization.
1627 if (elementIsVariable)
1628 EmitAutoVarCleanups(variable);
1629
John McCalld88687f2011-01-07 01:49:06 +00001630 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001631 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001632 {
1633 RunCleanupsScope Scope(*this);
1634 EmitStmt(S.getBody());
1635 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001636 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001637
John McCalld88687f2011-01-07 01:49:06 +00001638 // Destroy the element variable now.
1639 elementVariableScope.ForceCleanup();
1640
1641 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001642 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001643
John McCalld88687f2011-01-07 01:49:06 +00001644 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001645
John McCalld88687f2011-01-07 01:49:06 +00001646 // First we check in the local buffer.
1647 llvm::Value *indexPlusOne
1648 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001649
John McCalld88687f2011-01-07 01:49:06 +00001650 // If we haven't overrun the buffer yet, we can continue.
Stephen Hines651f13c2014-04-23 16:59:28 -07001651 // Set the branch weights based on the simplifying assumption that this is
1652 // like a while-loop, i.e., ignoring that the false branch fetches more
1653 // elements and then returns to the loop.
John McCalld88687f2011-01-07 01:49:06 +00001654 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
Stephen Hines651f13c2014-04-23 16:59:28 -07001655 LoopBodyBB, FetchMoreBB,
1656 PGO.createBranchWeights(Cnt.getCount(), EntryCount));
John McCalld88687f2011-01-07 01:49:06 +00001657
1658 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1659 count->addIncoming(count, AfterBody.getBlock());
1660
1661 // Otherwise, we have to fetch more elements.
1662 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001663
1664 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001665 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001666 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001667 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001668 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
John McCalld88687f2011-01-07 01:49:06 +00001670 // If we got a zero count, we're done.
1671 llvm::Value *refetchCount = CountRV.getScalarVal();
1672
1673 // (note that the message send might split FetchMoreBB)
1674 index->addIncoming(zero, Builder.GetInsertBlock());
1675 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1676
1677 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1678 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Anders Carlssonf484c312008-08-31 02:33:12 +00001680 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001681 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001682
John McCall57b3b6a2011-02-22 07:16:58 +00001683 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001684 // If the element was not a declaration, set it to be null.
1685
John McCalld88687f2011-01-07 01:49:06 +00001686 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1687 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001688 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001689 }
1690
Eric Christopher73fb3502011-10-13 21:45:18 +00001691 if (DI)
1692 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001693
John McCall990567c2011-07-27 01:07:15 +00001694 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001695 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001696 PopCleanupBlock();
1697
John McCallff8e1152010-07-23 21:56:41 +00001698 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001699}
1700
Mike Stump1eb44332009-09-09 15:08:12 +00001701void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001702 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001703}
1704
Mike Stump1eb44332009-09-09 15:08:12 +00001705void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001706 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1707}
1708
Chris Lattner10cac6f2008-11-15 21:26:17 +00001709void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001710 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001711 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001712}
1713
John McCall33e56f32011-09-10 06:18:15 +00001714/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001715/// primitive retain.
1716llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1717 llvm::Value *value) {
1718 return EmitARCRetain(type, value);
1719}
1720
1721namespace {
1722 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001723 CallObjCRelease(llvm::Value *object) : object(object) {}
1724 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001725
Stephen Hines651f13c2014-04-23 16:59:28 -07001726 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5b07e802013-03-13 03:10:54 +00001727 // Releases at the end of the full-expression are imprecise.
1728 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001729 }
1730 };
1731}
1732
John McCall33e56f32011-09-10 06:18:15 +00001733/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001734/// release at the end of the full-expression.
1735llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1736 llvm::Value *object) {
1737 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001738 // conditional.
1739 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001740 return object;
1741}
1742
1743llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1744 llvm::Value *value) {
1745 return EmitARCRetainAutorelease(type, value);
1746}
1747
John McCallb6a60792013-03-23 02:35:54 +00001748/// Given a number of pointers, inform the optimizer that they're
1749/// being intrinsically used up until this point in the program.
1750void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1751 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1752 if (!fn) {
1753 llvm::FunctionType *fnType =
Stephen Hines176edba2014-12-01 14:53:08 -08001754 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCallb6a60792013-03-23 02:35:54 +00001755 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1756 }
1757
1758 // This isn't really a "runtime" function, but as an intrinsic it
1759 // doesn't really matter as long as we align things up.
1760 EmitNounwindRuntimeCall(fn, values);
1761}
1762
John McCallf85e1932011-06-15 23:02:42 +00001763
1764static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001765 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001766 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001767 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1768
Michael Gottesman554b07d2013-02-02 00:57:44 +00001769 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmancfe18a12013-02-02 01:05:06 +00001770 // If the target runtime doesn't naturally support ARC, emit weak
1771 // references to the runtime support library. We don't really
1772 // permit this to fail, but we need a particular relocation style.
Michael Gottesman554b07d2013-02-02 00:57:44 +00001773 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00001774 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesman554b07d2013-02-02 00:57:44 +00001775 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1776 // If we have Native ARC, set nonlazybind attribute for these APIs for
1777 // performance.
Bill Wendling72390b32012-12-20 19:27:06 +00001778 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmandb99e8b2013-02-02 01:03:01 +00001779 }
Michael Gottesman554b07d2013-02-02 00:57:44 +00001780 }
John McCallf85e1932011-06-15 23:02:42 +00001781
1782 return fn;
1783}
1784
1785/// Perform an operation having the signature
1786/// i8* (i8*)
1787/// where a null input causes a no-op and returns null.
1788static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1789 llvm::Value *value,
1790 llvm::Constant *&fn,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001791 StringRef fnName,
1792 bool isTailCall = false) {
John McCallf85e1932011-06-15 23:02:42 +00001793 if (isa<llvm::ConstantPointerNull>(value)) return value;
1794
1795 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001796 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001797 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001798 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1799 }
1800
1801 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001802 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001803 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1804
1805 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001806 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001807 if (isTailCall)
1808 call->setTailCall();
John McCallf85e1932011-06-15 23:02:42 +00001809
1810 // Cast the result back to the original type.
1811 return CGF.Builder.CreateBitCast(call, origType);
1812}
1813
1814/// Perform an operation having the following signature:
1815/// i8* (i8**)
1816static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1817 llvm::Value *addr,
1818 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001819 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001820 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001821 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001822 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001823 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1824 }
1825
1826 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001827 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001828 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1829
1830 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001831 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00001832
1833 // Cast the result back to a dereference of the original type.
John McCallf85e1932011-06-15 23:02:42 +00001834 if (origType != CGF.Int8PtrPtrTy)
1835 result = CGF.Builder.CreateBitCast(result,
1836 cast<llvm::PointerType>(origType)->getElementType());
1837
1838 return result;
1839}
1840
1841/// Perform an operation having the following signature:
1842/// i8* (i8**, i8*)
1843static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1844 llvm::Value *addr,
1845 llvm::Value *value,
1846 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001847 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001848 bool ignored) {
1849 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1850 == value->getType());
1851
1852 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001853 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001854
Chris Lattner2acc6e32011-07-18 04:24:23 +00001855 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001856 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1857 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1858 }
1859
Chris Lattner2acc6e32011-07-18 04:24:23 +00001860 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001861
John McCallbd7370a2013-02-28 19:01:20 +00001862 llvm::Value *args[] = {
1863 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1864 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1865 };
1866 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001867
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001868 if (ignored) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001869
1870 return CGF.Builder.CreateBitCast(result, origType);
1871}
1872
1873/// Perform an operation having the following signature:
1874/// void (i8**, i8**)
1875static void emitARCCopyOperation(CodeGenFunction &CGF,
1876 llvm::Value *dst,
1877 llvm::Value *src,
1878 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001879 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001880 assert(dst->getType() == src->getType());
1881
1882 if (!fn) {
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001883 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1884
Chris Lattner2acc6e32011-07-18 04:24:23 +00001885 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001886 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1887 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1888 }
1889
John McCallbd7370a2013-02-28 19:01:20 +00001890 llvm::Value *args[] = {
1891 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1892 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1893 };
1894 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001895}
1896
1897/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001898/// call i8* \@objc_retain(i8* %value)
1899/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001900llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1901 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001902 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001903 else
1904 return EmitARCRetainNonBlock(value);
1905}
1906
1907/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001908/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001909llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1910 return emitARCValueOperation(*this, value,
1911 CGM.getARCEntrypoints().objc_retain,
1912 "objc_retain");
1913}
1914
1915/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001916/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001917///
1918/// \param mandatory - If false, emit the call with metadata
1919/// indicating that it's okay for the optimizer to eliminate this call
1920/// if it can prove that the block never escapes except down the stack.
1921llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1922 bool mandatory) {
1923 llvm::Value *result
1924 = emitARCValueOperation(*this, value,
1925 CGM.getARCEntrypoints().objc_retainBlock,
1926 "objc_retainBlock");
1927
1928 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1929 // tell the optimizer that it doesn't need to do this copy if the
1930 // block doesn't escape, where being passed as an argument doesn't
1931 // count as escaping.
1932 if (!mandatory && isa<llvm::Instruction>(result)) {
1933 llvm::CallInst *call
1934 = cast<llvm::CallInst>(result->stripPointerCasts());
1935 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1936
John McCall348f16f2011-10-04 06:23:45 +00001937 call->setMetadata("clang.arc.copy_on_escape",
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001938 llvm::MDNode::get(Builder.getContext(), None));
John McCall348f16f2011-10-04 06:23:45 +00001939 }
1940
1941 return result;
John McCallf85e1932011-06-15 23:02:42 +00001942}
1943
1944/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001945/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001946///
1947/// Yes, this function name is one character away from a different
1948/// call with completely different semantics.
1949llvm::Value *
1950CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1951 // Fetch the void(void) inline asm which marks that we're going to
1952 // retain the autoreleased return value.
1953 llvm::InlineAsm *&marker
1954 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1955 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001956 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001957 = CGM.getTargetCodeGenInfo()
1958 .getARCRetainAutoreleasedReturnValueMarker();
1959
1960 // If we have an empty assembly string, there's nothing to do.
1961 if (assembly.empty()) {
1962
1963 // Otherwise, at -O0, build an inline asm that we're going to call
1964 // in a moment.
1965 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1966 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001967 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001968
1969 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1970
1971 // If we're at -O1 and above, we don't want to litter the code
1972 // with this marker yet, so leave a breadcrumb for the ARC
1973 // optimizer to pick up.
1974 } else {
1975 llvm::NamedMDNode *metadata =
1976 CGM.getModule().getOrInsertNamedMetadata(
1977 "clang.arc.retainAutoreleasedReturnValueMarker");
1978 assert(metadata->getNumOperands() <= 1);
1979 if (metadata->getNumOperands() == 0) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001980 metadata->addOperand(llvm::MDNode::get(
1981 getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
John McCallf85e1932011-06-15 23:02:42 +00001982 }
1983 }
1984 }
1985
1986 // Call the marker asm if we made one, which we do only at -O0.
1987 if (marker) Builder.CreateCall(marker);
1988
1989 return emitARCValueOperation(*this, value,
1990 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1991 "objc_retainAutoreleasedReturnValue");
1992}
1993
1994/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001995/// call void \@objc_release(i8* %value)
John McCall5b07e802013-03-13 03:10:54 +00001996void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1997 ARCPreciseLifetime_t precise) {
John McCallf85e1932011-06-15 23:02:42 +00001998 if (isa<llvm::ConstantPointerNull>(value)) return;
1999
2000 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2001 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002002 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002003 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002004 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2005 }
2006
2007 // Cast the argument to 'id'.
2008 value = Builder.CreateBitCast(value, Int8PtrTy);
2009
2010 // Call objc_release.
John McCallbd7370a2013-02-28 19:01:20 +00002011 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002012
John McCall5b07e802013-03-13 03:10:54 +00002013 if (precise == ARCImpreciseLifetime) {
John McCallf85e1932011-06-15 23:02:42 +00002014 call->setMetadata("clang.imprecise_release",
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002015 llvm::MDNode::get(Builder.getContext(), None));
John McCallf85e1932011-06-15 23:02:42 +00002016 }
2017}
2018
John McCall015f33b2012-10-17 02:28:37 +00002019/// Destroy a __strong variable.
2020///
2021/// At -O0, emit a call to store 'null' into the address;
2022/// instrumenting tools prefer this because the address is exposed,
2023/// but it's relatively cumbersome to optimize.
2024///
2025/// At -O1 and above, just load and call objc_release.
2026///
2027/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall5b07e802013-03-13 03:10:54 +00002028void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2029 ARCPreciseLifetime_t precise) {
John McCall015f33b2012-10-17 02:28:37 +00002030 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2031 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2032 llvm::Value *null = llvm::ConstantPointerNull::get(
2033 cast<llvm::PointerType>(addrTy->getElementType()));
2034 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2035 return;
2036 }
2037
2038 llvm::Value *value = Builder.CreateLoad(addr);
2039 EmitARCRelease(value, precise);
2040}
2041
John McCallf85e1932011-06-15 23:02:42 +00002042/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002043/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002044llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2045 llvm::Value *value,
2046 bool ignored) {
2047 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2048 == value->getType());
2049
2050 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2051 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002052 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00002053 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00002054 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2055 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2056 }
2057
John McCallbd7370a2013-02-28 19:01:20 +00002058 llvm::Value *args[] = {
2059 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2060 Builder.CreateBitCast(value, Int8PtrTy)
2061 };
2062 EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00002063
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002064 if (ignored) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002065 return value;
2066}
2067
2068/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002069/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002070/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00002071llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00002072 llvm::Value *newValue,
2073 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00002074 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00002075 bool isBlock = type->isBlockPointerType();
2076
2077 // Use a store barrier at -O0 unless this is a block type or the
2078 // lvalue is inadequately aligned.
2079 if (shouldUseFusedARCCalls() &&
2080 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00002081 (dst.getAlignment().isZero() ||
2082 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00002083 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2084 }
2085
2086 // Otherwise, split it out.
2087
2088 // Retain the new value.
2089 newValue = EmitARCRetain(type, newValue);
2090
2091 // Read the old value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002092 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00002093
2094 // Store. We do this before the release so that any deallocs won't
2095 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002096 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002097
2098 // Finally, release the old value.
John McCall5b07e802013-03-13 03:10:54 +00002099 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002100
2101 return newValue;
2102}
2103
2104/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002105/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002106llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2107 return emitARCValueOperation(*this, value,
2108 CGM.getARCEntrypoints().objc_autorelease,
2109 "objc_autorelease");
2110}
2111
2112/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002113/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002114llvm::Value *
2115CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2116 return emitARCValueOperation(*this, value,
2117 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002118 "objc_autoreleaseReturnValue",
2119 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002120}
2121
2122/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002123/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002124llvm::Value *
2125CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2126 return emitARCValueOperation(*this, value,
2127 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002128 "objc_retainAutoreleaseReturnValue",
2129 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002130}
2131
2132/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002133/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002134/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002135/// %retain = call i8* \@objc_retainBlock(i8* %value)
2136/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002137llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2138 llvm::Value *value) {
2139 if (!type->isBlockPointerType())
2140 return EmitARCRetainAutoreleaseNonBlock(value);
2141
2142 if (isa<llvm::ConstantPointerNull>(value)) return value;
2143
Chris Lattner2acc6e32011-07-18 04:24:23 +00002144 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002145 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002146 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002147 value = EmitARCAutorelease(value);
2148 return Builder.CreateBitCast(value, origType);
2149}
2150
2151/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002152/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002153llvm::Value *
2154CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2155 return emitARCValueOperation(*this, value,
2156 CGM.getARCEntrypoints().objc_retainAutorelease,
2157 "objc_retainAutorelease");
2158}
2159
James Dennett9d96e9c2012-06-22 05:41:30 +00002160/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002161/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2162llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2163 return emitARCLoadOperation(*this, addr,
2164 CGM.getARCEntrypoints().objc_loadWeak,
2165 "objc_loadWeak");
2166}
2167
James Dennett9d96e9c2012-06-22 05:41:30 +00002168/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002169llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2170 return emitARCLoadOperation(*this, addr,
2171 CGM.getARCEntrypoints().objc_loadWeakRetained,
2172 "objc_loadWeakRetained");
2173}
2174
James Dennett9d96e9c2012-06-22 05:41:30 +00002175/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002176/// Returns %value.
2177llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2178 llvm::Value *value,
2179 bool ignored) {
2180 return emitARCStoreOperation(*this, addr, value,
2181 CGM.getARCEntrypoints().objc_storeWeak,
2182 "objc_storeWeak", ignored);
2183}
2184
James Dennett9d96e9c2012-06-22 05:41:30 +00002185/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002186/// Returns %value. %addr is known to not have a current weak entry.
2187/// Essentially equivalent to:
2188/// *addr = nil; objc_storeWeak(addr, value);
2189void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2190 // If we're initializing to null, just write null to memory; no need
2191 // to get the runtime involved. But don't do this if optimization
2192 // is enabled, because accounting for this would make the optimizer
2193 // much more complicated.
2194 if (isa<llvm::ConstantPointerNull>(value) &&
2195 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2196 Builder.CreateStore(value, addr);
2197 return;
2198 }
2199
2200 emitARCStoreOperation(*this, addr, value,
2201 CGM.getARCEntrypoints().objc_initWeak,
2202 "objc_initWeak", /*ignored*/ true);
2203}
2204
James Dennett9d96e9c2012-06-22 05:41:30 +00002205/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002206/// Essentially objc_storeWeak(addr, nil).
2207void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2208 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2209 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002210 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002211 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002212 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2213 }
2214
2215 // Cast the argument to 'id*'.
2216 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2217
John McCallbd7370a2013-02-28 19:01:20 +00002218 EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00002219}
2220
James Dennett9d96e9c2012-06-22 05:41:30 +00002221/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002222/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2223/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2224void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2225 emitARCCopyOperation(*this, dst, src,
2226 CGM.getARCEntrypoints().objc_moveWeak,
2227 "objc_moveWeak");
2228}
2229
James Dennett9d96e9c2012-06-22 05:41:30 +00002230/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002231/// Disregards the current value in %dest. Essentially
2232/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2233void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2234 emitARCCopyOperation(*this, dst, src,
2235 CGM.getARCEntrypoints().objc_copyWeak,
2236 "objc_copyWeak");
2237}
2238
2239/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002240/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002241llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2242 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2243 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002244 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002245 llvm::FunctionType::get(Int8PtrTy, false);
2246 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2247 }
2248
John McCallbd7370a2013-02-28 19:01:20 +00002249 return EmitNounwindRuntimeCall(fn);
John McCallf85e1932011-06-15 23:02:42 +00002250}
2251
2252/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002253/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002254void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2255 assert(value->getType() == Int8PtrTy);
2256
2257 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2258 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002259 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002260 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002261
2262 // We don't want to use a weak import here; instead we should not
2263 // fall into this path.
2264 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2265 }
2266
John McCallb57f6b32013-04-16 21:29:40 +00002267 // objc_autoreleasePoolPop can throw.
2268 EmitRuntimeCallOrInvoke(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002269}
2270
2271/// Produce the code to do an MRR version objc_autoreleasepool_push.
2272/// Which is: [[NSAutoreleasePool alloc] init];
2273/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2274/// init is declared as: - (id) init; in its NSObject super class.
2275///
2276llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2277 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +00002278 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCallf85e1932011-06-15 23:02:42 +00002279 // [NSAutoreleasePool alloc]
2280 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2281 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2282 CallArgList Args;
2283 RValue AllocRV =
2284 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2285 getContext().getObjCIdType(),
2286 AllocSel, Receiver, Args);
2287
2288 // [Receiver init]
2289 Receiver = AllocRV.getScalarVal();
2290 II = &CGM.getContext().Idents.get("init");
2291 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2292 RValue InitRV =
2293 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2294 getContext().getObjCIdType(),
2295 InitSel, Receiver, Args);
2296 return InitRV.getScalarVal();
2297}
2298
2299/// Produce the code to do a primitive release.
2300/// [tmp drain];
2301void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2302 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2303 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2304 CallArgList Args;
2305 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2306 getContext().VoidTy, DrainSel, Arg, Args);
2307}
2308
John McCallbdc4d802011-07-09 01:37:26 +00002309void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2310 llvm::Value *addr,
2311 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002312 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002313}
2314
2315void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2316 llvm::Value *addr,
2317 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002318 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002319}
2320
2321void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2322 llvm::Value *addr,
2323 QualType type) {
2324 CGF.EmitARCDestroyWeak(addr);
2325}
2326
John McCallf85e1932011-06-15 23:02:42 +00002327namespace {
John McCallf85e1932011-06-15 23:02:42 +00002328 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2329 llvm::Value *Token;
2330
2331 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2332
Stephen Hines651f13c2014-04-23 16:59:28 -07002333 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002334 CGF.EmitObjCAutoreleasePoolPop(Token);
2335 }
2336 };
2337 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2338 llvm::Value *Token;
2339
2340 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2341
Stephen Hines651f13c2014-04-23 16:59:28 -07002342 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002343 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2344 }
2345 };
2346}
2347
2348void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002349 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002350 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2351 else
2352 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2353}
2354
John McCallf85e1932011-06-15 23:02:42 +00002355static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2356 LValue lvalue,
2357 QualType type) {
2358 switch (type.getObjCLifetime()) {
2359 case Qualifiers::OCL_None:
2360 case Qualifiers::OCL_ExplicitNone:
2361 case Qualifiers::OCL_Strong:
2362 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002363 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2364 SourceLocation()).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002365 false);
2366
2367 case Qualifiers::OCL_Weak:
2368 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2369 true);
2370 }
2371
2372 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002373}
2374
2375static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2376 const Expr *e) {
2377 e = e->IgnoreParens();
2378 QualType type = e->getType();
2379
John McCall21480112011-08-30 00:57:29 +00002380 // If we're loading retained from a __strong xvalue, we can avoid
2381 // an extra retain/release pair by zeroing out the source of this
2382 // "move" operation.
2383 if (e->isXValue() &&
2384 !type.isConstQualified() &&
2385 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2386 // Emit the lvalue.
2387 LValue lv = CGF.EmitLValue(e);
2388
2389 // Load the object pointer.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002390 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2391 SourceLocation()).getScalarVal();
John McCall21480112011-08-30 00:57:29 +00002392
2393 // Set the source pointer to NULL.
2394 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2395
2396 return TryEmitResult(result, true);
2397 }
2398
John McCallf85e1932011-06-15 23:02:42 +00002399 // As a very special optimization, in ARC++, if the l-value is the
2400 // result of a non-volatile assignment, do a simple retain of the
2401 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002402 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002403 !type.isVolatileQualified() &&
2404 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2405 isa<BinaryOperator>(e) &&
2406 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2407 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2408
2409 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2410}
2411
2412static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2413 llvm::Value *value);
2414
2415/// Given that the given expression is some sort of call (which does
2416/// not return retained), emit a retain following it.
2417static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2418 llvm::Value *value = CGF.EmitScalarExpr(e);
2419 return emitARCRetainAfterCall(CGF, value);
2420}
2421
2422static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2423 llvm::Value *value) {
2424 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2425 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2426
2427 // Place the retain immediately following the call.
2428 CGF.Builder.SetInsertPoint(call->getParent(),
2429 ++llvm::BasicBlock::iterator(call));
2430 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2431
2432 CGF.Builder.restoreIP(ip);
2433 return value;
2434 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2435 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2436
2437 // Place the retain at the beginning of the normal destination block.
2438 llvm::BasicBlock *BB = invoke->getNormalDest();
2439 CGF.Builder.SetInsertPoint(BB, BB->begin());
2440 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2441
2442 CGF.Builder.restoreIP(ip);
2443 return value;
2444
2445 // Bitcasts can arise because of related-result returns. Rewrite
2446 // the operand.
2447 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2448 llvm::Value *operand = bitcast->getOperand(0);
2449 operand = emitARCRetainAfterCall(CGF, operand);
2450 bitcast->setOperand(0, operand);
2451 return bitcast;
2452
2453 // Generic fall-back case.
2454 } else {
2455 // Retain using the non-block variant: we never need to do a copy
2456 // of a block that's been returned to us.
2457 return CGF.EmitARCRetainNonBlock(value);
2458 }
2459}
2460
John McCalldc05b112011-09-10 01:16:55 +00002461/// Determine whether it might be important to emit a separate
2462/// objc_retain_block on the result of the given expression, or
2463/// whether it's okay to just emit it in a +1 context.
2464static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2465 assert(e->getType()->isBlockPointerType());
2466 e = e->IgnoreParens();
2467
2468 // For future goodness, emit block expressions directly in +1
2469 // contexts if we can.
2470 if (isa<BlockExpr>(e))
2471 return false;
2472
2473 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2474 switch (cast->getCastKind()) {
2475 // Emitting these operations in +1 contexts is goodness.
2476 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002477 case CK_ARCReclaimReturnedObject:
2478 case CK_ARCConsumeObject:
2479 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002480 return false;
2481
2482 // These operations preserve a block type.
2483 case CK_NoOp:
2484 case CK_BitCast:
2485 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2486
2487 // These operations are known to be bad (or haven't been considered).
2488 case CK_AnyPointerToBlockPointerCast:
2489 default:
2490 return true;
2491 }
2492 }
2493
2494 return true;
2495}
2496
John McCall4b9c2d22011-11-06 09:01:30 +00002497/// Try to emit a PseudoObjectExpr at +1.
2498///
2499/// This massively duplicates emitPseudoObjectRValue.
2500static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2501 const PseudoObjectExpr *E) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002502 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCall4b9c2d22011-11-06 09:01:30 +00002503
2504 // Find the result expression.
2505 const Expr *resultExpr = E->getResultExpr();
2506 assert(resultExpr);
2507 TryEmitResult result;
2508
2509 for (PseudoObjectExpr::const_semantics_iterator
2510 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2511 const Expr *semantic = *i;
2512
2513 // If this semantic expression is an opaque value, bind it
2514 // to the result of its source expression.
2515 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2516 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2517 OVMA opaqueData;
2518
2519 // If this semantic is the result of the pseudo-object
2520 // expression, try to evaluate the source as +1.
2521 if (ov == resultExpr) {
2522 assert(!OVMA::shouldBindAsLValue(ov));
2523 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2524 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2525
2526 // Otherwise, just bind it.
2527 } else {
2528 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2529 }
2530 opaques.push_back(opaqueData);
2531
2532 // Otherwise, if the expression is the result, evaluate it
2533 // and remember the result.
2534 } else if (semantic == resultExpr) {
2535 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2536
2537 // Otherwise, evaluate the expression in an ignored context.
2538 } else {
2539 CGF.EmitIgnoredExpr(semantic);
2540 }
2541 }
2542
2543 // Unbind all the opaques now.
2544 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2545 opaques[i].unbind(CGF);
2546
2547 return result;
2548}
2549
John McCallf85e1932011-06-15 23:02:42 +00002550static TryEmitResult
2551tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002552 // We should *never* see a nested full-expression here, because if
2553 // we fail to emit at +1, our caller must not retain after we close
2554 // out the full-expression.
2555 assert(!isa<ExprWithCleanups>(e));
John McCall990567c2011-07-27 01:07:15 +00002556
John McCallf85e1932011-06-15 23:02:42 +00002557 // The desired result type, if it differs from the type of the
2558 // ultimate opaque expression.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002559 llvm::Type *resultType = nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002560
2561 while (true) {
2562 e = e->IgnoreParens();
2563
2564 // There's a break at the end of this if-chain; anything
2565 // that wants to keep looping has to explicitly continue.
2566 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2567 switch (ce->getCastKind()) {
2568 // No-op casts don't change the type, so we just ignore them.
2569 case CK_NoOp:
2570 e = ce->getSubExpr();
2571 continue;
2572
2573 case CK_LValueToRValue: {
2574 TryEmitResult loadResult
2575 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2576 if (resultType) {
2577 llvm::Value *value = loadResult.getPointer();
2578 value = CGF.Builder.CreateBitCast(value, resultType);
2579 loadResult.setPointer(value);
2580 }
2581 return loadResult;
2582 }
2583
2584 // These casts can change the type, so remember that and
2585 // soldier on. We only need to remember the outermost such
2586 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002587 case CK_CPointerToObjCPointerCast:
2588 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002589 case CK_AnyPointerToBlockPointerCast:
2590 case CK_BitCast:
2591 if (!resultType)
2592 resultType = CGF.ConvertType(ce->getType());
2593 e = ce->getSubExpr();
2594 assert(e->getType()->hasPointerRepresentation());
2595 continue;
2596
2597 // For consumptions, just emit the subexpression and thus elide
2598 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002599 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002600 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2601 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2602 return TryEmitResult(result, true);
2603 }
2604
John McCalldc05b112011-09-10 01:16:55 +00002605 // Block extends are net +0. Naively, we could just recurse on
2606 // the subexpression, but actually we need to ensure that the
2607 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002608 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002609 llvm::Value *result; // will be a +0 value
2610
2611 // If we can't safely assume the sub-expression will produce a
2612 // block-copied value, emit the sub-expression at +0.
2613 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2614 result = CGF.EmitScalarExpr(ce->getSubExpr());
2615
2616 // Otherwise, try to emit the sub-expression at +1 recursively.
2617 } else {
2618 TryEmitResult subresult
2619 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2620 result = subresult.getPointer();
2621
2622 // If that produced a retained value, just use that,
2623 // possibly casting down.
2624 if (subresult.getInt()) {
2625 if (resultType)
2626 result = CGF.Builder.CreateBitCast(result, resultType);
2627 return TryEmitResult(result, true);
2628 }
2629
2630 // Otherwise it's +0.
2631 }
2632
2633 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002634 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002635 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2636 return TryEmitResult(result, true);
2637 }
2638
John McCall7e5e5f42011-07-07 06:58:02 +00002639 // For reclaims, emit the subexpression as a retained call and
2640 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002641 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002642 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2643 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2644 return TryEmitResult(result, true);
2645 }
2646
John McCallf85e1932011-06-15 23:02:42 +00002647 default:
2648 break;
2649 }
2650
2651 // Skip __extension__.
2652 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2653 if (op->getOpcode() == UO_Extension) {
2654 e = op->getSubExpr();
2655 continue;
2656 }
2657
2658 // For calls and message sends, use the retained-call logic.
2659 // Delegate inits are a special case in that they're the only
2660 // returns-retained expression that *isn't* surrounded by
2661 // a consume.
2662 } else if (isa<CallExpr>(e) ||
2663 (isa<ObjCMessageExpr>(e) &&
2664 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2665 llvm::Value *result = emitARCRetainCall(CGF, e);
2666 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2667 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002668
2669 // Look through pseudo-object expressions.
2670 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2671 TryEmitResult result
2672 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2673 if (resultType) {
2674 llvm::Value *value = result.getPointer();
2675 value = CGF.Builder.CreateBitCast(value, resultType);
2676 result.setPointer(value);
2677 }
2678 return result;
John McCallf85e1932011-06-15 23:02:42 +00002679 }
2680
2681 // Conservatively halt the search at any other expression kind.
2682 break;
2683 }
2684
2685 // We didn't find an obvious production, so emit what we've got and
2686 // tell the caller that we didn't manage to retain.
2687 llvm::Value *result = CGF.EmitScalarExpr(e);
2688 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2689 return TryEmitResult(result, false);
2690}
2691
2692static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2693 LValue lvalue,
2694 QualType type) {
2695 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2696 llvm::Value *value = result.getPointer();
2697 if (!result.getInt())
2698 value = CGF.EmitARCRetain(type, value);
2699 return value;
2700}
2701
2702/// EmitARCRetainScalarExpr - Semantically equivalent to
2703/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2704/// best-effort attempt to peephole expressions that naturally produce
2705/// retained objects.
2706llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002707 // The retain needs to happen within the full-expression.
2708 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2709 enterFullExpression(cleanups);
2710 RunCleanupsScope scope(*this);
2711 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2712 }
2713
John McCallf85e1932011-06-15 23:02:42 +00002714 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2715 llvm::Value *value = result.getPointer();
2716 if (!result.getInt())
2717 value = EmitARCRetain(e->getType(), value);
2718 return value;
2719}
2720
2721llvm::Value *
2722CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002723 // The retain needs to happen within the full-expression.
2724 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2725 enterFullExpression(cleanups);
2726 RunCleanupsScope scope(*this);
2727 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2728 }
2729
John McCallf85e1932011-06-15 23:02:42 +00002730 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2731 llvm::Value *value = result.getPointer();
2732 if (result.getInt())
2733 value = EmitARCAutorelease(value);
2734 else
2735 value = EmitARCRetainAutorelease(e->getType(), value);
2736 return value;
2737}
2738
John McCall348f16f2011-10-04 06:23:45 +00002739llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2740 llvm::Value *result;
2741 bool doRetain;
2742
2743 if (shouldEmitSeparateBlockRetain(e)) {
2744 result = EmitScalarExpr(e);
2745 doRetain = true;
2746 } else {
2747 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2748 result = subresult.getPointer();
2749 doRetain = !subresult.getInt();
2750 }
2751
2752 if (doRetain)
2753 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2754 return EmitObjCConsumeObject(e->getType(), result);
2755}
2756
John McCall2b014d62011-10-01 10:32:24 +00002757llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2758 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002759 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002760 // Do so before running any cleanups for the full-expression.
John McCall72dcecc2013-02-12 00:25:08 +00002761 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall2b014d62011-10-01 10:32:24 +00002762 return EmitARCRetainAutoreleaseScalarExpr(expr);
2763 }
2764
2765 // Otherwise, use the normal scalar-expression emission. The
2766 // exception machinery doesn't do anything special with the
2767 // exception like retaining it, so there's no safety associated with
2768 // only running cleanups after the throw has started, and when it
2769 // matters it tends to be substantially inferior code.
2770 return EmitScalarExpr(expr);
2771}
2772
John McCallf85e1932011-06-15 23:02:42 +00002773std::pair<LValue,llvm::Value*>
2774CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2775 bool ignored) {
2776 // Evaluate the RHS first.
2777 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2778 llvm::Value *value = result.getPointer();
2779
John McCallfb720812011-07-28 07:23:35 +00002780 bool hasImmediateRetain = result.getInt();
2781
2782 // If we didn't emit a retained object, and the l-value is of block
2783 // type, then we need to emit the block-retain immediately in case
2784 // it invalidates the l-value.
2785 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002786 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002787 hasImmediateRetain = true;
2788 }
2789
John McCallf85e1932011-06-15 23:02:42 +00002790 LValue lvalue = EmitLValue(e->getLHS());
2791
2792 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002793 if (hasImmediateRetain) {
Nick Lewyckyc53143c2013-10-02 02:33:11 +00002794 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedman6da2c712011-12-03 04:14:32 +00002795 EmitStoreOfScalar(value, lvalue);
John McCall5b07e802013-03-13 03:10:54 +00002796 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002797 } else {
John McCall545d9962011-06-25 02:11:03 +00002798 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002799 }
2800
2801 return std::pair<LValue,llvm::Value*>(lvalue, value);
2802}
2803
2804std::pair<LValue,llvm::Value*>
2805CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2806 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2807 LValue lvalue = EmitLValue(e->getLHS());
2808
Eli Friedman6da2c712011-12-03 04:14:32 +00002809 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002810
2811 return std::pair<LValue,llvm::Value*>(lvalue, value);
2812}
2813
2814void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002815 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002816 const Stmt *subStmt = ARPS.getSubStmt();
2817 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2818
2819 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002820 if (DI)
2821 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002822
2823 // Keep track of the current cleanup stack depth.
2824 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00002825 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002826 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2827 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2828 } else {
2829 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2830 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2831 }
2832
Stephen Hines651f13c2014-04-23 16:59:28 -07002833 for (const auto *I : S.body())
2834 EmitStmt(I);
John McCallf85e1932011-06-15 23:02:42 +00002835
Eric Christopher73fb3502011-10-13 21:45:18 +00002836 if (DI)
2837 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002838}
John McCall0c24c802011-06-24 23:21:27 +00002839
2840/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2841/// make sure it survives garbage collection until this point.
2842void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2843 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002844 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002845 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002846 llvm::Value *extender
2847 = llvm::InlineAsm::get(extenderType,
2848 /* assembly */ "",
2849 /* constraints */ "r",
2850 /* side effects */ true);
2851
2852 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00002853 EmitNounwindRuntimeCall(extender, object);
John McCall0c24c802011-06-24 23:21:27 +00002854}
2855
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002856/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002857/// non-trivial copy assignment function, produce following helper function.
2858/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2859///
2860llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002861CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2862 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002863 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002864 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002865 return nullptr;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002866 QualType Ty = PID->getPropertyIvarDecl()->getType();
2867 if (!Ty->isRecordType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002868 return nullptr;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002869 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002870 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002871 return nullptr;
2872 llvm::Constant *HelperFn = nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002873 if (hasTrivialSetExpr(PID))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002874 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002875 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2876 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2877 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002878
2879 ASTContext &C = getContext();
2880 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002881 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002882 FunctionDecl *FD = FunctionDecl::Create(C,
2883 C.getTranslationUnitDecl(),
2884 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002885 SourceLocation(), II, C.VoidTy,
2886 nullptr, SC_Static,
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002887 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002888 false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002889
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002890 QualType DestTy = C.getPointerType(Ty);
2891 QualType SrcTy = Ty;
2892 SrcTy.addConst();
2893 SrcTy = C.getPointerType(SrcTy);
2894
2895 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002896 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002897 args.push_back(&dstDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002898 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002899 args.push_back(&srcDecl);
Stephen Hines651f13c2014-04-23 16:59:28 -07002900
2901 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2902 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2903
John McCallde5d3c72012-02-17 03:33:10 +00002904 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002905
2906 llvm::Function *Fn =
2907 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002908 "__assign_helper_atomic_property_",
2909 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002910
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002911 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002912
John McCallf4b88a42012-03-10 09:33:50 +00002913 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2914 VK_RValue, SourceLocation());
2915 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2916 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002917
John McCallf4b88a42012-03-10 09:33:50 +00002918 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2919 VK_RValue, SourceLocation());
2920 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2921 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002922
John McCallf4b88a42012-03-10 09:33:50 +00002923 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002924 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002925 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002926 Args, DestTy->getPointeeType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00002927 VK_LValue, SourceLocation(), false);
John McCallf4b88a42012-03-10 09:33:50 +00002928
2929 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002930
2931 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002932 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002933 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002934 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002935}
2936
2937llvm::Constant *
2938CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2939 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002940 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002941 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002942 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002943 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2944 QualType Ty = PD->getType();
2945 if (!Ty->isRecordType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002946 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002947 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002948 return nullptr;
2949 llvm::Constant *HelperFn = nullptr;
2950
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002951 if (hasTrivialGetExpr(PID))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002952 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002953 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2954 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2955 return HelperFn;
2956
2957
2958 ASTContext &C = getContext();
2959 IdentifierInfo *II
2960 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2961 FunctionDecl *FD = FunctionDecl::Create(C,
2962 C.getTranslationUnitDecl(),
2963 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002964 SourceLocation(), II, C.VoidTy,
2965 nullptr, SC_Static,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002966 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002967 false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002968
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002969 QualType DestTy = C.getPointerType(Ty);
2970 QualType SrcTy = Ty;
2971 SrcTy.addConst();
2972 SrcTy = C.getPointerType(SrcTy);
2973
2974 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002975 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002976 args.push_back(&dstDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002977 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002978 args.push_back(&srcDecl);
Stephen Hines651f13c2014-04-23 16:59:28 -07002979
2980 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2981 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2982
John McCallde5d3c72012-02-17 03:33:10 +00002983 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002984
2985 llvm::Function *Fn =
2986 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2987 "__copy_helper_atomic_property_", &CGM.getModule());
2988
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002989 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002990
John McCallf4b88a42012-03-10 09:33:50 +00002991 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002992 VK_RValue, SourceLocation());
2993
John McCallf4b88a42012-03-10 09:33:50 +00002994 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2995 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002996
2997 CXXConstructExpr *CXXConstExpr =
2998 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2999
3000 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00003001 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003002 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3003 ++A;
3004
3005 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3006 A != AEnd; ++A)
3007 ConstructorArgs.push_back(*A);
3008
3009 CXXConstructExpr *TheCXXConstructExpr =
3010 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3011 CXXConstExpr->getConstructor(),
3012 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003013 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003014 CXXConstExpr->hadMultipleCandidates(),
3015 CXXConstExpr->isListInitialization(),
Stephen Hines176edba2014-12-01 14:53:08 -08003016 CXXConstExpr->isStdInitListInitialization(),
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,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003055 Val, CallArgList(), nullptr, nullptr);
Eli Friedmancae40c42012-02-28 01:08:45 +00003056 Val = Result.getScalarVal();
3057 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3058 Ty, AutoreleaseSelector,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003059 Val, CallArgList(), nullptr, nullptr);
Eli Friedmancae40c42012-02-28 01:08:45 +00003060 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() {}