blob: 058ce5686a3b6beccb8bbc781d0edbdd27c93aa2 [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 Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/InlineAsm.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000027#include "llvm/Support/CallSite.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.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const Expr *SubExpr = E->getSubExpr();
Ted Kremeneke65b0862012-03-06 20:05:56 +000064 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000065 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
66 assert(BoxingMethod && "BoxingMethod is null");
67 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
68 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000069
70 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000071 // Assumes that the method was introduced in the class that should be
72 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000073 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000074 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000075 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Patrick Beard0caa3942012-04-19 00:25:12 +000076
77 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremeneke65b0862012-03-06 20:05:56 +000078 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beard0caa3942012-04-19 00:25:12 +000079 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremeneke65b0862012-03-06 20:05:56 +000080 CallArgList Args;
81 Args.add(RV, ArgQT);
Patrick Beard0caa3942012-04-19 00:25:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beard0caa3942012-04-19 00:25:12 +000084 BoxingMethod->getResultType(), Sel, Receiver, Args,
85 ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +000086 return Builder.CreateBitCast(result.getScalarVal(),
87 ConvertType(E->getType()));
88}
89
90llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
91 const ObjCMethodDecl *MethodWithObjects) {
92 ASTContext &Context = CGM.getContext();
93 const ObjCDictionaryLiteral *DLE = 0;
94 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
95 if (!ALE)
96 DLE = cast<ObjCDictionaryLiteral>(E);
97
98 // Compute the type of the array we're initializing.
99 uint64_t NumElements =
100 ALE ? ALE->getNumElements() : DLE->getNumElements();
101 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
102 NumElements);
103 QualType ElementType = Context.getObjCIdType().withConst();
104 QualType ElementArrayType
105 = Context.getConstantArrayType(ElementType, APNumElements,
106 ArrayType::Normal, /*IndexTypeQuals=*/0);
107
108 // Allocate the temporary array(s).
109 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
110 llvm::Value *Keys = 0;
111 if (DLE)
112 Keys = CreateMemTemp(ElementArrayType, "keys");
113
John McCall770a4c12013-04-04 00:20:38 +0000114 // In ARC, we may need to do extra work to keep all the keys and
115 // values alive until after the call.
116 SmallVector<llvm::Value *, 16> NeededObjects;
117 bool TrackNeededObjects =
118 (getLangOpts().ObjCAutoRefCount &&
119 CGM.getCodeGenOpts().OptimizationLevel != 0);
120
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 // Perform the actual initialialization of the array(s).
122 for (uint64_t i = 0; i < NumElements; i++) {
123 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000124 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000125 const Expr *Rhs = ALE->getElement(i);
126 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
127 ElementType,
128 Context.getTypeAlignInChars(Rhs->getType()),
129 Context);
John McCall770a4c12013-04-04 00:20:38 +0000130
131 llvm::Value *value = EmitScalarExpr(Rhs);
132 EmitStoreThroughLValue(RValue::get(value), LV, true);
133 if (TrackNeededObjects) {
134 NeededObjects.push_back(value);
135 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000136 } else {
John McCall770a4c12013-04-04 00:20:38 +0000137 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000138 const Expr *Key = DLE->getKeyValueElement(i).Key;
139 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
140 ElementType,
141 Context.getTypeAlignInChars(Key->getType()),
142 Context);
John McCall770a4c12013-04-04 00:20:38 +0000143 llvm::Value *keyValue = EmitScalarExpr(Key);
144 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000145
John McCall770a4c12013-04-04 00:20:38 +0000146 // Emit the value and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000147 const Expr *Value = DLE->getKeyValueElement(i).Value;
148 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
149 ElementType,
150 Context.getTypeAlignInChars(Value->getType()),
151 Context);
John McCall770a4c12013-04-04 00:20:38 +0000152 llvm::Value *valueValue = EmitScalarExpr(Value);
153 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
154 if (TrackNeededObjects) {
155 NeededObjects.push_back(keyValue);
156 NeededObjects.push_back(valueValue);
157 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000158 }
159 }
160
161 // Generate the argument list.
162 CallArgList Args;
163 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
164 const ParmVarDecl *argDecl = *PI++;
165 QualType ArgQT = argDecl->getType().getUnqualifiedType();
166 Args.add(RValue::get(Objects), ArgQT);
167 if (DLE) {
168 argDecl = *PI++;
169 ArgQT = argDecl->getType().getUnqualifiedType();
170 Args.add(RValue::get(Keys), ArgQT);
171 }
172 argDecl = *PI;
173 ArgQT = argDecl->getType().getUnqualifiedType();
174 llvm::Value *Count =
175 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
176 Args.add(RValue::get(Count), ArgQT);
177
178 // Generate a reference to the class pointer, which will be the receiver.
179 Selector Sel = MethodWithObjects->getSelector();
180 QualType ResultType = E->getType();
181 const ObjCObjectPointerType *InterfacePointerType
182 = ResultType->getAsObjCInterfacePointerType();
183 ObjCInterfaceDecl *Class
184 = InterfacePointerType->getObjectType()->getInterface();
185 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000186 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000187
188 // Generate the message send.
Eric Christopher5d2b8d92012-03-29 17:31:31 +0000189 RValue result
190 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
191 MethodWithObjects->getResultType(),
192 Sel,
193 Receiver, Args, Class,
194 MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000195
196 // The above message send needs these objects, but in ARC they are
197 // passed in a buffer that is essentially __unsafe_unretained.
198 // Therefore we must prevent the optimizer from releasing them until
199 // after the call.
200 if (TrackNeededObjects) {
201 EmitARCIntrinsicUse(NeededObjects);
202 }
203
Ted Kremeneke65b0862012-03-06 20:05:56 +0000204 return Builder.CreateBitCast(result.getScalarVal(),
205 ConvertType(E->getType()));
206}
207
208llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
209 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
210}
211
212llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
213 const ObjCDictionaryLiteral *E) {
214 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
215}
216
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000217/// Emit a selector.
218llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
219 // Untyped selector.
220 // Note that this implementation allows for non-constant strings to be passed
221 // as arguments to @selector(). Currently, the only thing preventing this
222 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000223 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000224}
225
Daniel Dunbar66912a12008-08-20 00:28:19 +0000226llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
227 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000228 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000229}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000230
Douglas Gregor33823722011-06-11 01:09:30 +0000231/// \brief Adjust the type of the result of an Objective-C message send
232/// expression when the method has a related result type.
233static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000234 QualType ExpT,
Douglas Gregor33823722011-06-11 01:09:30 +0000235 const ObjCMethodDecl *Method,
236 RValue Result) {
237 if (!Method)
238 return Result;
John McCall31168b02011-06-15 23:02:42 +0000239
Douglas Gregor33823722011-06-11 01:09:30 +0000240 if (!Method->hasRelatedResultType() ||
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000241 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor33823722011-06-11 01:09:30 +0000242 !Result.isScalar())
243 return Result;
244
245 // We have applied a related result type. Cast the rvalue appropriately.
246 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000247 CGF.ConvertType(ExpT)));
Douglas Gregor33823722011-06-11 01:09:30 +0000248}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000249
John McCallcf166702011-07-22 08:53:00 +0000250/// Decide whether to extend the lifetime of the receiver of a
251/// returns-inner-pointer message.
252static bool
253shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
254 switch (message->getReceiverKind()) {
255
256 // For a normal instance message, we should extend unless the
257 // receiver is loaded from a variable with precise lifetime.
258 case ObjCMessageExpr::Instance: {
259 const Expr *receiver = message->getInstanceReceiver();
260 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
261 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
262 receiver = ice->getSubExpr()->IgnoreParens();
263
264 // Only __strong variables.
265 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
266 return true;
267
268 // All ivars and fields have precise lifetime.
269 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
270 return false;
271
272 // Otherwise, check for variables.
273 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
274 if (!declRef) return true;
275 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
276 if (!var) return true;
277
278 // All variables have precise lifetime except local variables with
279 // automatic storage duration that aren't specially marked.
280 return (var->hasLocalStorage() &&
281 !var->hasAttr<ObjCPreciseLifetimeAttr>());
282 }
283
284 case ObjCMessageExpr::Class:
285 case ObjCMessageExpr::SuperClass:
286 // It's never necessary for class objects.
287 return false;
288
289 case ObjCMessageExpr::SuperInstance:
290 // We generally assume that 'self' lives throughout a method call.
291 return false;
292 }
293
294 llvm_unreachable("invalid receiver kind");
295}
296
John McCall78a15112010-05-22 01:48:05 +0000297RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
298 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000299 // Only the lookup mechanism and first two arguments of the method
300 // implementation vary between runtimes. We can get the receiver and
301 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall31168b02011-06-15 23:02:42 +0000303 bool isDelegateInit = E->isDelegateInitCall();
304
John McCallcf166702011-07-22 08:53:00 +0000305 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000306
John McCall31168b02011-06-15 23:02:42 +0000307 // We don't retain the receiver in delegate init calls, and this is
308 // safe because the receiver value is always loaded from 'self',
309 // which we zero out. We don't want to Block_copy block receivers,
310 // though.
311 bool retainSelf =
312 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000313 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000314 method &&
315 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000316
Daniel Dunbar8d480592008-08-11 18:12:00 +0000317 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000318 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000319 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +0000320 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000321 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000322 QualType ReceiverType;
Daniel Dunbarb2197802010-04-22 03:17:06 +0000323 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +0000324 switch (E->getReceiverKind()) {
325 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000326 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000327 if (retainSelf) {
328 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
329 E->getInstanceReceiver());
330 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000331 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000332 } else
333 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000334 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000335
Douglas Gregor9a129192010-04-21 00:45:42 +0000336 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000337 ReceiverType = E->getClassReceiver();
338 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000339 assert(ObjTy && "Invalid Objective-C class message send");
340 OID = ObjTy->getInterface();
341 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000342 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000343 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000344 break;
345 }
346
347 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000348 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000349 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000350 isSuperMessage = true;
351 break;
352
353 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000354 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000355 Receiver = LoadObjCSelf();
356 isSuperMessage = true;
357 isClassMessage = true;
358 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000359 }
360
John McCallcf166702011-07-22 08:53:00 +0000361 if (retainSelf)
362 Receiver = EmitARCRetainNonBlock(Receiver);
363
364 // In ARC, we sometimes want to "extend the lifetime"
365 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
366 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000367 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000368 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
369 shouldExtendReceiverForInnerPointerMessage(E))
370 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
371
John McCall31168b02011-06-15 23:02:42 +0000372 QualType ResultType =
John McCallcf166702011-07-22 08:53:00 +0000373 method ? method->getResultType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000374
Daniel Dunbarc722b852008-08-30 03:02:31 +0000375 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000376 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000377
John McCall31168b02011-06-15 23:02:42 +0000378 // For delegate init calls in ARC, do an unsafe store of null into
379 // self. This represents the call taking direct ownership of that
380 // value. We have to do this after emitting the other call
381 // arguments because they might also reference self, but we don't
382 // have to worry about any of them modifying self because that would
383 // be an undefined read and write of an object in unordered
384 // expressions.
385 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000386 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000387 "delegate init calls should only be marked in ARC");
388
389 // Do an unsafe store of null into self.
390 llvm::Value *selfAddr =
391 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
392 assert(selfAddr && "no self entry for a delegate init call?");
393
394 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
395 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000396
Douglas Gregor33823722011-06-11 01:09:30 +0000397 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000398 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000399 // super is only valid in an Objective-C method
400 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000401 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000402 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
403 E->getSelector(),
404 OMD->getClassInterface(),
405 isCategoryImpl,
406 Receiver,
407 isClassMessage,
408 Args,
John McCallcf166702011-07-22 08:53:00 +0000409 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000410 } else {
411 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
412 E->getSelector(),
413 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000414 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000415 }
John McCall31168b02011-06-15 23:02:42 +0000416
417 // For delegate init calls in ARC, implicitly store the result of
418 // the call back into self. This takes ownership of the value.
419 if (isDelegateInit) {
420 llvm::Value *selfAddr =
421 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
422 llvm::Value *newSelf = result.getScalarVal();
423
424 // The delegate return type isn't necessarily a matching type; in
425 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000426 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000427 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
428 newSelf = Builder.CreateBitCast(newSelf, selfTy);
429
430 Builder.CreateStore(newSelf, selfAddr);
431 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000432
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000433 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000434}
435
John McCall31168b02011-06-15 23:02:42 +0000436namespace {
437struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCall30317fd2011-07-12 20:27:29 +0000438 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +0000439 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000440
441 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000442 const ObjCInterfaceDecl *iface = impl->getClassInterface();
443 if (!iface->getSuperClass()) return;
444
John McCalldffafde2011-07-13 18:26:47 +0000445 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
446
John McCall31168b02011-06-15 23:02:42 +0000447 // Call [super dealloc] if we have a superclass.
448 llvm::Value *self = CGF.LoadObjCSelf();
449
450 CallArgList args;
451 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
452 CGF.getContext().VoidTy,
453 method->getSelector(),
454 iface,
John McCalldffafde2011-07-13 18:26:47 +0000455 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000456 self,
457 /*is class msg*/ false,
458 args,
459 method);
460 }
461};
462}
463
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000464/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
465/// the LLVM function and sets the other context used by
466/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000467void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000468 const ObjCContainerDecl *CD,
469 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000470 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000471 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000472 if (OMD->hasAttr<NoDebugAttr>())
473 DebugInfo = NULL; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000474
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000475 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000476
John McCalla729c622012-02-17 03:33:10 +0000477 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000478 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000479
John McCalla738c252011-03-09 04:27:21 +0000480 args.push_back(OMD->getSelfDecl());
481 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000482
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000483 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +0000484 E = OMD->param_end(); PI != E; ++PI)
John McCalla738c252011-03-09 04:27:21 +0000485 args.push_back(*PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000486
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000487 CurGD = OMD;
488
Devang Patele7ce5402011-05-19 23:37:41 +0000489 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000490
491 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000492 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000493 OMD->isInstanceMethod() &&
494 OMD->getSelector().isUnarySelector()) {
495 const IdentifierInfo *ident =
496 OMD->getSelector().getIdentifierInfoForSlot(0);
497 if (ident->isStr("dealloc"))
498 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
499 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000500}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000501
John McCall31168b02011-06-15 23:02:42 +0000502static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
503 LValue lvalue, QualType type);
504
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000505/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000506/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000507void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000508 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Adrian Prantlc6758872014-01-07 22:05:45 +0000509 EmitStmt(OMD->getBody());
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000510 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000511}
512
John McCallb923ece2011-09-12 23:06:44 +0000513/// emitStructGetterCall - Call the runtime function to load a property
514/// into the return value slot.
515static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
516 bool isAtomic, bool hasStrong) {
517 ASTContext &Context = CGF.getContext();
518
519 llvm::Value *src =
520 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
521 ivar, 0).getAddress();
522
523 // objc_copyStruct (ReturnValue, &structIvar,
524 // sizeof (Type of Ivar), isAtomic, false);
525 CallArgList args;
526
527 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
528 args.add(RValue::get(dest), Context.VoidPtrTy);
529
530 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
531 args.add(RValue::get(src), Context.VoidPtrTy);
532
533 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
534 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
535 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
536 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
537
538 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000539 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
540 FunctionType::ExtInfo(),
541 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000542 fn, ReturnValueSlot(), args);
543}
544
John McCallf4528ae2011-09-13 03:34:09 +0000545/// Determine whether the given architecture supports unaligned atomic
546/// accesses. They don't have to be fast, just faster than a function
547/// call and a mutex.
548static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000549 // FIXME: Allow unaligned atomic load/store on x86. (It is not
550 // currently supported by the backend.)
551 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000552}
553
554/// Return the maximum size that permits atomic accesses for the given
555/// architecture.
556static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
557 llvm::Triple::ArchType arch) {
558 // ARM has 8-byte atomic accesses, but it's not clear whether we
559 // want to rely on them here.
560
561 // In the default case, just assume that any size up to a pointer is
562 // fine given adequate alignment.
563 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
564}
565
566namespace {
567 class PropertyImplStrategy {
568 public:
569 enum StrategyKind {
570 /// The 'native' strategy is to use the architecture's provided
571 /// reads and writes.
572 Native,
573
574 /// Use objc_setProperty and objc_getProperty.
575 GetSetProperty,
576
577 /// Use objc_setProperty for the setter, but use expression
578 /// evaluation for the getter.
579 SetPropertyAndExpressionGet,
580
581 /// Use objc_copyStruct.
582 CopyStruct,
583
584 /// The 'expression' strategy is to emit normal assignment or
585 /// lvalue-to-rvalue expressions.
586 Expression
587 };
588
589 StrategyKind getKind() const { return StrategyKind(Kind); }
590
591 bool hasStrongMember() const { return HasStrong; }
592 bool isAtomic() const { return IsAtomic; }
593 bool isCopy() const { return IsCopy; }
594
595 CharUnits getIvarSize() const { return IvarSize; }
596 CharUnits getIvarAlignment() const { return IvarAlignment; }
597
598 PropertyImplStrategy(CodeGenModule &CGM,
599 const ObjCPropertyImplDecl *propImpl);
600
601 private:
602 unsigned Kind : 8;
603 unsigned IsAtomic : 1;
604 unsigned IsCopy : 1;
605 unsigned HasStrong : 1;
606
607 CharUnits IvarSize;
608 CharUnits IvarAlignment;
609 };
610}
611
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000612/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000613PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
614 const ObjCPropertyImplDecl *propImpl) {
615 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000616 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000617
John McCall43192862011-09-13 18:31:23 +0000618 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
619 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000620 HasStrong = false; // doesn't matter here.
621
622 // Evaluate the ivar's size and alignment.
623 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
624 QualType ivarType = ivar->getType();
625 llvm::tie(IvarSize, IvarAlignment)
626 = CGM.getContext().getTypeInfoInChars(ivarType);
627
628 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000629 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000630 if (IsCopy) {
631 Kind = GetSetProperty;
632 return;
633 }
634
John McCall43192862011-09-13 18:31:23 +0000635 // Handle retain.
636 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000637 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000638 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000639 // fallthrough
640
641 // In ARC, if the property is non-atomic, use expression emission,
642 // which translates to objc_storeStrong. This isn't required, but
643 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000644 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000645 // Using standard expression emission for the setter is only
646 // acceptable if the ivar is __strong, which won't be true if
647 // the property is annotated with __attribute__((NSObject)).
648 // TODO: falling all the way back to objc_setProperty here is
649 // just laziness, though; we could still use objc_storeStrong
650 // if we hacked it right.
651 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
652 Kind = Expression;
653 else
654 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000655 return;
656
657 // Otherwise, we need to at least use setProperty. However, if
658 // the property isn't atomic, we can use normal expression
659 // emission for the getter.
660 } else if (!IsAtomic) {
661 Kind = SetPropertyAndExpressionGet;
662 return;
663
664 // Otherwise, we have to use both setProperty and getProperty.
665 } else {
666 Kind = GetSetProperty;
667 return;
668 }
669 }
670
671 // If we're not atomic, just use expression accesses.
672 if (!IsAtomic) {
673 Kind = Expression;
674 return;
675 }
676
John McCall0e5c0862011-09-13 05:36:29 +0000677 // Properties on bitfield ivars need to be emitted using expression
678 // accesses even if they're nominally atomic.
679 if (ivar->isBitField()) {
680 Kind = Expression;
681 return;
682 }
683
John McCallf4528ae2011-09-13 03:34:09 +0000684 // GC-qualified or ARC-qualified ivars need to be emitted as
685 // expressions. This actually works out to being atomic anyway,
686 // except for ARC __strong, but that should trigger the above code.
687 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000688 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000689 CGM.getContext().getObjCGCAttrKind(ivarType))) {
690 Kind = Expression;
691 return;
692 }
693
694 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000695 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000696 if (const RecordType *recordType = ivarType->getAs<RecordType>())
697 HasStrong = recordType->getDecl()->hasObjectMember();
698
699 // We can never access structs with object members with a native
700 // access, because we need to use write barriers. This is what
701 // objc_copyStruct is for.
702 if (HasStrong) {
703 Kind = CopyStruct;
704 return;
705 }
706
707 // Otherwise, this is target-dependent and based on the size and
708 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000709
710 // If the size of the ivar is not a power of two, give up. We don't
711 // want to get into the business of doing compare-and-swaps.
712 if (!IvarSize.isPowerOfTwo()) {
713 Kind = CopyStruct;
714 return;
715 }
716
John McCallf4528ae2011-09-13 03:34:09 +0000717 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000718 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000719
720 // Most architectures require memory to fit within a single cache
721 // line, so the alignment has to be at least the size of the access.
722 // Otherwise we have to grab a lock.
723 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
724 Kind = CopyStruct;
725 return;
726 }
727
728 // If the ivar's size exceeds the architecture's maximum atomic
729 // access size, we have to use CopyStruct.
730 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
731 Kind = CopyStruct;
732 return;
733 }
734
735 // Otherwise, we can use native loads and stores.
736 Kind = Native;
737}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000738
James Dennettbe302452012-06-15 22:10:14 +0000739/// \brief Generate an Objective-C property getter function.
740///
741/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000742/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000743void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
744 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000745 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000746 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000747 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
748 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
749 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +0000750 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000751
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000752 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000753
754 FinishFunction();
755}
756
John McCallbdd81852011-09-13 06:00:03 +0000757static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
758 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000759 if (!getter) return true;
760
761 // Sema only makes only of these when the ivar has a C++ class type,
762 // so the form is pretty constrained.
763
John McCallbdd81852011-09-13 06:00:03 +0000764 // If the property has a reference type, we might just be binding a
765 // reference, in which case the result will be a gl-value. We should
766 // treat this as a non-trivial operation.
767 if (getter->isGLValue())
768 return false;
769
John McCallf4528ae2011-09-13 03:34:09 +0000770 // If we selected a trivial copy-constructor, we're okay.
771 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
772 return (construct->getConstructor()->isTrivial());
773
774 // The constructor might require cleanups (in which case it's never
775 // trivial).
776 assert(isa<ExprWithCleanups>(getter));
777 return false;
778}
779
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000780/// emitCPPObjectAtomicGetterCall - Call the runtime function to
781/// copy the ivar into the resturn slot.
782static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
783 llvm::Value *returnAddr,
784 ObjCIvarDecl *ivar,
785 llvm::Constant *AtomicHelperFn) {
786 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
787 // AtomicHelperFn);
788 CallArgList args;
789
790 // The 1st argument is the return Slot.
791 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
792
793 // The 2nd argument is the address of the ivar.
794 llvm::Value *ivarAddr =
795 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
796 CGF.LoadObjCSelf(), ivar, 0).getAddress();
797 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
798 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
799
800 // Third argument is the helper function.
801 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
802
803 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000804 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000805 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
806 args,
807 FunctionType::ExtInfo(),
808 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000809 copyCppAtomicObjectFn, ReturnValueSlot(), args);
810}
811
John McCallf4528ae2011-09-13 03:34:09 +0000812void
813CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000814 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000815 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000816 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000817 // If there's a non-trivial 'get' expression, we just have to emit that.
818 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000819 if (!AtomicHelperFn) {
820 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
821 /*nrvo*/ 0);
822 EmitReturnStmt(ret);
823 }
824 else {
825 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
826 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
827 ivar, AtomicHelperFn);
828 }
John McCallf4528ae2011-09-13 03:34:09 +0000829 return;
830 }
831
832 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
833 QualType propType = prop->getType();
834 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
835
836 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
837
838 // Pick an implementation strategy.
839 PropertyImplStrategy strategy(CGM, propImpl);
840 switch (strategy.getKind()) {
841 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000842 // We don't need to do anything for a zero-size struct.
843 if (strategy.getIvarSize().isZero())
844 return;
845
John McCallf4528ae2011-09-13 03:34:09 +0000846 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
847
848 // Currently, all atomic accesses have to be through integer
849 // types, so there's no point in trying to pick a prettier type.
850 llvm::Type *bitcastType =
851 llvm::Type::getIntNTy(getLLVMContext(),
852 getContext().toBits(strategy.getIvarSize()));
853 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
854
855 // Perform an atomic load. This does not impose ordering constraints.
856 llvm::Value *ivarAddr = LV.getAddress();
857 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
858 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
859 load->setAlignment(strategy.getIvarAlignment().getQuantity());
860 load->setAtomic(llvm::Unordered);
861
862 // Store that value into the return address. Doing this with a
863 // bitcast is likely to produce some pretty ugly IR, but it's not
864 // the *most* terrible thing in the world.
865 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
866
867 // Make sure we don't do an autorelease.
868 AutoreleaseResult = false;
869 return;
870 }
871
872 case PropertyImplStrategy::GetSetProperty: {
873 llvm::Value *getPropertyFn =
874 CGM.getObjCRuntime().GetPropertyGetFunction();
875 if (!getPropertyFn) {
876 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000877 return;
878 }
879
880 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
881 // FIXME: Can't this be simpler? This might even be worse than the
882 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000883 llvm::Value *cmd =
884 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
885 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
886 llvm::Value *ivarOffset =
887 EmitIvarOffset(classImpl->getClassInterface(), ivar);
888
889 CallArgList args;
890 args.add(RValue::get(self), getContext().getObjCIdType());
891 args.add(RValue::get(cmd), getContext().getObjCSelType());
892 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000893 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
894 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000895
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000896 // FIXME: We shouldn't need to get the function info here, the
897 // runtime already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +0000898 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
899 FunctionType::ExtInfo(),
900 RequiredArgs::All),
John McCallf4528ae2011-09-13 03:34:09 +0000901 getPropertyFn, ReturnValueSlot(), args);
902
Daniel Dunbara08dff12008-09-24 04:04:31 +0000903 // We need to fix the type here. Ivars with copy & retain are
904 // always objects so we don't need to worry about complex or
905 // aggregates.
Mike Stump11289f42009-09-09 15:08:12 +0000906 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian0ec8fbe2012-04-26 21:33:14 +0000907 getTypes().ConvertType(getterMethod->getResultType())));
John McCallf4528ae2011-09-13 03:34:09 +0000908
909 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000910
911 // objc_getProperty does an autorelease, so we should suppress ours.
912 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000913
John McCallf4528ae2011-09-13 03:34:09 +0000914 return;
915 }
916
917 case PropertyImplStrategy::CopyStruct:
918 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
919 strategy.hasStrongMember());
920 return;
921
922 case PropertyImplStrategy::Expression:
923 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
924 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
925
926 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000927 switch (getEvaluationKind(ivarType)) {
928 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000929 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall47fb9502013-03-07 21:37:08 +0000930 EmitStoreOfComplex(pair,
931 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
932 /*init*/ true);
933 return;
934 }
935 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000936 // The return value slot is guaranteed to not be aliased, but
937 // that's not necessarily the same as "on the stack", so
938 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000939 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000940 return;
941 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000942 llvm::Value *value;
943 if (propType->isReferenceType()) {
944 value = LV.getAddress();
945 } else {
946 // We want to load and autoreleaseReturnValue ARC __weak ivars.
947 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000948 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000949
950 // Otherwise we want to do a simple load, suppressing the
951 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000952 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000953 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000954 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000955 }
John McCall31168b02011-06-15 23:02:42 +0000956
John McCall24fada12011-07-22 05:23:13 +0000957 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000958 value = Builder.CreateBitCast(value,
959 ConvertType(GetterMethodDecl->getResultType()));
John McCall24fada12011-07-22 05:23:13 +0000960 }
961
962 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000963 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000964 }
John McCall47fb9502013-03-07 21:37:08 +0000965 }
966 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000967 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000968
John McCallf4528ae2011-09-13 03:34:09 +0000969 }
970 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000971}
972
John McCallb923ece2011-09-12 23:06:44 +0000973/// emitStructSetterCall - Call the runtime function to store the value
974/// from the first formal parameter into the given ivar.
975static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
976 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000977 // objc_copyStruct (&structIvar, &Arg,
978 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000979 CallArgList args;
980
981 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000982 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
983 CGF.LoadObjCSelf(), ivar, 0)
984 .getAddress();
985 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
986 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000987
988 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000989 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000990 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000991 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000992 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
993 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
994 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000995
996 // The third argument is the sizeof the type.
997 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +0000998 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
999 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001000
John McCallb923ece2011-09-12 23:06:44 +00001001 // The fourth argument is the 'isAtomic' flag.
1002 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001003
John McCallb923ece2011-09-12 23:06:44 +00001004 // The fifth argument is the 'hasStrong' flag.
1005 // FIXME: should this really always be false?
1006 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1007
1008 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001009 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1010 args,
1011 FunctionType::ExtInfo(),
1012 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001013 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001014}
1015
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001016/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1017/// the value from the first formal parameter into the given ivar, using
1018/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1019static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1020 ObjCMethodDecl *OMD,
1021 ObjCIvarDecl *ivar,
1022 llvm::Constant *AtomicHelperFn) {
1023 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1024 // AtomicHelperFn);
1025 CallArgList args;
1026
1027 // The first argument is the address of the ivar.
1028 llvm::Value *ivarAddr =
1029 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1030 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1031 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1032 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1033
1034 // The second argument is the address of the parameter variable.
1035 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001036 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001037 VK_LValue, SourceLocation());
1038 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1039 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1040 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1041
1042 // Third argument is the helper function.
1043 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1044
1045 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001046 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001047 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1048 args,
1049 FunctionType::ExtInfo(),
1050 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001051 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001052}
1053
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001054
John McCallf4528ae2011-09-13 03:34:09 +00001055static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1056 Expr *setter = PID->getSetterCXXAssignment();
1057 if (!setter) return true;
1058
1059 // Sema only makes only of these when the ivar has a C++ class type,
1060 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001061
1062 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001063 // This also implies that there's nothing non-trivial going on with
1064 // the arguments, because operator= can only be trivial if it's a
1065 // synthesized assignment operator and therefore both parameters are
1066 // references.
1067 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001068 if (const FunctionDecl *callee
1069 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1070 if (callee->isTrivial())
1071 return true;
1072 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001073 }
John McCall7f16c422011-09-10 09:17:20 +00001074
John McCallf4528ae2011-09-13 03:34:09 +00001075 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001076 return false;
1077}
1078
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001079static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001080 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001081 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001082 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001083}
1084
John McCall7f16c422011-09-10 09:17:20 +00001085void
1086CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001087 const ObjCPropertyImplDecl *propImpl,
1088 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001089 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001090 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001091 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001092
1093 // Just use the setter expression if Sema gave us one and it's
1094 // non-trivial.
1095 if (!hasTrivialSetExpr(propImpl)) {
1096 if (!AtomicHelperFn)
1097 // If non-atomic, assignment is called directly.
1098 EmitStmt(propImpl->getSetterCXXAssignment());
1099 else
1100 // If atomic, assignment is called via a locking api.
1101 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1102 AtomicHelperFn);
1103 return;
1104 }
John McCall7f16c422011-09-10 09:17:20 +00001105
John McCallf4528ae2011-09-13 03:34:09 +00001106 PropertyImplStrategy strategy(CGM, propImpl);
1107 switch (strategy.getKind()) {
1108 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001109 // We don't need to do anything for a zero-size struct.
1110 if (strategy.getIvarSize().isZero())
1111 return;
1112
John McCallf4528ae2011-09-13 03:34:09 +00001113 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +00001114
John McCallf4528ae2011-09-13 03:34:09 +00001115 LValue ivarLValue =
1116 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1117 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001118
John McCallf4528ae2011-09-13 03:34:09 +00001119 // Currently, all atomic accesses have to be through integer
1120 // types, so there's no point in trying to pick a prettier type.
1121 llvm::Type *bitcastType =
1122 llvm::Type::getIntNTy(getLLVMContext(),
1123 getContext().toBits(strategy.getIvarSize()));
1124 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1125
1126 // Cast both arguments to the chosen operation type.
1127 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1128 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1129
1130 // This bitcast load is likely to cause some nasty IR.
1131 llvm::Value *load = Builder.CreateLoad(argAddr);
1132
1133 // Perform an atomic store. There are no memory ordering requirements.
1134 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1135 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1136 store->setAtomic(llvm::Unordered);
1137 return;
1138 }
1139
1140 case PropertyImplStrategy::GetSetProperty:
1141 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001142
1143 llvm::Value *setOptimizedPropertyFn = 0;
1144 llvm::Value *setPropertyFn = 0;
1145 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001146 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001147 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001148 CGM.getObjCRuntime()
1149 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1150 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001151 if (!setOptimizedPropertyFn) {
1152 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1153 return;
1154 }
John McCall7f16c422011-09-10 09:17:20 +00001155 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001156 else {
1157 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1158 if (!setPropertyFn) {
1159 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1160 return;
1161 }
1162 }
1163
John McCall7f16c422011-09-10 09:17:20 +00001164 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1165 // <is-atomic>, <is-copy>).
1166 llvm::Value *cmd =
1167 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1168 llvm::Value *self =
1169 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1170 llvm::Value *ivarOffset =
1171 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1172 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1173 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1174
1175 CallArgList args;
1176 args.add(RValue::get(self), getContext().getObjCIdType());
1177 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001178 if (setOptimizedPropertyFn) {
1179 args.add(RValue::get(arg), getContext().getObjCIdType());
1180 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001181 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1182 FunctionType::ExtInfo(),
1183 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001184 setOptimizedPropertyFn, ReturnValueSlot(), args);
1185 } else {
1186 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1187 args.add(RValue::get(arg), getContext().getObjCIdType());
1188 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1189 getContext().BoolTy);
1190 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1191 getContext().BoolTy);
1192 // FIXME: We shouldn't need to get the function info here, the runtime
1193 // already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001194 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1195 FunctionType::ExtInfo(),
1196 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001197 setPropertyFn, ReturnValueSlot(), args);
1198 }
1199
John McCall7f16c422011-09-10 09:17:20 +00001200 return;
1201 }
1202
John McCallf4528ae2011-09-13 03:34:09 +00001203 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001204 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001205 return;
John McCallf4528ae2011-09-13 03:34:09 +00001206
1207 case PropertyImplStrategy::Expression:
1208 break;
John McCall7f16c422011-09-10 09:17:20 +00001209 }
1210
1211 // Otherwise, fake up some ASTs and emit a normal assignment.
1212 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001213 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1214 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001215 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1216 selfDecl->getType(), CK_LValueToRValue, &self,
1217 VK_RValue);
1218 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001219 SourceLocation(), SourceLocation(),
1220 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001221
1222 ParmVarDecl *argDecl = *setterMethod->param_begin();
1223 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001224 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001225 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1226 argType.getUnqualifiedType(), CK_LValueToRValue,
1227 &arg, VK_RValue);
1228
1229 // The property type can differ from the ivar type in some situations with
1230 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1231 // The following absurdity is just to ensure well-formed IR.
1232 CastKind argCK = CK_NoOp;
1233 if (ivarRef.getType()->isObjCObjectPointerType()) {
1234 if (argLoad.getType()->isObjCObjectPointerType())
1235 argCK = CK_BitCast;
1236 else if (argLoad.getType()->isBlockPointerType())
1237 argCK = CK_BlockPointerToObjCPointerCast;
1238 else
1239 argCK = CK_CPointerToObjCPointerCast;
1240 } else if (ivarRef.getType()->isBlockPointerType()) {
1241 if (argLoad.getType()->isBlockPointerType())
1242 argCK = CK_BitCast;
1243 else
1244 argCK = CK_AnyPointerToBlockPointerCast;
1245 } else if (ivarRef.getType()->isPointerType()) {
1246 argCK = CK_BitCast;
1247 }
1248 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1249 ivarRef.getType(), argCK, &argLoad,
1250 VK_RValue);
1251 Expr *finalArg = &argLoad;
1252 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1253 argLoad.getType()))
1254 finalArg = &argCast;
1255
1256
1257 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1258 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001259 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001260 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001261}
1262
James Dennettbe302452012-06-15 22:10:14 +00001263/// \brief Generate an Objective-C property setter function.
1264///
1265/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001266/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001267void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1268 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001269 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001270 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001271 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1272 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1273 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +00001274 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001275
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001276 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001277
1278 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001279}
1280
John McCall6a4fa522011-03-22 07:05:39 +00001281namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001282 struct DestroyIvar : EHScopeStack::Cleanup {
1283 private:
1284 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001285 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001286 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001287 bool useEHCleanupForArray;
1288 public:
1289 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1290 CodeGenFunction::Destroyer *destroyer,
1291 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001292 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001293 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001294
John McCall30317fd2011-07-12 20:27:29 +00001295 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +00001296 LValue lvalue
1297 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1298 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001299 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001300 }
1301 };
1302}
1303
John McCall4bd0fb12011-07-12 16:41:08 +00001304/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1305static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1306 llvm::Value *addr,
1307 QualType type) {
1308 llvm::Value *null = getNullForVariable(addr);
1309 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1310}
John McCall31168b02011-06-15 23:02:42 +00001311
John McCall6a4fa522011-03-22 07:05:39 +00001312static void emitCXXDestructMethod(CodeGenFunction &CGF,
1313 ObjCImplementationDecl *impl) {
1314 CodeGenFunction::RunCleanupsScope scope(CGF);
1315
1316 llvm::Value *self = CGF.LoadObjCSelf();
1317
Jordy Rosea91768e2011-07-22 02:08:32 +00001318 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1319 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001320 ivar; ivar = ivar->getNextIvar()) {
1321 QualType type = ivar->getType();
1322
John McCall6a4fa522011-03-22 07:05:39 +00001323 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001324 QualType::DestructionKind dtorKind = type.isDestructedType();
1325 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001326
John McCall4bd0fb12011-07-12 16:41:08 +00001327 CodeGenFunction::Destroyer *destroyer = 0;
John McCall6a4fa522011-03-22 07:05:39 +00001328
John McCall4bd0fb12011-07-12 16:41:08 +00001329 // Use a call to objc_storeStrong to destroy strong ivars, for the
1330 // general benefit of the tools.
1331 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001332 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001333
John McCall4bd0fb12011-07-12 16:41:08 +00001334 // Otherwise use the default for the destruction kind.
1335 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001336 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001337 }
John McCall4bd0fb12011-07-12 16:41:08 +00001338
1339 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1340
1341 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1342 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001343 }
1344
1345 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1346}
1347
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001348void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1349 ObjCMethodDecl *MD,
1350 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001351 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001352 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001353
1354 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001355 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001356 // Suppress the final autorelease in ARC.
1357 AutoreleaseResult = false;
1358
John McCall6a4fa522011-03-22 07:05:39 +00001359 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1360 E = IMP->init_end(); B != E; ++B) {
1361 CXXCtorInitializer *IvarInit = (*B);
Francois Pichetd583da02010-12-04 09:14:42 +00001362 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +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
1508 // empty; skip all this.
1509 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1510 EmptyBB, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001511
John McCall1c926b72011-01-07 01:49:06 +00001512 // Otherwise, initialize the loop.
1513 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001514
John McCall1c926b72011-01-07 01:49:06 +00001515 // Save the initial mutations value. This is the value at an
1516 // address that was written into the state object by
1517 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001518 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001519 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001520 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001521 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001522
John McCall1c926b72011-01-07 01:49:06 +00001523 llvm::Value *initialMutations =
1524 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001525
Justin Bogneref512b92014-01-06 22:27:43 +00001526 RegionCounter Cnt = getPGORegionCounter(&S);
1527
John McCall1c926b72011-01-07 01:49:06 +00001528 // Start looping. This is the point we return to whenever we have a
1529 // fresh, non-empty batch of objects.
1530 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1531 EmitBlock(LoopBodyBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001532 Cnt.beginRegion(Builder);
Mike Stump11289f42009-09-09 15:08:12 +00001533
John McCall1c926b72011-01-07 01:49:06 +00001534 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001535 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001536 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001537
John McCall1c926b72011-01-07 01:49:06 +00001538 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001539 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001540 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001541
John McCall1c926b72011-01-07 01:49:06 +00001542 // Check whether the mutations value has changed from where it was
1543 // at start. StateMutationsPtr should actually be invariant between
1544 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001545 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001546 llvm::Value *currentMutations
1547 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001548
John McCall1c926b72011-01-07 01:49:06 +00001549 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001550 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001551
John McCall1c926b72011-01-07 01:49:06 +00001552 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1553 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001554
John McCall1c926b72011-01-07 01:49:06 +00001555 // If so, call the enumeration-mutation function.
1556 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001557 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001558 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001559 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001560 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001561 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001562 // FIXME: We shouldn't need to get the function info here, the runtime already
1563 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001564 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1565 FunctionType::ExtInfo(),
1566 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001567 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001568
John McCall1c926b72011-01-07 01:49:06 +00001569 // Otherwise, or if the mutation function returns, just continue.
1570 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001571
John McCall1c926b72011-01-07 01:49:06 +00001572 // Initialize the element variable.
1573 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001574 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001575 LValue elementLValue;
1576 QualType elementType;
1577 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001578 // Initialize the variable, in case it's a __block variable or something.
1579 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001580
John McCall9e2e22f2011-02-22 07:16:58 +00001581 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001582 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001583 VK_LValue, SourceLocation());
1584 elementLValue = EmitLValue(&tempDRE);
1585 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001586 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001587
1588 if (D->isARCPseudoStrong())
1589 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001590 } else {
1591 elementLValue = LValue(); // suppress warning
1592 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001593 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001594 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001595 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001596
1597 // Fetch the buffer out of the enumeration state.
1598 // TODO: this pointer should actually be invariant between
1599 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001600 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001601 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001602 llvm::Value *EnumStateItems =
1603 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001604
John McCall1c926b72011-01-07 01:49:06 +00001605 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001606 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001607 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1608 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCall1c926b72011-01-07 01:49:06 +00001610 // Cast that value to the right type.
1611 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1612 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001613
John McCall1c926b72011-01-07 01:49:06 +00001614 // Make sure we have an l-value. Yes, this gets evaluated every
1615 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001616 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001617 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001618 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001619 } else {
1620 EmitScalarInit(CurrentItem, elementLValue);
1621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
John McCall9e2e22f2011-02-22 07:16:58 +00001623 // If we do have an element variable, this assignment is the end of
1624 // its initialization.
1625 if (elementIsVariable)
1626 EmitAutoVarCleanups(variable);
1627
John McCall1c926b72011-01-07 01:49:06 +00001628 // Perform the loop body, setting up break and continue labels.
Justin Bogneref512b92014-01-06 22:27:43 +00001629 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody, &Cnt));
John McCall1c926b72011-01-07 01:49:06 +00001630 {
1631 RunCleanupsScope Scope(*this);
1632 EmitStmt(S.getBody());
1633 }
Anders Carlsson75658592008-08-31 02:33:12 +00001634 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001635
John McCall1c926b72011-01-07 01:49:06 +00001636 // Destroy the element variable now.
1637 elementVariableScope.ForceCleanup();
1638
1639 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001640 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001641
John McCall1c926b72011-01-07 01:49:06 +00001642 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001643
John McCall1c926b72011-01-07 01:49:06 +00001644 // First we check in the local buffer.
1645 llvm::Value *indexPlusOne
1646 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001647
Justin Bogneref512b92014-01-06 22:27:43 +00001648 // TODO: We should probably model this as a "continue" for PGO
John McCall1c926b72011-01-07 01:49:06 +00001649 // If we haven't overrun the buffer yet, we can continue.
1650 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1651 LoopBodyBB, FetchMoreBB);
1652
1653 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1654 count->addIncoming(count, AfterBody.getBlock());
1655
1656 // Otherwise, we have to fetch more elements.
1657 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001658
1659 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001660 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001661 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001662 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001663 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001664
John McCall1c926b72011-01-07 01:49:06 +00001665 // If we got a zero count, we're done.
1666 llvm::Value *refetchCount = CountRV.getScalarVal();
1667
1668 // (note that the message send might split FetchMoreBB)
1669 index->addIncoming(zero, Builder.GetInsertBlock());
1670 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1671
Justin Bogneref512b92014-01-06 22:27:43 +00001672 // TODO: We should be applying PGO weights here, but this needs to handle the
1673 // branch before FetchMoreBB or we risk getting the numbers wrong.
John McCall1c926b72011-01-07 01:49:06 +00001674 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1675 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001676
Anders Carlsson75658592008-08-31 02:33:12 +00001677 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001678 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001679
John McCall9e2e22f2011-02-22 07:16:58 +00001680 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001681 // If the element was not a declaration, set it to be null.
1682
John McCall1c926b72011-01-07 01:49:06 +00001683 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1684 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001685 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001686 }
1687
Eric Christopher7cdf9482011-10-13 21:45:18 +00001688 if (DI)
1689 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001690
John McCall53848232011-07-27 01:07:15 +00001691 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001692 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001693 PopCleanupBlock();
1694
John McCallad5d61e2010-07-23 21:56:41 +00001695 EmitBlock(LoopEnd.getBlock());
Justin Bogneref512b92014-01-06 22:27:43 +00001696 // TODO: Once we calculate PGO weights above, set the region count here
Anders Carlsson2e744e82008-08-30 19:51:14 +00001697}
1698
Mike Stump11289f42009-09-09 15:08:12 +00001699void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001700 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001701}
1702
Mike Stump11289f42009-09-09 15:08:12 +00001703void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001704 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1705}
1706
Chris Lattnere132e242008-11-15 21:26:17 +00001707void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001708 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001709 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001710}
1711
John McCall2d637d22011-09-10 06:18:15 +00001712/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001713/// primitive retain.
1714llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1715 llvm::Value *value) {
1716 return EmitARCRetain(type, value);
1717}
1718
1719namespace {
1720 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001721 CallObjCRelease(llvm::Value *object) : object(object) {}
1722 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001723
John McCall30317fd2011-07-12 20:27:29 +00001724 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallcdda29c2013-03-13 03:10:54 +00001725 // Releases at the end of the full-expression are imprecise.
1726 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001727 }
1728 };
1729}
1730
John McCall2d637d22011-09-10 06:18:15 +00001731/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001732/// release at the end of the full-expression.
1733llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1734 llvm::Value *object) {
1735 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001736 // conditional.
1737 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001738 return object;
1739}
1740
1741llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1742 llvm::Value *value) {
1743 return EmitARCRetainAutorelease(type, value);
1744}
1745
John McCalleff18842013-03-23 02:35:54 +00001746/// Given a number of pointers, inform the optimizer that they're
1747/// being intrinsically used up until this point in the program.
1748void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1749 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1750 if (!fn) {
1751 llvm::FunctionType *fnType =
1752 llvm::FunctionType::get(CGM.VoidTy, ArrayRef<llvm::Type*>(), true);
1753 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1754 }
1755
1756 // This isn't really a "runtime" function, but as an intrinsic it
1757 // doesn't really matter as long as we align things up.
1758 EmitNounwindRuntimeCall(fn, values);
1759}
1760
John McCall31168b02011-06-15 23:02:42 +00001761
1762static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001763 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001764 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001765 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1766
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001767 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001768 // If the target runtime doesn't naturally support ARC, emit weak
1769 // references to the runtime support library. We don't really
1770 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001771 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001772 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001773 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1774 // If we have Native ARC, set nonlazybind attribute for these APIs for
1775 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001776 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001777 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001778 }
John McCall31168b02011-06-15 23:02:42 +00001779
1780 return fn;
1781}
1782
1783/// Perform an operation having the signature
1784/// i8* (i8*)
1785/// where a null input causes a no-op and returns null.
1786static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1787 llvm::Value *value,
1788 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001789 StringRef fnName,
1790 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001791 if (isa<llvm::ConstantPointerNull>(value)) return value;
1792
1793 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001794 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001795 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001796 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1797 }
1798
1799 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001800 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001801 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1802
1803 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001804 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001805 if (isTailCall)
1806 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001807
1808 // Cast the result back to the original type.
1809 return CGF.Builder.CreateBitCast(call, origType);
1810}
1811
1812/// Perform an operation having the following signature:
1813/// i8* (i8**)
1814static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1815 llvm::Value *addr,
1816 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001817 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001818 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001819 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001820 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001821 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1822 }
1823
1824 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001825 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001826 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1827
1828 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001829 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00001830
1831 // Cast the result back to a dereference of the original type.
John McCall31168b02011-06-15 23:02:42 +00001832 if (origType != CGF.Int8PtrPtrTy)
1833 result = CGF.Builder.CreateBitCast(result,
1834 cast<llvm::PointerType>(origType)->getElementType());
1835
1836 return result;
1837}
1838
1839/// Perform an operation having the following signature:
1840/// i8* (i8**, i8*)
1841static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1842 llvm::Value *addr,
1843 llvm::Value *value,
1844 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001845 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001846 bool ignored) {
1847 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1848 == value->getType());
1849
1850 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001851 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001852
Chris Lattner2192fe52011-07-18 04:24:23 +00001853 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001854 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1855 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1856 }
1857
Chris Lattner2192fe52011-07-18 04:24:23 +00001858 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001859
John McCall882987f2013-02-28 19:01:20 +00001860 llvm::Value *args[] = {
1861 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1862 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1863 };
1864 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001865
1866 if (ignored) return 0;
1867
1868 return CGF.Builder.CreateBitCast(result, origType);
1869}
1870
1871/// Perform an operation having the following signature:
1872/// void (i8**, i8**)
1873static void emitARCCopyOperation(CodeGenFunction &CGF,
1874 llvm::Value *dst,
1875 llvm::Value *src,
1876 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001877 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001878 assert(dst->getType() == src->getType());
1879
1880 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001881 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1882
Chris Lattner2192fe52011-07-18 04:24:23 +00001883 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001884 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1885 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1886 }
1887
John McCall882987f2013-02-28 19:01:20 +00001888 llvm::Value *args[] = {
1889 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1890 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1891 };
1892 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001893}
1894
1895/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001896/// call i8* \@objc_retain(i8* %value)
1897/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001898llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1899 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001900 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001901 else
1902 return EmitARCRetainNonBlock(value);
1903}
1904
1905/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001906/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001907llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1908 return emitARCValueOperation(*this, value,
1909 CGM.getARCEntrypoints().objc_retain,
1910 "objc_retain");
1911}
1912
1913/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001914/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001915///
1916/// \param mandatory - If false, emit the call with metadata
1917/// indicating that it's okay for the optimizer to eliminate this call
1918/// if it can prove that the block never escapes except down the stack.
1919llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1920 bool mandatory) {
1921 llvm::Value *result
1922 = emitARCValueOperation(*this, value,
1923 CGM.getARCEntrypoints().objc_retainBlock,
1924 "objc_retainBlock");
1925
1926 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1927 // tell the optimizer that it doesn't need to do this copy if the
1928 // block doesn't escape, where being passed as an argument doesn't
1929 // count as escaping.
1930 if (!mandatory && isa<llvm::Instruction>(result)) {
1931 llvm::CallInst *call
1932 = cast<llvm::CallInst>(result->stripPointerCasts());
1933 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1934
1935 SmallVector<llvm::Value*,1> args;
1936 call->setMetadata("clang.arc.copy_on_escape",
1937 llvm::MDNode::get(Builder.getContext(), args));
1938 }
1939
1940 return result;
John McCall31168b02011-06-15 23:02:42 +00001941}
1942
1943/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001944/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001945///
1946/// Yes, this function name is one character away from a different
1947/// call with completely different semantics.
1948llvm::Value *
1949CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1950 // Fetch the void(void) inline asm which marks that we're going to
1951 // retain the autoreleased return value.
1952 llvm::InlineAsm *&marker
1953 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1954 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001955 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001956 = CGM.getTargetCodeGenInfo()
1957 .getARCRetainAutoreleasedReturnValueMarker();
1958
1959 // If we have an empty assembly string, there's nothing to do.
1960 if (assembly.empty()) {
1961
1962 // Otherwise, at -O0, build an inline asm that we're going to call
1963 // in a moment.
1964 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1965 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001966 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001967
1968 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1969
1970 // If we're at -O1 and above, we don't want to litter the code
1971 // with this marker yet, so leave a breadcrumb for the ARC
1972 // optimizer to pick up.
1973 } else {
1974 llvm::NamedMDNode *metadata =
1975 CGM.getModule().getOrInsertNamedMetadata(
1976 "clang.arc.retainAutoreleasedReturnValueMarker");
1977 assert(metadata->getNumOperands() <= 1);
1978 if (metadata->getNumOperands() == 0) {
1979 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00001980 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00001981 }
1982 }
1983 }
1984
1985 // Call the marker asm if we made one, which we do only at -O0.
1986 if (marker) Builder.CreateCall(marker);
1987
1988 return emitARCValueOperation(*this, value,
1989 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1990 "objc_retainAutoreleasedReturnValue");
1991}
1992
1993/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00001994/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00001995void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1996 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00001997 if (isa<llvm::ConstantPointerNull>(value)) return;
1998
1999 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2000 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002001 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002002 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002003 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2004 }
2005
2006 // Cast the argument to 'id'.
2007 value = Builder.CreateBitCast(value, Int8PtrTy);
2008
2009 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002010 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002011
John McCallcdda29c2013-03-13 03:10:54 +00002012 if (precise == ARCImpreciseLifetime) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002013 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00002014 call->setMetadata("clang.imprecise_release",
2015 llvm::MDNode::get(Builder.getContext(), args));
2016 }
2017}
2018
John McCalle68b8f42012-10-17 02:28:37 +00002019/// Destroy a __strong variable.
2020///
2021/// At -O0, emit a call to store 'null' into the address;
2022/// instrumenting tools prefer this because the address is exposed,
2023/// but it's relatively cumbersome to optimize.
2024///
2025/// At -O1 and above, just load and call objc_release.
2026///
2027/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCallcdda29c2013-03-13 03:10:54 +00002028void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2029 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002030 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2031 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2032 llvm::Value *null = llvm::ConstantPointerNull::get(
2033 cast<llvm::PointerType>(addrTy->getElementType()));
2034 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2035 return;
2036 }
2037
2038 llvm::Value *value = Builder.CreateLoad(addr);
2039 EmitARCRelease(value, precise);
2040}
2041
John McCall31168b02011-06-15 23:02:42 +00002042/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002043/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002044llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2045 llvm::Value *value,
2046 bool ignored) {
2047 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2048 == value->getType());
2049
2050 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2051 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002052 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002053 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002054 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2055 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2056 }
2057
John McCall882987f2013-02-28 19:01:20 +00002058 llvm::Value *args[] = {
2059 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2060 Builder.CreateBitCast(value, Int8PtrTy)
2061 };
2062 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002063
2064 if (ignored) return 0;
2065 return value;
2066}
2067
2068/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002069/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002070/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002071llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002072 llvm::Value *newValue,
2073 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002074 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002075 bool isBlock = type->isBlockPointerType();
2076
2077 // Use a store barrier at -O0 unless this is a block type or the
2078 // lvalue is inadequately aligned.
2079 if (shouldUseFusedARCCalls() &&
2080 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002081 (dst.getAlignment().isZero() ||
2082 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002083 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2084 }
2085
2086 // Otherwise, split it out.
2087
2088 // Retain the new value.
2089 newValue = EmitARCRetain(type, newValue);
2090
2091 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002092 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002093
2094 // Store. We do this before the release so that any deallocs won't
2095 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002096 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002097
2098 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002099 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002100
2101 return newValue;
2102}
2103
2104/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002105/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002106llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2107 return emitARCValueOperation(*this, value,
2108 CGM.getARCEntrypoints().objc_autorelease,
2109 "objc_autorelease");
2110}
2111
2112/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002113/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002114llvm::Value *
2115CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2116 return emitARCValueOperation(*this, value,
2117 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002118 "objc_autoreleaseReturnValue",
2119 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002120}
2121
2122/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002123/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002124llvm::Value *
2125CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2126 return emitARCValueOperation(*this, value,
2127 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002128 "objc_retainAutoreleaseReturnValue",
2129 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002130}
2131
2132/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002133/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002134/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002135/// %retain = call i8* \@objc_retainBlock(i8* %value)
2136/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002137llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2138 llvm::Value *value) {
2139 if (!type->isBlockPointerType())
2140 return EmitARCRetainAutoreleaseNonBlock(value);
2141
2142 if (isa<llvm::ConstantPointerNull>(value)) return value;
2143
Chris Lattner2192fe52011-07-18 04:24:23 +00002144 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002145 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002146 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002147 value = EmitARCAutorelease(value);
2148 return Builder.CreateBitCast(value, origType);
2149}
2150
2151/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002152/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002153llvm::Value *
2154CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2155 return emitARCValueOperation(*this, value,
2156 CGM.getARCEntrypoints().objc_retainAutorelease,
2157 "objc_retainAutorelease");
2158}
2159
James Dennett14c41ea2012-06-22 05:41:30 +00002160/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002161/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2162llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2163 return emitARCLoadOperation(*this, addr,
2164 CGM.getARCEntrypoints().objc_loadWeak,
2165 "objc_loadWeak");
2166}
2167
James Dennett14c41ea2012-06-22 05:41:30 +00002168/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002169llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2170 return emitARCLoadOperation(*this, addr,
2171 CGM.getARCEntrypoints().objc_loadWeakRetained,
2172 "objc_loadWeakRetained");
2173}
2174
James Dennett14c41ea2012-06-22 05:41:30 +00002175/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002176/// Returns %value.
2177llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2178 llvm::Value *value,
2179 bool ignored) {
2180 return emitARCStoreOperation(*this, addr, value,
2181 CGM.getARCEntrypoints().objc_storeWeak,
2182 "objc_storeWeak", ignored);
2183}
2184
James Dennett14c41ea2012-06-22 05:41:30 +00002185/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002186/// Returns %value. %addr is known to not have a current weak entry.
2187/// Essentially equivalent to:
2188/// *addr = nil; objc_storeWeak(addr, value);
2189void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2190 // If we're initializing to null, just write null to memory; no need
2191 // to get the runtime involved. But don't do this if optimization
2192 // is enabled, because accounting for this would make the optimizer
2193 // much more complicated.
2194 if (isa<llvm::ConstantPointerNull>(value) &&
2195 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2196 Builder.CreateStore(value, addr);
2197 return;
2198 }
2199
2200 emitARCStoreOperation(*this, addr, value,
2201 CGM.getARCEntrypoints().objc_initWeak,
2202 "objc_initWeak", /*ignored*/ true);
2203}
2204
James Dennett14c41ea2012-06-22 05:41:30 +00002205/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002206/// Essentially objc_storeWeak(addr, nil).
2207void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2208 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2209 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002210 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002211 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002212 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2213 }
2214
2215 // Cast the argument to 'id*'.
2216 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2217
John McCall882987f2013-02-28 19:01:20 +00002218 EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00002219}
2220
James Dennett14c41ea2012-06-22 05:41:30 +00002221/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002222/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2223/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2224void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2225 emitARCCopyOperation(*this, dst, src,
2226 CGM.getARCEntrypoints().objc_moveWeak,
2227 "objc_moveWeak");
2228}
2229
James Dennett14c41ea2012-06-22 05:41:30 +00002230/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002231/// Disregards the current value in %dest. Essentially
2232/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2233void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2234 emitARCCopyOperation(*this, dst, src,
2235 CGM.getARCEntrypoints().objc_copyWeak,
2236 "objc_copyWeak");
2237}
2238
2239/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002240/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002241llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2242 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2243 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002244 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002245 llvm::FunctionType::get(Int8PtrTy, false);
2246 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2247 }
2248
John McCall882987f2013-02-28 19:01:20 +00002249 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002250}
2251
2252/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002253/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002254void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2255 assert(value->getType() == Int8PtrTy);
2256
2257 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2258 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002259 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002260 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002261
2262 // We don't want to use a weak import here; instead we should not
2263 // fall into this path.
2264 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2265 }
2266
John McCallb7ff6db2013-04-16 21:29:40 +00002267 // objc_autoreleasePoolPop can throw.
2268 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002269}
2270
2271/// Produce the code to do an MRR version objc_autoreleasepool_push.
2272/// Which is: [[NSAutoreleasePool alloc] init];
2273/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2274/// init is declared as: - (id) init; in its NSObject super class.
2275///
2276llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2277 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002278 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002279 // [NSAutoreleasePool alloc]
2280 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2281 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2282 CallArgList Args;
2283 RValue AllocRV =
2284 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2285 getContext().getObjCIdType(),
2286 AllocSel, Receiver, Args);
2287
2288 // [Receiver init]
2289 Receiver = AllocRV.getScalarVal();
2290 II = &CGM.getContext().Idents.get("init");
2291 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2292 RValue InitRV =
2293 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2294 getContext().getObjCIdType(),
2295 InitSel, Receiver, Args);
2296 return InitRV.getScalarVal();
2297}
2298
2299/// Produce the code to do a primitive release.
2300/// [tmp drain];
2301void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2302 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2303 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2304 CallArgList Args;
2305 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2306 getContext().VoidTy, DrainSel, Arg, Args);
2307}
2308
John McCall82fe67b2011-07-09 01:37:26 +00002309void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2310 llvm::Value *addr,
2311 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002312 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002313}
2314
2315void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2316 llvm::Value *addr,
2317 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002318 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002319}
2320
2321void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2322 llvm::Value *addr,
2323 QualType type) {
2324 CGF.EmitARCDestroyWeak(addr);
2325}
2326
John McCall31168b02011-06-15 23:02:42 +00002327namespace {
John McCall31168b02011-06-15 23:02:42 +00002328 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2329 llvm::Value *Token;
2330
2331 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2332
John McCall30317fd2011-07-12 20:27:29 +00002333 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002334 CGF.EmitObjCAutoreleasePoolPop(Token);
2335 }
2336 };
2337 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2338 llvm::Value *Token;
2339
2340 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2341
John McCall30317fd2011-07-12 20:27:29 +00002342 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002343 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2344 }
2345 };
2346}
2347
2348void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002349 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002350 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2351 else
2352 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2353}
2354
John McCall31168b02011-06-15 23:02:42 +00002355static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2356 LValue lvalue,
2357 QualType type) {
2358 switch (type.getObjCLifetime()) {
2359 case Qualifiers::OCL_None:
2360 case Qualifiers::OCL_ExplicitNone:
2361 case Qualifiers::OCL_Strong:
2362 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002363 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2364 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002365 false);
2366
2367 case Qualifiers::OCL_Weak:
2368 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2369 true);
2370 }
2371
2372 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002373}
2374
2375static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2376 const Expr *e) {
2377 e = e->IgnoreParens();
2378 QualType type = e->getType();
2379
John McCall154a2fd2011-08-30 00:57:29 +00002380 // If we're loading retained from a __strong xvalue, we can avoid
2381 // an extra retain/release pair by zeroing out the source of this
2382 // "move" operation.
2383 if (e->isXValue() &&
2384 !type.isConstQualified() &&
2385 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2386 // Emit the lvalue.
2387 LValue lv = CGF.EmitLValue(e);
2388
2389 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002390 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2391 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002392
2393 // Set the source pointer to NULL.
2394 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2395
2396 return TryEmitResult(result, true);
2397 }
2398
John McCall31168b02011-06-15 23:02:42 +00002399 // As a very special optimization, in ARC++, if the l-value is the
2400 // result of a non-volatile assignment, do a simple retain of the
2401 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002402 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002403 !type.isVolatileQualified() &&
2404 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2405 isa<BinaryOperator>(e) &&
2406 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2407 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2408
2409 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2410}
2411
2412static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2413 llvm::Value *value);
2414
2415/// Given that the given expression is some sort of call (which does
2416/// not return retained), emit a retain following it.
2417static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2418 llvm::Value *value = CGF.EmitScalarExpr(e);
2419 return emitARCRetainAfterCall(CGF, value);
2420}
2421
2422static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2423 llvm::Value *value) {
2424 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2425 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2426
2427 // Place the retain immediately following the call.
2428 CGF.Builder.SetInsertPoint(call->getParent(),
2429 ++llvm::BasicBlock::iterator(call));
2430 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2431
2432 CGF.Builder.restoreIP(ip);
2433 return value;
2434 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2435 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2436
2437 // Place the retain at the beginning of the normal destination block.
2438 llvm::BasicBlock *BB = invoke->getNormalDest();
2439 CGF.Builder.SetInsertPoint(BB, BB->begin());
2440 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2441
2442 CGF.Builder.restoreIP(ip);
2443 return value;
2444
2445 // Bitcasts can arise because of related-result returns. Rewrite
2446 // the operand.
2447 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2448 llvm::Value *operand = bitcast->getOperand(0);
2449 operand = emitARCRetainAfterCall(CGF, operand);
2450 bitcast->setOperand(0, operand);
2451 return bitcast;
2452
2453 // Generic fall-back case.
2454 } else {
2455 // Retain using the non-block variant: we never need to do a copy
2456 // of a block that's been returned to us.
2457 return CGF.EmitARCRetainNonBlock(value);
2458 }
2459}
2460
John McCallcd78e802011-09-10 01:16:55 +00002461/// Determine whether it might be important to emit a separate
2462/// objc_retain_block on the result of the given expression, or
2463/// whether it's okay to just emit it in a +1 context.
2464static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2465 assert(e->getType()->isBlockPointerType());
2466 e = e->IgnoreParens();
2467
2468 // For future goodness, emit block expressions directly in +1
2469 // contexts if we can.
2470 if (isa<BlockExpr>(e))
2471 return false;
2472
2473 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2474 switch (cast->getCastKind()) {
2475 // Emitting these operations in +1 contexts is goodness.
2476 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002477 case CK_ARCReclaimReturnedObject:
2478 case CK_ARCConsumeObject:
2479 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002480 return false;
2481
2482 // These operations preserve a block type.
2483 case CK_NoOp:
2484 case CK_BitCast:
2485 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2486
2487 // These operations are known to be bad (or haven't been considered).
2488 case CK_AnyPointerToBlockPointerCast:
2489 default:
2490 return true;
2491 }
2492 }
2493
2494 return true;
2495}
2496
John McCallfe96e0b2011-11-06 09:01:30 +00002497/// Try to emit a PseudoObjectExpr at +1.
2498///
2499/// This massively duplicates emitPseudoObjectRValue.
2500static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2501 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002502 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002503
2504 // Find the result expression.
2505 const Expr *resultExpr = E->getResultExpr();
2506 assert(resultExpr);
2507 TryEmitResult result;
2508
2509 for (PseudoObjectExpr::const_semantics_iterator
2510 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2511 const Expr *semantic = *i;
2512
2513 // If this semantic expression is an opaque value, bind it
2514 // to the result of its source expression.
2515 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2516 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2517 OVMA opaqueData;
2518
2519 // If this semantic is the result of the pseudo-object
2520 // expression, try to evaluate the source as +1.
2521 if (ov == resultExpr) {
2522 assert(!OVMA::shouldBindAsLValue(ov));
2523 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2524 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2525
2526 // Otherwise, just bind it.
2527 } else {
2528 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2529 }
2530 opaques.push_back(opaqueData);
2531
2532 // Otherwise, if the expression is the result, evaluate it
2533 // and remember the result.
2534 } else if (semantic == resultExpr) {
2535 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2536
2537 // Otherwise, evaluate the expression in an ignored context.
2538 } else {
2539 CGF.EmitIgnoredExpr(semantic);
2540 }
2541 }
2542
2543 // Unbind all the opaques now.
2544 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2545 opaques[i].unbind(CGF);
2546
2547 return result;
2548}
2549
John McCall31168b02011-06-15 23:02:42 +00002550static TryEmitResult
2551tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002552 // We should *never* see a nested full-expression here, because if
2553 // we fail to emit at +1, our caller must not retain after we close
2554 // out the full-expression.
2555 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002556
John McCall31168b02011-06-15 23:02:42 +00002557 // The desired result type, if it differs from the type of the
2558 // ultimate opaque expression.
Chris Lattner2192fe52011-07-18 04:24:23 +00002559 llvm::Type *resultType = 0;
John McCall31168b02011-06-15 23:02:42 +00002560
2561 while (true) {
2562 e = e->IgnoreParens();
2563
2564 // There's a break at the end of this if-chain; anything
2565 // that wants to keep looping has to explicitly continue.
2566 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2567 switch (ce->getCastKind()) {
2568 // No-op casts don't change the type, so we just ignore them.
2569 case CK_NoOp:
2570 e = ce->getSubExpr();
2571 continue;
2572
2573 case CK_LValueToRValue: {
2574 TryEmitResult loadResult
2575 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2576 if (resultType) {
2577 llvm::Value *value = loadResult.getPointer();
2578 value = CGF.Builder.CreateBitCast(value, resultType);
2579 loadResult.setPointer(value);
2580 }
2581 return loadResult;
2582 }
2583
2584 // These casts can change the type, so remember that and
2585 // soldier on. We only need to remember the outermost such
2586 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002587 case CK_CPointerToObjCPointerCast:
2588 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002589 case CK_AnyPointerToBlockPointerCast:
2590 case CK_BitCast:
2591 if (!resultType)
2592 resultType = CGF.ConvertType(ce->getType());
2593 e = ce->getSubExpr();
2594 assert(e->getType()->hasPointerRepresentation());
2595 continue;
2596
2597 // For consumptions, just emit the subexpression and thus elide
2598 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002599 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002600 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2601 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2602 return TryEmitResult(result, true);
2603 }
2604
John McCallcd78e802011-09-10 01:16:55 +00002605 // Block extends are net +0. Naively, we could just recurse on
2606 // the subexpression, but actually we need to ensure that the
2607 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002608 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002609 llvm::Value *result; // will be a +0 value
2610
2611 // If we can't safely assume the sub-expression will produce a
2612 // block-copied value, emit the sub-expression at +0.
2613 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2614 result = CGF.EmitScalarExpr(ce->getSubExpr());
2615
2616 // Otherwise, try to emit the sub-expression at +1 recursively.
2617 } else {
2618 TryEmitResult subresult
2619 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2620 result = subresult.getPointer();
2621
2622 // If that produced a retained value, just use that,
2623 // possibly casting down.
2624 if (subresult.getInt()) {
2625 if (resultType)
2626 result = CGF.Builder.CreateBitCast(result, resultType);
2627 return TryEmitResult(result, true);
2628 }
2629
2630 // Otherwise it's +0.
2631 }
2632
2633 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002634 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002635 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2636 return TryEmitResult(result, true);
2637 }
2638
John McCall4db5c3c2011-07-07 06:58:02 +00002639 // For reclaims, emit the subexpression as a retained call and
2640 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002641 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002642 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2643 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2644 return TryEmitResult(result, true);
2645 }
2646
John McCall31168b02011-06-15 23:02:42 +00002647 default:
2648 break;
2649 }
2650
2651 // Skip __extension__.
2652 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2653 if (op->getOpcode() == UO_Extension) {
2654 e = op->getSubExpr();
2655 continue;
2656 }
2657
2658 // For calls and message sends, use the retained-call logic.
2659 // Delegate inits are a special case in that they're the only
2660 // returns-retained expression that *isn't* surrounded by
2661 // a consume.
2662 } else if (isa<CallExpr>(e) ||
2663 (isa<ObjCMessageExpr>(e) &&
2664 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2665 llvm::Value *result = emitARCRetainCall(CGF, e);
2666 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2667 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002668
2669 // Look through pseudo-object expressions.
2670 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2671 TryEmitResult result
2672 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2673 if (resultType) {
2674 llvm::Value *value = result.getPointer();
2675 value = CGF.Builder.CreateBitCast(value, resultType);
2676 result.setPointer(value);
2677 }
2678 return result;
John McCall31168b02011-06-15 23:02:42 +00002679 }
2680
2681 // Conservatively halt the search at any other expression kind.
2682 break;
2683 }
2684
2685 // We didn't find an obvious production, so emit what we've got and
2686 // tell the caller that we didn't manage to retain.
2687 llvm::Value *result = CGF.EmitScalarExpr(e);
2688 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2689 return TryEmitResult(result, false);
2690}
2691
2692static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2693 LValue lvalue,
2694 QualType type) {
2695 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2696 llvm::Value *value = result.getPointer();
2697 if (!result.getInt())
2698 value = CGF.EmitARCRetain(type, value);
2699 return value;
2700}
2701
2702/// EmitARCRetainScalarExpr - Semantically equivalent to
2703/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2704/// best-effort attempt to peephole expressions that naturally produce
2705/// retained objects.
2706llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002707 // The retain needs to happen within the full-expression.
2708 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2709 enterFullExpression(cleanups);
2710 RunCleanupsScope scope(*this);
2711 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2712 }
2713
John McCall31168b02011-06-15 23:02:42 +00002714 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2715 llvm::Value *value = result.getPointer();
2716 if (!result.getInt())
2717 value = EmitARCRetain(e->getType(), value);
2718 return value;
2719}
2720
2721llvm::Value *
2722CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002723 // The retain needs to happen within the full-expression.
2724 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2725 enterFullExpression(cleanups);
2726 RunCleanupsScope scope(*this);
2727 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2728 }
2729
John McCall31168b02011-06-15 23:02:42 +00002730 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2731 llvm::Value *value = result.getPointer();
2732 if (result.getInt())
2733 value = EmitARCAutorelease(value);
2734 else
2735 value = EmitARCRetainAutorelease(e->getType(), value);
2736 return value;
2737}
2738
John McCallff613032011-10-04 06:23:45 +00002739llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2740 llvm::Value *result;
2741 bool doRetain;
2742
2743 if (shouldEmitSeparateBlockRetain(e)) {
2744 result = EmitScalarExpr(e);
2745 doRetain = true;
2746 } else {
2747 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2748 result = subresult.getPointer();
2749 doRetain = !subresult.getInt();
2750 }
2751
2752 if (doRetain)
2753 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2754 return EmitObjCConsumeObject(e->getType(), result);
2755}
2756
John McCall248512a2011-10-01 10:32:24 +00002757llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2758 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002759 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002760 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002761 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002762 return EmitARCRetainAutoreleaseScalarExpr(expr);
2763 }
2764
2765 // Otherwise, use the normal scalar-expression emission. The
2766 // exception machinery doesn't do anything special with the
2767 // exception like retaining it, so there's no safety associated with
2768 // only running cleanups after the throw has started, and when it
2769 // matters it tends to be substantially inferior code.
2770 return EmitScalarExpr(expr);
2771}
2772
John McCall31168b02011-06-15 23:02:42 +00002773std::pair<LValue,llvm::Value*>
2774CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2775 bool ignored) {
2776 // Evaluate the RHS first.
2777 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2778 llvm::Value *value = result.getPointer();
2779
John McCallb726a552011-07-28 07:23:35 +00002780 bool hasImmediateRetain = result.getInt();
2781
2782 // If we didn't emit a retained object, and the l-value is of block
2783 // type, then we need to emit the block-retain immediately in case
2784 // it invalidates the l-value.
2785 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002786 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002787 hasImmediateRetain = true;
2788 }
2789
John McCall31168b02011-06-15 23:02:42 +00002790 LValue lvalue = EmitLValue(e->getLHS());
2791
2792 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002793 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002794 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002795 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002796 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002797 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002798 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002799 }
2800
2801 return std::pair<LValue,llvm::Value*>(lvalue, value);
2802}
2803
2804std::pair<LValue,llvm::Value*>
2805CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2806 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2807 LValue lvalue = EmitLValue(e->getLHS());
2808
Eli Friedmana0544d62011-12-03 04:14:32 +00002809 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002810
2811 return std::pair<LValue,llvm::Value*>(lvalue, value);
2812}
2813
2814void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002815 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002816 const Stmt *subStmt = ARPS.getSubStmt();
2817 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2818
2819 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002820 if (DI)
2821 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002822
2823 // Keep track of the current cleanup stack depth.
2824 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002825 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002826 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2827 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2828 } else {
2829 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2830 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2831 }
2832
2833 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2834 E = S.body_end(); I != E; ++I)
2835 EmitStmt(*I);
2836
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())
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002866 return 0;
2867 QualType Ty = PID->getPropertyIvarDecl()->getType();
2868 if (!Ty->isRecordType())
2869 return 0;
2870 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002871 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002872 return 0;
Fariborz Jahanian1bed4132012-01-08 19:13:23 +00002873 llvm::Constant * HelperFn = 0;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002874 if (hasTrivialSetExpr(PID))
2875 return 0;
2876 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(),
2886 SourceLocation(), II, C.VoidTy, 0,
2887 SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002888 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002889 false);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002890
2891 QualType DestTy = C.getPointerType(Ty);
2892 QualType SrcTy = Ty;
2893 SrcTy.addConst();
2894 SrcTy = C.getPointerType(SrcTy);
2895
2896 FunctionArgList args;
2897 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2898 args.push_back(&dstDecl);
2899 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2900 args.push_back(&srcDecl);
2901
2902 const CGFunctionInfo &FI =
John McCalla729c622012-02-17 03:33:10 +00002903 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2904 FunctionType::ExtInfo(),
2905 RequiredArgs::All);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002906
John McCalla729c622012-02-17 03:33:10 +00002907 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002908
2909 llvm::Function *Fn =
2910 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002911 "__assign_helper_atomic_property_",
2912 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002913
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002914 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2915
John McCall113bee02012-03-10 09:33:50 +00002916 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2917 VK_RValue, SourceLocation());
2918 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2919 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002920
John McCall113bee02012-03-10 09:33:50 +00002921 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2922 VK_RValue, SourceLocation());
2923 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2924 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002925
John McCall113bee02012-03-10 09:33:50 +00002926 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002927 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002928 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002929 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002930 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002931
2932 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002933
2934 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002935 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002936 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002937 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002938}
2939
2940llvm::Constant *
2941CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2942 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002943 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002944 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002945 return 0;
2946 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2947 QualType Ty = PD->getType();
2948 if (!Ty->isRecordType())
2949 return 0;
2950 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2951 return 0;
2952 llvm::Constant * HelperFn = 0;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002953
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002954 if (hasTrivialGetExpr(PID))
2955 return 0;
2956 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2957 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2958 return HelperFn;
2959
2960
2961 ASTContext &C = getContext();
2962 IdentifierInfo *II
2963 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2964 FunctionDecl *FD = FunctionDecl::Create(C,
2965 C.getTranslationUnitDecl(),
2966 SourceLocation(),
2967 SourceLocation(), II, C.VoidTy, 0,
2968 SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002969 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002970 false);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002971
2972 QualType DestTy = C.getPointerType(Ty);
2973 QualType SrcTy = Ty;
2974 SrcTy.addConst();
2975 SrcTy = C.getPointerType(SrcTy);
2976
2977 FunctionArgList args;
2978 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2979 args.push_back(&dstDecl);
2980 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2981 args.push_back(&srcDecl);
2982
2983 const CGFunctionInfo &FI =
John McCalla729c622012-02-17 03:33:10 +00002984 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2985 FunctionType::ExtInfo(),
2986 RequiredArgs::All);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002987
John McCalla729c622012-02-17 03:33:10 +00002988 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002989
2990 llvm::Function *Fn =
2991 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2992 "__copy_helper_atomic_property_", &CGM.getModule());
2993
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002994 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2995
John McCall113bee02012-03-10 09:33:50 +00002996 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002997 VK_RValue, SourceLocation());
2998
John McCall113bee02012-03-10 09:33:50 +00002999 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3000 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003001
3002 CXXConstructExpr *CXXConstExpr =
3003 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3004
3005 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003006 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003007 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3008 ++A;
3009
3010 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3011 A != AEnd; ++A)
3012 ConstructorArgs.push_back(*A);
3013
3014 CXXConstructExpr *TheCXXConstructExpr =
3015 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3016 CXXConstExpr->getConstructor(),
3017 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003018 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003019 CXXConstExpr->hadMultipleCandidates(),
3020 CXXConstExpr->isListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003021 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003022 CXXConstExpr->getConstructionKind(),
3023 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003024
John McCall113bee02012-03-10 09:33:50 +00003025 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3026 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003027
John McCall113bee02012-03-10 09:33:50 +00003028 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003029 CharUnits Alignment
3030 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003031 EmitAggExpr(TheCXXConstructExpr,
3032 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3033 AggValueSlot::IsDestructed,
3034 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003035 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003036
3037 FinishFunction();
3038 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3039 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3040 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003041}
3042
Eli Friedmanec75fec2012-02-28 01:08:45 +00003043llvm::Value *
3044CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3045 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003046 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3047 Selector CopySelector =
3048 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003049 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3050 Selector AutoreleaseSelector =
3051 getContext().Selectors.getNullarySelector(AutoreleaseID);
3052
3053 // Emit calls to retain/autorelease.
3054 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3055 llvm::Value *Val = Block;
3056 RValue Result;
3057 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003058 Ty, CopySelector,
Eli Friedmanec75fec2012-02-28 01:08:45 +00003059 Val, CallArgList(), 0, 0);
3060 Val = Result.getScalarVal();
3061 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3062 Ty, AutoreleaseSelector,
3063 Val, CallArgList(), 0, 0);
3064 Val = Result.getScalarVal();
3065 return Val;
3066}
3067
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003068
Ted Kremenek43e06332008-04-09 15:51:31 +00003069CGObjCRuntime::~CGObjCRuntime() {}