blob: ca67c4bd1c168558ff05a475900e1b2d5b9d9b2a [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Lacey8b549992013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCallf85e1932011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000034static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000035 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000036 const ObjCMethodDecl *Method,
37 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000038
39/// Given the address of a variable of pointer type, find the correct
40/// null to store into it.
41static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000042 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000043 cast<llvm::PointerType>(addr->getType())->getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
Chris Lattner8fdf3282008-06-24 17:04:18 +000047/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000048llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000049{
David Chisnall0d13f6f2010-01-23 02:40:42 +000050 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000052 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000053 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000054}
55
Patrick Beardeb382ec2012-04-19 00:25:12 +000056/// EmitObjCBoxedExpr - This routine generates code to call
57/// the appropriate expression boxing method. This will either be
58/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000059///
Eric Christopher16098f32012-03-29 17:31:31 +000060llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000061CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Generate the correct selector for this literal's concrete type.
Patrick Beardeb382ec2012-04-19 00:25:12 +000063 const Expr *SubExpr = E->getSubExpr();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000064 // Get the method.
Patrick Beardeb382ec2012-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 Kremenekebcb57a2012-03-06 20:05:56 +000069
70 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-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 Kremenekebcb57a2012-03-06 20:05:56 +000073 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000074 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCallbd7370a2013-02-28 19:01:20 +000075 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Patrick Beardeb382ec2012-04-19 00:25:12 +000076
77 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000078 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beardeb382ec2012-04-19 00:25:12 +000079 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000080 CallArgList Args;
81 Args.add(RV, ArgQT);
Stephen Hines651f13c2014-04-23 16:59:28 -070082
83 RValue result = Runtime.GenerateMessageSend(
84 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
85 Args, ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-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();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070093 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +000094 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).
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700109 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
110 llvm::Value *Keys = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000111 if (DLE)
112 Keys = CreateMemTemp(ElementArrayType, "keys");
113
John McCall527842f2013-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 Kremenekebcb57a2012-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 McCall527842f2013-04-04 00:20:38 +0000124 // Emit the element and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-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 McCall527842f2013-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 Kremenekebcb57a2012-03-06 20:05:56 +0000136 } else {
John McCall527842f2013-04-04 00:20:38 +0000137 // Emit the key and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-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 McCall527842f2013-04-04 00:20:38 +0000143 llvm::Value *keyValue = EmitScalarExpr(Key);
144 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000145
John McCall527842f2013-04-04 00:20:38 +0000146 // Emit the value and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-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 McCall527842f2013-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 Kremenekebcb57a2012-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 McCallbd7370a2013-02-28 19:01:20 +0000186 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000187
188 // Generate the message send.
Stephen Hines651f13c2014-04-23 16:59:28 -0700189 RValue result = Runtime.GenerateMessageSend(
190 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
191 Receiver, Args, Class, MethodWithObjects);
John McCall527842f2013-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 Kremenekebcb57a2012-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 Lattner8fdf3282008-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 McCallbd7370a2013-02-28 19:01:20 +0000220 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000221}
222
Daniel Dunbared7c6182008-08-20 00:28:19 +0000223llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
224 // FIXME: This should pass the Decl not the name.
John McCallbd7370a2013-02-28 19:01:20 +0000225 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbared7c6182008-08-20 00:28:19 +0000226}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000227
Douglas Gregor926df6c2011-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 Jahanian490a52b2012-05-29 19:56:01 +0000231 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000232 const ObjCMethodDecl *Method,
233 RValue Result) {
234 if (!Method)
235 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000236
Douglas Gregor926df6c2011-06-11 01:09:30 +0000237 if (!Method->hasRelatedResultType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700238 CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
Douglas Gregor926df6c2011-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 Jahanian490a52b2012-05-29 19:56:01 +0000244 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000245}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000246
John McCalldc7c5ad2011-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 McCallef072fd2010-05-22 01:48:05 +0000294RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
295 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-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 Stump1eb44332009-09-09 15:08:12 +0000299
John McCallf85e1932011-06-15 23:02:42 +0000300 bool isDelegateInit = E->isDelegateInitCall();
301
John McCalldc7c5ad2011-07-22 08:53:00 +0000302 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000303
John McCallf85e1932011-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 Blaikie4e4d0842012-03-11 07:00:24 +0000310 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000311 method &&
312 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000313
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000314 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000315 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000316 bool isClassMessage = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700317 ObjCInterfaceDecl *OID = nullptr;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000318 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000319 QualType ReceiverType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700320 llvm::Value *Receiver = nullptr;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000321 switch (E->getReceiverKind()) {
322 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000323 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000324 if (retainSelf) {
325 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
326 E->getInstanceReceiver());
327 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000328 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000329 } else
330 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000331 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000332
Douglas Gregor04badcf2010-04-21 00:45:42 +0000333 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000334 ReceiverType = E->getClassReceiver();
335 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-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 McCallbd7370a2013-02-28 19:01:20 +0000339 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000340 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000341 break;
342 }
343
344 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000345 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000346 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000347 isSuperMessage = true;
348 break;
349
350 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000351 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000352 Receiver = LoadObjCSelf();
353 isSuperMessage = true;
354 isClassMessage = true;
355 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000356 }
357
John McCalldc7c5ad2011-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 Blaikie4e4d0842012-03-11 07:00:24 +0000364 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000365 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
366 shouldExtendReceiverForInnerPointerMessage(E))
367 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
368
Stephen Hines651f13c2014-04-23 16:59:28 -0700369 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000370
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000371 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000372 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000373
John McCallf85e1932011-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 Blaikie4e4d0842012-03-11 07:00:24 +0000382 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-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 Carlsson7e70fb22010-06-21 20:59:55 +0000392
Douglas Gregor926df6c2011-06-11 01:09:30 +0000393 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000394 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000395 // super is only valid in an Objective-C method
396 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000397 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-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 McCalldc7c5ad2011-07-22 08:53:00 +0000405 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000406 } else {
407 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
408 E->getSelector(),
409 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000410 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000411 }
John McCallf85e1932011-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 Lattner2acc6e32011-07-18 04:24:23 +0000422 llvm::Type *selfTy =
John McCallf85e1932011-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 Jahanian4e1524b2012-01-29 20:27:13 +0000428
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000429 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000430}
431
John McCallf85e1932011-06-15 23:02:42 +0000432namespace {
433struct FinishARCDealloc : EHScopeStack::Cleanup {
Stephen Hines651f13c2014-04-23 16:59:28 -0700434 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +0000435 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000436
437 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000438 const ObjCInterfaceDecl *iface = impl->getClassInterface();
439 if (!iface->getSuperClass()) return;
440
John McCall799d34e2011-07-13 18:26:47 +0000441 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
442
John McCallf85e1932011-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 McCall799d34e2011-07-13 18:26:47 +0000451 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000452 self,
453 /*is class msg*/ false,
454 args,
455 method);
456 }
457};
458}
459
Daniel Dunbaraf05bb92008-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 Jahanian679a5022009-01-10 21:06:09 +0000463void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000464 const ObjCContainerDecl *CD,
465 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000466 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000467 // Check if we should generate debug info for this method.
David Blaikiec3030bc2013-08-26 20:33:21 +0000468 if (OMD->hasAttr<NoDebugAttr>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700469 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patel4800ea62010-04-05 21:09:15 +0000470
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000471 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000472
John McCallde5d3c72012-02-17 03:33:10 +0000473 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000474 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000475
John McCalld26bc762011-03-09 04:27:21 +0000476 args.push_back(OMD->getSelfDecl());
477 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000478
Stephen Hines651f13c2014-04-23 16:59:28 -0700479 for (const auto *PI : OMD->params())
480 args.push_back(PI);
Chris Lattner41110242008-06-17 18:05:57 +0000481
Peter Collingbourne14110472011-01-13 18:57:25 +0000482 CurGD = OMD;
483
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700484 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
485 OMD->getLocation(), StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000486
487 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000488 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000489 OMD->isInstanceMethod() &&
490 OMD->getSelector().isUnarySelector()) {
491 const IdentifierInfo *ident =
492 OMD->getSelector().getIdentifierInfoForSlot(0);
493 if (ident->isStr("dealloc"))
494 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
495 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000496}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000497
John McCallf85e1932011-06-15 23:02:42 +0000498static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
499 LValue lvalue, QualType type);
500
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000501/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000502/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000503void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000504 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Stephen Hines651f13c2014-04-23 16:59:28 -0700505 PGO.assignRegionCounters(OMD, CurFn);
506 assert(isa<CompoundStmt>(OMD->getBody()));
507 RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
508 Cnt.beginRegion(Builder);
509 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000510 FinishFunction(OMD->getBodyRBrace());
Stephen Hines651f13c2014-04-23 16:59:28 -0700511 PGO.emitInstrumentationData();
512 PGO.destroyRegionCounters();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000513}
514
John McCall41bdde92011-09-12 23:06:44 +0000515/// emitStructGetterCall - Call the runtime function to load a property
516/// into the return value slot.
517static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
518 bool isAtomic, bool hasStrong) {
519 ASTContext &Context = CGF.getContext();
520
521 llvm::Value *src =
522 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
523 ivar, 0).getAddress();
524
525 // objc_copyStruct (ReturnValue, &structIvar,
526 // sizeof (Type of Ivar), isAtomic, false);
527 CallArgList args;
528
529 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
530 args.add(RValue::get(dest), Context.VoidPtrTy);
531
532 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
533 args.add(RValue::get(src), Context.VoidPtrTy);
534
535 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
536 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
537 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
538 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
539
540 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000541 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
542 FunctionType::ExtInfo(),
543 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000544 fn, ReturnValueSlot(), args);
545}
546
John McCall1e1f4872011-09-13 03:34:09 +0000547/// Determine whether the given architecture supports unaligned atomic
548/// accesses. They don't have to be fast, just faster than a function
549/// call and a mutex.
550static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000551 // FIXME: Allow unaligned atomic load/store on x86. (It is not
552 // currently supported by the backend.)
553 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000554}
555
556/// Return the maximum size that permits atomic accesses for the given
557/// architecture.
558static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
559 llvm::Triple::ArchType arch) {
560 // ARM has 8-byte atomic accesses, but it's not clear whether we
561 // want to rely on them here.
562
563 // In the default case, just assume that any size up to a pointer is
564 // fine given adequate alignment.
565 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
566}
567
568namespace {
569 class PropertyImplStrategy {
570 public:
571 enum StrategyKind {
572 /// The 'native' strategy is to use the architecture's provided
573 /// reads and writes.
574 Native,
575
576 /// Use objc_setProperty and objc_getProperty.
577 GetSetProperty,
578
579 /// Use objc_setProperty for the setter, but use expression
580 /// evaluation for the getter.
581 SetPropertyAndExpressionGet,
582
583 /// Use objc_copyStruct.
584 CopyStruct,
585
586 /// The 'expression' strategy is to emit normal assignment or
587 /// lvalue-to-rvalue expressions.
588 Expression
589 };
590
591 StrategyKind getKind() const { return StrategyKind(Kind); }
592
593 bool hasStrongMember() const { return HasStrong; }
594 bool isAtomic() const { return IsAtomic; }
595 bool isCopy() const { return IsCopy; }
596
597 CharUnits getIvarSize() const { return IvarSize; }
598 CharUnits getIvarAlignment() const { return IvarAlignment; }
599
600 PropertyImplStrategy(CodeGenModule &CGM,
601 const ObjCPropertyImplDecl *propImpl);
602
603 private:
604 unsigned Kind : 8;
605 unsigned IsAtomic : 1;
606 unsigned IsCopy : 1;
607 unsigned HasStrong : 1;
608
609 CharUnits IvarSize;
610 CharUnits IvarAlignment;
611 };
612}
613
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000614/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000615PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
616 const ObjCPropertyImplDecl *propImpl) {
617 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000618 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000619
John McCall265941b2011-09-13 18:31:23 +0000620 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
621 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000622 HasStrong = false; // doesn't matter here.
623
624 // Evaluate the ivar's size and alignment.
625 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
626 QualType ivarType = ivar->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700627 std::tie(IvarSize, IvarAlignment) =
628 CGM.getContext().getTypeInfoInChars(ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000629
630 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000631 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000632 if (IsCopy) {
633 Kind = GetSetProperty;
634 return;
635 }
636
John McCall265941b2011-09-13 18:31:23 +0000637 // Handle retain.
638 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000639 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000640 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000641 // fallthrough
642
643 // In ARC, if the property is non-atomic, use expression emission,
644 // which translates to objc_storeStrong. This isn't required, but
645 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000646 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld64c2eb2012-08-20 23:36:59 +0000647 // Using standard expression emission for the setter is only
648 // acceptable if the ivar is __strong, which won't be true if
649 // the property is annotated with __attribute__((NSObject)).
650 // TODO: falling all the way back to objc_setProperty here is
651 // just laziness, though; we could still use objc_storeStrong
652 // if we hacked it right.
653 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
654 Kind = Expression;
655 else
656 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000657 return;
658
659 // Otherwise, we need to at least use setProperty. However, if
660 // the property isn't atomic, we can use normal expression
661 // emission for the getter.
662 } else if (!IsAtomic) {
663 Kind = SetPropertyAndExpressionGet;
664 return;
665
666 // Otherwise, we have to use both setProperty and getProperty.
667 } else {
668 Kind = GetSetProperty;
669 return;
670 }
671 }
672
673 // If we're not atomic, just use expression accesses.
674 if (!IsAtomic) {
675 Kind = Expression;
676 return;
677 }
678
John McCall5889c602011-09-13 05:36:29 +0000679 // Properties on bitfield ivars need to be emitted using expression
680 // accesses even if they're nominally atomic.
681 if (ivar->isBitField()) {
682 Kind = Expression;
683 return;
684 }
685
John McCall1e1f4872011-09-13 03:34:09 +0000686 // GC-qualified or ARC-qualified ivars need to be emitted as
687 // expressions. This actually works out to being atomic anyway,
688 // except for ARC __strong, but that should trigger the above code.
689 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000690 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000691 CGM.getContext().getObjCGCAttrKind(ivarType))) {
692 Kind = Expression;
693 return;
694 }
695
696 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000697 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000698 if (const RecordType *recordType = ivarType->getAs<RecordType>())
699 HasStrong = recordType->getDecl()->hasObjectMember();
700
701 // We can never access structs with object members with a native
702 // access, because we need to use write barriers. This is what
703 // objc_copyStruct is for.
704 if (HasStrong) {
705 Kind = CopyStruct;
706 return;
707 }
708
709 // Otherwise, this is target-dependent and based on the size and
710 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000711
712 // If the size of the ivar is not a power of two, give up. We don't
713 // want to get into the business of doing compare-and-swaps.
714 if (!IvarSize.isPowerOfTwo()) {
715 Kind = CopyStruct;
716 return;
717 }
718
John McCall1e1f4872011-09-13 03:34:09 +0000719 llvm::Triple::ArchType arch =
John McCall64aa4b32013-04-16 22:48:15 +0000720 CGM.getTarget().getTriple().getArch();
John McCall1e1f4872011-09-13 03:34:09 +0000721
722 // Most architectures require memory to fit within a single cache
723 // line, so the alignment has to be at least the size of the access.
724 // Otherwise we have to grab a lock.
725 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
726 Kind = CopyStruct;
727 return;
728 }
729
730 // If the ivar's size exceeds the architecture's maximum atomic
731 // access size, we have to use CopyStruct.
732 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
733 Kind = CopyStruct;
734 return;
735 }
736
737 // Otherwise, we can use native loads and stores.
738 Kind = Native;
739}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000740
James Dennett2ee5ba32012-06-15 22:10:14 +0000741/// \brief Generate an Objective-C property getter function.
742///
743/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000744/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000745void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
746 const ObjCPropertyImplDecl *PID) {
Stephen Hines176edba2014-12-01 14:53:08 -0800747 llvm::Constant *AtomicHelperFn =
748 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000749 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
750 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
751 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000752 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000754 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000755
756 FinishFunction();
757}
758
John McCall6c11f0b2011-09-13 06:00:03 +0000759static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
760 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000761 if (!getter) return true;
762
763 // Sema only makes only of these when the ivar has a C++ class type,
764 // so the form is pretty constrained.
765
John McCall6c11f0b2011-09-13 06:00:03 +0000766 // If the property has a reference type, we might just be binding a
767 // reference, in which case the result will be a gl-value. We should
768 // treat this as a non-trivial operation.
769 if (getter->isGLValue())
770 return false;
771
John McCall1e1f4872011-09-13 03:34:09 +0000772 // If we selected a trivial copy-constructor, we're okay.
773 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
774 return (construct->getConstructor()->isTrivial());
775
776 // The constructor might require cleanups (in which case it's never
777 // trivial).
778 assert(isa<ExprWithCleanups>(getter));
779 return false;
780}
781
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000782/// emitCPPObjectAtomicGetterCall - Call the runtime function to
783/// copy the ivar into the resturn slot.
784static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
785 llvm::Value *returnAddr,
786 ObjCIvarDecl *ivar,
787 llvm::Constant *AtomicHelperFn) {
788 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
789 // AtomicHelperFn);
790 CallArgList args;
791
792 // The 1st argument is the return Slot.
793 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
794
795 // The 2nd argument is the address of the ivar.
796 llvm::Value *ivarAddr =
797 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
798 CGF.LoadObjCSelf(), ivar, 0).getAddress();
799 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
800 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
801
802 // Third argument is the helper function.
803 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
804
805 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +0000806 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000807 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
808 args,
809 FunctionType::ExtInfo(),
810 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000811 copyCppAtomicObjectFn, ReturnValueSlot(), args);
812}
813
John McCall1e1f4872011-09-13 03:34:09 +0000814void
815CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000816 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000817 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000818 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000819 // If there's a non-trivial 'get' expression, we just have to emit that.
820 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000821 if (!AtomicHelperFn) {
822 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700823 /*nrvo*/ nullptr);
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000824 EmitReturnStmt(ret);
825 }
826 else {
827 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
828 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
829 ivar, AtomicHelperFn);
830 }
John McCall1e1f4872011-09-13 03:34:09 +0000831 return;
832 }
833
834 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
835 QualType propType = prop->getType();
836 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
837
838 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
839
840 // Pick an implementation strategy.
841 PropertyImplStrategy strategy(CGM, propImpl);
842 switch (strategy.getKind()) {
843 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +0000844 // We don't need to do anything for a zero-size struct.
845 if (strategy.getIvarSize().isZero())
846 return;
847
John McCall1e1f4872011-09-13 03:34:09 +0000848 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
849
850 // Currently, all atomic accesses have to be through integer
851 // types, so there's no point in trying to pick a prettier type.
852 llvm::Type *bitcastType =
853 llvm::Type::getIntNTy(getLLVMContext(),
854 getContext().toBits(strategy.getIvarSize()));
855 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
856
857 // Perform an atomic load. This does not impose ordering constraints.
858 llvm::Value *ivarAddr = LV.getAddress();
859 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
860 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
861 load->setAlignment(strategy.getIvarAlignment().getQuantity());
862 load->setAtomic(llvm::Unordered);
863
864 // Store that value into the return address. Doing this with a
865 // bitcast is likely to produce some pretty ugly IR, but it's not
866 // the *most* terrible thing in the world.
867 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
868
869 // Make sure we don't do an autorelease.
870 AutoreleaseResult = false;
871 return;
872 }
873
874 case PropertyImplStrategy::GetSetProperty: {
875 llvm::Value *getPropertyFn =
876 CGM.getObjCRuntime().GetPropertyGetFunction();
877 if (!getPropertyFn) {
878 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000879 return;
880 }
881
882 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
883 // FIXME: Can't this be simpler? This might even be worse than the
884 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000885 llvm::Value *cmd =
886 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
887 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
888 llvm::Value *ivarOffset =
889 EmitIvarOffset(classImpl->getClassInterface(), ivar);
890
891 CallArgList args;
892 args.add(RValue::get(self), getContext().getObjCIdType());
893 args.add(RValue::get(cmd), getContext().getObjCSelType());
894 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000895 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
896 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000897
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000898 // FIXME: We shouldn't need to get the function info here, the
899 // runtime already should have computed it to build the function.
Stephen Hines651f13c2014-04-23 16:59:28 -0700900 llvm::Instruction *CallInstruction;
John McCall0f3d0972012-07-07 06:41:13 +0000901 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
902 FunctionType::ExtInfo(),
903 RequiredArgs::All),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700904 getPropertyFn, ReturnValueSlot(), args, nullptr,
Stephen Hines651f13c2014-04-23 16:59:28 -0700905 &CallInstruction);
906 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
907 call->setTailCall();
John McCall1e1f4872011-09-13 03:34:09 +0000908
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000909 // We need to fix the type here. Ivars with copy & retain are
910 // always objects so we don't need to worry about complex or
911 // aggregates.
Stephen Hines651f13c2014-04-23 16:59:28 -0700912 RV = RValue::get(Builder.CreateBitCast(
913 RV.getScalarVal(),
914 getTypes().ConvertType(getterMethod->getReturnType())));
John McCall1e1f4872011-09-13 03:34:09 +0000915
916 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000917
918 // objc_getProperty does an autorelease, so we should suppress ours.
919 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000920
John McCall1e1f4872011-09-13 03:34:09 +0000921 return;
922 }
923
924 case PropertyImplStrategy::CopyStruct:
925 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
926 strategy.hasStrongMember());
927 return;
928
929 case PropertyImplStrategy::Expression:
930 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
931 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
932
933 QualType ivarType = ivar->getType();
John McCall9d232c82013-03-07 21:37:08 +0000934 switch (getEvaluationKind(ivarType)) {
935 case TEK_Complex: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000936 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall9d232c82013-03-07 21:37:08 +0000937 EmitStoreOfComplex(pair,
938 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
939 /*init*/ true);
940 return;
941 }
942 case TEK_Aggregate:
John McCall1e1f4872011-09-13 03:34:09 +0000943 // The return value slot is guaranteed to not be aliased, but
944 // that's not necessarily the same as "on the stack", so
945 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000946 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall9d232c82013-03-07 21:37:08 +0000947 return;
948 case TEK_Scalar: {
John McCallba3dd902011-07-22 05:23:13 +0000949 llvm::Value *value;
950 if (propType->isReferenceType()) {
951 value = LV.getAddress();
952 } else {
953 // We want to load and autoreleaseReturnValue ARC __weak ivars.
954 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000955 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000956
957 // Otherwise we want to do a simple load, suppressing the
958 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000959 } else {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000960 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCallba3dd902011-07-22 05:23:13 +0000961 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000962 }
John McCallf85e1932011-06-15 23:02:42 +0000963
John McCallba3dd902011-07-22 05:23:13 +0000964 value = Builder.CreateBitCast(value, ConvertType(propType));
Stephen Hines651f13c2014-04-23 16:59:28 -0700965 value = Builder.CreateBitCast(
966 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCallba3dd902011-07-22 05:23:13 +0000967 }
968
969 EmitReturnOfRValue(RValue::get(value), propType);
John McCall9d232c82013-03-07 21:37:08 +0000970 return;
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000971 }
John McCall9d232c82013-03-07 21:37:08 +0000972 }
973 llvm_unreachable("bad evaluation kind");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000974 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000975
John McCall1e1f4872011-09-13 03:34:09 +0000976 }
977 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000978}
979
John McCall41bdde92011-09-12 23:06:44 +0000980/// emitStructSetterCall - Call the runtime function to store the value
981/// from the first formal parameter into the given ivar.
982static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
983 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000984 // objc_copyStruct (&structIvar, &Arg,
985 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000986 CallArgList args;
987
988 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000989 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
990 CGF.LoadObjCSelf(), ivar, 0)
991 .getAddress();
992 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
993 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000994
995 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000996 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000997 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000998 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000999 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1000 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1001 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +00001002
1003 // The third argument is the sizeof the type.
1004 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +00001005 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1006 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +00001007
John McCall41bdde92011-09-12 23:06:44 +00001008 // The fourth argument is the 'isAtomic' flag.
1009 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +00001010
John McCall41bdde92011-09-12 23:06:44 +00001011 // The fifth argument is the 'hasStrong' flag.
1012 // FIXME: should this really always be false?
1013 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1014
1015 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001016 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1017 args,
1018 FunctionType::ExtInfo(),
1019 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +00001020 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +00001021}
1022
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001023/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1024/// the value from the first formal parameter into the given ivar, using
1025/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1026static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1027 ObjCMethodDecl *OMD,
1028 ObjCIvarDecl *ivar,
1029 llvm::Constant *AtomicHelperFn) {
1030 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1031 // AtomicHelperFn);
1032 CallArgList args;
1033
1034 // The first argument is the address of the ivar.
1035 llvm::Value *ivarAddr =
1036 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1037 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1038 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1039 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1040
1041 // The second argument is the address of the parameter variable.
1042 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001043 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001044 VK_LValue, SourceLocation());
1045 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1046 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1047 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1048
1049 // Third argument is the helper function.
1050 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1051
1052 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +00001053 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001054 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1055 args,
1056 FunctionType::ExtInfo(),
1057 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001058 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001059}
1060
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001061
John McCall1e1f4872011-09-13 03:34:09 +00001062static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1063 Expr *setter = PID->getSetterCXXAssignment();
1064 if (!setter) return true;
1065
1066 // Sema only makes only of these when the ivar has a C++ class type,
1067 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001068
1069 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001070 // This also implies that there's nothing non-trivial going on with
1071 // the arguments, because operator= can only be trivial if it's a
1072 // synthesized assignment operator and therefore both parameters are
1073 // references.
1074 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001075 if (const FunctionDecl *callee
1076 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1077 if (callee->isTrivial())
1078 return true;
1079 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001080 }
John McCall71c758d2011-09-10 09:17:20 +00001081
John McCall1e1f4872011-09-13 03:34:09 +00001082 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001083 return false;
1084}
1085
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001086static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001087 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001088 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001089 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001090}
1091
John McCall71c758d2011-09-10 09:17:20 +00001092void
1093CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001094 const ObjCPropertyImplDecl *propImpl,
1095 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001096 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001097 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001098 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001099
1100 // Just use the setter expression if Sema gave us one and it's
1101 // non-trivial.
1102 if (!hasTrivialSetExpr(propImpl)) {
1103 if (!AtomicHelperFn)
1104 // If non-atomic, assignment is called directly.
1105 EmitStmt(propImpl->getSetterCXXAssignment());
1106 else
1107 // If atomic, assignment is called via a locking api.
1108 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1109 AtomicHelperFn);
1110 return;
1111 }
John McCall71c758d2011-09-10 09:17:20 +00001112
John McCall1e1f4872011-09-13 03:34:09 +00001113 PropertyImplStrategy strategy(CGM, propImpl);
1114 switch (strategy.getKind()) {
1115 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +00001116 // We don't need to do anything for a zero-size struct.
1117 if (strategy.getIvarSize().isZero())
1118 return;
1119
John McCall1e1f4872011-09-13 03:34:09 +00001120 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001121
John McCall1e1f4872011-09-13 03:34:09 +00001122 LValue ivarLValue =
1123 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1124 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001125
John McCall1e1f4872011-09-13 03:34:09 +00001126 // Currently, all atomic accesses have to be through integer
1127 // types, so there's no point in trying to pick a prettier type.
1128 llvm::Type *bitcastType =
1129 llvm::Type::getIntNTy(getLLVMContext(),
1130 getContext().toBits(strategy.getIvarSize()));
1131 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1132
1133 // Cast both arguments to the chosen operation type.
1134 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1135 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1136
1137 // This bitcast load is likely to cause some nasty IR.
1138 llvm::Value *load = Builder.CreateLoad(argAddr);
1139
1140 // Perform an atomic store. There are no memory ordering requirements.
1141 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1142 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1143 store->setAtomic(llvm::Unordered);
1144 return;
1145 }
1146
1147 case PropertyImplStrategy::GetSetProperty:
1148 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001149
1150 llvm::Value *setOptimizedPropertyFn = nullptr;
1151 llvm::Value *setPropertyFn = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001152 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001153 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001154 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001155 CGM.getObjCRuntime()
1156 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1157 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001158 if (!setOptimizedPropertyFn) {
1159 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1160 return;
1161 }
John McCall71c758d2011-09-10 09:17:20 +00001162 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001163 else {
1164 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1165 if (!setPropertyFn) {
1166 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1167 return;
1168 }
1169 }
1170
John McCall71c758d2011-09-10 09:17:20 +00001171 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1172 // <is-atomic>, <is-copy>).
1173 llvm::Value *cmd =
1174 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1175 llvm::Value *self =
1176 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1177 llvm::Value *ivarOffset =
1178 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1179 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1180 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1181
1182 CallArgList args;
1183 args.add(RValue::get(self), getContext().getObjCIdType());
1184 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001185 if (setOptimizedPropertyFn) {
1186 args.add(RValue::get(arg), getContext().getObjCIdType());
1187 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001188 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1189 FunctionType::ExtInfo(),
1190 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001191 setOptimizedPropertyFn, ReturnValueSlot(), args);
1192 } else {
1193 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1194 args.add(RValue::get(arg), getContext().getObjCIdType());
1195 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1196 getContext().BoolTy);
1197 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1198 getContext().BoolTy);
1199 // FIXME: We shouldn't need to get the function info here, the runtime
1200 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001201 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1202 FunctionType::ExtInfo(),
1203 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001204 setPropertyFn, ReturnValueSlot(), args);
1205 }
1206
John McCall71c758d2011-09-10 09:17:20 +00001207 return;
1208 }
1209
John McCall1e1f4872011-09-13 03:34:09 +00001210 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001211 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001212 return;
John McCall1e1f4872011-09-13 03:34:09 +00001213
1214 case PropertyImplStrategy::Expression:
1215 break;
John McCall71c758d2011-09-10 09:17:20 +00001216 }
1217
1218 // Otherwise, fake up some ASTs and emit a normal assignment.
1219 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001220 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1221 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001222 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1223 selfDecl->getType(), CK_LValueToRValue, &self,
1224 VK_RValue);
1225 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001226 SourceLocation(), SourceLocation(),
1227 &selfLoad, true, true);
John McCall71c758d2011-09-10 09:17:20 +00001228
1229 ParmVarDecl *argDecl = *setterMethod->param_begin();
1230 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001231 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001232 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1233 argType.getUnqualifiedType(), CK_LValueToRValue,
1234 &arg, VK_RValue);
1235
1236 // The property type can differ from the ivar type in some situations with
1237 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1238 // The following absurdity is just to ensure well-formed IR.
1239 CastKind argCK = CK_NoOp;
1240 if (ivarRef.getType()->isObjCObjectPointerType()) {
1241 if (argLoad.getType()->isObjCObjectPointerType())
1242 argCK = CK_BitCast;
1243 else if (argLoad.getType()->isBlockPointerType())
1244 argCK = CK_BlockPointerToObjCPointerCast;
1245 else
1246 argCK = CK_CPointerToObjCPointerCast;
1247 } else if (ivarRef.getType()->isBlockPointerType()) {
1248 if (argLoad.getType()->isBlockPointerType())
1249 argCK = CK_BitCast;
1250 else
1251 argCK = CK_AnyPointerToBlockPointerCast;
1252 } else if (ivarRef.getType()->isPointerType()) {
1253 argCK = CK_BitCast;
1254 }
1255 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1256 ivarRef.getType(), argCK, &argLoad,
1257 VK_RValue);
1258 Expr *finalArg = &argLoad;
1259 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1260 argLoad.getType()))
1261 finalArg = &argCast;
1262
1263
1264 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1265 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +00001266 SourceLocation(), false);
John McCall71c758d2011-09-10 09:17:20 +00001267 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001268}
1269
James Dennett2ee5ba32012-06-15 22:10:14 +00001270/// \brief Generate an Objective-C property setter function.
1271///
1272/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001273/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001274void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1275 const ObjCPropertyImplDecl *PID) {
Stephen Hines176edba2014-12-01 14:53:08 -08001276 llvm::Constant *AtomicHelperFn =
1277 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001278 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1279 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1280 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001281 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001282
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001283 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001284
1285 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001286}
1287
John McCalle81ac692011-03-22 07:05:39 +00001288namespace {
John McCall9928c482011-07-12 16:41:08 +00001289 struct DestroyIvar : EHScopeStack::Cleanup {
1290 private:
1291 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001292 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001293 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001294 bool useEHCleanupForArray;
1295 public:
1296 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1297 CodeGenFunction::Destroyer *destroyer,
1298 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001299 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001300 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001301
Stephen Hines651f13c2014-04-23 16:59:28 -07001302 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall9928c482011-07-12 16:41:08 +00001303 LValue lvalue
1304 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1305 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001306 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001307 }
1308 };
1309}
1310
John McCall9928c482011-07-12 16:41:08 +00001311/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1312static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1313 llvm::Value *addr,
1314 QualType type) {
1315 llvm::Value *null = getNullForVariable(addr);
1316 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1317}
John McCallf85e1932011-06-15 23:02:42 +00001318
John McCalle81ac692011-03-22 07:05:39 +00001319static void emitCXXDestructMethod(CodeGenFunction &CGF,
1320 ObjCImplementationDecl *impl) {
1321 CodeGenFunction::RunCleanupsScope scope(CGF);
1322
1323 llvm::Value *self = CGF.LoadObjCSelf();
1324
Jordy Rosedb8264e2011-07-22 02:08:32 +00001325 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1326 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001327 ivar; ivar = ivar->getNextIvar()) {
1328 QualType type = ivar->getType();
1329
John McCalle81ac692011-03-22 07:05:39 +00001330 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001331 QualType::DestructionKind dtorKind = type.isDestructedType();
1332 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001333
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001334 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCalle81ac692011-03-22 07:05:39 +00001335
John McCall9928c482011-07-12 16:41:08 +00001336 // Use a call to objc_storeStrong to destroy strong ivars, for the
1337 // general benefit of the tools.
1338 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001339 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001340
John McCall9928c482011-07-12 16:41:08 +00001341 // Otherwise use the default for the destruction kind.
1342 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001343 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001344 }
John McCall9928c482011-07-12 16:41:08 +00001345
1346 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1347
1348 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1349 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001350 }
1351
1352 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1353}
1354
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001355void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1356 ObjCMethodDecl *MD,
1357 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001358 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001359 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001360
1361 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001362 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001363 // Suppress the final autorelease in ARC.
1364 AutoreleaseResult = false;
1365
Stephen Hines651f13c2014-04-23 16:59:28 -07001366 for (const auto *IvarInit : IMP->inits()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001367 FieldDecl *Field = IvarInit->getAnyMember();
Stephen Hines651f13c2014-04-23 16:59:28 -07001368 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001369 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1370 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001371 EmitAggExpr(IvarInit->getInit(),
1372 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001373 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001374 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001375 }
1376 // constructor returns 'self'.
1377 CodeGenTypes &Types = CGM.getTypes();
1378 QualType IdTy(CGM.getContext().getObjCIdType());
1379 llvm::Value *SelfAsId =
1380 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1381 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001382
1383 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001384 } else {
John McCalle81ac692011-03-22 07:05:39 +00001385 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001386 }
1387 FinishFunction();
1388}
1389
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001390bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1391 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1392 it++; it++;
1393 const ABIArgInfo &AI = it->info;
1394 // FIXME. Is this sufficient check?
1395 return (AI.getKind() == ABIArgInfo::Indirect);
1396}
1397
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001398bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001399 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001400 return false;
1401 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1402 return FDTTy->getDecl()->hasObjectMember();
1403 return false;
1404}
1405
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001406llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCallf5ebf9b2013-05-03 07:33:41 +00001407 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1408 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1409 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001410 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner41110242008-06-17 18:05:57 +00001411}
1412
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001413QualType CodeGenFunction::TypeOfSelfObject() {
1414 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1415 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001416 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1417 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001418 return PTy->getPointeeType();
1419}
1420
Chris Lattner74391b42009-03-22 21:03:39 +00001421void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001422 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001423 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001425 if (!EnumerationMutationFn) {
1426 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1427 return;
1428 }
1429
Devang Patelbcbd03a2011-01-19 01:36:36 +00001430 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001431 if (DI)
1432 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001433
Devang Patel9d99f2d2011-06-13 23:15:32 +00001434 // The local variable comes into scope immediately.
1435 AutoVarEmission variable = AutoVarEmission::invalid();
1436 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1437 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1438
John McCalld88687f2011-01-07 01:49:06 +00001439 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Anders Carlssonf484c312008-08-31 02:33:12 +00001441 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001442 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001443 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001444 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Anders Carlssonf484c312008-08-31 02:33:12 +00001446 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001447 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
John McCalld88687f2011-01-07 01:49:06 +00001449 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001450 IdentifierInfo *II[] = {
1451 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1452 &CGM.getContext().Idents.get("objects"),
1453 &CGM.getContext().Idents.get("count")
1454 };
1455 Selector FastEnumSel =
1456 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001457
1458 QualType ItemsTy =
1459 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001460 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001461 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001462 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001463
John McCall990567c2011-07-27 01:07:15 +00001464 // Emit the collection pointer. In ARC, we do a retain.
1465 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001466 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001467 Collection = EmitARCRetainScalarExpr(S.getCollection());
1468
1469 // Enter a cleanup to do the release.
1470 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1471 } else {
1472 Collection = EmitScalarExpr(S.getCollection());
1473 }
Mike Stump1eb44332009-09-09 15:08:12 +00001474
John McCall4b302d32011-08-05 00:14:38 +00001475 // The 'continue' label needs to appear within the cleanup for the
1476 // collection object.
1477 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1478
John McCalld88687f2011-01-07 01:49:06 +00001479 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001480 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001481
1482 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001483 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001484
John McCalld88687f2011-01-07 01:49:06 +00001485 // The second argument is a temporary array with space for NumItems
1486 // pointers. We'll actually be loading elements from the array
1487 // pointer written into the control state; this buffer is so that
1488 // collections that *aren't* backed by arrays can still queue up
1489 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001490 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCalld88687f2011-01-07 01:49:06 +00001492 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001493 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001494 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001495 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
John McCalld88687f2011-01-07 01:49:06 +00001497 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001498 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001499 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001500 getContext().UnsignedLongTy,
1501 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001502 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001503
John McCalld88687f2011-01-07 01:49:06 +00001504 // The initial number of objects that were returned in the buffer.
1505 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001506
John McCalld88687f2011-01-07 01:49:06 +00001507 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1508 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001509
John McCalld88687f2011-01-07 01:49:06 +00001510 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001511
John McCalld88687f2011-01-07 01:49:06 +00001512 // If the limit pointer was zero to begin with, the collection is
Stephen Hines651f13c2014-04-23 16:59:28 -07001513 // empty; skip all this. Set the branch weight assuming this has the same
1514 // probability of exiting the loop as any other loop exit.
1515 uint64_t EntryCount = PGO.getCurrentRegionCount();
1516 RegionCounter Cnt = getPGORegionCounter(&S);
John McCalld88687f2011-01-07 01:49:06 +00001517 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
Stephen Hines651f13c2014-04-23 16:59:28 -07001518 EmptyBB, LoopInitBB,
1519 PGO.createBranchWeights(EntryCount, Cnt.getCount()));
Anders Carlssonf484c312008-08-31 02:33:12 +00001520
John McCalld88687f2011-01-07 01:49:06 +00001521 // Otherwise, initialize the loop.
1522 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001523
John McCalld88687f2011-01-07 01:49:06 +00001524 // Save the initial mutations value. This is the value at an
1525 // address that was written into the state object by
1526 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001527 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001528 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001529 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001530 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001531
John McCalld88687f2011-01-07 01:49:06 +00001532 llvm::Value *initialMutations =
1533 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001534
John McCalld88687f2011-01-07 01:49:06 +00001535 // Start looping. This is the point we return to whenever we have a
1536 // fresh, non-empty batch of objects.
1537 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1538 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
John McCalld88687f2011-01-07 01:49:06 +00001540 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001541 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001542 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001543
John McCalld88687f2011-01-07 01:49:06 +00001544 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001545 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001546 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Stephen Hines651f13c2014-04-23 16:59:28 -07001548 Cnt.beginRegion(Builder);
1549
John McCalld88687f2011-01-07 01:49:06 +00001550 // Check whether the mutations value has changed from where it was
1551 // at start. StateMutationsPtr should actually be invariant between
1552 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001553 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001554 llvm::Value *currentMutations
1555 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001556
John McCalld88687f2011-01-07 01:49:06 +00001557 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001558 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001559
John McCalld88687f2011-01-07 01:49:06 +00001560 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1561 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
John McCalld88687f2011-01-07 01:49:06 +00001563 // If so, call the enumeration-mutation function.
1564 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001565 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001566 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001567 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001568 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001569 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001570 // FIXME: We shouldn't need to get the function info here, the runtime already
1571 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001572 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1573 FunctionType::ExtInfo(),
1574 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001575 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
John McCalld88687f2011-01-07 01:49:06 +00001577 // Otherwise, or if the mutation function returns, just continue.
1578 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
John McCalld88687f2011-01-07 01:49:06 +00001580 // Initialize the element variable.
1581 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001582 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001583 LValue elementLValue;
1584 QualType elementType;
1585 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001586 // Initialize the variable, in case it's a __block variable or something.
1587 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001588
John McCall57b3b6a2011-02-22 07:16:58 +00001589 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001590 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001591 VK_LValue, SourceLocation());
1592 elementLValue = EmitLValue(&tempDRE);
1593 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001594 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001595
1596 if (D->isARCPseudoStrong())
1597 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001598 } else {
1599 elementLValue = LValue(); // suppress warning
1600 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001601 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001602 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001603 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001604
1605 // Fetch the buffer out of the enumeration state.
1606 // TODO: this pointer should actually be invariant between
1607 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001608 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001609 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001610 llvm::Value *EnumStateItems =
1611 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001612
John McCalld88687f2011-01-07 01:49:06 +00001613 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001614 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001615 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1616 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001617
John McCalld88687f2011-01-07 01:49:06 +00001618 // Cast that value to the right type.
1619 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1620 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001621
John McCalld88687f2011-01-07 01:49:06 +00001622 // Make sure we have an l-value. Yes, this gets evaluated every
1623 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001624 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001625 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001626 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001627 } else {
1628 EmitScalarInit(CurrentItem, elementLValue);
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
John McCall57b3b6a2011-02-22 07:16:58 +00001631 // If we do have an element variable, this assignment is the end of
1632 // its initialization.
1633 if (elementIsVariable)
1634 EmitAutoVarCleanups(variable);
1635
John McCalld88687f2011-01-07 01:49:06 +00001636 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001637 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001638 {
1639 RunCleanupsScope Scope(*this);
1640 EmitStmt(S.getBody());
1641 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001642 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001643
John McCalld88687f2011-01-07 01:49:06 +00001644 // Destroy the element variable now.
1645 elementVariableScope.ForceCleanup();
1646
1647 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001648 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001649
John McCalld88687f2011-01-07 01:49:06 +00001650 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001651
John McCalld88687f2011-01-07 01:49:06 +00001652 // First we check in the local buffer.
1653 llvm::Value *indexPlusOne
1654 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001655
John McCalld88687f2011-01-07 01:49:06 +00001656 // If we haven't overrun the buffer yet, we can continue.
Stephen Hines651f13c2014-04-23 16:59:28 -07001657 // Set the branch weights based on the simplifying assumption that this is
1658 // like a while-loop, i.e., ignoring that the false branch fetches more
1659 // elements and then returns to the loop.
John McCalld88687f2011-01-07 01:49:06 +00001660 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
Stephen Hines651f13c2014-04-23 16:59:28 -07001661 LoopBodyBB, FetchMoreBB,
1662 PGO.createBranchWeights(Cnt.getCount(), EntryCount));
John McCalld88687f2011-01-07 01:49:06 +00001663
1664 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1665 count->addIncoming(count, AfterBody.getBlock());
1666
1667 // Otherwise, we have to fetch more elements.
1668 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
1670 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001671 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001672 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001673 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001674 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001675
John McCalld88687f2011-01-07 01:49:06 +00001676 // If we got a zero count, we're done.
1677 llvm::Value *refetchCount = CountRV.getScalarVal();
1678
1679 // (note that the message send might split FetchMoreBB)
1680 index->addIncoming(zero, Builder.GetInsertBlock());
1681 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1682
1683 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1684 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Anders Carlssonf484c312008-08-31 02:33:12 +00001686 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001687 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001688
John McCall57b3b6a2011-02-22 07:16:58 +00001689 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001690 // If the element was not a declaration, set it to be null.
1691
John McCalld88687f2011-01-07 01:49:06 +00001692 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1693 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001694 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001695 }
1696
Eric Christopher73fb3502011-10-13 21:45:18 +00001697 if (DI)
1698 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001699
John McCall990567c2011-07-27 01:07:15 +00001700 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001701 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001702 PopCleanupBlock();
1703
John McCallff8e1152010-07-23 21:56:41 +00001704 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001705}
1706
Mike Stump1eb44332009-09-09 15:08:12 +00001707void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001708 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001709}
1710
Mike Stump1eb44332009-09-09 15:08:12 +00001711void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001712 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1713}
1714
Chris Lattner10cac6f2008-11-15 21:26:17 +00001715void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001716 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001717 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001718}
1719
John McCall33e56f32011-09-10 06:18:15 +00001720/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001721/// primitive retain.
1722llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1723 llvm::Value *value) {
1724 return EmitARCRetain(type, value);
1725}
1726
1727namespace {
1728 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001729 CallObjCRelease(llvm::Value *object) : object(object) {}
1730 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001731
Stephen Hines651f13c2014-04-23 16:59:28 -07001732 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5b07e802013-03-13 03:10:54 +00001733 // Releases at the end of the full-expression are imprecise.
1734 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001735 }
1736 };
1737}
1738
John McCall33e56f32011-09-10 06:18:15 +00001739/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001740/// release at the end of the full-expression.
1741llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1742 llvm::Value *object) {
1743 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001744 // conditional.
1745 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001746 return object;
1747}
1748
1749llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1750 llvm::Value *value) {
1751 return EmitARCRetainAutorelease(type, value);
1752}
1753
John McCallb6a60792013-03-23 02:35:54 +00001754/// Given a number of pointers, inform the optimizer that they're
1755/// being intrinsically used up until this point in the program.
1756void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1757 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1758 if (!fn) {
1759 llvm::FunctionType *fnType =
Stephen Hines176edba2014-12-01 14:53:08 -08001760 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCallb6a60792013-03-23 02:35:54 +00001761 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1762 }
1763
1764 // This isn't really a "runtime" function, but as an intrinsic it
1765 // doesn't really matter as long as we align things up.
1766 EmitNounwindRuntimeCall(fn, values);
1767}
1768
John McCallf85e1932011-06-15 23:02:42 +00001769
1770static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001771 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001772 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001773 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1774
Michael Gottesman554b07d2013-02-02 00:57:44 +00001775 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmancfe18a12013-02-02 01:05:06 +00001776 // If the target runtime doesn't naturally support ARC, emit weak
1777 // references to the runtime support library. We don't really
1778 // permit this to fail, but we need a particular relocation style.
Michael Gottesman554b07d2013-02-02 00:57:44 +00001779 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00001780 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesman554b07d2013-02-02 00:57:44 +00001781 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1782 // If we have Native ARC, set nonlazybind attribute for these APIs for
1783 // performance.
Bill Wendling72390b32012-12-20 19:27:06 +00001784 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmandb99e8b2013-02-02 01:03:01 +00001785 }
Michael Gottesman554b07d2013-02-02 00:57:44 +00001786 }
John McCallf85e1932011-06-15 23:02:42 +00001787
1788 return fn;
1789}
1790
1791/// Perform an operation having the signature
1792/// i8* (i8*)
1793/// where a null input causes a no-op and returns null.
1794static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1795 llvm::Value *value,
1796 llvm::Constant *&fn,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001797 StringRef fnName,
1798 bool isTailCall = false) {
John McCallf85e1932011-06-15 23:02:42 +00001799 if (isa<llvm::ConstantPointerNull>(value)) return value;
1800
1801 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001802 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001803 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001804 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1805 }
1806
1807 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001808 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001809 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1810
1811 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001812 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001813 if (isTailCall)
1814 call->setTailCall();
John McCallf85e1932011-06-15 23:02:42 +00001815
1816 // Cast the result back to the original type.
1817 return CGF.Builder.CreateBitCast(call, origType);
1818}
1819
1820/// Perform an operation having the following signature:
1821/// i8* (i8**)
1822static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1823 llvm::Value *addr,
1824 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001825 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001826 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001827 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001828 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001829 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1830 }
1831
1832 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001833 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001834 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1835
1836 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001837 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00001838
1839 // Cast the result back to a dereference of the original type.
John McCallf85e1932011-06-15 23:02:42 +00001840 if (origType != CGF.Int8PtrPtrTy)
1841 result = CGF.Builder.CreateBitCast(result,
1842 cast<llvm::PointerType>(origType)->getElementType());
1843
1844 return result;
1845}
1846
1847/// Perform an operation having the following signature:
1848/// i8* (i8**, i8*)
1849static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1850 llvm::Value *addr,
1851 llvm::Value *value,
1852 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001853 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001854 bool ignored) {
1855 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1856 == value->getType());
1857
1858 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001859 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001860
Chris Lattner2acc6e32011-07-18 04:24:23 +00001861 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001862 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1863 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1864 }
1865
Chris Lattner2acc6e32011-07-18 04:24:23 +00001866 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001867
John McCallbd7370a2013-02-28 19:01:20 +00001868 llvm::Value *args[] = {
1869 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1870 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1871 };
1872 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001873
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001874 if (ignored) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001875
1876 return CGF.Builder.CreateBitCast(result, origType);
1877}
1878
1879/// Perform an operation having the following signature:
1880/// void (i8**, i8**)
1881static void emitARCCopyOperation(CodeGenFunction &CGF,
1882 llvm::Value *dst,
1883 llvm::Value *src,
1884 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001885 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001886 assert(dst->getType() == src->getType());
1887
1888 if (!fn) {
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001889 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1890
Chris Lattner2acc6e32011-07-18 04:24:23 +00001891 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001892 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1893 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1894 }
1895
John McCallbd7370a2013-02-28 19:01:20 +00001896 llvm::Value *args[] = {
1897 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1898 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1899 };
1900 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001901}
1902
1903/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001904/// call i8* \@objc_retain(i8* %value)
1905/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001906llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1907 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001908 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001909 else
1910 return EmitARCRetainNonBlock(value);
1911}
1912
1913/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001914/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001915llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1916 return emitARCValueOperation(*this, value,
1917 CGM.getARCEntrypoints().objc_retain,
1918 "objc_retain");
1919}
1920
1921/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001922/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001923///
1924/// \param mandatory - If false, emit the call with metadata
1925/// indicating that it's okay for the optimizer to eliminate this call
1926/// if it can prove that the block never escapes except down the stack.
1927llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1928 bool mandatory) {
1929 llvm::Value *result
1930 = emitARCValueOperation(*this, value,
1931 CGM.getARCEntrypoints().objc_retainBlock,
1932 "objc_retainBlock");
1933
1934 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1935 // tell the optimizer that it doesn't need to do this copy if the
1936 // block doesn't escape, where being passed as an argument doesn't
1937 // count as escaping.
1938 if (!mandatory && isa<llvm::Instruction>(result)) {
1939 llvm::CallInst *call
1940 = cast<llvm::CallInst>(result->stripPointerCasts());
1941 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1942
1943 SmallVector<llvm::Value*,1> args;
1944 call->setMetadata("clang.arc.copy_on_escape",
1945 llvm::MDNode::get(Builder.getContext(), args));
1946 }
1947
1948 return result;
John McCallf85e1932011-06-15 23:02:42 +00001949}
1950
1951/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001952/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001953///
1954/// Yes, this function name is one character away from a different
1955/// call with completely different semantics.
1956llvm::Value *
1957CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1958 // Fetch the void(void) inline asm which marks that we're going to
1959 // retain the autoreleased return value.
1960 llvm::InlineAsm *&marker
1961 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1962 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001963 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001964 = CGM.getTargetCodeGenInfo()
1965 .getARCRetainAutoreleasedReturnValueMarker();
1966
1967 // If we have an empty assembly string, there's nothing to do.
1968 if (assembly.empty()) {
1969
1970 // Otherwise, at -O0, build an inline asm that we're going to call
1971 // in a moment.
1972 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1973 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001974 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001975
1976 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1977
1978 // If we're at -O1 and above, we don't want to litter the code
1979 // with this marker yet, so leave a breadcrumb for the ARC
1980 // optimizer to pick up.
1981 } else {
1982 llvm::NamedMDNode *metadata =
1983 CGM.getModule().getOrInsertNamedMetadata(
1984 "clang.arc.retainAutoreleasedReturnValueMarker");
1985 assert(metadata->getNumOperands() <= 1);
1986 if (metadata->getNumOperands() == 0) {
1987 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001988 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001989 }
1990 }
1991 }
1992
1993 // Call the marker asm if we made one, which we do only at -O0.
1994 if (marker) Builder.CreateCall(marker);
1995
1996 return emitARCValueOperation(*this, value,
1997 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1998 "objc_retainAutoreleasedReturnValue");
1999}
2000
2001/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002002/// call void \@objc_release(i8* %value)
John McCall5b07e802013-03-13 03:10:54 +00002003void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2004 ARCPreciseLifetime_t precise) {
John McCallf85e1932011-06-15 23:02:42 +00002005 if (isa<llvm::ConstantPointerNull>(value)) return;
2006
2007 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2008 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002009 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002010 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002011 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2012 }
2013
2014 // Cast the argument to 'id'.
2015 value = Builder.CreateBitCast(value, Int8PtrTy);
2016
2017 // Call objc_release.
John McCallbd7370a2013-02-28 19:01:20 +00002018 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002019
John McCall5b07e802013-03-13 03:10:54 +00002020 if (precise == ARCImpreciseLifetime) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002021 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00002022 call->setMetadata("clang.imprecise_release",
2023 llvm::MDNode::get(Builder.getContext(), args));
2024 }
2025}
2026
John McCall015f33b2012-10-17 02:28:37 +00002027/// Destroy a __strong variable.
2028///
2029/// At -O0, emit a call to store 'null' into the address;
2030/// instrumenting tools prefer this because the address is exposed,
2031/// but it's relatively cumbersome to optimize.
2032///
2033/// At -O1 and above, just load and call objc_release.
2034///
2035/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall5b07e802013-03-13 03:10:54 +00002036void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2037 ARCPreciseLifetime_t precise) {
John McCall015f33b2012-10-17 02:28:37 +00002038 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2039 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2040 llvm::Value *null = llvm::ConstantPointerNull::get(
2041 cast<llvm::PointerType>(addrTy->getElementType()));
2042 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2043 return;
2044 }
2045
2046 llvm::Value *value = Builder.CreateLoad(addr);
2047 EmitARCRelease(value, precise);
2048}
2049
John McCallf85e1932011-06-15 23:02:42 +00002050/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002051/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002052llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2053 llvm::Value *value,
2054 bool ignored) {
2055 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2056 == value->getType());
2057
2058 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2059 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002060 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00002061 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00002062 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2063 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2064 }
2065
John McCallbd7370a2013-02-28 19:01:20 +00002066 llvm::Value *args[] = {
2067 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2068 Builder.CreateBitCast(value, Int8PtrTy)
2069 };
2070 EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00002071
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002072 if (ignored) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002073 return value;
2074}
2075
2076/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002077/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002078/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00002079llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00002080 llvm::Value *newValue,
2081 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00002082 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00002083 bool isBlock = type->isBlockPointerType();
2084
2085 // Use a store barrier at -O0 unless this is a block type or the
2086 // lvalue is inadequately aligned.
2087 if (shouldUseFusedARCCalls() &&
2088 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00002089 (dst.getAlignment().isZero() ||
2090 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00002091 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2092 }
2093
2094 // Otherwise, split it out.
2095
2096 // Retain the new value.
2097 newValue = EmitARCRetain(type, newValue);
2098
2099 // Read the old value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002100 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00002101
2102 // Store. We do this before the release so that any deallocs won't
2103 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002104 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002105
2106 // Finally, release the old value.
John McCall5b07e802013-03-13 03:10:54 +00002107 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002108
2109 return newValue;
2110}
2111
2112/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002113/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002114llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2115 return emitARCValueOperation(*this, value,
2116 CGM.getARCEntrypoints().objc_autorelease,
2117 "objc_autorelease");
2118}
2119
2120/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002121/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002122llvm::Value *
2123CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2124 return emitARCValueOperation(*this, value,
2125 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002126 "objc_autoreleaseReturnValue",
2127 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002128}
2129
2130/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002131/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002132llvm::Value *
2133CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2134 return emitARCValueOperation(*this, value,
2135 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002136 "objc_retainAutoreleaseReturnValue",
2137 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002138}
2139
2140/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002141/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002142/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002143/// %retain = call i8* \@objc_retainBlock(i8* %value)
2144/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002145llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2146 llvm::Value *value) {
2147 if (!type->isBlockPointerType())
2148 return EmitARCRetainAutoreleaseNonBlock(value);
2149
2150 if (isa<llvm::ConstantPointerNull>(value)) return value;
2151
Chris Lattner2acc6e32011-07-18 04:24:23 +00002152 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002153 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002154 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002155 value = EmitARCAutorelease(value);
2156 return Builder.CreateBitCast(value, origType);
2157}
2158
2159/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002160/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002161llvm::Value *
2162CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2163 return emitARCValueOperation(*this, value,
2164 CGM.getARCEntrypoints().objc_retainAutorelease,
2165 "objc_retainAutorelease");
2166}
2167
James Dennett9d96e9c2012-06-22 05:41:30 +00002168/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002169/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2170llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2171 return emitARCLoadOperation(*this, addr,
2172 CGM.getARCEntrypoints().objc_loadWeak,
2173 "objc_loadWeak");
2174}
2175
James Dennett9d96e9c2012-06-22 05:41:30 +00002176/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002177llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2178 return emitARCLoadOperation(*this, addr,
2179 CGM.getARCEntrypoints().objc_loadWeakRetained,
2180 "objc_loadWeakRetained");
2181}
2182
James Dennett9d96e9c2012-06-22 05:41:30 +00002183/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002184/// Returns %value.
2185llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2186 llvm::Value *value,
2187 bool ignored) {
2188 return emitARCStoreOperation(*this, addr, value,
2189 CGM.getARCEntrypoints().objc_storeWeak,
2190 "objc_storeWeak", ignored);
2191}
2192
James Dennett9d96e9c2012-06-22 05:41:30 +00002193/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002194/// Returns %value. %addr is known to not have a current weak entry.
2195/// Essentially equivalent to:
2196/// *addr = nil; objc_storeWeak(addr, value);
2197void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2198 // If we're initializing to null, just write null to memory; no need
2199 // to get the runtime involved. But don't do this if optimization
2200 // is enabled, because accounting for this would make the optimizer
2201 // much more complicated.
2202 if (isa<llvm::ConstantPointerNull>(value) &&
2203 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2204 Builder.CreateStore(value, addr);
2205 return;
2206 }
2207
2208 emitARCStoreOperation(*this, addr, value,
2209 CGM.getARCEntrypoints().objc_initWeak,
2210 "objc_initWeak", /*ignored*/ true);
2211}
2212
James Dennett9d96e9c2012-06-22 05:41:30 +00002213/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002214/// Essentially objc_storeWeak(addr, nil).
2215void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2216 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2217 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002218 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002219 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002220 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2221 }
2222
2223 // Cast the argument to 'id*'.
2224 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2225
John McCallbd7370a2013-02-28 19:01:20 +00002226 EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00002227}
2228
James Dennett9d96e9c2012-06-22 05:41:30 +00002229/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002230/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2231/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2232void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2233 emitARCCopyOperation(*this, dst, src,
2234 CGM.getARCEntrypoints().objc_moveWeak,
2235 "objc_moveWeak");
2236}
2237
James Dennett9d96e9c2012-06-22 05:41:30 +00002238/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002239/// Disregards the current value in %dest. Essentially
2240/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2241void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2242 emitARCCopyOperation(*this, dst, src,
2243 CGM.getARCEntrypoints().objc_copyWeak,
2244 "objc_copyWeak");
2245}
2246
2247/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002248/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002249llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2250 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2251 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002252 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002253 llvm::FunctionType::get(Int8PtrTy, false);
2254 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2255 }
2256
John McCallbd7370a2013-02-28 19:01:20 +00002257 return EmitNounwindRuntimeCall(fn);
John McCallf85e1932011-06-15 23:02:42 +00002258}
2259
2260/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002261/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002262void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2263 assert(value->getType() == Int8PtrTy);
2264
2265 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2266 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002267 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002268 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002269
2270 // We don't want to use a weak import here; instead we should not
2271 // fall into this path.
2272 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2273 }
2274
John McCallb57f6b32013-04-16 21:29:40 +00002275 // objc_autoreleasePoolPop can throw.
2276 EmitRuntimeCallOrInvoke(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002277}
2278
2279/// Produce the code to do an MRR version objc_autoreleasepool_push.
2280/// Which is: [[NSAutoreleasePool alloc] init];
2281/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2282/// init is declared as: - (id) init; in its NSObject super class.
2283///
2284llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2285 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +00002286 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCallf85e1932011-06-15 23:02:42 +00002287 // [NSAutoreleasePool alloc]
2288 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2289 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2290 CallArgList Args;
2291 RValue AllocRV =
2292 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2293 getContext().getObjCIdType(),
2294 AllocSel, Receiver, Args);
2295
2296 // [Receiver init]
2297 Receiver = AllocRV.getScalarVal();
2298 II = &CGM.getContext().Idents.get("init");
2299 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2300 RValue InitRV =
2301 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2302 getContext().getObjCIdType(),
2303 InitSel, Receiver, Args);
2304 return InitRV.getScalarVal();
2305}
2306
2307/// Produce the code to do a primitive release.
2308/// [tmp drain];
2309void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2310 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2311 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2312 CallArgList Args;
2313 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2314 getContext().VoidTy, DrainSel, Arg, Args);
2315}
2316
John McCallbdc4d802011-07-09 01:37:26 +00002317void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2318 llvm::Value *addr,
2319 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002320 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002321}
2322
2323void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2324 llvm::Value *addr,
2325 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002326 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002327}
2328
2329void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2330 llvm::Value *addr,
2331 QualType type) {
2332 CGF.EmitARCDestroyWeak(addr);
2333}
2334
John McCallf85e1932011-06-15 23:02:42 +00002335namespace {
John McCallf85e1932011-06-15 23:02:42 +00002336 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2337 llvm::Value *Token;
2338
2339 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2340
Stephen Hines651f13c2014-04-23 16:59:28 -07002341 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002342 CGF.EmitObjCAutoreleasePoolPop(Token);
2343 }
2344 };
2345 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2346 llvm::Value *Token;
2347
2348 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2349
Stephen Hines651f13c2014-04-23 16:59:28 -07002350 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002351 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2352 }
2353 };
2354}
2355
2356void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002357 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002358 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2359 else
2360 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2361}
2362
John McCallf85e1932011-06-15 23:02:42 +00002363static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2364 LValue lvalue,
2365 QualType type) {
2366 switch (type.getObjCLifetime()) {
2367 case Qualifiers::OCL_None:
2368 case Qualifiers::OCL_ExplicitNone:
2369 case Qualifiers::OCL_Strong:
2370 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002371 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2372 SourceLocation()).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002373 false);
2374
2375 case Qualifiers::OCL_Weak:
2376 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2377 true);
2378 }
2379
2380 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002381}
2382
2383static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2384 const Expr *e) {
2385 e = e->IgnoreParens();
2386 QualType type = e->getType();
2387
John McCall21480112011-08-30 00:57:29 +00002388 // If we're loading retained from a __strong xvalue, we can avoid
2389 // an extra retain/release pair by zeroing out the source of this
2390 // "move" operation.
2391 if (e->isXValue() &&
2392 !type.isConstQualified() &&
2393 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2394 // Emit the lvalue.
2395 LValue lv = CGF.EmitLValue(e);
2396
2397 // Load the object pointer.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002398 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2399 SourceLocation()).getScalarVal();
John McCall21480112011-08-30 00:57:29 +00002400
2401 // Set the source pointer to NULL.
2402 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2403
2404 return TryEmitResult(result, true);
2405 }
2406
John McCallf85e1932011-06-15 23:02:42 +00002407 // As a very special optimization, in ARC++, if the l-value is the
2408 // result of a non-volatile assignment, do a simple retain of the
2409 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002410 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002411 !type.isVolatileQualified() &&
2412 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2413 isa<BinaryOperator>(e) &&
2414 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2415 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2416
2417 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2418}
2419
2420static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2421 llvm::Value *value);
2422
2423/// Given that the given expression is some sort of call (which does
2424/// not return retained), emit a retain following it.
2425static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2426 llvm::Value *value = CGF.EmitScalarExpr(e);
2427 return emitARCRetainAfterCall(CGF, value);
2428}
2429
2430static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2431 llvm::Value *value) {
2432 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2433 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2434
2435 // Place the retain immediately following the call.
2436 CGF.Builder.SetInsertPoint(call->getParent(),
2437 ++llvm::BasicBlock::iterator(call));
2438 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2439
2440 CGF.Builder.restoreIP(ip);
2441 return value;
2442 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2443 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2444
2445 // Place the retain at the beginning of the normal destination block.
2446 llvm::BasicBlock *BB = invoke->getNormalDest();
2447 CGF.Builder.SetInsertPoint(BB, BB->begin());
2448 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2449
2450 CGF.Builder.restoreIP(ip);
2451 return value;
2452
2453 // Bitcasts can arise because of related-result returns. Rewrite
2454 // the operand.
2455 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2456 llvm::Value *operand = bitcast->getOperand(0);
2457 operand = emitARCRetainAfterCall(CGF, operand);
2458 bitcast->setOperand(0, operand);
2459 return bitcast;
2460
2461 // Generic fall-back case.
2462 } else {
2463 // Retain using the non-block variant: we never need to do a copy
2464 // of a block that's been returned to us.
2465 return CGF.EmitARCRetainNonBlock(value);
2466 }
2467}
2468
John McCalldc05b112011-09-10 01:16:55 +00002469/// Determine whether it might be important to emit a separate
2470/// objc_retain_block on the result of the given expression, or
2471/// whether it's okay to just emit it in a +1 context.
2472static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2473 assert(e->getType()->isBlockPointerType());
2474 e = e->IgnoreParens();
2475
2476 // For future goodness, emit block expressions directly in +1
2477 // contexts if we can.
2478 if (isa<BlockExpr>(e))
2479 return false;
2480
2481 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2482 switch (cast->getCastKind()) {
2483 // Emitting these operations in +1 contexts is goodness.
2484 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002485 case CK_ARCReclaimReturnedObject:
2486 case CK_ARCConsumeObject:
2487 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002488 return false;
2489
2490 // These operations preserve a block type.
2491 case CK_NoOp:
2492 case CK_BitCast:
2493 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2494
2495 // These operations are known to be bad (or haven't been considered).
2496 case CK_AnyPointerToBlockPointerCast:
2497 default:
2498 return true;
2499 }
2500 }
2501
2502 return true;
2503}
2504
John McCall4b9c2d22011-11-06 09:01:30 +00002505/// Try to emit a PseudoObjectExpr at +1.
2506///
2507/// This massively duplicates emitPseudoObjectRValue.
2508static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2509 const PseudoObjectExpr *E) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002510 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCall4b9c2d22011-11-06 09:01:30 +00002511
2512 // Find the result expression.
2513 const Expr *resultExpr = E->getResultExpr();
2514 assert(resultExpr);
2515 TryEmitResult result;
2516
2517 for (PseudoObjectExpr::const_semantics_iterator
2518 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2519 const Expr *semantic = *i;
2520
2521 // If this semantic expression is an opaque value, bind it
2522 // to the result of its source expression.
2523 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2524 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2525 OVMA opaqueData;
2526
2527 // If this semantic is the result of the pseudo-object
2528 // expression, try to evaluate the source as +1.
2529 if (ov == resultExpr) {
2530 assert(!OVMA::shouldBindAsLValue(ov));
2531 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2532 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2533
2534 // Otherwise, just bind it.
2535 } else {
2536 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2537 }
2538 opaques.push_back(opaqueData);
2539
2540 // Otherwise, if the expression is the result, evaluate it
2541 // and remember the result.
2542 } else if (semantic == resultExpr) {
2543 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2544
2545 // Otherwise, evaluate the expression in an ignored context.
2546 } else {
2547 CGF.EmitIgnoredExpr(semantic);
2548 }
2549 }
2550
2551 // Unbind all the opaques now.
2552 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2553 opaques[i].unbind(CGF);
2554
2555 return result;
2556}
2557
John McCallf85e1932011-06-15 23:02:42 +00002558static TryEmitResult
2559tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002560 // We should *never* see a nested full-expression here, because if
2561 // we fail to emit at +1, our caller must not retain after we close
2562 // out the full-expression.
2563 assert(!isa<ExprWithCleanups>(e));
John McCall990567c2011-07-27 01:07:15 +00002564
John McCallf85e1932011-06-15 23:02:42 +00002565 // The desired result type, if it differs from the type of the
2566 // ultimate opaque expression.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002567 llvm::Type *resultType = nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002568
2569 while (true) {
2570 e = e->IgnoreParens();
2571
2572 // There's a break at the end of this if-chain; anything
2573 // that wants to keep looping has to explicitly continue.
2574 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2575 switch (ce->getCastKind()) {
2576 // No-op casts don't change the type, so we just ignore them.
2577 case CK_NoOp:
2578 e = ce->getSubExpr();
2579 continue;
2580
2581 case CK_LValueToRValue: {
2582 TryEmitResult loadResult
2583 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2584 if (resultType) {
2585 llvm::Value *value = loadResult.getPointer();
2586 value = CGF.Builder.CreateBitCast(value, resultType);
2587 loadResult.setPointer(value);
2588 }
2589 return loadResult;
2590 }
2591
2592 // These casts can change the type, so remember that and
2593 // soldier on. We only need to remember the outermost such
2594 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002595 case CK_CPointerToObjCPointerCast:
2596 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002597 case CK_AnyPointerToBlockPointerCast:
2598 case CK_BitCast:
2599 if (!resultType)
2600 resultType = CGF.ConvertType(ce->getType());
2601 e = ce->getSubExpr();
2602 assert(e->getType()->hasPointerRepresentation());
2603 continue;
2604
2605 // For consumptions, just emit the subexpression and thus elide
2606 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002607 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002608 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2609 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2610 return TryEmitResult(result, true);
2611 }
2612
John McCalldc05b112011-09-10 01:16:55 +00002613 // Block extends are net +0. Naively, we could just recurse on
2614 // the subexpression, but actually we need to ensure that the
2615 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002616 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002617 llvm::Value *result; // will be a +0 value
2618
2619 // If we can't safely assume the sub-expression will produce a
2620 // block-copied value, emit the sub-expression at +0.
2621 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2622 result = CGF.EmitScalarExpr(ce->getSubExpr());
2623
2624 // Otherwise, try to emit the sub-expression at +1 recursively.
2625 } else {
2626 TryEmitResult subresult
2627 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2628 result = subresult.getPointer();
2629
2630 // If that produced a retained value, just use that,
2631 // possibly casting down.
2632 if (subresult.getInt()) {
2633 if (resultType)
2634 result = CGF.Builder.CreateBitCast(result, resultType);
2635 return TryEmitResult(result, true);
2636 }
2637
2638 // Otherwise it's +0.
2639 }
2640
2641 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002642 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002643 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2644 return TryEmitResult(result, true);
2645 }
2646
John McCall7e5e5f42011-07-07 06:58:02 +00002647 // For reclaims, emit the subexpression as a retained call and
2648 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002649 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002650 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2651 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2652 return TryEmitResult(result, true);
2653 }
2654
John McCallf85e1932011-06-15 23:02:42 +00002655 default:
2656 break;
2657 }
2658
2659 // Skip __extension__.
2660 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2661 if (op->getOpcode() == UO_Extension) {
2662 e = op->getSubExpr();
2663 continue;
2664 }
2665
2666 // For calls and message sends, use the retained-call logic.
2667 // Delegate inits are a special case in that they're the only
2668 // returns-retained expression that *isn't* surrounded by
2669 // a consume.
2670 } else if (isa<CallExpr>(e) ||
2671 (isa<ObjCMessageExpr>(e) &&
2672 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2673 llvm::Value *result = emitARCRetainCall(CGF, e);
2674 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2675 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002676
2677 // Look through pseudo-object expressions.
2678 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2679 TryEmitResult result
2680 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2681 if (resultType) {
2682 llvm::Value *value = result.getPointer();
2683 value = CGF.Builder.CreateBitCast(value, resultType);
2684 result.setPointer(value);
2685 }
2686 return result;
John McCallf85e1932011-06-15 23:02:42 +00002687 }
2688
2689 // Conservatively halt the search at any other expression kind.
2690 break;
2691 }
2692
2693 // We didn't find an obvious production, so emit what we've got and
2694 // tell the caller that we didn't manage to retain.
2695 llvm::Value *result = CGF.EmitScalarExpr(e);
2696 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2697 return TryEmitResult(result, false);
2698}
2699
2700static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2701 LValue lvalue,
2702 QualType type) {
2703 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2704 llvm::Value *value = result.getPointer();
2705 if (!result.getInt())
2706 value = CGF.EmitARCRetain(type, value);
2707 return value;
2708}
2709
2710/// EmitARCRetainScalarExpr - Semantically equivalent to
2711/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2712/// best-effort attempt to peephole expressions that naturally produce
2713/// retained objects.
2714llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002715 // The retain needs to happen within the full-expression.
2716 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2717 enterFullExpression(cleanups);
2718 RunCleanupsScope scope(*this);
2719 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2720 }
2721
John McCallf85e1932011-06-15 23:02:42 +00002722 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2723 llvm::Value *value = result.getPointer();
2724 if (!result.getInt())
2725 value = EmitARCRetain(e->getType(), value);
2726 return value;
2727}
2728
2729llvm::Value *
2730CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002731 // The retain needs to happen within the full-expression.
2732 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2733 enterFullExpression(cleanups);
2734 RunCleanupsScope scope(*this);
2735 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2736 }
2737
John McCallf85e1932011-06-15 23:02:42 +00002738 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2739 llvm::Value *value = result.getPointer();
2740 if (result.getInt())
2741 value = EmitARCAutorelease(value);
2742 else
2743 value = EmitARCRetainAutorelease(e->getType(), value);
2744 return value;
2745}
2746
John McCall348f16f2011-10-04 06:23:45 +00002747llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2748 llvm::Value *result;
2749 bool doRetain;
2750
2751 if (shouldEmitSeparateBlockRetain(e)) {
2752 result = EmitScalarExpr(e);
2753 doRetain = true;
2754 } else {
2755 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2756 result = subresult.getPointer();
2757 doRetain = !subresult.getInt();
2758 }
2759
2760 if (doRetain)
2761 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2762 return EmitObjCConsumeObject(e->getType(), result);
2763}
2764
John McCall2b014d62011-10-01 10:32:24 +00002765llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2766 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002767 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002768 // Do so before running any cleanups for the full-expression.
John McCall72dcecc2013-02-12 00:25:08 +00002769 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall2b014d62011-10-01 10:32:24 +00002770 return EmitARCRetainAutoreleaseScalarExpr(expr);
2771 }
2772
2773 // Otherwise, use the normal scalar-expression emission. The
2774 // exception machinery doesn't do anything special with the
2775 // exception like retaining it, so there's no safety associated with
2776 // only running cleanups after the throw has started, and when it
2777 // matters it tends to be substantially inferior code.
2778 return EmitScalarExpr(expr);
2779}
2780
John McCallf85e1932011-06-15 23:02:42 +00002781std::pair<LValue,llvm::Value*>
2782CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2783 bool ignored) {
2784 // Evaluate the RHS first.
2785 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2786 llvm::Value *value = result.getPointer();
2787
John McCallfb720812011-07-28 07:23:35 +00002788 bool hasImmediateRetain = result.getInt();
2789
2790 // If we didn't emit a retained object, and the l-value is of block
2791 // type, then we need to emit the block-retain immediately in case
2792 // it invalidates the l-value.
2793 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002794 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002795 hasImmediateRetain = true;
2796 }
2797
John McCallf85e1932011-06-15 23:02:42 +00002798 LValue lvalue = EmitLValue(e->getLHS());
2799
2800 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002801 if (hasImmediateRetain) {
Nick Lewyckyc53143c2013-10-02 02:33:11 +00002802 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedman6da2c712011-12-03 04:14:32 +00002803 EmitStoreOfScalar(value, lvalue);
John McCall5b07e802013-03-13 03:10:54 +00002804 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002805 } else {
John McCall545d9962011-06-25 02:11:03 +00002806 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002807 }
2808
2809 return std::pair<LValue,llvm::Value*>(lvalue, value);
2810}
2811
2812std::pair<LValue,llvm::Value*>
2813CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2814 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2815 LValue lvalue = EmitLValue(e->getLHS());
2816
Eli Friedman6da2c712011-12-03 04:14:32 +00002817 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002818
2819 return std::pair<LValue,llvm::Value*>(lvalue, value);
2820}
2821
2822void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002823 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002824 const Stmt *subStmt = ARPS.getSubStmt();
2825 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2826
2827 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002828 if (DI)
2829 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002830
2831 // Keep track of the current cleanup stack depth.
2832 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00002833 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002834 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2835 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2836 } else {
2837 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2838 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2839 }
2840
Stephen Hines651f13c2014-04-23 16:59:28 -07002841 for (const auto *I : S.body())
2842 EmitStmt(I);
John McCallf85e1932011-06-15 23:02:42 +00002843
Eric Christopher73fb3502011-10-13 21:45:18 +00002844 if (DI)
2845 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002846}
John McCall0c24c802011-06-24 23:21:27 +00002847
2848/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2849/// make sure it survives garbage collection until this point.
2850void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2851 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002852 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002853 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002854 llvm::Value *extender
2855 = llvm::InlineAsm::get(extenderType,
2856 /* assembly */ "",
2857 /* constraints */ "r",
2858 /* side effects */ true);
2859
2860 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00002861 EmitNounwindRuntimeCall(extender, object);
John McCall0c24c802011-06-24 23:21:27 +00002862}
2863
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002864/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002865/// non-trivial copy assignment function, produce following helper function.
2866/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2867///
2868llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002869CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2870 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002871 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002872 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002873 return nullptr;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002874 QualType Ty = PID->getPropertyIvarDecl()->getType();
2875 if (!Ty->isRecordType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002876 return nullptr;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002877 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002878 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002879 return nullptr;
2880 llvm::Constant *HelperFn = nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002881 if (hasTrivialSetExpr(PID))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002882 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002883 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2884 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2885 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002886
2887 ASTContext &C = getContext();
2888 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002889 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002890 FunctionDecl *FD = FunctionDecl::Create(C,
2891 C.getTranslationUnitDecl(),
2892 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002893 SourceLocation(), II, C.VoidTy,
2894 nullptr, SC_Static,
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002895 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002896 false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002897
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002898 QualType DestTy = C.getPointerType(Ty);
2899 QualType SrcTy = Ty;
2900 SrcTy.addConst();
2901 SrcTy = C.getPointerType(SrcTy);
2902
2903 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002904 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002905 args.push_back(&dstDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002906 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002907 args.push_back(&srcDecl);
Stephen Hines651f13c2014-04-23 16:59:28 -07002908
2909 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2910 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2911
John McCallde5d3c72012-02-17 03:33:10 +00002912 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002913
2914 llvm::Function *Fn =
2915 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002916 "__assign_helper_atomic_property_",
2917 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002918
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002919 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002920
John McCallf4b88a42012-03-10 09:33:50 +00002921 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2922 VK_RValue, SourceLocation());
2923 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2924 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002925
John McCallf4b88a42012-03-10 09:33:50 +00002926 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2927 VK_RValue, SourceLocation());
2928 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2929 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002930
John McCallf4b88a42012-03-10 09:33:50 +00002931 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002932 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002933 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002934 Args, DestTy->getPointeeType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00002935 VK_LValue, SourceLocation(), false);
John McCallf4b88a42012-03-10 09:33:50 +00002936
2937 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002938
2939 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002940 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002941 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002942 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002943}
2944
2945llvm::Constant *
2946CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2947 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002948 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002949 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002950 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002951 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2952 QualType Ty = PD->getType();
2953 if (!Ty->isRecordType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002954 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002955 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002956 return nullptr;
2957 llvm::Constant *HelperFn = nullptr;
2958
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002959 if (hasTrivialGetExpr(PID))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002960 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002961 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2962 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2963 return HelperFn;
2964
2965
2966 ASTContext &C = getContext();
2967 IdentifierInfo *II
2968 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2969 FunctionDecl *FD = FunctionDecl::Create(C,
2970 C.getTranslationUnitDecl(),
2971 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002972 SourceLocation(), II, C.VoidTy,
2973 nullptr, SC_Static,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002974 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002975 false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002976
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002977 QualType DestTy = C.getPointerType(Ty);
2978 QualType SrcTy = Ty;
2979 SrcTy.addConst();
2980 SrcTy = C.getPointerType(SrcTy);
2981
2982 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002983 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002984 args.push_back(&dstDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002985 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002986 args.push_back(&srcDecl);
Stephen Hines651f13c2014-04-23 16:59:28 -07002987
2988 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2989 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2990
John McCallde5d3c72012-02-17 03:33:10 +00002991 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002992
2993 llvm::Function *Fn =
2994 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2995 "__copy_helper_atomic_property_", &CGM.getModule());
2996
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002997 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002998
John McCallf4b88a42012-03-10 09:33:50 +00002999 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003000 VK_RValue, SourceLocation());
3001
John McCallf4b88a42012-03-10 09:33:50 +00003002 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3003 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003004
3005 CXXConstructExpr *CXXConstExpr =
3006 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3007
3008 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00003009 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003010 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3011 ++A;
3012
3013 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3014 A != AEnd; ++A)
3015 ConstructorArgs.push_back(*A);
3016
3017 CXXConstructExpr *TheCXXConstructExpr =
3018 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3019 CXXConstExpr->getConstructor(),
3020 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003021 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003022 CXXConstExpr->hadMultipleCandidates(),
3023 CXXConstExpr->isListInitialization(),
Stephen Hines176edba2014-12-01 14:53:08 -08003024 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003025 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00003026 CXXConstExpr->getConstructionKind(),
3027 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003028
John McCallf4b88a42012-03-10 09:33:50 +00003029 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3030 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003031
John McCallf4b88a42012-03-10 09:33:50 +00003032 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00003033 CharUnits Alignment
3034 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003035 EmitAggExpr(TheCXXConstructExpr,
3036 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3037 AggValueSlot::IsDestructed,
3038 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00003039 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003040
3041 FinishFunction();
3042 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3043 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3044 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003045}
3046
Eli Friedmancae40c42012-02-28 01:08:45 +00003047llvm::Value *
3048CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3049 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003050 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3051 Selector CopySelector =
3052 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00003053 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3054 Selector AutoreleaseSelector =
3055 getContext().Selectors.getNullarySelector(AutoreleaseID);
3056
3057 // Emit calls to retain/autorelease.
3058 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3059 llvm::Value *Val = Block;
3060 RValue Result;
3061 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003062 Ty, CopySelector,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003063 Val, CallArgList(), nullptr, nullptr);
Eli Friedmancae40c42012-02-28 01:08:45 +00003064 Val = Result.getScalarVal();
3065 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3066 Ty, AutoreleaseSelector,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003067 Val, CallArgList(), nullptr, nullptr);
Eli Friedmancae40c42012-02-28 01:08:45 +00003068 Val = Result.getScalarVal();
3069 return Val;
3070}
3071
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003072
Ted Kremenek2979ec72008-04-09 15:51:31 +00003073CGObjCRuntime::~CGObjCRuntime() {}