blob: f78bb0b3106f1aa9052aec4d7f8e9f5d65480bda [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremeneke65b0862012-03-06 20:05:56 +000034static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +000035 QualType ET,
Ted Kremeneke65b0862012-03-06 20:05:56 +000036 const ObjCMethodDecl *Method,
37 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000038
39/// Given the address of a variable of pointer type, find the correct
40/// null to store into it.
41static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2192fe52011-07-18 04:24:23 +000042 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000043 cast<llvm::PointerType>(addr->getType())->getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
Chris Lattnerb1d329d2008-06-24 17:04:18 +000047/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000048llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000049{
David Chisnall481e3a82010-01-23 02:40:42 +000050 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000052 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000053 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000054}
55
Patrick Beard0caa3942012-04-19 00:25:12 +000056/// EmitObjCBoxedExpr - This routine generates code to call
57/// the appropriate expression boxing method. This will either be
58/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000059///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000060llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000061CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Generate the correct selector for this literal's concrete type.
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);
Alp Toker314cc812014-01-25 16:55:45 +000082
83 RValue result = Runtime.GenerateMessageSend(
84 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
85 Args, 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.
Alp Toker314cc812014-01-25 16:55:45 +0000189 RValue result = Runtime.GenerateMessageSend(
190 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
191 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000192
193 // The above message send needs these objects, but in ARC they are
194 // passed in a buffer that is essentially __unsafe_unretained.
195 // Therefore we must prevent the optimizer from releasing them until
196 // after the call.
197 if (TrackNeededObjects) {
198 EmitARCIntrinsicUse(NeededObjects);
199 }
200
Ted Kremeneke65b0862012-03-06 20:05:56 +0000201 return Builder.CreateBitCast(result.getScalarVal(),
202 ConvertType(E->getType()));
203}
204
205llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
206 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
207}
208
209llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
210 const ObjCDictionaryLiteral *E) {
211 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
212}
213
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000214/// Emit a selector.
215llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
216 // Untyped selector.
217 // Note that this implementation allows for non-constant strings to be passed
218 // as arguments to @selector(). Currently, the only thing preventing this
219 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000220 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000221}
222
Daniel Dunbar66912a12008-08-20 00:28:19 +0000223llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
224 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000225 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000226}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000227
Douglas Gregor33823722011-06-11 01:09:30 +0000228/// \brief Adjust the type of the result of an Objective-C message send
229/// expression when the method has a related result type.
230static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000231 QualType ExpT,
Douglas Gregor33823722011-06-11 01:09:30 +0000232 const ObjCMethodDecl *Method,
233 RValue Result) {
234 if (!Method)
235 return Result;
John McCall31168b02011-06-15 23:02:42 +0000236
Douglas Gregor33823722011-06-11 01:09:30 +0000237 if (!Method->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +0000238 CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
Douglas Gregor33823722011-06-11 01:09:30 +0000239 !Result.isScalar())
240 return Result;
241
242 // We have applied a related result type. Cast the rvalue appropriately.
243 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000244 CGF.ConvertType(ExpT)));
Douglas Gregor33823722011-06-11 01:09:30 +0000245}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000246
John McCallcf166702011-07-22 08:53:00 +0000247/// Decide whether to extend the lifetime of the receiver of a
248/// returns-inner-pointer message.
249static bool
250shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
251 switch (message->getReceiverKind()) {
252
253 // For a normal instance message, we should extend unless the
254 // receiver is loaded from a variable with precise lifetime.
255 case ObjCMessageExpr::Instance: {
256 const Expr *receiver = message->getInstanceReceiver();
257 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
258 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
259 receiver = ice->getSubExpr()->IgnoreParens();
260
261 // Only __strong variables.
262 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
263 return true;
264
265 // All ivars and fields have precise lifetime.
266 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
267 return false;
268
269 // Otherwise, check for variables.
270 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
271 if (!declRef) return true;
272 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
273 if (!var) return true;
274
275 // All variables have precise lifetime except local variables with
276 // automatic storage duration that aren't specially marked.
277 return (var->hasLocalStorage() &&
278 !var->hasAttr<ObjCPreciseLifetimeAttr>());
279 }
280
281 case ObjCMessageExpr::Class:
282 case ObjCMessageExpr::SuperClass:
283 // It's never necessary for class objects.
284 return false;
285
286 case ObjCMessageExpr::SuperInstance:
287 // We generally assume that 'self' lives throughout a method call.
288 return false;
289 }
290
291 llvm_unreachable("invalid receiver kind");
292}
293
John McCall78a15112010-05-22 01:48:05 +0000294RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
295 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000296 // Only the lookup mechanism and first two arguments of the method
297 // implementation vary between runtimes. We can get the receiver and
298 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000299
John McCall31168b02011-06-15 23:02:42 +0000300 bool isDelegateInit = E->isDelegateInitCall();
301
John McCallcf166702011-07-22 08:53:00 +0000302 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000303
John McCall31168b02011-06-15 23:02:42 +0000304 // We don't retain the receiver in delegate init calls, and this is
305 // safe because the receiver value is always loaded from 'self',
306 // which we zero out. We don't want to Block_copy block receivers,
307 // though.
308 bool retainSelf =
309 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000311 method &&
312 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000313
Daniel Dunbar8d480592008-08-11 18:12:00 +0000314 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000315 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000316 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +0000317 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000318 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000319 QualType ReceiverType;
Daniel Dunbarb2197802010-04-22 03:17:06 +0000320 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +0000321 switch (E->getReceiverKind()) {
322 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000323 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000324 if (retainSelf) {
325 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
326 E->getInstanceReceiver());
327 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000328 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000329 } else
330 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000331 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000332
Douglas Gregor9a129192010-04-21 00:45:42 +0000333 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000334 ReceiverType = E->getClassReceiver();
335 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000336 assert(ObjTy && "Invalid Objective-C class message send");
337 OID = ObjTy->getInterface();
338 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000339 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000340 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000341 break;
342 }
343
344 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000345 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000346 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000347 isSuperMessage = true;
348 break;
349
350 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000351 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000352 Receiver = LoadObjCSelf();
353 isSuperMessage = true;
354 isClassMessage = true;
355 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000356 }
357
John McCallcf166702011-07-22 08:53:00 +0000358 if (retainSelf)
359 Receiver = EmitARCRetainNonBlock(Receiver);
360
361 // In ARC, we sometimes want to "extend the lifetime"
362 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
363 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000364 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000365 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
366 shouldExtendReceiverForInnerPointerMessage(E))
367 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
368
Alp Toker314cc812014-01-25 16:55:45 +0000369 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000370
Daniel Dunbarc722b852008-08-30 03:02:31 +0000371 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000372 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000373
John McCall31168b02011-06-15 23:02:42 +0000374 // For delegate init calls in ARC, do an unsafe store of null into
375 // self. This represents the call taking direct ownership of that
376 // value. We have to do this after emitting the other call
377 // arguments because they might also reference self, but we don't
378 // have to worry about any of them modifying self because that would
379 // be an undefined read and write of an object in unordered
380 // expressions.
381 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000382 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000383 "delegate init calls should only be marked in ARC");
384
385 // Do an unsafe store of null into self.
386 llvm::Value *selfAddr =
387 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
388 assert(selfAddr && "no self entry for a delegate init call?");
389
390 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
391 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000392
Douglas Gregor33823722011-06-11 01:09:30 +0000393 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000394 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000395 // super is only valid in an Objective-C method
396 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000397 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000398 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
399 E->getSelector(),
400 OMD->getClassInterface(),
401 isCategoryImpl,
402 Receiver,
403 isClassMessage,
404 Args,
John McCallcf166702011-07-22 08:53:00 +0000405 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000406 } else {
407 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
408 E->getSelector(),
409 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000410 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000411 }
John McCall31168b02011-06-15 23:02:42 +0000412
413 // For delegate init calls in ARC, implicitly store the result of
414 // the call back into self. This takes ownership of the value.
415 if (isDelegateInit) {
416 llvm::Value *selfAddr =
417 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
418 llvm::Value *newSelf = result.getScalarVal();
419
420 // The delegate return type isn't necessarily a matching type; in
421 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000422 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000423 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
424 newSelf = Builder.CreateBitCast(newSelf, selfTy);
425
426 Builder.CreateStore(newSelf, selfAddr);
427 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000428
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000429 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000430}
431
John McCall31168b02011-06-15 23:02:42 +0000432namespace {
433struct FinishARCDealloc : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000434 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000435 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000436
437 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000438 const ObjCInterfaceDecl *iface = impl->getClassInterface();
439 if (!iface->getSuperClass()) return;
440
John McCalldffafde2011-07-13 18:26:47 +0000441 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
442
John McCall31168b02011-06-15 23:02:42 +0000443 // Call [super dealloc] if we have a superclass.
444 llvm::Value *self = CGF.LoadObjCSelf();
445
446 CallArgList args;
447 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
448 CGF.getContext().VoidTy,
449 method->getSelector(),
450 iface,
John McCalldffafde2011-07-13 18:26:47 +0000451 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000452 self,
453 /*is class msg*/ false,
454 args,
455 method);
456 }
457};
458}
459
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000460/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
461/// the LLVM function and sets the other context used by
462/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000463void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000464 const ObjCContainerDecl *CD,
465 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000466 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000467 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000468 if (OMD->hasAttr<NoDebugAttr>())
469 DebugInfo = NULL; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000470
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000471 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000472
John McCalla729c622012-02-17 03:33:10 +0000473 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000474 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000475
John McCalla738c252011-03-09 04:27:21 +0000476 args.push_back(OMD->getSelfDecl());
477 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000478
Aaron Ballman43b68be2014-03-07 17:50:17 +0000479 for (const auto *PI : OMD->params())
480 args.push_back(PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000481
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000482 CurGD = OMD;
483
Alp Toker314cc812014-01-25 16:55:45 +0000484 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args, StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000485
486 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000487 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000488 OMD->isInstanceMethod() &&
489 OMD->getSelector().isUnarySelector()) {
490 const IdentifierInfo *ident =
491 OMD->getSelector().getIdentifierInfoForSlot(0);
492 if (ident->isStr("dealloc"))
493 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
494 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000495}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000496
John McCall31168b02011-06-15 23:02:42 +0000497static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
498 LValue lvalue, QualType type);
499
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000500/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000501/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000502void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000503 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000504 PGO.assignRegionCounters(OMD, CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000505 assert(isa<CompoundStmt>(OMD->getBody()));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000506 RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
507 Cnt.beginRegion(Builder);
Adrian Prantl56741e22014-01-07 22:05:55 +0000508 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000509 FinishFunction(OMD->getBodyRBrace());
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000510 PGO.emitInstrumentationData();
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000511 PGO.destroyRegionCounters();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000512}
513
John McCallb923ece2011-09-12 23:06:44 +0000514/// emitStructGetterCall - Call the runtime function to load a property
515/// into the return value slot.
516static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
517 bool isAtomic, bool hasStrong) {
518 ASTContext &Context = CGF.getContext();
519
520 llvm::Value *src =
521 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
522 ivar, 0).getAddress();
523
524 // objc_copyStruct (ReturnValue, &structIvar,
525 // sizeof (Type of Ivar), isAtomic, false);
526 CallArgList args;
527
528 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
529 args.add(RValue::get(dest), Context.VoidPtrTy);
530
531 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
532 args.add(RValue::get(src), Context.VoidPtrTy);
533
534 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
535 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
536 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
537 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
538
539 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000540 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
541 FunctionType::ExtInfo(),
542 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000543 fn, ReturnValueSlot(), args);
544}
545
John McCallf4528ae2011-09-13 03:34:09 +0000546/// Determine whether the given architecture supports unaligned atomic
547/// accesses. They don't have to be fast, just faster than a function
548/// call and a mutex.
549static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000550 // FIXME: Allow unaligned atomic load/store on x86. (It is not
551 // currently supported by the backend.)
552 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000553}
554
555/// Return the maximum size that permits atomic accesses for the given
556/// architecture.
557static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
558 llvm::Triple::ArchType arch) {
559 // ARM has 8-byte atomic accesses, but it's not clear whether we
560 // want to rely on them here.
561
562 // In the default case, just assume that any size up to a pointer is
563 // fine given adequate alignment.
564 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
565}
566
567namespace {
568 class PropertyImplStrategy {
569 public:
570 enum StrategyKind {
571 /// The 'native' strategy is to use the architecture's provided
572 /// reads and writes.
573 Native,
574
575 /// Use objc_setProperty and objc_getProperty.
576 GetSetProperty,
577
578 /// Use objc_setProperty for the setter, but use expression
579 /// evaluation for the getter.
580 SetPropertyAndExpressionGet,
581
582 /// Use objc_copyStruct.
583 CopyStruct,
584
585 /// The 'expression' strategy is to emit normal assignment or
586 /// lvalue-to-rvalue expressions.
587 Expression
588 };
589
590 StrategyKind getKind() const { return StrategyKind(Kind); }
591
592 bool hasStrongMember() const { return HasStrong; }
593 bool isAtomic() const { return IsAtomic; }
594 bool isCopy() const { return IsCopy; }
595
596 CharUnits getIvarSize() const { return IvarSize; }
597 CharUnits getIvarAlignment() const { return IvarAlignment; }
598
599 PropertyImplStrategy(CodeGenModule &CGM,
600 const ObjCPropertyImplDecl *propImpl);
601
602 private:
603 unsigned Kind : 8;
604 unsigned IsAtomic : 1;
605 unsigned IsCopy : 1;
606 unsigned HasStrong : 1;
607
608 CharUnits IvarSize;
609 CharUnits IvarAlignment;
610 };
611}
612
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000613/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000614PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
615 const ObjCPropertyImplDecl *propImpl) {
616 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000617 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000618
John McCall43192862011-09-13 18:31:23 +0000619 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
620 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000621 HasStrong = false; // doesn't matter here.
622
623 // Evaluate the ivar's size and alignment.
624 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
625 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000626 std::tie(IvarSize, IvarAlignment) =
627 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000628
629 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000630 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000631 if (IsCopy) {
632 Kind = GetSetProperty;
633 return;
634 }
635
John McCall43192862011-09-13 18:31:23 +0000636 // Handle retain.
637 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000638 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000639 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000640 // fallthrough
641
642 // In ARC, if the property is non-atomic, use expression emission,
643 // which translates to objc_storeStrong. This isn't required, but
644 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000645 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000646 // Using standard expression emission for the setter is only
647 // acceptable if the ivar is __strong, which won't be true if
648 // the property is annotated with __attribute__((NSObject)).
649 // TODO: falling all the way back to objc_setProperty here is
650 // just laziness, though; we could still use objc_storeStrong
651 // if we hacked it right.
652 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
653 Kind = Expression;
654 else
655 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000656 return;
657
658 // Otherwise, we need to at least use setProperty. However, if
659 // the property isn't atomic, we can use normal expression
660 // emission for the getter.
661 } else if (!IsAtomic) {
662 Kind = SetPropertyAndExpressionGet;
663 return;
664
665 // Otherwise, we have to use both setProperty and getProperty.
666 } else {
667 Kind = GetSetProperty;
668 return;
669 }
670 }
671
672 // If we're not atomic, just use expression accesses.
673 if (!IsAtomic) {
674 Kind = Expression;
675 return;
676 }
677
John McCall0e5c0862011-09-13 05:36:29 +0000678 // Properties on bitfield ivars need to be emitted using expression
679 // accesses even if they're nominally atomic.
680 if (ivar->isBitField()) {
681 Kind = Expression;
682 return;
683 }
684
John McCallf4528ae2011-09-13 03:34:09 +0000685 // GC-qualified or ARC-qualified ivars need to be emitted as
686 // expressions. This actually works out to being atomic anyway,
687 // except for ARC __strong, but that should trigger the above code.
688 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000689 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000690 CGM.getContext().getObjCGCAttrKind(ivarType))) {
691 Kind = Expression;
692 return;
693 }
694
695 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000696 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000697 if (const RecordType *recordType = ivarType->getAs<RecordType>())
698 HasStrong = recordType->getDecl()->hasObjectMember();
699
700 // We can never access structs with object members with a native
701 // access, because we need to use write barriers. This is what
702 // objc_copyStruct is for.
703 if (HasStrong) {
704 Kind = CopyStruct;
705 return;
706 }
707
708 // Otherwise, this is target-dependent and based on the size and
709 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000710
711 // If the size of the ivar is not a power of two, give up. We don't
712 // want to get into the business of doing compare-and-swaps.
713 if (!IvarSize.isPowerOfTwo()) {
714 Kind = CopyStruct;
715 return;
716 }
717
John McCallf4528ae2011-09-13 03:34:09 +0000718 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000719 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000720
721 // Most architectures require memory to fit within a single cache
722 // line, so the alignment has to be at least the size of the access.
723 // Otherwise we have to grab a lock.
724 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
725 Kind = CopyStruct;
726 return;
727 }
728
729 // If the ivar's size exceeds the architecture's maximum atomic
730 // access size, we have to use CopyStruct.
731 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
732 Kind = CopyStruct;
733 return;
734 }
735
736 // Otherwise, we can use native loads and stores.
737 Kind = Native;
738}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000739
James Dennettbe302452012-06-15 22:10:14 +0000740/// \brief Generate an Objective-C property getter function.
741///
742/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000743/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000744void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
745 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000746 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000747 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000748 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
749 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
750 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +0000751 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000752
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000753 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000754
755 FinishFunction();
756}
757
John McCallbdd81852011-09-13 06:00:03 +0000758static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
759 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000760 if (!getter) return true;
761
762 // Sema only makes only of these when the ivar has a C++ class type,
763 // so the form is pretty constrained.
764
John McCallbdd81852011-09-13 06:00:03 +0000765 // If the property has a reference type, we might just be binding a
766 // reference, in which case the result will be a gl-value. We should
767 // treat this as a non-trivial operation.
768 if (getter->isGLValue())
769 return false;
770
John McCallf4528ae2011-09-13 03:34:09 +0000771 // If we selected a trivial copy-constructor, we're okay.
772 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
773 return (construct->getConstructor()->isTrivial());
774
775 // The constructor might require cleanups (in which case it's never
776 // trivial).
777 assert(isa<ExprWithCleanups>(getter));
778 return false;
779}
780
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000781/// emitCPPObjectAtomicGetterCall - Call the runtime function to
782/// copy the ivar into the resturn slot.
783static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
784 llvm::Value *returnAddr,
785 ObjCIvarDecl *ivar,
786 llvm::Constant *AtomicHelperFn) {
787 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
788 // AtomicHelperFn);
789 CallArgList args;
790
791 // The 1st argument is the return Slot.
792 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
793
794 // The 2nd argument is the address of the ivar.
795 llvm::Value *ivarAddr =
796 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
797 CGF.LoadObjCSelf(), ivar, 0).getAddress();
798 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
799 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
800
801 // Third argument is the helper function.
802 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
803
804 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000805 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000806 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
807 args,
808 FunctionType::ExtInfo(),
809 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000810 copyCppAtomicObjectFn, ReturnValueSlot(), args);
811}
812
John McCallf4528ae2011-09-13 03:34:09 +0000813void
814CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000815 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000816 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000817 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000818 // If there's a non-trivial 'get' expression, we just have to emit that.
819 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000820 if (!AtomicHelperFn) {
821 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
822 /*nrvo*/ 0);
823 EmitReturnStmt(ret);
824 }
825 else {
826 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
827 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
828 ivar, AtomicHelperFn);
829 }
John McCallf4528ae2011-09-13 03:34:09 +0000830 return;
831 }
832
833 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
834 QualType propType = prop->getType();
835 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
836
837 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
838
839 // Pick an implementation strategy.
840 PropertyImplStrategy strategy(CGM, propImpl);
841 switch (strategy.getKind()) {
842 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000843 // We don't need to do anything for a zero-size struct.
844 if (strategy.getIvarSize().isZero())
845 return;
846
John McCallf4528ae2011-09-13 03:34:09 +0000847 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
848
849 // Currently, all atomic accesses have to be through integer
850 // types, so there's no point in trying to pick a prettier type.
851 llvm::Type *bitcastType =
852 llvm::Type::getIntNTy(getLLVMContext(),
853 getContext().toBits(strategy.getIvarSize()));
854 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
855
856 // Perform an atomic load. This does not impose ordering constraints.
857 llvm::Value *ivarAddr = LV.getAddress();
858 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
859 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
860 load->setAlignment(strategy.getIvarAlignment().getQuantity());
861 load->setAtomic(llvm::Unordered);
862
863 // Store that value into the return address. Doing this with a
864 // bitcast is likely to produce some pretty ugly IR, but it's not
865 // the *most* terrible thing in the world.
866 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
867
868 // Make sure we don't do an autorelease.
869 AutoreleaseResult = false;
870 return;
871 }
872
873 case PropertyImplStrategy::GetSetProperty: {
874 llvm::Value *getPropertyFn =
875 CGM.getObjCRuntime().GetPropertyGetFunction();
876 if (!getPropertyFn) {
877 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000878 return;
879 }
880
881 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
882 // FIXME: Can't this be simpler? This might even be worse than the
883 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000884 llvm::Value *cmd =
885 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
886 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
887 llvm::Value *ivarOffset =
888 EmitIvarOffset(classImpl->getClassInterface(), ivar);
889
890 CallArgList args;
891 args.add(RValue::get(self), getContext().getObjCIdType());
892 args.add(RValue::get(cmd), getContext().getObjCSelType());
893 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000894 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
895 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000896
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000897 // FIXME: We shouldn't need to get the function info here, the
898 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000899 llvm::Instruction *CallInstruction;
John McCall8dda7b22012-07-07 06:41:13 +0000900 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
901 FunctionType::ExtInfo(),
902 RequiredArgs::All),
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000903 getPropertyFn, ReturnValueSlot(), args, 0,
904 &CallInstruction);
905 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
906 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000907
Daniel Dunbara08dff12008-09-24 04:04:31 +0000908 // We need to fix the type here. Ivars with copy & retain are
909 // always objects so we don't need to worry about complex or
910 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000911 RV = RValue::get(Builder.CreateBitCast(
912 RV.getScalarVal(),
913 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000914
915 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000916
917 // objc_getProperty does an autorelease, so we should suppress ours.
918 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000919
John McCallf4528ae2011-09-13 03:34:09 +0000920 return;
921 }
922
923 case PropertyImplStrategy::CopyStruct:
924 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
925 strategy.hasStrongMember());
926 return;
927
928 case PropertyImplStrategy::Expression:
929 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
930 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
931
932 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000933 switch (getEvaluationKind(ivarType)) {
934 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000935 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall47fb9502013-03-07 21:37:08 +0000936 EmitStoreOfComplex(pair,
937 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
938 /*init*/ true);
939 return;
940 }
941 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000942 // The return value slot is guaranteed to not be aliased, but
943 // that's not necessarily the same as "on the stack", so
944 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000945 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000946 return;
947 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000948 llvm::Value *value;
949 if (propType->isReferenceType()) {
950 value = LV.getAddress();
951 } else {
952 // We want to load and autoreleaseReturnValue ARC __weak ivars.
953 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000954 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000955
956 // Otherwise we want to do a simple load, suppressing the
957 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000958 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000959 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000960 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000961 }
John McCall31168b02011-06-15 23:02:42 +0000962
John McCall24fada12011-07-22 05:23:13 +0000963 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +0000964 value = Builder.CreateBitCast(
965 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +0000966 }
967
968 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000969 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000970 }
John McCall47fb9502013-03-07 21:37:08 +0000971 }
972 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000973 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000974
John McCallf4528ae2011-09-13 03:34:09 +0000975 }
976 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000977}
978
John McCallb923ece2011-09-12 23:06:44 +0000979/// emitStructSetterCall - Call the runtime function to store the value
980/// from the first formal parameter into the given ivar.
981static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
982 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000983 // objc_copyStruct (&structIvar, &Arg,
984 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000985 CallArgList args;
986
987 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000988 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
989 CGF.LoadObjCSelf(), ivar, 0)
990 .getAddress();
991 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
992 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000993
994 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000995 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000996 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000997 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000998 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
999 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1000 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001001
1002 // The third argument is the sizeof the type.
1003 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001004 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1005 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001006
John McCallb923ece2011-09-12 23:06:44 +00001007 // The fourth argument is the 'isAtomic' flag.
1008 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001009
John McCallb923ece2011-09-12 23:06:44 +00001010 // The fifth argument is the 'hasStrong' flag.
1011 // FIXME: should this really always be false?
1012 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1013
1014 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001015 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1016 args,
1017 FunctionType::ExtInfo(),
1018 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001019 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001020}
1021
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001022/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1023/// the value from the first formal parameter into the given ivar, using
1024/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1025static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1026 ObjCMethodDecl *OMD,
1027 ObjCIvarDecl *ivar,
1028 llvm::Constant *AtomicHelperFn) {
1029 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1030 // AtomicHelperFn);
1031 CallArgList args;
1032
1033 // The first argument is the address of the ivar.
1034 llvm::Value *ivarAddr =
1035 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1036 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1037 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1038 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1039
1040 // The second argument is the address of the parameter variable.
1041 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001042 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001043 VK_LValue, SourceLocation());
1044 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1045 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1046 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1047
1048 // Third argument is the helper function.
1049 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1050
1051 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001052 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001053 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1054 args,
1055 FunctionType::ExtInfo(),
1056 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001057 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001058}
1059
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001060
John McCallf4528ae2011-09-13 03:34:09 +00001061static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1062 Expr *setter = PID->getSetterCXXAssignment();
1063 if (!setter) return true;
1064
1065 // Sema only makes only of these when the ivar has a C++ class type,
1066 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001067
1068 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001069 // This also implies that there's nothing non-trivial going on with
1070 // the arguments, because operator= can only be trivial if it's a
1071 // synthesized assignment operator and therefore both parameters are
1072 // references.
1073 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001074 if (const FunctionDecl *callee
1075 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1076 if (callee->isTrivial())
1077 return true;
1078 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001079 }
John McCall7f16c422011-09-10 09:17:20 +00001080
John McCallf4528ae2011-09-13 03:34:09 +00001081 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001082 return false;
1083}
1084
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001085static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001086 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001087 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001088 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001089}
1090
John McCall7f16c422011-09-10 09:17:20 +00001091void
1092CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001093 const ObjCPropertyImplDecl *propImpl,
1094 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001095 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001096 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001097 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001098
1099 // Just use the setter expression if Sema gave us one and it's
1100 // non-trivial.
1101 if (!hasTrivialSetExpr(propImpl)) {
1102 if (!AtomicHelperFn)
1103 // If non-atomic, assignment is called directly.
1104 EmitStmt(propImpl->getSetterCXXAssignment());
1105 else
1106 // If atomic, assignment is called via a locking api.
1107 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1108 AtomicHelperFn);
1109 return;
1110 }
John McCall7f16c422011-09-10 09:17:20 +00001111
John McCallf4528ae2011-09-13 03:34:09 +00001112 PropertyImplStrategy strategy(CGM, propImpl);
1113 switch (strategy.getKind()) {
1114 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001115 // We don't need to do anything for a zero-size struct.
1116 if (strategy.getIvarSize().isZero())
1117 return;
1118
John McCallf4528ae2011-09-13 03:34:09 +00001119 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +00001120
John McCallf4528ae2011-09-13 03:34:09 +00001121 LValue ivarLValue =
1122 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1123 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001124
John McCallf4528ae2011-09-13 03:34:09 +00001125 // Currently, all atomic accesses have to be through integer
1126 // types, so there's no point in trying to pick a prettier type.
1127 llvm::Type *bitcastType =
1128 llvm::Type::getIntNTy(getLLVMContext(),
1129 getContext().toBits(strategy.getIvarSize()));
1130 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1131
1132 // Cast both arguments to the chosen operation type.
1133 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1134 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1135
1136 // This bitcast load is likely to cause some nasty IR.
1137 llvm::Value *load = Builder.CreateLoad(argAddr);
1138
1139 // Perform an atomic store. There are no memory ordering requirements.
1140 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1141 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1142 store->setAtomic(llvm::Unordered);
1143 return;
1144 }
1145
1146 case PropertyImplStrategy::GetSetProperty:
1147 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001148
1149 llvm::Value *setOptimizedPropertyFn = 0;
1150 llvm::Value *setPropertyFn = 0;
1151 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001152 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001153 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001154 CGM.getObjCRuntime()
1155 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1156 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001157 if (!setOptimizedPropertyFn) {
1158 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1159 return;
1160 }
John McCall7f16c422011-09-10 09:17:20 +00001161 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001162 else {
1163 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1164 if (!setPropertyFn) {
1165 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1166 return;
1167 }
1168 }
1169
John McCall7f16c422011-09-10 09:17:20 +00001170 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1171 // <is-atomic>, <is-copy>).
1172 llvm::Value *cmd =
1173 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1174 llvm::Value *self =
1175 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1176 llvm::Value *ivarOffset =
1177 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1178 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1179 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1180
1181 CallArgList args;
1182 args.add(RValue::get(self), getContext().getObjCIdType());
1183 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001184 if (setOptimizedPropertyFn) {
1185 args.add(RValue::get(arg), getContext().getObjCIdType());
1186 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001187 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1188 FunctionType::ExtInfo(),
1189 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001190 setOptimizedPropertyFn, ReturnValueSlot(), args);
1191 } else {
1192 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1193 args.add(RValue::get(arg), getContext().getObjCIdType());
1194 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1195 getContext().BoolTy);
1196 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1197 getContext().BoolTy);
1198 // FIXME: We shouldn't need to get the function info here, the runtime
1199 // already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001200 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1201 FunctionType::ExtInfo(),
1202 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001203 setPropertyFn, ReturnValueSlot(), args);
1204 }
1205
John McCall7f16c422011-09-10 09:17:20 +00001206 return;
1207 }
1208
John McCallf4528ae2011-09-13 03:34:09 +00001209 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001210 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001211 return;
John McCallf4528ae2011-09-13 03:34:09 +00001212
1213 case PropertyImplStrategy::Expression:
1214 break;
John McCall7f16c422011-09-10 09:17:20 +00001215 }
1216
1217 // Otherwise, fake up some ASTs and emit a normal assignment.
1218 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001219 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1220 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001221 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1222 selfDecl->getType(), CK_LValueToRValue, &self,
1223 VK_RValue);
1224 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001225 SourceLocation(), SourceLocation(),
1226 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001227
1228 ParmVarDecl *argDecl = *setterMethod->param_begin();
1229 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001230 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001231 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1232 argType.getUnqualifiedType(), CK_LValueToRValue,
1233 &arg, VK_RValue);
1234
1235 // The property type can differ from the ivar type in some situations with
1236 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1237 // The following absurdity is just to ensure well-formed IR.
1238 CastKind argCK = CK_NoOp;
1239 if (ivarRef.getType()->isObjCObjectPointerType()) {
1240 if (argLoad.getType()->isObjCObjectPointerType())
1241 argCK = CK_BitCast;
1242 else if (argLoad.getType()->isBlockPointerType())
1243 argCK = CK_BlockPointerToObjCPointerCast;
1244 else
1245 argCK = CK_CPointerToObjCPointerCast;
1246 } else if (ivarRef.getType()->isBlockPointerType()) {
1247 if (argLoad.getType()->isBlockPointerType())
1248 argCK = CK_BitCast;
1249 else
1250 argCK = CK_AnyPointerToBlockPointerCast;
1251 } else if (ivarRef.getType()->isPointerType()) {
1252 argCK = CK_BitCast;
1253 }
1254 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1255 ivarRef.getType(), argCK, &argLoad,
1256 VK_RValue);
1257 Expr *finalArg = &argLoad;
1258 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1259 argLoad.getType()))
1260 finalArg = &argCast;
1261
1262
1263 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1264 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001265 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001266 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001267}
1268
James Dennettbe302452012-06-15 22:10:14 +00001269/// \brief Generate an Objective-C property setter function.
1270///
1271/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001272/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001273void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1274 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001275 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001276 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001277 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1278 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1279 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +00001280 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001281
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001282 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001283
1284 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001285}
1286
John McCall6a4fa522011-03-22 07:05:39 +00001287namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001288 struct DestroyIvar : EHScopeStack::Cleanup {
1289 private:
1290 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001291 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001292 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001293 bool useEHCleanupForArray;
1294 public:
1295 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1296 CodeGenFunction::Destroyer *destroyer,
1297 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001298 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001299 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001300
Craig Topper4f12f102014-03-12 06:41:41 +00001301 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001302 LValue lvalue
1303 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1304 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001305 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001306 }
1307 };
1308}
1309
John McCall4bd0fb12011-07-12 16:41:08 +00001310/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1311static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1312 llvm::Value *addr,
1313 QualType type) {
1314 llvm::Value *null = getNullForVariable(addr);
1315 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1316}
John McCall31168b02011-06-15 23:02:42 +00001317
John McCall6a4fa522011-03-22 07:05:39 +00001318static void emitCXXDestructMethod(CodeGenFunction &CGF,
1319 ObjCImplementationDecl *impl) {
1320 CodeGenFunction::RunCleanupsScope scope(CGF);
1321
1322 llvm::Value *self = CGF.LoadObjCSelf();
1323
Jordy Rosea91768e2011-07-22 02:08:32 +00001324 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1325 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001326 ivar; ivar = ivar->getNextIvar()) {
1327 QualType type = ivar->getType();
1328
John McCall6a4fa522011-03-22 07:05:39 +00001329 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001330 QualType::DestructionKind dtorKind = type.isDestructedType();
1331 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001332
John McCall4bd0fb12011-07-12 16:41:08 +00001333 CodeGenFunction::Destroyer *destroyer = 0;
John McCall6a4fa522011-03-22 07:05:39 +00001334
John McCall4bd0fb12011-07-12 16:41:08 +00001335 // Use a call to objc_storeStrong to destroy strong ivars, for the
1336 // general benefit of the tools.
1337 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001338 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001339
John McCall4bd0fb12011-07-12 16:41:08 +00001340 // Otherwise use the default for the destruction kind.
1341 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001342 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001343 }
John McCall4bd0fb12011-07-12 16:41:08 +00001344
1345 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1346
1347 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1348 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001349 }
1350
1351 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1352}
1353
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001354void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1355 ObjCMethodDecl *MD,
1356 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001357 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001358 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001359
1360 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001361 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001362 // Suppress the final autorelease in ARC.
1363 AutoreleaseResult = false;
1364
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001365 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001366 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001367 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001368 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1369 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001370 EmitAggExpr(IvarInit->getInit(),
1371 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001372 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001373 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001374 }
1375 // constructor returns 'self'.
1376 CodeGenTypes &Types = CGM.getTypes();
1377 QualType IdTy(CGM.getContext().getObjCIdType());
1378 llvm::Value *SelfAsId =
1379 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1380 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001381
1382 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001383 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001384 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001385 }
1386 FinishFunction();
1387}
1388
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001389bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1390 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1391 it++; it++;
1392 const ABIArgInfo &AI = it->info;
1393 // FIXME. Is this sufficient check?
1394 return (AI.getKind() == ABIArgInfo::Indirect);
1395}
1396
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001397bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001398 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001399 return false;
1400 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1401 return FDTTy->getDecl()->hasObjectMember();
1402 return false;
1403}
1404
Daniel Dunbara08dff12008-09-24 04:04:31 +00001405llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001406 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1407 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1408 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001409 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001410}
1411
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001412QualType CodeGenFunction::TypeOfSelfObject() {
1413 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1414 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001415 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1416 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001417 return PTy->getPointeeType();
1418}
1419
Chris Lattnerd4808922009-03-22 21:03:39 +00001420void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001421 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001422 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001423
Daniel Dunbara08dff12008-09-24 04:04:31 +00001424 if (!EnumerationMutationFn) {
1425 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1426 return;
1427 }
1428
Devang Pateld2d66652011-01-19 01:36:36 +00001429 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001430 if (DI)
1431 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001432
Devang Patel297207f2011-06-13 23:15:32 +00001433 // The local variable comes into scope immediately.
1434 AutoVarEmission variable = AutoVarEmission::invalid();
1435 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1436 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1437
John McCall1c926b72011-01-07 01:49:06 +00001438 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001439
Anders Carlsson75658592008-08-31 02:33:12 +00001440 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001441 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001442 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001443 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Anders Carlsson75658592008-08-31 02:33:12 +00001445 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001446 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001447
John McCall1c926b72011-01-07 01:49:06 +00001448 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001449 IdentifierInfo *II[] = {
1450 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1451 &CGM.getContext().Idents.get("objects"),
1452 &CGM.getContext().Idents.get("count")
1453 };
1454 Selector FastEnumSel =
1455 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001456
1457 QualType ItemsTy =
1458 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001459 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001460 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001461 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001462
John McCall53848232011-07-27 01:07:15 +00001463 // Emit the collection pointer. In ARC, we do a retain.
1464 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001465 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001466 Collection = EmitARCRetainScalarExpr(S.getCollection());
1467
1468 // Enter a cleanup to do the release.
1469 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1470 } else {
1471 Collection = EmitScalarExpr(S.getCollection());
1472 }
Mike Stump11289f42009-09-09 15:08:12 +00001473
John McCall91e82dd2011-08-05 00:14:38 +00001474 // The 'continue' label needs to appear within the cleanup for the
1475 // collection object.
1476 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1477
John McCall1c926b72011-01-07 01:49:06 +00001478 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001479 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001480
1481 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001482 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001483
John McCall1c926b72011-01-07 01:49:06 +00001484 // The second argument is a temporary array with space for NumItems
1485 // pointers. We'll actually be loading elements from the array
1486 // pointer written into the control state; this buffer is so that
1487 // collections that *aren't* backed by arrays can still queue up
1488 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001489 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001490
John McCall1c926b72011-01-07 01:49:06 +00001491 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001492 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001493 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001494 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001495
John McCall1c926b72011-01-07 01:49:06 +00001496 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001497 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001498 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001499 getContext().UnsignedLongTy,
1500 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001501 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001502
John McCall1c926b72011-01-07 01:49:06 +00001503 // The initial number of objects that were returned in the buffer.
1504 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001505
John McCall1c926b72011-01-07 01:49:06 +00001506 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1507 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001508
John McCall1c926b72011-01-07 01:49:06 +00001509 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001510
John McCall1c926b72011-01-07 01:49:06 +00001511 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001512 // empty; skip all this. Set the branch weight assuming this has the same
1513 // probability of exiting the loop as any other loop exit.
1514 uint64_t EntryCount = PGO.getCurrentRegionCount();
1515 RegionCounter Cnt = getPGORegionCounter(&S);
John McCall1c926b72011-01-07 01:49:06 +00001516 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001517 EmptyBB, LoopInitBB,
1518 PGO.createBranchWeights(EntryCount, Cnt.getCount()));
Anders Carlsson75658592008-08-31 02:33:12 +00001519
John McCall1c926b72011-01-07 01:49:06 +00001520 // Otherwise, initialize the loop.
1521 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001522
John McCall1c926b72011-01-07 01:49:06 +00001523 // Save the initial mutations value. This is the value at an
1524 // address that was written into the state object by
1525 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001526 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001527 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001528 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001529 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001530
John McCall1c926b72011-01-07 01:49:06 +00001531 llvm::Value *initialMutations =
1532 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001533
John McCall1c926b72011-01-07 01:49:06 +00001534 // Start looping. This is the point we return to whenever we have a
1535 // fresh, non-empty batch of objects.
1536 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1537 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001538
John McCall1c926b72011-01-07 01:49:06 +00001539 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001540 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001541 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001542
John McCall1c926b72011-01-07 01:49:06 +00001543 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001544 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001545 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001546
Bob Wilson8ab16912014-02-24 01:13:09 +00001547 Cnt.beginRegion(Builder);
1548
John McCall1c926b72011-01-07 01:49:06 +00001549 // Check whether the mutations value has changed from where it was
1550 // at start. StateMutationsPtr should actually be invariant between
1551 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001552 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001553 llvm::Value *currentMutations
1554 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001555
John McCall1c926b72011-01-07 01:49:06 +00001556 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001557 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001558
John McCall1c926b72011-01-07 01:49:06 +00001559 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1560 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001561
John McCall1c926b72011-01-07 01:49:06 +00001562 // If so, call the enumeration-mutation function.
1563 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001564 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001565 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001566 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001567 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001568 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001569 // FIXME: We shouldn't need to get the function info here, the runtime already
1570 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001571 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1572 FunctionType::ExtInfo(),
1573 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001574 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001575
John McCall1c926b72011-01-07 01:49:06 +00001576 // Otherwise, or if the mutation function returns, just continue.
1577 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001578
John McCall1c926b72011-01-07 01:49:06 +00001579 // Initialize the element variable.
1580 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001581 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001582 LValue elementLValue;
1583 QualType elementType;
1584 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001585 // Initialize the variable, in case it's a __block variable or something.
1586 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001587
John McCall9e2e22f2011-02-22 07:16:58 +00001588 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001589 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001590 VK_LValue, SourceLocation());
1591 elementLValue = EmitLValue(&tempDRE);
1592 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001593 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001594
1595 if (D->isARCPseudoStrong())
1596 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001597 } else {
1598 elementLValue = LValue(); // suppress warning
1599 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001600 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001601 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001602 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001603
1604 // Fetch the buffer out of the enumeration state.
1605 // TODO: this pointer should actually be invariant between
1606 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001607 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001608 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001609 llvm::Value *EnumStateItems =
1610 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001611
John McCall1c926b72011-01-07 01:49:06 +00001612 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001613 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001614 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1615 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001616
John McCall1c926b72011-01-07 01:49:06 +00001617 // Cast that value to the right type.
1618 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1619 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall1c926b72011-01-07 01:49:06 +00001621 // Make sure we have an l-value. Yes, this gets evaluated every
1622 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001623 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001624 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001625 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001626 } else {
1627 EmitScalarInit(CurrentItem, elementLValue);
1628 }
Mike Stump11289f42009-09-09 15:08:12 +00001629
John McCall9e2e22f2011-02-22 07:16:58 +00001630 // If we do have an element variable, this assignment is the end of
1631 // its initialization.
1632 if (elementIsVariable)
1633 EmitAutoVarCleanups(variable);
1634
John McCall1c926b72011-01-07 01:49:06 +00001635 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001636 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001637 {
1638 RunCleanupsScope Scope(*this);
1639 EmitStmt(S.getBody());
1640 }
Anders Carlsson75658592008-08-31 02:33:12 +00001641 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCall1c926b72011-01-07 01:49:06 +00001643 // Destroy the element variable now.
1644 elementVariableScope.ForceCleanup();
1645
1646 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001647 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001648
John McCall1c926b72011-01-07 01:49:06 +00001649 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001650
John McCall1c926b72011-01-07 01:49:06 +00001651 // First we check in the local buffer.
1652 llvm::Value *indexPlusOne
1653 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001654
John McCall1c926b72011-01-07 01:49:06 +00001655 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001656 // Set the branch weights based on the simplifying assumption that this is
1657 // like a while-loop, i.e., ignoring that the false branch fetches more
1658 // elements and then returns to the loop.
John McCall1c926b72011-01-07 01:49:06 +00001659 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001660 LoopBodyBB, FetchMoreBB,
1661 PGO.createBranchWeights(Cnt.getCount(), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001662
1663 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1664 count->addIncoming(count, AfterBody.getBlock());
1665
1666 // Otherwise, we have to fetch more elements.
1667 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001668
1669 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001670 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001671 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001672 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001673 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001674
John McCall1c926b72011-01-07 01:49:06 +00001675 // If we got a zero count, we're done.
1676 llvm::Value *refetchCount = CountRV.getScalarVal();
1677
1678 // (note that the message send might split FetchMoreBB)
1679 index->addIncoming(zero, Builder.GetInsertBlock());
1680 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1681
1682 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1683 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001684
Anders Carlsson75658592008-08-31 02:33:12 +00001685 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001686 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001687
John McCall9e2e22f2011-02-22 07:16:58 +00001688 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001689 // If the element was not a declaration, set it to be null.
1690
John McCall1c926b72011-01-07 01:49:06 +00001691 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1692 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001693 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001694 }
1695
Eric Christopher7cdf9482011-10-13 21:45:18 +00001696 if (DI)
1697 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001698
John McCall53848232011-07-27 01:07:15 +00001699 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001700 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001701 PopCleanupBlock();
1702
John McCallad5d61e2010-07-23 21:56:41 +00001703 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001704}
1705
Mike Stump11289f42009-09-09 15:08:12 +00001706void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001707 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001708}
1709
Mike Stump11289f42009-09-09 15:08:12 +00001710void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001711 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1712}
1713
Chris Lattnere132e242008-11-15 21:26:17 +00001714void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001715 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001716 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001717}
1718
John McCall2d637d22011-09-10 06:18:15 +00001719/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001720/// primitive retain.
1721llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1722 llvm::Value *value) {
1723 return EmitARCRetain(type, value);
1724}
1725
1726namespace {
1727 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001728 CallObjCRelease(llvm::Value *object) : object(object) {}
1729 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001730
Craig Topper4f12f102014-03-12 06:41:41 +00001731 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001732 // Releases at the end of the full-expression are imprecise.
1733 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001734 }
1735 };
1736}
1737
John McCall2d637d22011-09-10 06:18:15 +00001738/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001739/// release at the end of the full-expression.
1740llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1741 llvm::Value *object) {
1742 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001743 // conditional.
1744 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001745 return object;
1746}
1747
1748llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1749 llvm::Value *value) {
1750 return EmitARCRetainAutorelease(type, value);
1751}
1752
John McCalleff18842013-03-23 02:35:54 +00001753/// Given a number of pointers, inform the optimizer that they're
1754/// being intrinsically used up until this point in the program.
1755void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1756 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1757 if (!fn) {
1758 llvm::FunctionType *fnType =
1759 llvm::FunctionType::get(CGM.VoidTy, ArrayRef<llvm::Type*>(), true);
1760 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1761 }
1762
1763 // This isn't really a "runtime" function, but as an intrinsic it
1764 // doesn't really matter as long as we align things up.
1765 EmitNounwindRuntimeCall(fn, values);
1766}
1767
John McCall31168b02011-06-15 23:02:42 +00001768
1769static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001770 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001771 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001772 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1773
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001774 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001775 // If the target runtime doesn't naturally support ARC, emit weak
1776 // references to the runtime support library. We don't really
1777 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001778 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001779 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001780 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1781 // If we have Native ARC, set nonlazybind attribute for these APIs for
1782 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001783 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001784 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001785 }
John McCall31168b02011-06-15 23:02:42 +00001786
1787 return fn;
1788}
1789
1790/// Perform an operation having the signature
1791/// i8* (i8*)
1792/// where a null input causes a no-op and returns null.
1793static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1794 llvm::Value *value,
1795 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001796 StringRef fnName,
1797 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001798 if (isa<llvm::ConstantPointerNull>(value)) return value;
1799
1800 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001801 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001802 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001803 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1804 }
1805
1806 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001807 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001808 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1809
1810 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001811 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001812 if (isTailCall)
1813 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001814
1815 // Cast the result back to the original type.
1816 return CGF.Builder.CreateBitCast(call, origType);
1817}
1818
1819/// Perform an operation having the following signature:
1820/// i8* (i8**)
1821static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1822 llvm::Value *addr,
1823 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001824 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001825 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001826 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001827 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001828 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1829 }
1830
1831 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001832 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001833 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1834
1835 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001836 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00001837
1838 // Cast the result back to a dereference of the original type.
John McCall31168b02011-06-15 23:02:42 +00001839 if (origType != CGF.Int8PtrPtrTy)
1840 result = CGF.Builder.CreateBitCast(result,
1841 cast<llvm::PointerType>(origType)->getElementType());
1842
1843 return result;
1844}
1845
1846/// Perform an operation having the following signature:
1847/// i8* (i8**, i8*)
1848static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1849 llvm::Value *addr,
1850 llvm::Value *value,
1851 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001852 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001853 bool ignored) {
1854 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1855 == value->getType());
1856
1857 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001858 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001859
Chris Lattner2192fe52011-07-18 04:24:23 +00001860 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001861 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1862 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1863 }
1864
Chris Lattner2192fe52011-07-18 04:24:23 +00001865 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001866
John McCall882987f2013-02-28 19:01:20 +00001867 llvm::Value *args[] = {
1868 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1869 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1870 };
1871 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001872
1873 if (ignored) return 0;
1874
1875 return CGF.Builder.CreateBitCast(result, origType);
1876}
1877
1878/// Perform an operation having the following signature:
1879/// void (i8**, i8**)
1880static void emitARCCopyOperation(CodeGenFunction &CGF,
1881 llvm::Value *dst,
1882 llvm::Value *src,
1883 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001885 assert(dst->getType() == src->getType());
1886
1887 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001888 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1889
Chris Lattner2192fe52011-07-18 04:24:23 +00001890 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001891 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1892 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1893 }
1894
John McCall882987f2013-02-28 19:01:20 +00001895 llvm::Value *args[] = {
1896 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1897 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1898 };
1899 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001900}
1901
1902/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001903/// call i8* \@objc_retain(i8* %value)
1904/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001905llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1906 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001907 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001908 else
1909 return EmitARCRetainNonBlock(value);
1910}
1911
1912/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001913/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001914llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1915 return emitARCValueOperation(*this, value,
1916 CGM.getARCEntrypoints().objc_retain,
1917 "objc_retain");
1918}
1919
1920/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001921/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001922///
1923/// \param mandatory - If false, emit the call with metadata
1924/// indicating that it's okay for the optimizer to eliminate this call
1925/// if it can prove that the block never escapes except down the stack.
1926llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1927 bool mandatory) {
1928 llvm::Value *result
1929 = emitARCValueOperation(*this, value,
1930 CGM.getARCEntrypoints().objc_retainBlock,
1931 "objc_retainBlock");
1932
1933 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1934 // tell the optimizer that it doesn't need to do this copy if the
1935 // block doesn't escape, where being passed as an argument doesn't
1936 // count as escaping.
1937 if (!mandatory && isa<llvm::Instruction>(result)) {
1938 llvm::CallInst *call
1939 = cast<llvm::CallInst>(result->stripPointerCasts());
1940 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1941
1942 SmallVector<llvm::Value*,1> args;
1943 call->setMetadata("clang.arc.copy_on_escape",
1944 llvm::MDNode::get(Builder.getContext(), args));
1945 }
1946
1947 return result;
John McCall31168b02011-06-15 23:02:42 +00001948}
1949
1950/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001951/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001952///
1953/// Yes, this function name is one character away from a different
1954/// call with completely different semantics.
1955llvm::Value *
1956CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1957 // Fetch the void(void) inline asm which marks that we're going to
1958 // retain the autoreleased return value.
1959 llvm::InlineAsm *&marker
1960 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1961 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001962 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001963 = CGM.getTargetCodeGenInfo()
1964 .getARCRetainAutoreleasedReturnValueMarker();
1965
1966 // If we have an empty assembly string, there's nothing to do.
1967 if (assembly.empty()) {
1968
1969 // Otherwise, at -O0, build an inline asm that we're going to call
1970 // in a moment.
1971 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1972 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001973 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001974
1975 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1976
1977 // If we're at -O1 and above, we don't want to litter the code
1978 // with this marker yet, so leave a breadcrumb for the ARC
1979 // optimizer to pick up.
1980 } else {
1981 llvm::NamedMDNode *metadata =
1982 CGM.getModule().getOrInsertNamedMetadata(
1983 "clang.arc.retainAutoreleasedReturnValueMarker");
1984 assert(metadata->getNumOperands() <= 1);
1985 if (metadata->getNumOperands() == 0) {
1986 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00001987 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00001988 }
1989 }
1990 }
1991
1992 // Call the marker asm if we made one, which we do only at -O0.
1993 if (marker) Builder.CreateCall(marker);
1994
1995 return emitARCValueOperation(*this, value,
1996 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1997 "objc_retainAutoreleasedReturnValue");
1998}
1999
2000/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002001/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002002void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2003 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002004 if (isa<llvm::ConstantPointerNull>(value)) return;
2005
2006 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2007 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002008 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002009 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002010 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2011 }
2012
2013 // Cast the argument to 'id'.
2014 value = Builder.CreateBitCast(value, Int8PtrTy);
2015
2016 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002017 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002018
John McCallcdda29c2013-03-13 03:10:54 +00002019 if (precise == ARCImpreciseLifetime) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002020 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00002021 call->setMetadata("clang.imprecise_release",
2022 llvm::MDNode::get(Builder.getContext(), args));
2023 }
2024}
2025
John McCalle68b8f42012-10-17 02:28:37 +00002026/// Destroy a __strong variable.
2027///
2028/// At -O0, emit a call to store 'null' into the address;
2029/// instrumenting tools prefer this because the address is exposed,
2030/// but it's relatively cumbersome to optimize.
2031///
2032/// At -O1 and above, just load and call objc_release.
2033///
2034/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCallcdda29c2013-03-13 03:10:54 +00002035void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2036 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002037 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2038 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2039 llvm::Value *null = llvm::ConstantPointerNull::get(
2040 cast<llvm::PointerType>(addrTy->getElementType()));
2041 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2042 return;
2043 }
2044
2045 llvm::Value *value = Builder.CreateLoad(addr);
2046 EmitARCRelease(value, precise);
2047}
2048
John McCall31168b02011-06-15 23:02:42 +00002049/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002050/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002051llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2052 llvm::Value *value,
2053 bool ignored) {
2054 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2055 == value->getType());
2056
2057 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2058 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002059 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002060 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002061 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2062 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2063 }
2064
John McCall882987f2013-02-28 19:01:20 +00002065 llvm::Value *args[] = {
2066 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2067 Builder.CreateBitCast(value, Int8PtrTy)
2068 };
2069 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002070
2071 if (ignored) return 0;
2072 return value;
2073}
2074
2075/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002076/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002077/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002078llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002079 llvm::Value *newValue,
2080 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002081 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002082 bool isBlock = type->isBlockPointerType();
2083
2084 // Use a store barrier at -O0 unless this is a block type or the
2085 // lvalue is inadequately aligned.
2086 if (shouldUseFusedARCCalls() &&
2087 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002088 (dst.getAlignment().isZero() ||
2089 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002090 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2091 }
2092
2093 // Otherwise, split it out.
2094
2095 // Retain the new value.
2096 newValue = EmitARCRetain(type, newValue);
2097
2098 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002099 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002100
2101 // Store. We do this before the release so that any deallocs won't
2102 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002103 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002104
2105 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002106 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002107
2108 return newValue;
2109}
2110
2111/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002112/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002113llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2114 return emitARCValueOperation(*this, value,
2115 CGM.getARCEntrypoints().objc_autorelease,
2116 "objc_autorelease");
2117}
2118
2119/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002120/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002121llvm::Value *
2122CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2123 return emitARCValueOperation(*this, value,
2124 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002125 "objc_autoreleaseReturnValue",
2126 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002127}
2128
2129/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002130/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002131llvm::Value *
2132CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2133 return emitARCValueOperation(*this, value,
2134 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002135 "objc_retainAutoreleaseReturnValue",
2136 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002137}
2138
2139/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002140/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002141/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002142/// %retain = call i8* \@objc_retainBlock(i8* %value)
2143/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002144llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2145 llvm::Value *value) {
2146 if (!type->isBlockPointerType())
2147 return EmitARCRetainAutoreleaseNonBlock(value);
2148
2149 if (isa<llvm::ConstantPointerNull>(value)) return value;
2150
Chris Lattner2192fe52011-07-18 04:24:23 +00002151 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002152 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002153 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002154 value = EmitARCAutorelease(value);
2155 return Builder.CreateBitCast(value, origType);
2156}
2157
2158/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002159/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002160llvm::Value *
2161CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2162 return emitARCValueOperation(*this, value,
2163 CGM.getARCEntrypoints().objc_retainAutorelease,
2164 "objc_retainAutorelease");
2165}
2166
James Dennett14c41ea2012-06-22 05:41:30 +00002167/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002168/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2169llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2170 return emitARCLoadOperation(*this, addr,
2171 CGM.getARCEntrypoints().objc_loadWeak,
2172 "objc_loadWeak");
2173}
2174
James Dennett14c41ea2012-06-22 05:41:30 +00002175/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002176llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2177 return emitARCLoadOperation(*this, addr,
2178 CGM.getARCEntrypoints().objc_loadWeakRetained,
2179 "objc_loadWeakRetained");
2180}
2181
James Dennett14c41ea2012-06-22 05:41:30 +00002182/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002183/// Returns %value.
2184llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2185 llvm::Value *value,
2186 bool ignored) {
2187 return emitARCStoreOperation(*this, addr, value,
2188 CGM.getARCEntrypoints().objc_storeWeak,
2189 "objc_storeWeak", ignored);
2190}
2191
James Dennett14c41ea2012-06-22 05:41:30 +00002192/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002193/// Returns %value. %addr is known to not have a current weak entry.
2194/// Essentially equivalent to:
2195/// *addr = nil; objc_storeWeak(addr, value);
2196void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2197 // If we're initializing to null, just write null to memory; no need
2198 // to get the runtime involved. But don't do this if optimization
2199 // is enabled, because accounting for this would make the optimizer
2200 // much more complicated.
2201 if (isa<llvm::ConstantPointerNull>(value) &&
2202 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2203 Builder.CreateStore(value, addr);
2204 return;
2205 }
2206
2207 emitARCStoreOperation(*this, addr, value,
2208 CGM.getARCEntrypoints().objc_initWeak,
2209 "objc_initWeak", /*ignored*/ true);
2210}
2211
James Dennett14c41ea2012-06-22 05:41:30 +00002212/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002213/// Essentially objc_storeWeak(addr, nil).
2214void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2215 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2216 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002217 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002218 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002219 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2220 }
2221
2222 // Cast the argument to 'id*'.
2223 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2224
John McCall882987f2013-02-28 19:01:20 +00002225 EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00002226}
2227
James Dennett14c41ea2012-06-22 05:41:30 +00002228/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002229/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2230/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2231void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2232 emitARCCopyOperation(*this, dst, src,
2233 CGM.getARCEntrypoints().objc_moveWeak,
2234 "objc_moveWeak");
2235}
2236
James Dennett14c41ea2012-06-22 05:41:30 +00002237/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002238/// Disregards the current value in %dest. Essentially
2239/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2240void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2241 emitARCCopyOperation(*this, dst, src,
2242 CGM.getARCEntrypoints().objc_copyWeak,
2243 "objc_copyWeak");
2244}
2245
2246/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002247/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002248llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2249 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2250 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002251 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002252 llvm::FunctionType::get(Int8PtrTy, false);
2253 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2254 }
2255
John McCall882987f2013-02-28 19:01:20 +00002256 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002257}
2258
2259/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002260/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002261void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2262 assert(value->getType() == Int8PtrTy);
2263
2264 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2265 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002266 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002267 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002268
2269 // We don't want to use a weak import here; instead we should not
2270 // fall into this path.
2271 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2272 }
2273
John McCallb7ff6db2013-04-16 21:29:40 +00002274 // objc_autoreleasePoolPop can throw.
2275 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002276}
2277
2278/// Produce the code to do an MRR version objc_autoreleasepool_push.
2279/// Which is: [[NSAutoreleasePool alloc] init];
2280/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2281/// init is declared as: - (id) init; in its NSObject super class.
2282///
2283llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2284 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002285 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002286 // [NSAutoreleasePool alloc]
2287 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2288 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2289 CallArgList Args;
2290 RValue AllocRV =
2291 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2292 getContext().getObjCIdType(),
2293 AllocSel, Receiver, Args);
2294
2295 // [Receiver init]
2296 Receiver = AllocRV.getScalarVal();
2297 II = &CGM.getContext().Idents.get("init");
2298 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2299 RValue InitRV =
2300 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2301 getContext().getObjCIdType(),
2302 InitSel, Receiver, Args);
2303 return InitRV.getScalarVal();
2304}
2305
2306/// Produce the code to do a primitive release.
2307/// [tmp drain];
2308void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2309 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2310 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2311 CallArgList Args;
2312 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2313 getContext().VoidTy, DrainSel, Arg, Args);
2314}
2315
John McCall82fe67b2011-07-09 01:37:26 +00002316void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2317 llvm::Value *addr,
2318 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002319 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002320}
2321
2322void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2323 llvm::Value *addr,
2324 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002325 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002326}
2327
2328void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2329 llvm::Value *addr,
2330 QualType type) {
2331 CGF.EmitARCDestroyWeak(addr);
2332}
2333
John McCall31168b02011-06-15 23:02:42 +00002334namespace {
John McCall31168b02011-06-15 23:02:42 +00002335 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2336 llvm::Value *Token;
2337
2338 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2339
Craig Topper4f12f102014-03-12 06:41:41 +00002340 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002341 CGF.EmitObjCAutoreleasePoolPop(Token);
2342 }
2343 };
2344 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2345 llvm::Value *Token;
2346
2347 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2348
Craig Topper4f12f102014-03-12 06:41:41 +00002349 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002350 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2351 }
2352 };
2353}
2354
2355void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002356 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002357 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2358 else
2359 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2360}
2361
John McCall31168b02011-06-15 23:02:42 +00002362static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2363 LValue lvalue,
2364 QualType type) {
2365 switch (type.getObjCLifetime()) {
2366 case Qualifiers::OCL_None:
2367 case Qualifiers::OCL_ExplicitNone:
2368 case Qualifiers::OCL_Strong:
2369 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002370 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2371 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002372 false);
2373
2374 case Qualifiers::OCL_Weak:
2375 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2376 true);
2377 }
2378
2379 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002380}
2381
2382static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2383 const Expr *e) {
2384 e = e->IgnoreParens();
2385 QualType type = e->getType();
2386
John McCall154a2fd2011-08-30 00:57:29 +00002387 // If we're loading retained from a __strong xvalue, we can avoid
2388 // an extra retain/release pair by zeroing out the source of this
2389 // "move" operation.
2390 if (e->isXValue() &&
2391 !type.isConstQualified() &&
2392 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2393 // Emit the lvalue.
2394 LValue lv = CGF.EmitLValue(e);
2395
2396 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002397 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2398 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002399
2400 // Set the source pointer to NULL.
2401 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2402
2403 return TryEmitResult(result, true);
2404 }
2405
John McCall31168b02011-06-15 23:02:42 +00002406 // As a very special optimization, in ARC++, if the l-value is the
2407 // result of a non-volatile assignment, do a simple retain of the
2408 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002409 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002410 !type.isVolatileQualified() &&
2411 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2412 isa<BinaryOperator>(e) &&
2413 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2414 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2415
2416 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2417}
2418
2419static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2420 llvm::Value *value);
2421
2422/// Given that the given expression is some sort of call (which does
2423/// not return retained), emit a retain following it.
2424static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2425 llvm::Value *value = CGF.EmitScalarExpr(e);
2426 return emitARCRetainAfterCall(CGF, value);
2427}
2428
2429static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2430 llvm::Value *value) {
2431 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2432 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2433
2434 // Place the retain immediately following the call.
2435 CGF.Builder.SetInsertPoint(call->getParent(),
2436 ++llvm::BasicBlock::iterator(call));
2437 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2438
2439 CGF.Builder.restoreIP(ip);
2440 return value;
2441 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2442 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2443
2444 // Place the retain at the beginning of the normal destination block.
2445 llvm::BasicBlock *BB = invoke->getNormalDest();
2446 CGF.Builder.SetInsertPoint(BB, BB->begin());
2447 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2448
2449 CGF.Builder.restoreIP(ip);
2450 return value;
2451
2452 // Bitcasts can arise because of related-result returns. Rewrite
2453 // the operand.
2454 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2455 llvm::Value *operand = bitcast->getOperand(0);
2456 operand = emitARCRetainAfterCall(CGF, operand);
2457 bitcast->setOperand(0, operand);
2458 return bitcast;
2459
2460 // Generic fall-back case.
2461 } else {
2462 // Retain using the non-block variant: we never need to do a copy
2463 // of a block that's been returned to us.
2464 return CGF.EmitARCRetainNonBlock(value);
2465 }
2466}
2467
John McCallcd78e802011-09-10 01:16:55 +00002468/// Determine whether it might be important to emit a separate
2469/// objc_retain_block on the result of the given expression, or
2470/// whether it's okay to just emit it in a +1 context.
2471static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2472 assert(e->getType()->isBlockPointerType());
2473 e = e->IgnoreParens();
2474
2475 // For future goodness, emit block expressions directly in +1
2476 // contexts if we can.
2477 if (isa<BlockExpr>(e))
2478 return false;
2479
2480 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2481 switch (cast->getCastKind()) {
2482 // Emitting these operations in +1 contexts is goodness.
2483 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002484 case CK_ARCReclaimReturnedObject:
2485 case CK_ARCConsumeObject:
2486 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002487 return false;
2488
2489 // These operations preserve a block type.
2490 case CK_NoOp:
2491 case CK_BitCast:
2492 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2493
2494 // These operations are known to be bad (or haven't been considered).
2495 case CK_AnyPointerToBlockPointerCast:
2496 default:
2497 return true;
2498 }
2499 }
2500
2501 return true;
2502}
2503
John McCallfe96e0b2011-11-06 09:01:30 +00002504/// Try to emit a PseudoObjectExpr at +1.
2505///
2506/// This massively duplicates emitPseudoObjectRValue.
2507static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2508 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002509 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002510
2511 // Find the result expression.
2512 const Expr *resultExpr = E->getResultExpr();
2513 assert(resultExpr);
2514 TryEmitResult result;
2515
2516 for (PseudoObjectExpr::const_semantics_iterator
2517 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2518 const Expr *semantic = *i;
2519
2520 // If this semantic expression is an opaque value, bind it
2521 // to the result of its source expression.
2522 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2523 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2524 OVMA opaqueData;
2525
2526 // If this semantic is the result of the pseudo-object
2527 // expression, try to evaluate the source as +1.
2528 if (ov == resultExpr) {
2529 assert(!OVMA::shouldBindAsLValue(ov));
2530 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2531 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2532
2533 // Otherwise, just bind it.
2534 } else {
2535 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2536 }
2537 opaques.push_back(opaqueData);
2538
2539 // Otherwise, if the expression is the result, evaluate it
2540 // and remember the result.
2541 } else if (semantic == resultExpr) {
2542 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2543
2544 // Otherwise, evaluate the expression in an ignored context.
2545 } else {
2546 CGF.EmitIgnoredExpr(semantic);
2547 }
2548 }
2549
2550 // Unbind all the opaques now.
2551 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2552 opaques[i].unbind(CGF);
2553
2554 return result;
2555}
2556
John McCall31168b02011-06-15 23:02:42 +00002557static TryEmitResult
2558tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002559 // We should *never* see a nested full-expression here, because if
2560 // we fail to emit at +1, our caller must not retain after we close
2561 // out the full-expression.
2562 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002563
John McCall31168b02011-06-15 23:02:42 +00002564 // The desired result type, if it differs from the type of the
2565 // ultimate opaque expression.
Chris Lattner2192fe52011-07-18 04:24:23 +00002566 llvm::Type *resultType = 0;
John McCall31168b02011-06-15 23:02:42 +00002567
2568 while (true) {
2569 e = e->IgnoreParens();
2570
2571 // There's a break at the end of this if-chain; anything
2572 // that wants to keep looping has to explicitly continue.
2573 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2574 switch (ce->getCastKind()) {
2575 // No-op casts don't change the type, so we just ignore them.
2576 case CK_NoOp:
2577 e = ce->getSubExpr();
2578 continue;
2579
2580 case CK_LValueToRValue: {
2581 TryEmitResult loadResult
2582 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2583 if (resultType) {
2584 llvm::Value *value = loadResult.getPointer();
2585 value = CGF.Builder.CreateBitCast(value, resultType);
2586 loadResult.setPointer(value);
2587 }
2588 return loadResult;
2589 }
2590
2591 // These casts can change the type, so remember that and
2592 // soldier on. We only need to remember the outermost such
2593 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002594 case CK_CPointerToObjCPointerCast:
2595 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002596 case CK_AnyPointerToBlockPointerCast:
2597 case CK_BitCast:
2598 if (!resultType)
2599 resultType = CGF.ConvertType(ce->getType());
2600 e = ce->getSubExpr();
2601 assert(e->getType()->hasPointerRepresentation());
2602 continue;
2603
2604 // For consumptions, just emit the subexpression and thus elide
2605 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002606 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002607 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2608 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2609 return TryEmitResult(result, true);
2610 }
2611
John McCallcd78e802011-09-10 01:16:55 +00002612 // Block extends are net +0. Naively, we could just recurse on
2613 // the subexpression, but actually we need to ensure that the
2614 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002615 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002616 llvm::Value *result; // will be a +0 value
2617
2618 // If we can't safely assume the sub-expression will produce a
2619 // block-copied value, emit the sub-expression at +0.
2620 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2621 result = CGF.EmitScalarExpr(ce->getSubExpr());
2622
2623 // Otherwise, try to emit the sub-expression at +1 recursively.
2624 } else {
2625 TryEmitResult subresult
2626 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2627 result = subresult.getPointer();
2628
2629 // If that produced a retained value, just use that,
2630 // possibly casting down.
2631 if (subresult.getInt()) {
2632 if (resultType)
2633 result = CGF.Builder.CreateBitCast(result, resultType);
2634 return TryEmitResult(result, true);
2635 }
2636
2637 // Otherwise it's +0.
2638 }
2639
2640 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002641 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002642 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2643 return TryEmitResult(result, true);
2644 }
2645
John McCall4db5c3c2011-07-07 06:58:02 +00002646 // For reclaims, emit the subexpression as a retained call and
2647 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002648 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002649 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2650 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2651 return TryEmitResult(result, true);
2652 }
2653
John McCall31168b02011-06-15 23:02:42 +00002654 default:
2655 break;
2656 }
2657
2658 // Skip __extension__.
2659 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2660 if (op->getOpcode() == UO_Extension) {
2661 e = op->getSubExpr();
2662 continue;
2663 }
2664
2665 // For calls and message sends, use the retained-call logic.
2666 // Delegate inits are a special case in that they're the only
2667 // returns-retained expression that *isn't* surrounded by
2668 // a consume.
2669 } else if (isa<CallExpr>(e) ||
2670 (isa<ObjCMessageExpr>(e) &&
2671 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2672 llvm::Value *result = emitARCRetainCall(CGF, e);
2673 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2674 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002675
2676 // Look through pseudo-object expressions.
2677 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2678 TryEmitResult result
2679 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2680 if (resultType) {
2681 llvm::Value *value = result.getPointer();
2682 value = CGF.Builder.CreateBitCast(value, resultType);
2683 result.setPointer(value);
2684 }
2685 return result;
John McCall31168b02011-06-15 23:02:42 +00002686 }
2687
2688 // Conservatively halt the search at any other expression kind.
2689 break;
2690 }
2691
2692 // We didn't find an obvious production, so emit what we've got and
2693 // tell the caller that we didn't manage to retain.
2694 llvm::Value *result = CGF.EmitScalarExpr(e);
2695 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2696 return TryEmitResult(result, false);
2697}
2698
2699static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2700 LValue lvalue,
2701 QualType type) {
2702 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2703 llvm::Value *value = result.getPointer();
2704 if (!result.getInt())
2705 value = CGF.EmitARCRetain(type, value);
2706 return value;
2707}
2708
2709/// EmitARCRetainScalarExpr - Semantically equivalent to
2710/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2711/// best-effort attempt to peephole expressions that naturally produce
2712/// retained objects.
2713llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002714 // The retain needs to happen within the full-expression.
2715 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2716 enterFullExpression(cleanups);
2717 RunCleanupsScope scope(*this);
2718 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2719 }
2720
John McCall31168b02011-06-15 23:02:42 +00002721 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2722 llvm::Value *value = result.getPointer();
2723 if (!result.getInt())
2724 value = EmitARCRetain(e->getType(), value);
2725 return value;
2726}
2727
2728llvm::Value *
2729CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002730 // The retain needs to happen within the full-expression.
2731 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2732 enterFullExpression(cleanups);
2733 RunCleanupsScope scope(*this);
2734 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2735 }
2736
John McCall31168b02011-06-15 23:02:42 +00002737 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2738 llvm::Value *value = result.getPointer();
2739 if (result.getInt())
2740 value = EmitARCAutorelease(value);
2741 else
2742 value = EmitARCRetainAutorelease(e->getType(), value);
2743 return value;
2744}
2745
John McCallff613032011-10-04 06:23:45 +00002746llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2747 llvm::Value *result;
2748 bool doRetain;
2749
2750 if (shouldEmitSeparateBlockRetain(e)) {
2751 result = EmitScalarExpr(e);
2752 doRetain = true;
2753 } else {
2754 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2755 result = subresult.getPointer();
2756 doRetain = !subresult.getInt();
2757 }
2758
2759 if (doRetain)
2760 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2761 return EmitObjCConsumeObject(e->getType(), result);
2762}
2763
John McCall248512a2011-10-01 10:32:24 +00002764llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2765 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002766 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002767 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002768 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002769 return EmitARCRetainAutoreleaseScalarExpr(expr);
2770 }
2771
2772 // Otherwise, use the normal scalar-expression emission. The
2773 // exception machinery doesn't do anything special with the
2774 // exception like retaining it, so there's no safety associated with
2775 // only running cleanups after the throw has started, and when it
2776 // matters it tends to be substantially inferior code.
2777 return EmitScalarExpr(expr);
2778}
2779
John McCall31168b02011-06-15 23:02:42 +00002780std::pair<LValue,llvm::Value*>
2781CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2782 bool ignored) {
2783 // Evaluate the RHS first.
2784 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2785 llvm::Value *value = result.getPointer();
2786
John McCallb726a552011-07-28 07:23:35 +00002787 bool hasImmediateRetain = result.getInt();
2788
2789 // If we didn't emit a retained object, and the l-value is of block
2790 // type, then we need to emit the block-retain immediately in case
2791 // it invalidates the l-value.
2792 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002793 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002794 hasImmediateRetain = true;
2795 }
2796
John McCall31168b02011-06-15 23:02:42 +00002797 LValue lvalue = EmitLValue(e->getLHS());
2798
2799 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002800 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002801 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002802 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002803 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002804 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002805 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002806 }
2807
2808 return std::pair<LValue,llvm::Value*>(lvalue, value);
2809}
2810
2811std::pair<LValue,llvm::Value*>
2812CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2813 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2814 LValue lvalue = EmitLValue(e->getLHS());
2815
Eli Friedmana0544d62011-12-03 04:14:32 +00002816 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002817
2818 return std::pair<LValue,llvm::Value*>(lvalue, value);
2819}
2820
2821void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002822 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002823 const Stmt *subStmt = ARPS.getSubStmt();
2824 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2825
2826 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002827 if (DI)
2828 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002829
2830 // Keep track of the current cleanup stack depth.
2831 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002832 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002833 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2834 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2835 } else {
2836 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2837 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2838 }
2839
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00002840 for (const auto *I : S.body())
2841 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00002842
Eric Christopher7cdf9482011-10-13 21:45:18 +00002843 if (DI)
2844 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002845}
John McCall1bd25562011-06-24 23:21:27 +00002846
2847/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2848/// make sure it survives garbage collection until this point.
2849void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2850 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002851 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002852 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002853 llvm::Value *extender
2854 = llvm::InlineAsm::get(extenderType,
2855 /* assembly */ "",
2856 /* constraints */ "r",
2857 /* side effects */ true);
2858
2859 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00002860 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00002861}
2862
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002863/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002864/// non-trivial copy assignment function, produce following helper function.
2865/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2866///
2867llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002868CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2869 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002870 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002871 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002872 return 0;
2873 QualType Ty = PID->getPropertyIvarDecl()->getType();
2874 if (!Ty->isRecordType())
2875 return 0;
2876 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002877 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002878 return 0;
Fariborz Jahanian1bed4132012-01-08 19:13:23 +00002879 llvm::Constant * HelperFn = 0;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002880 if (hasTrivialSetExpr(PID))
2881 return 0;
2882 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2883 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2884 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002885
2886 ASTContext &C = getContext();
2887 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002888 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002889 FunctionDecl *FD = FunctionDecl::Create(C,
2890 C.getTranslationUnitDecl(),
2891 SourceLocation(),
2892 SourceLocation(), II, C.VoidTy, 0,
2893 SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002894 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002895 false);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002896
2897 QualType DestTy = C.getPointerType(Ty);
2898 QualType SrcTy = Ty;
2899 SrcTy.addConst();
2900 SrcTy = C.getPointerType(SrcTy);
2901
2902 FunctionArgList args;
2903 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2904 args.push_back(&dstDecl);
2905 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2906 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002907
2908 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2909 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2910
John McCalla729c622012-02-17 03:33:10 +00002911 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002912
2913 llvm::Function *Fn =
2914 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002915 "__assign_helper_atomic_property_",
2916 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002917
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002918 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2919
John McCall113bee02012-03-10 09:33:50 +00002920 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2921 VK_RValue, SourceLocation());
2922 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2923 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002924
John McCall113bee02012-03-10 09:33:50 +00002925 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2926 VK_RValue, SourceLocation());
2927 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2928 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002929
John McCall113bee02012-03-10 09:33:50 +00002930 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002931 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002932 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002933 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002934 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002935
2936 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002937
2938 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002939 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002940 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002941 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002942}
2943
2944llvm::Constant *
2945CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2946 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002947 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002948 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002949 return 0;
2950 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2951 QualType Ty = PD->getType();
2952 if (!Ty->isRecordType())
2953 return 0;
2954 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2955 return 0;
2956 llvm::Constant * HelperFn = 0;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002957
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002958 if (hasTrivialGetExpr(PID))
2959 return 0;
2960 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2961 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2962 return HelperFn;
2963
2964
2965 ASTContext &C = getContext();
2966 IdentifierInfo *II
2967 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2968 FunctionDecl *FD = FunctionDecl::Create(C,
2969 C.getTranslationUnitDecl(),
2970 SourceLocation(),
2971 SourceLocation(), II, C.VoidTy, 0,
2972 SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002973 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002974 false);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002975
2976 QualType DestTy = C.getPointerType(Ty);
2977 QualType SrcTy = Ty;
2978 SrcTy.addConst();
2979 SrcTy = C.getPointerType(SrcTy);
2980
2981 FunctionArgList args;
2982 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2983 args.push_back(&dstDecl);
2984 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2985 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002986
2987 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2988 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2989
John McCalla729c622012-02-17 03:33:10 +00002990 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002991
2992 llvm::Function *Fn =
2993 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2994 "__copy_helper_atomic_property_", &CGM.getModule());
2995
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002996 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2997
John McCall113bee02012-03-10 09:33:50 +00002998 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002999 VK_RValue, SourceLocation());
3000
John McCall113bee02012-03-10 09:33:50 +00003001 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3002 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003003
3004 CXXConstructExpr *CXXConstExpr =
3005 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3006
3007 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003008 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003009 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3010 ++A;
3011
3012 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3013 A != AEnd; ++A)
3014 ConstructorArgs.push_back(*A);
3015
3016 CXXConstructExpr *TheCXXConstructExpr =
3017 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3018 CXXConstExpr->getConstructor(),
3019 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003020 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003021 CXXConstExpr->hadMultipleCandidates(),
3022 CXXConstExpr->isListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003023 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003024 CXXConstExpr->getConstructionKind(),
3025 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003026
John McCall113bee02012-03-10 09:33:50 +00003027 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3028 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003029
John McCall113bee02012-03-10 09:33:50 +00003030 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003031 CharUnits Alignment
3032 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003033 EmitAggExpr(TheCXXConstructExpr,
3034 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3035 AggValueSlot::IsDestructed,
3036 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003037 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003038
3039 FinishFunction();
3040 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3041 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3042 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003043}
3044
Eli Friedmanec75fec2012-02-28 01:08:45 +00003045llvm::Value *
3046CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3047 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003048 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3049 Selector CopySelector =
3050 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003051 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3052 Selector AutoreleaseSelector =
3053 getContext().Selectors.getNullarySelector(AutoreleaseID);
3054
3055 // Emit calls to retain/autorelease.
3056 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3057 llvm::Value *Val = Block;
3058 RValue Result;
3059 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003060 Ty, CopySelector,
Eli Friedmanec75fec2012-02-28 01:08:45 +00003061 Val, CallArgList(), 0, 0);
3062 Val = Result.getScalarVal();
3063 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3064 Ty, AutoreleaseSelector,
3065 Val, CallArgList(), 0, 0);
3066 Val = Result.getScalarVal();
3067 return Val;
3068}
3069
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003070
Ted Kremenek43e06332008-04-09 15:51:31 +00003071CGObjCRuntime::~CGObjCRuntime() {}