blob: 34c6d94f8817c800fc5f62b3a2ae7d697f648152 [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremeneke65b0862012-03-06 20:05:56 +000034static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +000035 QualType ET,
Ted Kremeneke65b0862012-03-06 20:05:56 +000036 const ObjCMethodDecl *Method,
37 RValue Result);
John McCall31168b02011-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 Lattner2192fe52011-07-18 04:24:23 +000042 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000043 cast<llvm::PointerType>(addr->getType())->getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
Chris Lattnerb1d329d2008-06-24 17:04:18 +000047/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000048llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000049{
David Chisnall481e3a82010-01-23 02:40:42 +000050 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000052 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000053 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000054}
55
Patrick Beard0caa3942012-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 Kremeneke65b0862012-03-06 20:05:56 +000059///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000060llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000061CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000063 // Get the method.
Patrick Beard0caa3942012-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 Kremeneke65b0862012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-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 Kremeneke65b0862012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CallArgList Args;
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000077 EmitCallArgs(Args, BoxingMethod, E->arg_begin(), E->arg_end());
Alp Toker314cc812014-01-25 16:55:45 +000078
79 RValue result = Runtime.GenerateMessageSend(
80 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
81 Args, ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +000082 return Builder.CreateBitCast(result.getScalarVal(),
83 ConvertType(E->getType()));
84}
85
86llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +000087 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000088 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +000089 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-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).
Craig Topper8a13c412014-05-21 05:09:00 +0000105 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
106 llvm::Value *Keys = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000107 if (DLE)
108 Keys = CreateMemTemp(ElementArrayType, "keys");
109
John McCall770a4c12013-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 Kremeneke65b0862012-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 McCall770a4c12013-04-04 00:20:38 +0000120 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-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 McCall770a4c12013-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 Kremeneke65b0862012-03-06 20:05:56 +0000132 } else {
John McCall770a4c12013-04-04 00:20:38 +0000133 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-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 McCall770a4c12013-04-04 00:20:38 +0000139 llvm::Value *keyValue = EmitScalarExpr(Key);
140 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141
John McCall770a4c12013-04-04 00:20:38 +0000142 // Emit the value and store it to the appropriate array slot.
Ted Kremeneke65b0862012-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 McCall770a4c12013-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 Kremeneke65b0862012-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 McCall882987f2013-02-28 19:01:20 +0000182 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000183
184 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000185 RValue result = Runtime.GenerateMessageSend(
186 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
187 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-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 Kremeneke65b0862012-03-06 20:05:56 +0000197 return Builder.CreateBitCast(result.getScalarVal(),
198 ConvertType(E->getType()));
199}
200
201llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000202 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000203}
204
205llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
206 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000207 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000208}
209
Chris Lattnerb1d329d2008-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 McCall882987f2013-02-28 19:01:20 +0000216 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000217}
218
Daniel Dunbar66912a12008-08-20 00:28:19 +0000219llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
220 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000221 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000222}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000223
Douglas Gregor33823722011-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 Jahanianb5dd2cb2012-05-29 19:56:01 +0000227 QualType ExpT,
Douglas Gregor33823722011-06-11 01:09:30 +0000228 const ObjCMethodDecl *Method,
229 RValue Result) {
230 if (!Method)
231 return Result;
John McCall31168b02011-06-15 23:02:42 +0000232
Douglas Gregor33823722011-06-11 01:09:30 +0000233 if (!Method->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +0000234 CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
Douglas Gregor33823722011-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 Jahanianb5dd2cb2012-05-29 19:56:01 +0000240 CGF.ConvertType(ExpT)));
Douglas Gregor33823722011-06-11 01:09:30 +0000241}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000242
John McCallcf166702011-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 McCall78a15112010-05-22 01:48:05 +0000290RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
291 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-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 Stump11289f42009-09-09 15:08:12 +0000295
John McCall31168b02011-06-15 23:02:42 +0000296 bool isDelegateInit = E->isDelegateInitCall();
297
John McCallcf166702011-07-22 08:53:00 +0000298 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000299
John McCall31168b02011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000306 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000307 method &&
308 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000309
Daniel Dunbar8d480592008-08-11 18:12:00 +0000310 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000311 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000312 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000313 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000314 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000315 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000316 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000317 switch (E->getReceiverKind()) {
318 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000319 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000320 if (retainSelf) {
321 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
322 E->getInstanceReceiver());
323 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000324 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000325 } else
326 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000327 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000328
Douglas Gregor9a129192010-04-21 00:45:42 +0000329 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000330 ReceiverType = E->getClassReceiver();
331 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-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 McCall882987f2013-02-28 19:01:20 +0000335 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000336 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000337 break;
338 }
339
340 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000341 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000342 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000343 isSuperMessage = true;
344 break;
345
346 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000347 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000348 Receiver = LoadObjCSelf();
349 isSuperMessage = true;
350 isClassMessage = true;
351 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000352 }
353
John McCallcf166702011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000360 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000361 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
362 shouldExtendReceiverForInnerPointerMessage(E))
363 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
364
Alp Toker314cc812014-01-25 16:55:45 +0000365 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000366
Daniel Dunbarc722b852008-08-30 03:02:31 +0000367 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000368 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000369
John McCall31168b02011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000378 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-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 Carlsson280e61f12010-06-21 20:59:55 +0000388
Douglas Gregor33823722011-06-11 01:09:30 +0000389 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000390 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000391 // super is only valid in an Objective-C method
392 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000393 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-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 McCallcf166702011-07-22 08:53:00 +0000401 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000402 } else {
403 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
404 E->getSelector(),
405 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000406 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000407 }
John McCall31168b02011-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 Lattner2192fe52011-07-18 04:24:23 +0000418 llvm::Type *selfTy =
John McCall31168b02011-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 Jahanian715fdd52012-01-29 20:27:13 +0000424
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000425 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000426}
427
John McCall31168b02011-06-15 23:02:42 +0000428namespace {
429struct FinishARCDealloc : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000430 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000431 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000432
433 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000434 const ObjCInterfaceDecl *iface = impl->getClassInterface();
435 if (!iface->getSuperClass()) return;
436
John McCalldffafde2011-07-13 18:26:47 +0000437 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
438
John McCall31168b02011-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 McCalldffafde2011-07-13 18:26:47 +0000447 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000448 self,
449 /*is class msg*/ false,
450 args,
451 method);
452 }
453};
454}
455
Daniel Dunbar89654ee2008-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 Jahanian0196a1c2009-01-10 21:06:09 +0000459void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000460 const ObjCContainerDecl *CD) {
461 SourceLocation StartLoc = OMD->getLocStart();
John McCalla738c252011-03-09 04:27:21 +0000462 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000463 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000464 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000465 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000466
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000467 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000468
John McCalla729c622012-02-17 03:33:10 +0000469 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000470 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000471
John McCalla738c252011-03-09 04:27:21 +0000472 args.push_back(OMD->getSelfDecl());
473 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000474
Aaron Ballman43b68be2014-03-07 17:50:17 +0000475 for (const auto *PI : OMD->params())
476 args.push_back(PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000477
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000478 CurGD = OMD;
David Blaikie47d28e02015-01-14 07:10:46 +0000479 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000480
Adrian Prantl42d71b92014-04-10 23:21:53 +0000481 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
482 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000483
484 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000485 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000486 OMD->isInstanceMethod() &&
487 OMD->getSelector().isUnarySelector()) {
488 const IdentifierInfo *ident =
489 OMD->getSelector().getIdentifierInfoForSlot(0);
490 if (ident->isStr("dealloc"))
491 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
492 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000493}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000494
John McCall31168b02011-06-15 23:02:42 +0000495static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
496 LValue lvalue, QualType type);
497
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000498/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000499/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000500void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000501 StartObjCMethod(OMD, OMD->getClassInterface());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000502 PGO.assignRegionCounters(OMD, CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000503 assert(isa<CompoundStmt>(OMD->getBody()));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000504 RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
505 Cnt.beginRegion(Builder);
Adrian Prantl56741e22014-01-07 22:05:55 +0000506 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000507 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000508}
509
John McCallb923ece2011-09-12 23:06:44 +0000510/// emitStructGetterCall - Call the runtime function to load a property
511/// into the return value slot.
512static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
513 bool isAtomic, bool hasStrong) {
514 ASTContext &Context = CGF.getContext();
515
516 llvm::Value *src =
517 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
518 ivar, 0).getAddress();
519
520 // objc_copyStruct (ReturnValue, &structIvar,
521 // sizeof (Type of Ivar), isAtomic, false);
522 CallArgList args;
523
524 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
525 args.add(RValue::get(dest), Context.VoidPtrTy);
526
527 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
528 args.add(RValue::get(src), Context.VoidPtrTy);
529
530 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
531 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
532 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
533 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
534
535 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000536 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
537 FunctionType::ExtInfo(),
538 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000539 fn, ReturnValueSlot(), args);
540}
541
John McCallf4528ae2011-09-13 03:34:09 +0000542/// Determine whether the given architecture supports unaligned atomic
543/// accesses. They don't have to be fast, just faster than a function
544/// call and a mutex.
545static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000546 // FIXME: Allow unaligned atomic load/store on x86. (It is not
547 // currently supported by the backend.)
548 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000549}
550
551/// Return the maximum size that permits atomic accesses for the given
552/// architecture.
553static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
554 llvm::Triple::ArchType arch) {
555 // ARM has 8-byte atomic accesses, but it's not clear whether we
556 // want to rely on them here.
557
558 // In the default case, just assume that any size up to a pointer is
559 // fine given adequate alignment.
560 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
561}
562
563namespace {
564 class PropertyImplStrategy {
565 public:
566 enum StrategyKind {
567 /// The 'native' strategy is to use the architecture's provided
568 /// reads and writes.
569 Native,
570
571 /// Use objc_setProperty and objc_getProperty.
572 GetSetProperty,
573
574 /// Use objc_setProperty for the setter, but use expression
575 /// evaluation for the getter.
576 SetPropertyAndExpressionGet,
577
578 /// Use objc_copyStruct.
579 CopyStruct,
580
581 /// The 'expression' strategy is to emit normal assignment or
582 /// lvalue-to-rvalue expressions.
583 Expression
584 };
585
586 StrategyKind getKind() const { return StrategyKind(Kind); }
587
588 bool hasStrongMember() const { return HasStrong; }
589 bool isAtomic() const { return IsAtomic; }
590 bool isCopy() const { return IsCopy; }
591
592 CharUnits getIvarSize() const { return IvarSize; }
593 CharUnits getIvarAlignment() const { return IvarAlignment; }
594
595 PropertyImplStrategy(CodeGenModule &CGM,
596 const ObjCPropertyImplDecl *propImpl);
597
598 private:
599 unsigned Kind : 8;
600 unsigned IsAtomic : 1;
601 unsigned IsCopy : 1;
602 unsigned HasStrong : 1;
603
604 CharUnits IvarSize;
605 CharUnits IvarAlignment;
606 };
607}
608
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000609/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000610PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
611 const ObjCPropertyImplDecl *propImpl) {
612 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000613 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000614
John McCall43192862011-09-13 18:31:23 +0000615 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
616 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000617 HasStrong = false; // doesn't matter here.
618
619 // Evaluate the ivar's size and alignment.
620 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
621 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000622 std::tie(IvarSize, IvarAlignment) =
623 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000624
625 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000626 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000627 if (IsCopy) {
628 Kind = GetSetProperty;
629 return;
630 }
631
John McCall43192862011-09-13 18:31:23 +0000632 // Handle retain.
633 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000634 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000636 // fallthrough
637
638 // In ARC, if the property is non-atomic, use expression emission,
639 // which translates to objc_storeStrong. This isn't required, but
640 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000641 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000642 // Using standard expression emission for the setter is only
643 // acceptable if the ivar is __strong, which won't be true if
644 // the property is annotated with __attribute__((NSObject)).
645 // TODO: falling all the way back to objc_setProperty here is
646 // just laziness, though; we could still use objc_storeStrong
647 // if we hacked it right.
648 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
649 Kind = Expression;
650 else
651 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000652 return;
653
654 // Otherwise, we need to at least use setProperty. However, if
655 // the property isn't atomic, we can use normal expression
656 // emission for the getter.
657 } else if (!IsAtomic) {
658 Kind = SetPropertyAndExpressionGet;
659 return;
660
661 // Otherwise, we have to use both setProperty and getProperty.
662 } else {
663 Kind = GetSetProperty;
664 return;
665 }
666 }
667
668 // If we're not atomic, just use expression accesses.
669 if (!IsAtomic) {
670 Kind = Expression;
671 return;
672 }
673
John McCall0e5c0862011-09-13 05:36:29 +0000674 // Properties on bitfield ivars need to be emitted using expression
675 // accesses even if they're nominally atomic.
676 if (ivar->isBitField()) {
677 Kind = Expression;
678 return;
679 }
680
John McCallf4528ae2011-09-13 03:34:09 +0000681 // GC-qualified or ARC-qualified ivars need to be emitted as
682 // expressions. This actually works out to being atomic anyway,
683 // except for ARC __strong, but that should trigger the above code.
684 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000685 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000686 CGM.getContext().getObjCGCAttrKind(ivarType))) {
687 Kind = Expression;
688 return;
689 }
690
691 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000692 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000693 if (const RecordType *recordType = ivarType->getAs<RecordType>())
694 HasStrong = recordType->getDecl()->hasObjectMember();
695
696 // We can never access structs with object members with a native
697 // access, because we need to use write barriers. This is what
698 // objc_copyStruct is for.
699 if (HasStrong) {
700 Kind = CopyStruct;
701 return;
702 }
703
704 // Otherwise, this is target-dependent and based on the size and
705 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000706
707 // If the size of the ivar is not a power of two, give up. We don't
708 // want to get into the business of doing compare-and-swaps.
709 if (!IvarSize.isPowerOfTwo()) {
710 Kind = CopyStruct;
711 return;
712 }
713
John McCallf4528ae2011-09-13 03:34:09 +0000714 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000715 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000716
717 // Most architectures require memory to fit within a single cache
718 // line, so the alignment has to be at least the size of the access.
719 // Otherwise we have to grab a lock.
720 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
721 Kind = CopyStruct;
722 return;
723 }
724
725 // If the ivar's size exceeds the architecture's maximum atomic
726 // access size, we have to use CopyStruct.
727 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
728 Kind = CopyStruct;
729 return;
730 }
731
732 // Otherwise, we can use native loads and stores.
733 Kind = Native;
734}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000735
James Dennettbe302452012-06-15 22:10:14 +0000736/// \brief Generate an Objective-C property getter function.
737///
738/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000739/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000740void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
741 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000742 llvm::Constant *AtomicHelperFn =
743 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000744 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
745 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
746 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000747 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000748
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000749 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000750
751 FinishFunction();
752}
753
John McCallbdd81852011-09-13 06:00:03 +0000754static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
755 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000756 if (!getter) return true;
757
758 // Sema only makes only of these when the ivar has a C++ class type,
759 // so the form is pretty constrained.
760
John McCallbdd81852011-09-13 06:00:03 +0000761 // If the property has a reference type, we might just be binding a
762 // reference, in which case the result will be a gl-value. We should
763 // treat this as a non-trivial operation.
764 if (getter->isGLValue())
765 return false;
766
John McCallf4528ae2011-09-13 03:34:09 +0000767 // If we selected a trivial copy-constructor, we're okay.
768 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
769 return (construct->getConstructor()->isTrivial());
770
771 // The constructor might require cleanups (in which case it's never
772 // trivial).
773 assert(isa<ExprWithCleanups>(getter));
774 return false;
775}
776
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000777/// emitCPPObjectAtomicGetterCall - Call the runtime function to
778/// copy the ivar into the resturn slot.
779static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
780 llvm::Value *returnAddr,
781 ObjCIvarDecl *ivar,
782 llvm::Constant *AtomicHelperFn) {
783 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
784 // AtomicHelperFn);
785 CallArgList args;
786
787 // The 1st argument is the return Slot.
788 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
789
790 // The 2nd argument is the address of the ivar.
791 llvm::Value *ivarAddr =
792 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
793 CGF.LoadObjCSelf(), ivar, 0).getAddress();
794 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
795 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
796
797 // Third argument is the helper function.
798 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
799
800 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000801 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000802 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
803 args,
804 FunctionType::ExtInfo(),
805 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000806 copyCppAtomicObjectFn, ReturnValueSlot(), args);
807}
808
John McCallf4528ae2011-09-13 03:34:09 +0000809void
810CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000811 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000812 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000813 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000814 // If there's a non-trivial 'get' expression, we just have to emit that.
815 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000816 if (!AtomicHelperFn) {
817 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000818 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000819 EmitReturnStmt(ret);
820 }
821 else {
822 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
823 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
824 ivar, AtomicHelperFn);
825 }
John McCallf4528ae2011-09-13 03:34:09 +0000826 return;
827 }
828
829 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
830 QualType propType = prop->getType();
831 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
832
833 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
834
835 // Pick an implementation strategy.
836 PropertyImplStrategy strategy(CGM, propImpl);
837 switch (strategy.getKind()) {
838 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000839 // We don't need to do anything for a zero-size struct.
840 if (strategy.getIvarSize().isZero())
841 return;
842
John McCallf4528ae2011-09-13 03:34:09 +0000843 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
844
845 // Currently, all atomic accesses have to be through integer
846 // types, so there's no point in trying to pick a prettier type.
847 llvm::Type *bitcastType =
848 llvm::Type::getIntNTy(getLLVMContext(),
849 getContext().toBits(strategy.getIvarSize()));
850 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
851
852 // Perform an atomic load. This does not impose ordering constraints.
853 llvm::Value *ivarAddr = LV.getAddress();
854 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
855 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
856 load->setAlignment(strategy.getIvarAlignment().getQuantity());
857 load->setAtomic(llvm::Unordered);
858
859 // Store that value into the return address. Doing this with a
860 // bitcast is likely to produce some pretty ugly IR, but it's not
861 // the *most* terrible thing in the world.
862 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
863
864 // Make sure we don't do an autorelease.
865 AutoreleaseResult = false;
866 return;
867 }
868
869 case PropertyImplStrategy::GetSetProperty: {
870 llvm::Value *getPropertyFn =
871 CGM.getObjCRuntime().GetPropertyGetFunction();
872 if (!getPropertyFn) {
873 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000874 return;
875 }
876
877 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
878 // FIXME: Can't this be simpler? This might even be worse than the
879 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000880 llvm::Value *cmd =
881 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
882 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
883 llvm::Value *ivarOffset =
884 EmitIvarOffset(classImpl->getClassInterface(), ivar);
885
886 CallArgList args;
887 args.add(RValue::get(self), getContext().getObjCIdType());
888 args.add(RValue::get(cmd), getContext().getObjCSelType());
889 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000890 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
891 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000892
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000893 // FIXME: We shouldn't need to get the function info here, the
894 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000895 llvm::Instruction *CallInstruction;
John McCall8dda7b22012-07-07 06:41:13 +0000896 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
897 FunctionType::ExtInfo(),
898 RequiredArgs::All),
Craig Topper8a13c412014-05-21 05:09:00 +0000899 getPropertyFn, ReturnValueSlot(), args, nullptr,
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000900 &CallInstruction);
901 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
902 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000903
Daniel Dunbara08dff12008-09-24 04:04:31 +0000904 // We need to fix the type here. Ivars with copy & retain are
905 // always objects so we don't need to worry about complex or
906 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000907 RV = RValue::get(Builder.CreateBitCast(
908 RV.getScalarVal(),
909 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000910
911 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000912
913 // objc_getProperty does an autorelease, so we should suppress ours.
914 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000915
John McCallf4528ae2011-09-13 03:34:09 +0000916 return;
917 }
918
919 case PropertyImplStrategy::CopyStruct:
920 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
921 strategy.hasStrongMember());
922 return;
923
924 case PropertyImplStrategy::Expression:
925 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
926 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
927
928 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000929 switch (getEvaluationKind(ivarType)) {
930 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000931 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall47fb9502013-03-07 21:37:08 +0000932 EmitStoreOfComplex(pair,
933 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
934 /*init*/ true);
935 return;
936 }
937 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000938 // The return value slot is guaranteed to not be aliased, but
939 // that's not necessarily the same as "on the stack", so
940 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000941 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000942 return;
943 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000944 llvm::Value *value;
945 if (propType->isReferenceType()) {
946 value = LV.getAddress();
947 } else {
948 // We want to load and autoreleaseReturnValue ARC __weak ivars.
949 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000950 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000951
952 // Otherwise we want to do a simple load, suppressing the
953 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000954 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000955 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000956 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000957 }
John McCall31168b02011-06-15 23:02:42 +0000958
John McCall24fada12011-07-22 05:23:13 +0000959 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +0000960 value = Builder.CreateBitCast(
961 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +0000962 }
963
964 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000965 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000966 }
John McCall47fb9502013-03-07 21:37:08 +0000967 }
968 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000969 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000970
John McCallf4528ae2011-09-13 03:34:09 +0000971 }
972 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000973}
974
John McCallb923ece2011-09-12 23:06:44 +0000975/// emitStructSetterCall - Call the runtime function to store the value
976/// from the first formal parameter into the given ivar.
977static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
978 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000979 // objc_copyStruct (&structIvar, &Arg,
980 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000981 CallArgList args;
982
983 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000984 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
985 CGF.LoadObjCSelf(), ivar, 0)
986 .getAddress();
987 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
988 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000989
990 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000991 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000992 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000993 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000994 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
995 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
996 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000997
998 // The third argument is the sizeof the type.
999 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001000 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1001 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001002
John McCallb923ece2011-09-12 23:06:44 +00001003 // The fourth argument is the 'isAtomic' flag.
1004 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001005
John McCallb923ece2011-09-12 23:06:44 +00001006 // The fifth argument is the 'hasStrong' flag.
1007 // FIXME: should this really always be false?
1008 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1009
1010 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001011 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1012 args,
1013 FunctionType::ExtInfo(),
1014 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001015 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001016}
1017
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001018/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1019/// the value from the first formal parameter into the given ivar, using
1020/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1021static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1022 ObjCMethodDecl *OMD,
1023 ObjCIvarDecl *ivar,
1024 llvm::Constant *AtomicHelperFn) {
1025 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1026 // AtomicHelperFn);
1027 CallArgList args;
1028
1029 // The first argument is the address of the ivar.
1030 llvm::Value *ivarAddr =
1031 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1032 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1033 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1034 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1035
1036 // The second argument is the address of the parameter variable.
1037 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001038 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001039 VK_LValue, SourceLocation());
1040 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1041 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1042 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1043
1044 // Third argument is the helper function.
1045 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1046
1047 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001048 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001049 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1050 args,
1051 FunctionType::ExtInfo(),
1052 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001053 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001054}
1055
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001056
John McCallf4528ae2011-09-13 03:34:09 +00001057static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1058 Expr *setter = PID->getSetterCXXAssignment();
1059 if (!setter) return true;
1060
1061 // Sema only makes only of these when the ivar has a C++ class type,
1062 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001063
1064 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001065 // This also implies that there's nothing non-trivial going on with
1066 // the arguments, because operator= can only be trivial if it's a
1067 // synthesized assignment operator and therefore both parameters are
1068 // references.
1069 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001070 if (const FunctionDecl *callee
1071 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1072 if (callee->isTrivial())
1073 return true;
1074 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001075 }
John McCall7f16c422011-09-10 09:17:20 +00001076
John McCallf4528ae2011-09-13 03:34:09 +00001077 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001078 return false;
1079}
1080
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001081static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001082 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001083 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001084 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001085}
1086
John McCall7f16c422011-09-10 09:17:20 +00001087void
1088CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001089 const ObjCPropertyImplDecl *propImpl,
1090 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001091 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001092 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001093 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001094
1095 // Just use the setter expression if Sema gave us one and it's
1096 // non-trivial.
1097 if (!hasTrivialSetExpr(propImpl)) {
1098 if (!AtomicHelperFn)
1099 // If non-atomic, assignment is called directly.
1100 EmitStmt(propImpl->getSetterCXXAssignment());
1101 else
1102 // If atomic, assignment is called via a locking api.
1103 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1104 AtomicHelperFn);
1105 return;
1106 }
John McCall7f16c422011-09-10 09:17:20 +00001107
John McCallf4528ae2011-09-13 03:34:09 +00001108 PropertyImplStrategy strategy(CGM, propImpl);
1109 switch (strategy.getKind()) {
1110 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001111 // We don't need to do anything for a zero-size struct.
1112 if (strategy.getIvarSize().isZero())
1113 return;
1114
John McCallf4528ae2011-09-13 03:34:09 +00001115 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +00001116
John McCallf4528ae2011-09-13 03:34:09 +00001117 LValue ivarLValue =
1118 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1119 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001120
John McCallf4528ae2011-09-13 03:34:09 +00001121 // Currently, all atomic accesses have to be through integer
1122 // types, so there's no point in trying to pick a prettier type.
1123 llvm::Type *bitcastType =
1124 llvm::Type::getIntNTy(getLLVMContext(),
1125 getContext().toBits(strategy.getIvarSize()));
1126 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1127
1128 // Cast both arguments to the chosen operation type.
1129 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1130 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1131
1132 // This bitcast load is likely to cause some nasty IR.
1133 llvm::Value *load = Builder.CreateLoad(argAddr);
1134
1135 // Perform an atomic store. There are no memory ordering requirements.
1136 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1137 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1138 store->setAtomic(llvm::Unordered);
1139 return;
1140 }
1141
1142 case PropertyImplStrategy::GetSetProperty:
1143 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001144
1145 llvm::Value *setOptimizedPropertyFn = nullptr;
1146 llvm::Value *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001147 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001148 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001149 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001150 CGM.getObjCRuntime()
1151 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1152 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001153 if (!setOptimizedPropertyFn) {
1154 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1155 return;
1156 }
John McCall7f16c422011-09-10 09:17:20 +00001157 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001158 else {
1159 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1160 if (!setPropertyFn) {
1161 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1162 return;
1163 }
1164 }
1165
John McCall7f16c422011-09-10 09:17:20 +00001166 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1167 // <is-atomic>, <is-copy>).
1168 llvm::Value *cmd =
1169 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1170 llvm::Value *self =
1171 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1172 llvm::Value *ivarOffset =
1173 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1174 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1175 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1176
1177 CallArgList args;
1178 args.add(RValue::get(self), getContext().getObjCIdType());
1179 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001180 if (setOptimizedPropertyFn) {
1181 args.add(RValue::get(arg), getContext().getObjCIdType());
1182 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001183 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1184 FunctionType::ExtInfo(),
1185 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001186 setOptimizedPropertyFn, ReturnValueSlot(), args);
1187 } else {
1188 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1189 args.add(RValue::get(arg), getContext().getObjCIdType());
1190 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1191 getContext().BoolTy);
1192 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1193 getContext().BoolTy);
1194 // FIXME: We shouldn't need to get the function info here, the runtime
1195 // already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001196 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1197 FunctionType::ExtInfo(),
1198 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001199 setPropertyFn, ReturnValueSlot(), args);
1200 }
1201
John McCall7f16c422011-09-10 09:17:20 +00001202 return;
1203 }
1204
John McCallf4528ae2011-09-13 03:34:09 +00001205 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001206 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001207 return;
John McCallf4528ae2011-09-13 03:34:09 +00001208
1209 case PropertyImplStrategy::Expression:
1210 break;
John McCall7f16c422011-09-10 09:17:20 +00001211 }
1212
1213 // Otherwise, fake up some ASTs and emit a normal assignment.
1214 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001215 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1216 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001217 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1218 selfDecl->getType(), CK_LValueToRValue, &self,
1219 VK_RValue);
1220 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001221 SourceLocation(), SourceLocation(),
1222 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001223
1224 ParmVarDecl *argDecl = *setterMethod->param_begin();
1225 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001226 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001227 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1228 argType.getUnqualifiedType(), CK_LValueToRValue,
1229 &arg, VK_RValue);
1230
1231 // The property type can differ from the ivar type in some situations with
1232 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1233 // The following absurdity is just to ensure well-formed IR.
1234 CastKind argCK = CK_NoOp;
1235 if (ivarRef.getType()->isObjCObjectPointerType()) {
1236 if (argLoad.getType()->isObjCObjectPointerType())
1237 argCK = CK_BitCast;
1238 else if (argLoad.getType()->isBlockPointerType())
1239 argCK = CK_BlockPointerToObjCPointerCast;
1240 else
1241 argCK = CK_CPointerToObjCPointerCast;
1242 } else if (ivarRef.getType()->isBlockPointerType()) {
1243 if (argLoad.getType()->isBlockPointerType())
1244 argCK = CK_BitCast;
1245 else
1246 argCK = CK_AnyPointerToBlockPointerCast;
1247 } else if (ivarRef.getType()->isPointerType()) {
1248 argCK = CK_BitCast;
1249 }
1250 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1251 ivarRef.getType(), argCK, &argLoad,
1252 VK_RValue);
1253 Expr *finalArg = &argLoad;
1254 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1255 argLoad.getType()))
1256 finalArg = &argCast;
1257
1258
1259 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1260 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001261 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001262 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001263}
1264
James Dennettbe302452012-06-15 22:10:14 +00001265/// \brief Generate an Objective-C property setter function.
1266///
1267/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001268/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001269void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1270 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001271 llvm::Constant *AtomicHelperFn =
1272 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001273 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1274 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1275 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001276 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001277
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001278 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001279
1280 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001281}
1282
John McCall6a4fa522011-03-22 07:05:39 +00001283namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001284 struct DestroyIvar : EHScopeStack::Cleanup {
1285 private:
1286 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001287 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001288 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001289 bool useEHCleanupForArray;
1290 public:
1291 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1292 CodeGenFunction::Destroyer *destroyer,
1293 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001294 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001295 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001296
Craig Topper4f12f102014-03-12 06:41:41 +00001297 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001298 LValue lvalue
1299 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1300 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001301 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001302 }
1303 };
1304}
1305
John McCall4bd0fb12011-07-12 16:41:08 +00001306/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1307static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1308 llvm::Value *addr,
1309 QualType type) {
1310 llvm::Value *null = getNullForVariable(addr);
1311 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1312}
John McCall31168b02011-06-15 23:02:42 +00001313
John McCall6a4fa522011-03-22 07:05:39 +00001314static void emitCXXDestructMethod(CodeGenFunction &CGF,
1315 ObjCImplementationDecl *impl) {
1316 CodeGenFunction::RunCleanupsScope scope(CGF);
1317
1318 llvm::Value *self = CGF.LoadObjCSelf();
1319
Jordy Rosea91768e2011-07-22 02:08:32 +00001320 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1321 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001322 ivar; ivar = ivar->getNextIvar()) {
1323 QualType type = ivar->getType();
1324
John McCall6a4fa522011-03-22 07:05:39 +00001325 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001326 QualType::DestructionKind dtorKind = type.isDestructedType();
1327 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001328
Craig Topper8a13c412014-05-21 05:09:00 +00001329 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001330
John McCall4bd0fb12011-07-12 16:41:08 +00001331 // Use a call to objc_storeStrong to destroy strong ivars, for the
1332 // general benefit of the tools.
1333 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001334 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001335
John McCall4bd0fb12011-07-12 16:41:08 +00001336 // Otherwise use the default for the destruction kind.
1337 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001338 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001339 }
John McCall4bd0fb12011-07-12 16:41:08 +00001340
1341 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1342
1343 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1344 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001345 }
1346
1347 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1348}
1349
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001350void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1351 ObjCMethodDecl *MD,
1352 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001353 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001354 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001355
1356 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001357 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001358 // Suppress the final autorelease in ARC.
1359 AutoreleaseResult = false;
1360
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001361 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001362 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001363 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001364 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1365 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001366 EmitAggExpr(IvarInit->getInit(),
1367 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001368 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001369 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001370 }
1371 // constructor returns 'self'.
1372 CodeGenTypes &Types = CGM.getTypes();
1373 QualType IdTy(CGM.getContext().getObjCIdType());
1374 llvm::Value *SelfAsId =
1375 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1376 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001377
1378 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001379 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001380 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001381 }
1382 FinishFunction();
1383}
1384
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001385bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1386 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1387 it++; it++;
1388 const ABIArgInfo &AI = it->info;
1389 // FIXME. Is this sufficient check?
1390 return (AI.getKind() == ABIArgInfo::Indirect);
1391}
1392
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001393bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001394 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001395 return false;
1396 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1397 return FDTTy->getDecl()->hasObjectMember();
1398 return false;
1399}
1400
Daniel Dunbara08dff12008-09-24 04:04:31 +00001401llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001402 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1403 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1404 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001405 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001406}
1407
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001408QualType CodeGenFunction::TypeOfSelfObject() {
1409 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1410 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001411 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1412 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001413 return PTy->getPointeeType();
1414}
1415
Chris Lattnerd4808922009-03-22 21:03:39 +00001416void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001417 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001418 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001419
Daniel Dunbara08dff12008-09-24 04:04:31 +00001420 if (!EnumerationMutationFn) {
1421 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1422 return;
1423 }
1424
Devang Pateld2d66652011-01-19 01:36:36 +00001425 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001426 if (DI)
1427 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001428
Devang Patel297207f2011-06-13 23:15:32 +00001429 // The local variable comes into scope immediately.
1430 AutoVarEmission variable = AutoVarEmission::invalid();
1431 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1432 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1433
John McCall1c926b72011-01-07 01:49:06 +00001434 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001435
Anders Carlsson75658592008-08-31 02:33:12 +00001436 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001437 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001438 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001439 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001440
Anders Carlsson75658592008-08-31 02:33:12 +00001441 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001442 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001443
John McCall1c926b72011-01-07 01:49:06 +00001444 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001445 IdentifierInfo *II[] = {
1446 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1447 &CGM.getContext().Idents.get("objects"),
1448 &CGM.getContext().Idents.get("count")
1449 };
1450 Selector FastEnumSel =
1451 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001452
1453 QualType ItemsTy =
1454 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001455 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001456 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001457 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001458
John McCall53848232011-07-27 01:07:15 +00001459 // Emit the collection pointer. In ARC, we do a retain.
1460 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001461 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001462 Collection = EmitARCRetainScalarExpr(S.getCollection());
1463
1464 // Enter a cleanup to do the release.
1465 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1466 } else {
1467 Collection = EmitScalarExpr(S.getCollection());
1468 }
Mike Stump11289f42009-09-09 15:08:12 +00001469
John McCall91e82dd2011-08-05 00:14:38 +00001470 // The 'continue' label needs to appear within the cleanup for the
1471 // collection object.
1472 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1473
John McCall1c926b72011-01-07 01:49:06 +00001474 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001475 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001476
1477 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001478 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001479
John McCall1c926b72011-01-07 01:49:06 +00001480 // The second argument is a temporary array with space for NumItems
1481 // pointers. We'll actually be loading elements from the array
1482 // pointer written into the control state; this buffer is so that
1483 // collections that *aren't* backed by arrays can still queue up
1484 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001485 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001486
John McCall1c926b72011-01-07 01:49:06 +00001487 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001488 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001489 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001490 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001491
John McCall1c926b72011-01-07 01:49:06 +00001492 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001493 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001494 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001495 getContext().UnsignedLongTy,
1496 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001497 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001498
John McCall1c926b72011-01-07 01:49:06 +00001499 // The initial number of objects that were returned in the buffer.
1500 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001501
John McCall1c926b72011-01-07 01:49:06 +00001502 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1503 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001504
John McCall1c926b72011-01-07 01:49:06 +00001505 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001506
John McCall1c926b72011-01-07 01:49:06 +00001507 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001508 // empty; skip all this. Set the branch weight assuming this has the same
1509 // probability of exiting the loop as any other loop exit.
1510 uint64_t EntryCount = PGO.getCurrentRegionCount();
1511 RegionCounter Cnt = getPGORegionCounter(&S);
John McCall1c926b72011-01-07 01:49:06 +00001512 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001513 EmptyBB, LoopInitBB,
1514 PGO.createBranchWeights(EntryCount, Cnt.getCount()));
Anders Carlsson75658592008-08-31 02:33:12 +00001515
John McCall1c926b72011-01-07 01:49:06 +00001516 // Otherwise, initialize the loop.
1517 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCall1c926b72011-01-07 01:49:06 +00001519 // Save the initial mutations value. This is the value at an
1520 // address that was written into the state object by
1521 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001522 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001523 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001524 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001525 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001526
John McCall1c926b72011-01-07 01:49:06 +00001527 llvm::Value *initialMutations =
1528 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall1c926b72011-01-07 01:49:06 +00001530 // Start looping. This is the point we return to whenever we have a
1531 // fresh, non-empty batch of objects.
1532 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1533 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001534
John McCall1c926b72011-01-07 01:49:06 +00001535 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001536 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001537 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001538
John McCall1c926b72011-01-07 01:49:06 +00001539 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001540 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001541 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001542
Bob Wilson8ab16912014-02-24 01:13:09 +00001543 Cnt.beginRegion(Builder);
1544
John McCall1c926b72011-01-07 01:49:06 +00001545 // Check whether the mutations value has changed from where it was
1546 // at start. StateMutationsPtr should actually be invariant between
1547 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001548 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001549 llvm::Value *currentMutations
1550 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001551
John McCall1c926b72011-01-07 01:49:06 +00001552 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001553 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001554
John McCall1c926b72011-01-07 01:49:06 +00001555 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1556 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001557
John McCall1c926b72011-01-07 01:49:06 +00001558 // If so, call the enumeration-mutation function.
1559 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001560 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001561 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001562 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001563 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001564 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001565 // FIXME: We shouldn't need to get the function info here, the runtime already
1566 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001567 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1568 FunctionType::ExtInfo(),
1569 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001570 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001571
John McCall1c926b72011-01-07 01:49:06 +00001572 // Otherwise, or if the mutation function returns, just continue.
1573 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001574
John McCall1c926b72011-01-07 01:49:06 +00001575 // Initialize the element variable.
1576 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001577 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001578 LValue elementLValue;
1579 QualType elementType;
1580 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001581 // Initialize the variable, in case it's a __block variable or something.
1582 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001583
John McCall9e2e22f2011-02-22 07:16:58 +00001584 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001585 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001586 VK_LValue, SourceLocation());
1587 elementLValue = EmitLValue(&tempDRE);
1588 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001589 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001590
1591 if (D->isARCPseudoStrong())
1592 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001593 } else {
1594 elementLValue = LValue(); // suppress warning
1595 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001596 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001597 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001598 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001599
1600 // Fetch the buffer out of the enumeration state.
1601 // TODO: this pointer should actually be invariant between
1602 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001603 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001604 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001605 llvm::Value *EnumStateItems =
1606 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001607
John McCall1c926b72011-01-07 01:49:06 +00001608 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001609 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001610 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1611 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001612
John McCall1c926b72011-01-07 01:49:06 +00001613 // Cast that value to the right type.
1614 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1615 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001616
John McCall1c926b72011-01-07 01:49:06 +00001617 // Make sure we have an l-value. Yes, this gets evaluated every
1618 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001619 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001620 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001621 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001622 } else {
1623 EmitScalarInit(CurrentItem, elementLValue);
1624 }
Mike Stump11289f42009-09-09 15:08:12 +00001625
John McCall9e2e22f2011-02-22 07:16:58 +00001626 // If we do have an element variable, this assignment is the end of
1627 // its initialization.
1628 if (elementIsVariable)
1629 EmitAutoVarCleanups(variable);
1630
John McCall1c926b72011-01-07 01:49:06 +00001631 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001632 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001633 {
1634 RunCleanupsScope Scope(*this);
1635 EmitStmt(S.getBody());
1636 }
Anders Carlsson75658592008-08-31 02:33:12 +00001637 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001638
John McCall1c926b72011-01-07 01:49:06 +00001639 // Destroy the element variable now.
1640 elementVariableScope.ForceCleanup();
1641
1642 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001643 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001644
John McCall1c926b72011-01-07 01:49:06 +00001645 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001646
John McCall1c926b72011-01-07 01:49:06 +00001647 // First we check in the local buffer.
1648 llvm::Value *indexPlusOne
1649 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001650
John McCall1c926b72011-01-07 01:49:06 +00001651 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001652 // Set the branch weights based on the simplifying assumption that this is
1653 // like a while-loop, i.e., ignoring that the false branch fetches more
1654 // elements and then returns to the loop.
John McCall1c926b72011-01-07 01:49:06 +00001655 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001656 LoopBodyBB, FetchMoreBB,
1657 PGO.createBranchWeights(Cnt.getCount(), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001658
1659 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1660 count->addIncoming(count, AfterBody.getBlock());
1661
1662 // Otherwise, we have to fetch more elements.
1663 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001664
1665 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001666 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001667 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001668 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001669 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001670
John McCall1c926b72011-01-07 01:49:06 +00001671 // If we got a zero count, we're done.
1672 llvm::Value *refetchCount = CountRV.getScalarVal();
1673
1674 // (note that the message send might split FetchMoreBB)
1675 index->addIncoming(zero, Builder.GetInsertBlock());
1676 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1677
1678 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1679 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Anders Carlsson75658592008-08-31 02:33:12 +00001681 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001682 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001683
John McCall9e2e22f2011-02-22 07:16:58 +00001684 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001685 // If the element was not a declaration, set it to be null.
1686
John McCall1c926b72011-01-07 01:49:06 +00001687 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1688 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001689 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001690 }
1691
Eric Christopher7cdf9482011-10-13 21:45:18 +00001692 if (DI)
1693 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001694
John McCall53848232011-07-27 01:07:15 +00001695 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001696 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001697 PopCleanupBlock();
1698
John McCallad5d61e2010-07-23 21:56:41 +00001699 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001700}
1701
Mike Stump11289f42009-09-09 15:08:12 +00001702void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001703 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001704}
1705
Mike Stump11289f42009-09-09 15:08:12 +00001706void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001707 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1708}
1709
Chris Lattnere132e242008-11-15 21:26:17 +00001710void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001711 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001712 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001713}
1714
John McCall2d637d22011-09-10 06:18:15 +00001715/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001716/// primitive retain.
1717llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1718 llvm::Value *value) {
1719 return EmitARCRetain(type, value);
1720}
1721
1722namespace {
1723 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001724 CallObjCRelease(llvm::Value *object) : object(object) {}
1725 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001726
Craig Topper4f12f102014-03-12 06:41:41 +00001727 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001728 // Releases at the end of the full-expression are imprecise.
1729 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001730 }
1731 };
1732}
1733
John McCall2d637d22011-09-10 06:18:15 +00001734/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001735/// release at the end of the full-expression.
1736llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1737 llvm::Value *object) {
1738 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001739 // conditional.
1740 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001741 return object;
1742}
1743
1744llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1745 llvm::Value *value) {
1746 return EmitARCRetainAutorelease(type, value);
1747}
1748
John McCalleff18842013-03-23 02:35:54 +00001749/// Given a number of pointers, inform the optimizer that they're
1750/// being intrinsically used up until this point in the program.
1751void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1752 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1753 if (!fn) {
1754 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001755 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001756 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1757 }
1758
1759 // This isn't really a "runtime" function, but as an intrinsic it
1760 // doesn't really matter as long as we align things up.
1761 EmitNounwindRuntimeCall(fn, values);
1762}
1763
John McCall31168b02011-06-15 23:02:42 +00001764
1765static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001766 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001767 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001768 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1769
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001770 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001771 // If the target runtime doesn't naturally support ARC, emit weak
1772 // references to the runtime support library. We don't really
1773 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001774 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001775 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001776 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1777 // If we have Native ARC, set nonlazybind attribute for these APIs for
1778 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001779 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001780 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001781 }
John McCall31168b02011-06-15 23:02:42 +00001782
1783 return fn;
1784}
1785
1786/// Perform an operation having the signature
1787/// i8* (i8*)
1788/// where a null input causes a no-op and returns null.
1789static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1790 llvm::Value *value,
1791 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001792 StringRef fnName,
1793 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001794 if (isa<llvm::ConstantPointerNull>(value)) return value;
1795
1796 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001797 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001798 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001799 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1800 }
1801
1802 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001803 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001804 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1805
1806 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001807 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001808 if (isTailCall)
1809 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001810
1811 // Cast the result back to the original type.
1812 return CGF.Builder.CreateBitCast(call, origType);
1813}
1814
1815/// Perform an operation having the following signature:
1816/// i8* (i8**)
1817static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1818 llvm::Value *addr,
1819 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001820 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001821 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001822 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001823 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001824 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1825 }
1826
1827 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001828 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001829 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1830
1831 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001832 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00001833
1834 // Cast the result back to a dereference of the original type.
John McCall31168b02011-06-15 23:02:42 +00001835 if (origType != CGF.Int8PtrPtrTy)
1836 result = CGF.Builder.CreateBitCast(result,
1837 cast<llvm::PointerType>(origType)->getElementType());
1838
1839 return result;
1840}
1841
1842/// Perform an operation having the following signature:
1843/// i8* (i8**, i8*)
1844static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1845 llvm::Value *addr,
1846 llvm::Value *value,
1847 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001848 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001849 bool ignored) {
1850 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1851 == value->getType());
1852
1853 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001854 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001855
Chris Lattner2192fe52011-07-18 04:24:23 +00001856 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001857 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1858 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1859 }
1860
Chris Lattner2192fe52011-07-18 04:24:23 +00001861 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001862
John McCall882987f2013-02-28 19:01:20 +00001863 llvm::Value *args[] = {
1864 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1865 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1866 };
1867 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001868
Craig Topper8a13c412014-05-21 05:09:00 +00001869 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001870
1871 return CGF.Builder.CreateBitCast(result, origType);
1872}
1873
1874/// Perform an operation having the following signature:
1875/// void (i8**, i8**)
1876static void emitARCCopyOperation(CodeGenFunction &CGF,
1877 llvm::Value *dst,
1878 llvm::Value *src,
1879 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001880 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001881 assert(dst->getType() == src->getType());
1882
1883 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001884 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1885
Chris Lattner2192fe52011-07-18 04:24:23 +00001886 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001887 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1888 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1889 }
1890
John McCall882987f2013-02-28 19:01:20 +00001891 llvm::Value *args[] = {
1892 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1893 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1894 };
1895 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001896}
1897
1898/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001899/// call i8* \@objc_retain(i8* %value)
1900/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001901llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1902 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001903 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001904 else
1905 return EmitARCRetainNonBlock(value);
1906}
1907
1908/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001909/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001910llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1911 return emitARCValueOperation(*this, value,
1912 CGM.getARCEntrypoints().objc_retain,
1913 "objc_retain");
1914}
1915
1916/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001917/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001918///
1919/// \param mandatory - If false, emit the call with metadata
1920/// indicating that it's okay for the optimizer to eliminate this call
1921/// if it can prove that the block never escapes except down the stack.
1922llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1923 bool mandatory) {
1924 llvm::Value *result
1925 = emitARCValueOperation(*this, value,
1926 CGM.getARCEntrypoints().objc_retainBlock,
1927 "objc_retainBlock");
1928
1929 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1930 // tell the optimizer that it doesn't need to do this copy if the
1931 // block doesn't escape, where being passed as an argument doesn't
1932 // count as escaping.
1933 if (!mandatory && isa<llvm::Instruction>(result)) {
1934 llvm::CallInst *call
1935 = cast<llvm::CallInst>(result->stripPointerCasts());
1936 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1937
John McCallff613032011-10-04 06:23:45 +00001938 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001939 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00001940 }
1941
1942 return result;
John McCall31168b02011-06-15 23:02:42 +00001943}
1944
1945/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001946/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001947///
1948/// Yes, this function name is one character away from a different
1949/// call with completely different semantics.
1950llvm::Value *
1951CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1952 // Fetch the void(void) inline asm which marks that we're going to
1953 // retain the autoreleased return value.
1954 llvm::InlineAsm *&marker
1955 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1956 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001957 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001958 = CGM.getTargetCodeGenInfo()
1959 .getARCRetainAutoreleasedReturnValueMarker();
1960
1961 // If we have an empty assembly string, there's nothing to do.
1962 if (assembly.empty()) {
1963
1964 // Otherwise, at -O0, build an inline asm that we're going to call
1965 // in a moment.
1966 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1967 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001968 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001969
1970 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1971
1972 // If we're at -O1 and above, we don't want to litter the code
1973 // with this marker yet, so leave a breadcrumb for the ARC
1974 // optimizer to pick up.
1975 } else {
1976 llvm::NamedMDNode *metadata =
1977 CGM.getModule().getOrInsertNamedMetadata(
1978 "clang.arc.retainAutoreleasedReturnValueMarker");
1979 assert(metadata->getNumOperands() <= 1);
1980 if (metadata->getNumOperands() == 0) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001981 metadata->addOperand(llvm::MDNode::get(
1982 getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
John McCall31168b02011-06-15 23:02:42 +00001983 }
1984 }
1985 }
1986
1987 // Call the marker asm if we made one, which we do only at -O0.
1988 if (marker) Builder.CreateCall(marker);
1989
1990 return emitARCValueOperation(*this, value,
1991 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1992 "objc_retainAutoreleasedReturnValue");
1993}
1994
1995/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00001996/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00001997void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1998 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00001999 if (isa<llvm::ConstantPointerNull>(value)) return;
2000
2001 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2002 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002003 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002004 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002005 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2006 }
2007
2008 // Cast the argument to 'id'.
2009 value = Builder.CreateBitCast(value, Int8PtrTy);
2010
2011 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002012 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002013
John McCallcdda29c2013-03-13 03:10:54 +00002014 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002015 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002016 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002017 }
2018}
2019
John McCalle68b8f42012-10-17 02:28:37 +00002020/// Destroy a __strong variable.
2021///
2022/// At -O0, emit a call to store 'null' into the address;
2023/// instrumenting tools prefer this because the address is exposed,
2024/// but it's relatively cumbersome to optimize.
2025///
2026/// At -O1 and above, just load and call objc_release.
2027///
2028/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCallcdda29c2013-03-13 03:10:54 +00002029void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2030 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002031 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2032 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2033 llvm::Value *null = llvm::ConstantPointerNull::get(
2034 cast<llvm::PointerType>(addrTy->getElementType()));
2035 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2036 return;
2037 }
2038
2039 llvm::Value *value = Builder.CreateLoad(addr);
2040 EmitARCRelease(value, precise);
2041}
2042
John McCall31168b02011-06-15 23:02:42 +00002043/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002044/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002045llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2046 llvm::Value *value,
2047 bool ignored) {
2048 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2049 == value->getType());
2050
2051 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2052 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002053 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002054 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002055 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2056 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2057 }
2058
John McCall882987f2013-02-28 19:01:20 +00002059 llvm::Value *args[] = {
2060 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2061 Builder.CreateBitCast(value, Int8PtrTy)
2062 };
2063 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002064
Craig Topper8a13c412014-05-21 05:09:00 +00002065 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002066 return value;
2067}
2068
2069/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002070/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002071/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002072llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002073 llvm::Value *newValue,
2074 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002075 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002076 bool isBlock = type->isBlockPointerType();
2077
2078 // Use a store barrier at -O0 unless this is a block type or the
2079 // lvalue is inadequately aligned.
2080 if (shouldUseFusedARCCalls() &&
2081 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002082 (dst.getAlignment().isZero() ||
2083 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002084 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2085 }
2086
2087 // Otherwise, split it out.
2088
2089 // Retain the new value.
2090 newValue = EmitARCRetain(type, newValue);
2091
2092 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002093 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002094
2095 // Store. We do this before the release so that any deallocs won't
2096 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002097 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002098
2099 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002100 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002101
2102 return newValue;
2103}
2104
2105/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002106/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002107llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2108 return emitARCValueOperation(*this, value,
2109 CGM.getARCEntrypoints().objc_autorelease,
2110 "objc_autorelease");
2111}
2112
2113/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002114/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002115llvm::Value *
2116CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2117 return emitARCValueOperation(*this, value,
2118 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002119 "objc_autoreleaseReturnValue",
2120 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002121}
2122
2123/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002124/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002125llvm::Value *
2126CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2127 return emitARCValueOperation(*this, value,
2128 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002129 "objc_retainAutoreleaseReturnValue",
2130 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002131}
2132
2133/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002134/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002135/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002136/// %retain = call i8* \@objc_retainBlock(i8* %value)
2137/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002138llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2139 llvm::Value *value) {
2140 if (!type->isBlockPointerType())
2141 return EmitARCRetainAutoreleaseNonBlock(value);
2142
2143 if (isa<llvm::ConstantPointerNull>(value)) return value;
2144
Chris Lattner2192fe52011-07-18 04:24:23 +00002145 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002146 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002147 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002148 value = EmitARCAutorelease(value);
2149 return Builder.CreateBitCast(value, origType);
2150}
2151
2152/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002153/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002154llvm::Value *
2155CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2156 return emitARCValueOperation(*this, value,
2157 CGM.getARCEntrypoints().objc_retainAutorelease,
2158 "objc_retainAutorelease");
2159}
2160
James Dennett14c41ea2012-06-22 05:41:30 +00002161/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002162/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2163llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2164 return emitARCLoadOperation(*this, addr,
2165 CGM.getARCEntrypoints().objc_loadWeak,
2166 "objc_loadWeak");
2167}
2168
James Dennett14c41ea2012-06-22 05:41:30 +00002169/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002170llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2171 return emitARCLoadOperation(*this, addr,
2172 CGM.getARCEntrypoints().objc_loadWeakRetained,
2173 "objc_loadWeakRetained");
2174}
2175
James Dennett14c41ea2012-06-22 05:41:30 +00002176/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002177/// Returns %value.
2178llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2179 llvm::Value *value,
2180 bool ignored) {
2181 return emitARCStoreOperation(*this, addr, value,
2182 CGM.getARCEntrypoints().objc_storeWeak,
2183 "objc_storeWeak", ignored);
2184}
2185
James Dennett14c41ea2012-06-22 05:41:30 +00002186/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002187/// Returns %value. %addr is known to not have a current weak entry.
2188/// Essentially equivalent to:
2189/// *addr = nil; objc_storeWeak(addr, value);
2190void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2191 // If we're initializing to null, just write null to memory; no need
2192 // to get the runtime involved. But don't do this if optimization
2193 // is enabled, because accounting for this would make the optimizer
2194 // much more complicated.
2195 if (isa<llvm::ConstantPointerNull>(value) &&
2196 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2197 Builder.CreateStore(value, addr);
2198 return;
2199 }
2200
2201 emitARCStoreOperation(*this, addr, value,
2202 CGM.getARCEntrypoints().objc_initWeak,
2203 "objc_initWeak", /*ignored*/ true);
2204}
2205
James Dennett14c41ea2012-06-22 05:41:30 +00002206/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002207/// Essentially objc_storeWeak(addr, nil).
2208void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2209 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2210 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002211 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002212 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002213 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2214 }
2215
2216 // Cast the argument to 'id*'.
2217 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2218
John McCall882987f2013-02-28 19:01:20 +00002219 EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00002220}
2221
James Dennett14c41ea2012-06-22 05:41:30 +00002222/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002223/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2224/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2225void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2226 emitARCCopyOperation(*this, dst, src,
2227 CGM.getARCEntrypoints().objc_moveWeak,
2228 "objc_moveWeak");
2229}
2230
James Dennett14c41ea2012-06-22 05:41:30 +00002231/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002232/// Disregards the current value in %dest. Essentially
2233/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2234void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2235 emitARCCopyOperation(*this, dst, src,
2236 CGM.getARCEntrypoints().objc_copyWeak,
2237 "objc_copyWeak");
2238}
2239
2240/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002241/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002242llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2243 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2244 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002245 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002246 llvm::FunctionType::get(Int8PtrTy, false);
2247 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2248 }
2249
John McCall882987f2013-02-28 19:01:20 +00002250 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002251}
2252
2253/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002254/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002255void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2256 assert(value->getType() == Int8PtrTy);
2257
2258 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2259 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002260 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002261 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002262
2263 // We don't want to use a weak import here; instead we should not
2264 // fall into this path.
2265 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2266 }
2267
John McCallb7ff6db2013-04-16 21:29:40 +00002268 // objc_autoreleasePoolPop can throw.
2269 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002270}
2271
2272/// Produce the code to do an MRR version objc_autoreleasepool_push.
2273/// Which is: [[NSAutoreleasePool alloc] init];
2274/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2275/// init is declared as: - (id) init; in its NSObject super class.
2276///
2277llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2278 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002279 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002280 // [NSAutoreleasePool alloc]
2281 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2282 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2283 CallArgList Args;
2284 RValue AllocRV =
2285 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2286 getContext().getObjCIdType(),
2287 AllocSel, Receiver, Args);
2288
2289 // [Receiver init]
2290 Receiver = AllocRV.getScalarVal();
2291 II = &CGM.getContext().Idents.get("init");
2292 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2293 RValue InitRV =
2294 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2295 getContext().getObjCIdType(),
2296 InitSel, Receiver, Args);
2297 return InitRV.getScalarVal();
2298}
2299
2300/// Produce the code to do a primitive release.
2301/// [tmp drain];
2302void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2303 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2304 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2305 CallArgList Args;
2306 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2307 getContext().VoidTy, DrainSel, Arg, Args);
2308}
2309
John McCall82fe67b2011-07-09 01:37:26 +00002310void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2311 llvm::Value *addr,
2312 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002313 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002314}
2315
2316void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2317 llvm::Value *addr,
2318 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002319 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002320}
2321
2322void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2323 llvm::Value *addr,
2324 QualType type) {
2325 CGF.EmitARCDestroyWeak(addr);
2326}
2327
John McCall31168b02011-06-15 23:02:42 +00002328namespace {
John McCall31168b02011-06-15 23:02:42 +00002329 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2330 llvm::Value *Token;
2331
2332 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2333
Craig Topper4f12f102014-03-12 06:41:41 +00002334 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002335 CGF.EmitObjCAutoreleasePoolPop(Token);
2336 }
2337 };
2338 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2339 llvm::Value *Token;
2340
2341 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2342
Craig Topper4f12f102014-03-12 06:41:41 +00002343 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002344 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2345 }
2346 };
2347}
2348
2349void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002351 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2352 else
2353 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2354}
2355
John McCall31168b02011-06-15 23:02:42 +00002356static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2357 LValue lvalue,
2358 QualType type) {
2359 switch (type.getObjCLifetime()) {
2360 case Qualifiers::OCL_None:
2361 case Qualifiers::OCL_ExplicitNone:
2362 case Qualifiers::OCL_Strong:
2363 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002364 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2365 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002366 false);
2367
2368 case Qualifiers::OCL_Weak:
2369 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2370 true);
2371 }
2372
2373 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002374}
2375
2376static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2377 const Expr *e) {
2378 e = e->IgnoreParens();
2379 QualType type = e->getType();
2380
John McCall154a2fd2011-08-30 00:57:29 +00002381 // If we're loading retained from a __strong xvalue, we can avoid
2382 // an extra retain/release pair by zeroing out the source of this
2383 // "move" operation.
2384 if (e->isXValue() &&
2385 !type.isConstQualified() &&
2386 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2387 // Emit the lvalue.
2388 LValue lv = CGF.EmitLValue(e);
2389
2390 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002391 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2392 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002393
2394 // Set the source pointer to NULL.
2395 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2396
2397 return TryEmitResult(result, true);
2398 }
2399
John McCall31168b02011-06-15 23:02:42 +00002400 // As a very special optimization, in ARC++, if the l-value is the
2401 // result of a non-volatile assignment, do a simple retain of the
2402 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002403 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002404 !type.isVolatileQualified() &&
2405 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2406 isa<BinaryOperator>(e) &&
2407 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2408 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2409
2410 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2411}
2412
2413static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2414 llvm::Value *value);
2415
2416/// Given that the given expression is some sort of call (which does
2417/// not return retained), emit a retain following it.
2418static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2419 llvm::Value *value = CGF.EmitScalarExpr(e);
2420 return emitARCRetainAfterCall(CGF, value);
2421}
2422
2423static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2424 llvm::Value *value) {
2425 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2426 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2427
2428 // Place the retain immediately following the call.
2429 CGF.Builder.SetInsertPoint(call->getParent(),
2430 ++llvm::BasicBlock::iterator(call));
2431 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2432
2433 CGF.Builder.restoreIP(ip);
2434 return value;
2435 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2436 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2437
2438 // Place the retain at the beginning of the normal destination block.
2439 llvm::BasicBlock *BB = invoke->getNormalDest();
2440 CGF.Builder.SetInsertPoint(BB, BB->begin());
2441 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2442
2443 CGF.Builder.restoreIP(ip);
2444 return value;
2445
2446 // Bitcasts can arise because of related-result returns. Rewrite
2447 // the operand.
2448 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2449 llvm::Value *operand = bitcast->getOperand(0);
2450 operand = emitARCRetainAfterCall(CGF, operand);
2451 bitcast->setOperand(0, operand);
2452 return bitcast;
2453
2454 // Generic fall-back case.
2455 } else {
2456 // Retain using the non-block variant: we never need to do a copy
2457 // of a block that's been returned to us.
2458 return CGF.EmitARCRetainNonBlock(value);
2459 }
2460}
2461
John McCallcd78e802011-09-10 01:16:55 +00002462/// Determine whether it might be important to emit a separate
2463/// objc_retain_block on the result of the given expression, or
2464/// whether it's okay to just emit it in a +1 context.
2465static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2466 assert(e->getType()->isBlockPointerType());
2467 e = e->IgnoreParens();
2468
2469 // For future goodness, emit block expressions directly in +1
2470 // contexts if we can.
2471 if (isa<BlockExpr>(e))
2472 return false;
2473
2474 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2475 switch (cast->getCastKind()) {
2476 // Emitting these operations in +1 contexts is goodness.
2477 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002478 case CK_ARCReclaimReturnedObject:
2479 case CK_ARCConsumeObject:
2480 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002481 return false;
2482
2483 // These operations preserve a block type.
2484 case CK_NoOp:
2485 case CK_BitCast:
2486 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2487
2488 // These operations are known to be bad (or haven't been considered).
2489 case CK_AnyPointerToBlockPointerCast:
2490 default:
2491 return true;
2492 }
2493 }
2494
2495 return true;
2496}
2497
John McCallfe96e0b2011-11-06 09:01:30 +00002498/// Try to emit a PseudoObjectExpr at +1.
2499///
2500/// This massively duplicates emitPseudoObjectRValue.
2501static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2502 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002503 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002504
2505 // Find the result expression.
2506 const Expr *resultExpr = E->getResultExpr();
2507 assert(resultExpr);
2508 TryEmitResult result;
2509
2510 for (PseudoObjectExpr::const_semantics_iterator
2511 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2512 const Expr *semantic = *i;
2513
2514 // If this semantic expression is an opaque value, bind it
2515 // to the result of its source expression.
2516 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2517 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2518 OVMA opaqueData;
2519
2520 // If this semantic is the result of the pseudo-object
2521 // expression, try to evaluate the source as +1.
2522 if (ov == resultExpr) {
2523 assert(!OVMA::shouldBindAsLValue(ov));
2524 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2525 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2526
2527 // Otherwise, just bind it.
2528 } else {
2529 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2530 }
2531 opaques.push_back(opaqueData);
2532
2533 // Otherwise, if the expression is the result, evaluate it
2534 // and remember the result.
2535 } else if (semantic == resultExpr) {
2536 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2537
2538 // Otherwise, evaluate the expression in an ignored context.
2539 } else {
2540 CGF.EmitIgnoredExpr(semantic);
2541 }
2542 }
2543
2544 // Unbind all the opaques now.
2545 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2546 opaques[i].unbind(CGF);
2547
2548 return result;
2549}
2550
John McCall31168b02011-06-15 23:02:42 +00002551static TryEmitResult
2552tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002553 // We should *never* see a nested full-expression here, because if
2554 // we fail to emit at +1, our caller must not retain after we close
2555 // out the full-expression.
2556 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002557
John McCall31168b02011-06-15 23:02:42 +00002558 // The desired result type, if it differs from the type of the
2559 // ultimate opaque expression.
Craig Topper8a13c412014-05-21 05:09:00 +00002560 llvm::Type *resultType = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002561
2562 while (true) {
2563 e = e->IgnoreParens();
2564
2565 // There's a break at the end of this if-chain; anything
2566 // that wants to keep looping has to explicitly continue.
2567 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2568 switch (ce->getCastKind()) {
2569 // No-op casts don't change the type, so we just ignore them.
2570 case CK_NoOp:
2571 e = ce->getSubExpr();
2572 continue;
2573
2574 case CK_LValueToRValue: {
2575 TryEmitResult loadResult
2576 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2577 if (resultType) {
2578 llvm::Value *value = loadResult.getPointer();
2579 value = CGF.Builder.CreateBitCast(value, resultType);
2580 loadResult.setPointer(value);
2581 }
2582 return loadResult;
2583 }
2584
2585 // These casts can change the type, so remember that and
2586 // soldier on. We only need to remember the outermost such
2587 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002588 case CK_CPointerToObjCPointerCast:
2589 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002590 case CK_AnyPointerToBlockPointerCast:
2591 case CK_BitCast:
2592 if (!resultType)
2593 resultType = CGF.ConvertType(ce->getType());
2594 e = ce->getSubExpr();
2595 assert(e->getType()->hasPointerRepresentation());
2596 continue;
2597
2598 // For consumptions, just emit the subexpression and thus elide
2599 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002600 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002601 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2602 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2603 return TryEmitResult(result, true);
2604 }
2605
John McCallcd78e802011-09-10 01:16:55 +00002606 // Block extends are net +0. Naively, we could just recurse on
2607 // the subexpression, but actually we need to ensure that the
2608 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002609 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002610 llvm::Value *result; // will be a +0 value
2611
2612 // If we can't safely assume the sub-expression will produce a
2613 // block-copied value, emit the sub-expression at +0.
2614 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2615 result = CGF.EmitScalarExpr(ce->getSubExpr());
2616
2617 // Otherwise, try to emit the sub-expression at +1 recursively.
2618 } else {
2619 TryEmitResult subresult
2620 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2621 result = subresult.getPointer();
2622
2623 // If that produced a retained value, just use that,
2624 // possibly casting down.
2625 if (subresult.getInt()) {
2626 if (resultType)
2627 result = CGF.Builder.CreateBitCast(result, resultType);
2628 return TryEmitResult(result, true);
2629 }
2630
2631 // Otherwise it's +0.
2632 }
2633
2634 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002635 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002636 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2637 return TryEmitResult(result, true);
2638 }
2639
John McCall4db5c3c2011-07-07 06:58:02 +00002640 // For reclaims, emit the subexpression as a retained call and
2641 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002642 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002643 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2644 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2645 return TryEmitResult(result, true);
2646 }
2647
John McCall31168b02011-06-15 23:02:42 +00002648 default:
2649 break;
2650 }
2651
2652 // Skip __extension__.
2653 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2654 if (op->getOpcode() == UO_Extension) {
2655 e = op->getSubExpr();
2656 continue;
2657 }
2658
2659 // For calls and message sends, use the retained-call logic.
2660 // Delegate inits are a special case in that they're the only
2661 // returns-retained expression that *isn't* surrounded by
2662 // a consume.
2663 } else if (isa<CallExpr>(e) ||
2664 (isa<ObjCMessageExpr>(e) &&
2665 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2666 llvm::Value *result = emitARCRetainCall(CGF, e);
2667 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2668 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002669
2670 // Look through pseudo-object expressions.
2671 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2672 TryEmitResult result
2673 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2674 if (resultType) {
2675 llvm::Value *value = result.getPointer();
2676 value = CGF.Builder.CreateBitCast(value, resultType);
2677 result.setPointer(value);
2678 }
2679 return result;
John McCall31168b02011-06-15 23:02:42 +00002680 }
2681
2682 // Conservatively halt the search at any other expression kind.
2683 break;
2684 }
2685
2686 // We didn't find an obvious production, so emit what we've got and
2687 // tell the caller that we didn't manage to retain.
2688 llvm::Value *result = CGF.EmitScalarExpr(e);
2689 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2690 return TryEmitResult(result, false);
2691}
2692
2693static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2694 LValue lvalue,
2695 QualType type) {
2696 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2697 llvm::Value *value = result.getPointer();
2698 if (!result.getInt())
2699 value = CGF.EmitARCRetain(type, value);
2700 return value;
2701}
2702
2703/// EmitARCRetainScalarExpr - Semantically equivalent to
2704/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2705/// best-effort attempt to peephole expressions that naturally produce
2706/// retained objects.
2707llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002708 // The retain needs to happen within the full-expression.
2709 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2710 enterFullExpression(cleanups);
2711 RunCleanupsScope scope(*this);
2712 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2713 }
2714
John McCall31168b02011-06-15 23:02:42 +00002715 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2716 llvm::Value *value = result.getPointer();
2717 if (!result.getInt())
2718 value = EmitARCRetain(e->getType(), value);
2719 return value;
2720}
2721
2722llvm::Value *
2723CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002724 // The retain needs to happen within the full-expression.
2725 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2726 enterFullExpression(cleanups);
2727 RunCleanupsScope scope(*this);
2728 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2729 }
2730
John McCall31168b02011-06-15 23:02:42 +00002731 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2732 llvm::Value *value = result.getPointer();
2733 if (result.getInt())
2734 value = EmitARCAutorelease(value);
2735 else
2736 value = EmitARCRetainAutorelease(e->getType(), value);
2737 return value;
2738}
2739
John McCallff613032011-10-04 06:23:45 +00002740llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2741 llvm::Value *result;
2742 bool doRetain;
2743
2744 if (shouldEmitSeparateBlockRetain(e)) {
2745 result = EmitScalarExpr(e);
2746 doRetain = true;
2747 } else {
2748 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2749 result = subresult.getPointer();
2750 doRetain = !subresult.getInt();
2751 }
2752
2753 if (doRetain)
2754 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2755 return EmitObjCConsumeObject(e->getType(), result);
2756}
2757
John McCall248512a2011-10-01 10:32:24 +00002758llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2759 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002760 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002761 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002762 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002763 return EmitARCRetainAutoreleaseScalarExpr(expr);
2764 }
2765
2766 // Otherwise, use the normal scalar-expression emission. The
2767 // exception machinery doesn't do anything special with the
2768 // exception like retaining it, so there's no safety associated with
2769 // only running cleanups after the throw has started, and when it
2770 // matters it tends to be substantially inferior code.
2771 return EmitScalarExpr(expr);
2772}
2773
John McCall31168b02011-06-15 23:02:42 +00002774std::pair<LValue,llvm::Value*>
2775CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2776 bool ignored) {
2777 // Evaluate the RHS first.
2778 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2779 llvm::Value *value = result.getPointer();
2780
John McCallb726a552011-07-28 07:23:35 +00002781 bool hasImmediateRetain = result.getInt();
2782
2783 // If we didn't emit a retained object, and the l-value is of block
2784 // type, then we need to emit the block-retain immediately in case
2785 // it invalidates the l-value.
2786 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002787 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002788 hasImmediateRetain = true;
2789 }
2790
John McCall31168b02011-06-15 23:02:42 +00002791 LValue lvalue = EmitLValue(e->getLHS());
2792
2793 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002794 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002795 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002796 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002797 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002798 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002799 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002800 }
2801
2802 return std::pair<LValue,llvm::Value*>(lvalue, value);
2803}
2804
2805std::pair<LValue,llvm::Value*>
2806CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2807 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2808 LValue lvalue = EmitLValue(e->getLHS());
2809
Eli Friedmana0544d62011-12-03 04:14:32 +00002810 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002811
2812 return std::pair<LValue,llvm::Value*>(lvalue, value);
2813}
2814
2815void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002816 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002817 const Stmt *subStmt = ARPS.getSubStmt();
2818 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2819
2820 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002821 if (DI)
2822 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002823
2824 // Keep track of the current cleanup stack depth.
2825 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002826 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002827 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2828 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2829 } else {
2830 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2831 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2832 }
2833
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00002834 for (const auto *I : S.body())
2835 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00002836
Eric Christopher7cdf9482011-10-13 21:45:18 +00002837 if (DI)
2838 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002839}
John McCall1bd25562011-06-24 23:21:27 +00002840
2841/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2842/// make sure it survives garbage collection until this point.
2843void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2844 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002845 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002846 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002847 llvm::Value *extender
2848 = llvm::InlineAsm::get(extenderType,
2849 /* assembly */ "",
2850 /* constraints */ "r",
2851 /* side effects */ true);
2852
2853 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00002854 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00002855}
2856
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002857/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002858/// non-trivial copy assignment function, produce following helper function.
2859/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2860///
2861llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002862CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2863 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002864 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002865 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002866 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002867 QualType Ty = PID->getPropertyIvarDecl()->getType();
2868 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002869 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002870 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002871 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002872 return nullptr;
2873 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002874 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002875 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002876 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2877 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2878 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002879
2880 ASTContext &C = getContext();
2881 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002882 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002883 FunctionDecl *FD = FunctionDecl::Create(C,
2884 C.getTranslationUnitDecl(),
2885 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002886 SourceLocation(), II, C.VoidTy,
2887 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002888 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002889 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002890
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002891 QualType DestTy = C.getPointerType(Ty);
2892 QualType SrcTy = Ty;
2893 SrcTy.addConst();
2894 SrcTy = C.getPointerType(SrcTy);
2895
2896 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002897 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002898 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002899 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002900 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002901
2902 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2903 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2904
John McCalla729c622012-02-17 03:33:10 +00002905 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002906
2907 llvm::Function *Fn =
2908 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002909 "__assign_helper_atomic_property_",
2910 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002911
Adrian Prantl22e66b42014-04-11 01:13:04 +00002912 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002913
John McCall113bee02012-03-10 09:33:50 +00002914 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2915 VK_RValue, SourceLocation());
2916 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2917 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002918
John McCall113bee02012-03-10 09:33:50 +00002919 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2920 VK_RValue, SourceLocation());
2921 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2922 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002923
John McCall113bee02012-03-10 09:33:50 +00002924 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002925 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002926 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002927 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002928 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002929
2930 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002931
2932 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002933 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002934 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002935 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002936}
2937
2938llvm::Constant *
2939CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2940 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002941 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002942 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002943 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002944 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2945 QualType Ty = PD->getType();
2946 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002947 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002948 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002949 return nullptr;
2950 llvm::Constant *HelperFn = nullptr;
2951
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002952 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002953 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002954 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2955 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2956 return HelperFn;
2957
2958
2959 ASTContext &C = getContext();
2960 IdentifierInfo *II
2961 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2962 FunctionDecl *FD = FunctionDecl::Create(C,
2963 C.getTranslationUnitDecl(),
2964 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002965 SourceLocation(), II, C.VoidTy,
2966 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002967 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002968 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002969
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002970 QualType DestTy = C.getPointerType(Ty);
2971 QualType SrcTy = Ty;
2972 SrcTy.addConst();
2973 SrcTy = C.getPointerType(SrcTy);
2974
2975 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002976 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002977 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002978 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002979 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002980
2981 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2982 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2983
John McCalla729c622012-02-17 03:33:10 +00002984 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002985
2986 llvm::Function *Fn =
2987 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2988 "__copy_helper_atomic_property_", &CGM.getModule());
2989
Adrian Prantl22e66b42014-04-11 01:13:04 +00002990 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002991
John McCall113bee02012-03-10 09:33:50 +00002992 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002993 VK_RValue, SourceLocation());
2994
John McCall113bee02012-03-10 09:33:50 +00002995 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2996 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002997
2998 CXXConstructExpr *CXXConstExpr =
2999 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3000
3001 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003002 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003003 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3004 ++A;
3005
3006 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3007 A != AEnd; ++A)
3008 ConstructorArgs.push_back(*A);
3009
3010 CXXConstructExpr *TheCXXConstructExpr =
3011 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3012 CXXConstExpr->getConstructor(),
3013 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003014 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003015 CXXConstExpr->hadMultipleCandidates(),
3016 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003017 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003018 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003019 CXXConstExpr->getConstructionKind(),
3020 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003021
John McCall113bee02012-03-10 09:33:50 +00003022 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3023 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003024
John McCall113bee02012-03-10 09:33:50 +00003025 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003026 CharUnits Alignment
3027 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003028 EmitAggExpr(TheCXXConstructExpr,
3029 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3030 AggValueSlot::IsDestructed,
3031 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003032 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003033
3034 FinishFunction();
3035 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3036 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3037 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003038}
3039
Eli Friedmanec75fec2012-02-28 01:08:45 +00003040llvm::Value *
3041CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3042 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003043 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3044 Selector CopySelector =
3045 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003046 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3047 Selector AutoreleaseSelector =
3048 getContext().Selectors.getNullarySelector(AutoreleaseID);
3049
3050 // Emit calls to retain/autorelease.
3051 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3052 llvm::Value *Val = Block;
3053 RValue Result;
3054 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003055 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003056 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003057 Val = Result.getScalarVal();
3058 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3059 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003060 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003061 Val = Result.getScalarVal();
3062 return Val;
3063}
3064
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003065
Ted Kremenek43e06332008-04-09 15:51:31 +00003066CGObjCRuntime::~CGObjCRuntime() {}