blob: a0b92c9938100760f9c2262338f4b7a16ebcf807 [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
David Chisnall481e3a82010-01-23 02:40:42 +000048 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000049 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Patrick Beard0caa3942012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000056/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000058///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000059llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000064 const Expr *SubExpr = E->getSubExpr();
Patrick Beard0caa3942012-04-19 00:25:12 +000065 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000070 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000077 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
79
80 // ObjCBoxedExpr supports boxing of structs and unions
81 // via [NSValue valueWithBytes:objCType:]
82 const QualType ValueType(SubExpr->getType().getCanonicalType());
83 if (ValueType->isObjCBoxableRecordType()) {
84 // Emit CodeGen for first parameter
85 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000086 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000087 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000088 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000090
91 // Create char array to store type encoding
92 std::string Str;
93 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000094 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Alex Denisovfde64952015-06-26 05:28:36 +000095
96 // Cast type encoding to correct type
97 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
100
101 Args.add(RValue::get(Cast), EncodingQT);
102 } else {
103 Args.add(EmitAnyExpr(SubExpr), ArgQT);
104 }
Alp Toker314cc812014-01-25 16:55:45 +0000105
106 RValue result = Runtime.GenerateMessageSend(
107 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108 Args, ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000109 return Builder.CreateBitCast(result.getScalarVal(),
110 ConvertType(E->getType()));
111}
112
113llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000114 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000116 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000117 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
118 if (!ALE)
119 DLE = cast<ObjCDictionaryLiteral>(E);
120
121 // Compute the type of the array we're initializing.
122 uint64_t NumElements =
123 ALE ? ALE->getNumElements() : DLE->getNumElements();
124 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
125 NumElements);
126 QualType ElementType = Context.getObjCIdType().withConst();
127 QualType ElementArrayType
128 = Context.getConstantArrayType(ElementType, APNumElements,
129 ArrayType::Normal, /*IndexTypeQuals=*/0);
130
131 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000132 Address Objects = CreateMemTemp(ElementArrayType, "objects");
133 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000134 if (DLE)
135 Keys = CreateMemTemp(ElementArrayType, "keys");
136
John McCall770a4c12013-04-04 00:20:38 +0000137 // In ARC, we may need to do extra work to keep all the keys and
138 // values alive until after the call.
139 SmallVector<llvm::Value *, 16> NeededObjects;
140 bool TrackNeededObjects =
141 (getLangOpts().ObjCAutoRefCount &&
142 CGM.getCodeGenOpts().OptimizationLevel != 0);
143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 // Perform the actual initialialization of the array(s).
145 for (uint64_t i = 0; i < NumElements; i++) {
146 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000147 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 const Expr *Rhs = ALE->getElement(i);
John McCall7f416cc2015-09-08 08:05:57 +0000149 LValue LV = MakeAddrLValue(
150 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
151 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000152
153 llvm::Value *value = EmitScalarExpr(Rhs);
154 EmitStoreThroughLValue(RValue::get(value), LV, true);
155 if (TrackNeededObjects) {
156 NeededObjects.push_back(value);
157 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000158 } else {
John McCall770a4c12013-04-04 00:20:38 +0000159 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000160 const Expr *Key = DLE->getKeyValueElement(i).Key;
John McCall7f416cc2015-09-08 08:05:57 +0000161 LValue KeyLV = MakeAddrLValue(
162 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
163 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000164 llvm::Value *keyValue = EmitScalarExpr(Key);
165 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000166
John McCall770a4c12013-04-04 00:20:38 +0000167 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000168 const Expr *Value = DLE->getKeyValueElement(i).Value;
John McCall7f416cc2015-09-08 08:05:57 +0000169 LValue ValueLV = MakeAddrLValue(
170 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
171 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000172 llvm::Value *valueValue = EmitScalarExpr(Value);
173 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
174 if (TrackNeededObjects) {
175 NeededObjects.push_back(keyValue);
176 NeededObjects.push_back(valueValue);
177 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000178 }
179 }
180
181 // Generate the argument list.
182 CallArgList Args;
183 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
184 const ParmVarDecl *argDecl = *PI++;
185 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000186 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000187 if (DLE) {
188 argDecl = *PI++;
189 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000190 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000191 }
192 argDecl = *PI;
193 ArgQT = argDecl->getType().getUnqualifiedType();
194 llvm::Value *Count =
195 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
196 Args.add(RValue::get(Count), ArgQT);
197
198 // Generate a reference to the class pointer, which will be the receiver.
199 Selector Sel = MethodWithObjects->getSelector();
200 QualType ResultType = E->getType();
201 const ObjCObjectPointerType *InterfacePointerType
202 = ResultType->getAsObjCInterfacePointerType();
203 ObjCInterfaceDecl *Class
204 = InterfacePointerType->getObjectType()->getInterface();
205 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000206 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000207
208 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000209 RValue result = Runtime.GenerateMessageSend(
210 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
211 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000212
213 // The above message send needs these objects, but in ARC they are
214 // passed in a buffer that is essentially __unsafe_unretained.
215 // Therefore we must prevent the optimizer from releasing them until
216 // after the call.
217 if (TrackNeededObjects) {
218 EmitARCIntrinsicUse(NeededObjects);
219 }
220
Ted Kremeneke65b0862012-03-06 20:05:56 +0000221 return Builder.CreateBitCast(result.getScalarVal(),
222 ConvertType(E->getType()));
223}
224
225llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000226 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227}
228
229llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
230 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000231 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000232}
233
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000234/// Emit a selector.
235llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
236 // Untyped selector.
237 // Note that this implementation allows for non-constant strings to be passed
238 // as arguments to @selector(). Currently, the only thing preventing this
239 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000240 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000241}
242
Daniel Dunbar66912a12008-08-20 00:28:19 +0000243llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
244 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000245 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000246}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000247
Douglas Gregore83b9562015-07-07 03:57:53 +0000248/// \brief Adjust the type of an Objective-C object that doesn't match up due
249/// to type erasure at various points, e.g., related result types or the use
250/// of parameterized classes.
251static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
252 RValue Result) {
253 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000254 return Result;
John McCall31168b02011-06-15 23:02:42 +0000255
Douglas Gregore83b9562015-07-07 03:57:53 +0000256 // If the converted types are the same, we're done.
257 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
258 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000259 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000260
261 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000262 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000263 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000264}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000265
John McCallcf166702011-07-22 08:53:00 +0000266/// Decide whether to extend the lifetime of the receiver of a
267/// returns-inner-pointer message.
268static bool
269shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
270 switch (message->getReceiverKind()) {
271
272 // For a normal instance message, we should extend unless the
273 // receiver is loaded from a variable with precise lifetime.
274 case ObjCMessageExpr::Instance: {
275 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000276
277 // Look through OVEs.
278 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
279 if (opaque->getSourceExpr())
280 receiver = opaque->getSourceExpr()->IgnoreParens();
281 }
282
John McCallcf166702011-07-22 08:53:00 +0000283 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
284 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
285 receiver = ice->getSubExpr()->IgnoreParens();
286
John McCall6380a282015-09-09 23:37:17 +0000287 // Look through OVEs.
288 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
289 if (opaque->getSourceExpr())
290 receiver = opaque->getSourceExpr()->IgnoreParens();
291 }
292
John McCallcf166702011-07-22 08:53:00 +0000293 // Only __strong variables.
294 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
295 return true;
296
297 // All ivars and fields have precise lifetime.
298 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
299 return false;
300
301 // Otherwise, check for variables.
302 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
303 if (!declRef) return true;
304 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
305 if (!var) return true;
306
307 // All variables have precise lifetime except local variables with
308 // automatic storage duration that aren't specially marked.
309 return (var->hasLocalStorage() &&
310 !var->hasAttr<ObjCPreciseLifetimeAttr>());
311 }
312
313 case ObjCMessageExpr::Class:
314 case ObjCMessageExpr::SuperClass:
315 // It's never necessary for class objects.
316 return false;
317
318 case ObjCMessageExpr::SuperInstance:
319 // We generally assume that 'self' lives throughout a method call.
320 return false;
321 }
322
323 llvm_unreachable("invalid receiver kind");
324}
325
John McCall78a15112010-05-22 01:48:05 +0000326RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
327 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000328 // Only the lookup mechanism and first two arguments of the method
329 // implementation vary between runtimes. We can get the receiver and
330 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000331
John McCall31168b02011-06-15 23:02:42 +0000332 bool isDelegateInit = E->isDelegateInitCall();
333
John McCallcf166702011-07-22 08:53:00 +0000334 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000335
John McCall31168b02011-06-15 23:02:42 +0000336 // We don't retain the receiver in delegate init calls, and this is
337 // safe because the receiver value is always loaded from 'self',
338 // which we zero out. We don't want to Block_copy block receivers,
339 // though.
340 bool retainSelf =
341 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000342 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000343 method &&
344 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000345
Daniel Dunbar8d480592008-08-11 18:12:00 +0000346 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000347 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000348 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000349 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000350 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000351 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000352 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000353 switch (E->getReceiverKind()) {
354 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000355 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000356 if (retainSelf) {
357 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
358 E->getInstanceReceiver());
359 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000360 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000361 } else
362 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000363 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000364
Douglas Gregor9a129192010-04-21 00:45:42 +0000365 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000366 ReceiverType = E->getClassReceiver();
367 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000368 assert(ObjTy && "Invalid Objective-C class message send");
369 OID = ObjTy->getInterface();
370 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000371 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000372 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000373 break;
374 }
375
376 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000377 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000378 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000379 isSuperMessage = true;
380 break;
381
382 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000383 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000384 Receiver = LoadObjCSelf();
385 isSuperMessage = true;
386 isClassMessage = true;
387 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000388 }
389
John McCallcf166702011-07-22 08:53:00 +0000390 if (retainSelf)
391 Receiver = EmitARCRetainNonBlock(Receiver);
392
393 // In ARC, we sometimes want to "extend the lifetime"
394 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
395 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000396 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000397 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
398 shouldExtendReceiverForInnerPointerMessage(E))
399 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
400
Alp Toker314cc812014-01-25 16:55:45 +0000401 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000402
Daniel Dunbarc722b852008-08-30 03:02:31 +0000403 CallArgList Args;
David Blaikief05779e2015-07-21 18:37:18 +0000404 EmitCallArgs(Args, method, E->arguments());
Mike Stump11289f42009-09-09 15:08:12 +0000405
John McCall31168b02011-06-15 23:02:42 +0000406 // For delegate init calls in ARC, do an unsafe store of null into
407 // self. This represents the call taking direct ownership of that
408 // value. We have to do this after emitting the other call
409 // arguments because they might also reference self, but we don't
410 // have to worry about any of them modifying self because that would
411 // be an undefined read and write of an object in unordered
412 // expressions.
413 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000414 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000415 "delegate init calls should only be marked in ARC");
416
417 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000418 Address selfAddr =
419 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000420 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
421 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000422
Douglas Gregor33823722011-06-11 01:09:30 +0000423 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000424 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000425 // super is only valid in an Objective-C method
426 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000427 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000428 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
429 E->getSelector(),
430 OMD->getClassInterface(),
431 isCategoryImpl,
432 Receiver,
433 isClassMessage,
434 Args,
John McCallcf166702011-07-22 08:53:00 +0000435 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000436 } else {
437 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
438 E->getSelector(),
439 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000440 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000441 }
John McCall31168b02011-06-15 23:02:42 +0000442
443 // For delegate init calls in ARC, implicitly store the result of
444 // the call back into self. This takes ownership of the value.
445 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000446 Address selfAddr =
447 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000448 llvm::Value *newSelf = result.getScalarVal();
449
450 // The delegate return type isn't necessarily a matching type; in
451 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000452 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000453 newSelf = Builder.CreateBitCast(newSelf, selfTy);
454
455 Builder.CreateStore(newSelf, selfAddr);
456 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000457
Douglas Gregore83b9562015-07-07 03:57:53 +0000458 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000459}
460
John McCall31168b02011-06-15 23:02:42 +0000461namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000462struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000463 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000464 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000465
466 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000467 const ObjCInterfaceDecl *iface = impl->getClassInterface();
468 if (!iface->getSuperClass()) return;
469
John McCalldffafde2011-07-13 18:26:47 +0000470 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
471
John McCall31168b02011-06-15 23:02:42 +0000472 // Call [super dealloc] if we have a superclass.
473 llvm::Value *self = CGF.LoadObjCSelf();
474
475 CallArgList args;
476 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
477 CGF.getContext().VoidTy,
478 method->getSelector(),
479 iface,
John McCalldffafde2011-07-13 18:26:47 +0000480 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000481 self,
482 /*is class msg*/ false,
483 args,
484 method);
485 }
486};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000487}
John McCall31168b02011-06-15 23:02:42 +0000488
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000489/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
490/// the LLVM function and sets the other context used by
491/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000492void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000493 const ObjCContainerDecl *CD) {
494 SourceLocation StartLoc = OMD->getLocStart();
John McCalla738c252011-03-09 04:27:21 +0000495 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000496 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000497 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000498 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000499
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000500 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000501
John McCalla729c622012-02-17 03:33:10 +0000502 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000503 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000504
John McCalla738c252011-03-09 04:27:21 +0000505 args.push_back(OMD->getSelfDecl());
506 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000507
Benjamin Kramerf9890422015-02-17 16:48:30 +0000508 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000509
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000510 CurGD = OMD;
David Blaikie47d28e02015-01-14 07:10:46 +0000511 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000512
Adrian Prantl42d71b92014-04-10 23:21:53 +0000513 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
514 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000515
516 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000517 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000518 OMD->isInstanceMethod() &&
519 OMD->getSelector().isUnarySelector()) {
520 const IdentifierInfo *ident =
521 OMD->getSelector().getIdentifierInfoForSlot(0);
522 if (ident->isStr("dealloc"))
523 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
524 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000525}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000526
John McCall31168b02011-06-15 23:02:42 +0000527static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
528 LValue lvalue, QualType type);
529
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000530/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000531/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000532void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000533 StartObjCMethod(OMD, OMD->getClassInterface());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000534 PGO.assignRegionCounters(OMD, CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000535 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000536 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000537 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000538 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000539}
540
John McCallb923ece2011-09-12 23:06:44 +0000541/// emitStructGetterCall - Call the runtime function to load a property
542/// into the return value slot.
543static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
544 bool isAtomic, bool hasStrong) {
545 ASTContext &Context = CGF.getContext();
546
John McCall7f416cc2015-09-08 08:05:57 +0000547 Address src =
548 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
549 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000550
551 // objc_copyStruct (ReturnValue, &structIvar,
552 // sizeof (Type of Ivar), isAtomic, false);
553 CallArgList args;
554
John McCall7f416cc2015-09-08 08:05:57 +0000555 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
556 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000557
558 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000559 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000560
561 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
562 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
563 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
564 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
565
566 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000567 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
568 FunctionType::ExtInfo(),
569 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000570 fn, ReturnValueSlot(), args);
571}
572
John McCallf4528ae2011-09-13 03:34:09 +0000573/// Determine whether the given architecture supports unaligned atomic
574/// accesses. They don't have to be fast, just faster than a function
575/// call and a mutex.
576static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000577 // FIXME: Allow unaligned atomic load/store on x86. (It is not
578 // currently supported by the backend.)
579 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000580}
581
582/// Return the maximum size that permits atomic accesses for the given
583/// architecture.
584static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
585 llvm::Triple::ArchType arch) {
586 // ARM has 8-byte atomic accesses, but it's not clear whether we
587 // want to rely on them here.
588
589 // In the default case, just assume that any size up to a pointer is
590 // fine given adequate alignment.
591 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
592}
593
594namespace {
595 class PropertyImplStrategy {
596 public:
597 enum StrategyKind {
598 /// The 'native' strategy is to use the architecture's provided
599 /// reads and writes.
600 Native,
601
602 /// Use objc_setProperty and objc_getProperty.
603 GetSetProperty,
604
605 /// Use objc_setProperty for the setter, but use expression
606 /// evaluation for the getter.
607 SetPropertyAndExpressionGet,
608
609 /// Use objc_copyStruct.
610 CopyStruct,
611
612 /// The 'expression' strategy is to emit normal assignment or
613 /// lvalue-to-rvalue expressions.
614 Expression
615 };
616
617 StrategyKind getKind() const { return StrategyKind(Kind); }
618
619 bool hasStrongMember() const { return HasStrong; }
620 bool isAtomic() const { return IsAtomic; }
621 bool isCopy() const { return IsCopy; }
622
623 CharUnits getIvarSize() const { return IvarSize; }
624 CharUnits getIvarAlignment() const { return IvarAlignment; }
625
626 PropertyImplStrategy(CodeGenModule &CGM,
627 const ObjCPropertyImplDecl *propImpl);
628
629 private:
630 unsigned Kind : 8;
631 unsigned IsAtomic : 1;
632 unsigned IsCopy : 1;
633 unsigned HasStrong : 1;
634
635 CharUnits IvarSize;
636 CharUnits IvarAlignment;
637 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000638}
John McCallf4528ae2011-09-13 03:34:09 +0000639
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000640/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000641PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
642 const ObjCPropertyImplDecl *propImpl) {
643 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000644 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000645
John McCall43192862011-09-13 18:31:23 +0000646 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
647 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000648 HasStrong = false; // doesn't matter here.
649
650 // Evaluate the ivar's size and alignment.
651 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
652 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000653 std::tie(IvarSize, IvarAlignment) =
654 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000655
656 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000657 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000658 if (IsCopy) {
659 Kind = GetSetProperty;
660 return;
661 }
662
John McCall43192862011-09-13 18:31:23 +0000663 // Handle retain.
664 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000665 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000666 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000667 // fallthrough
668
669 // In ARC, if the property is non-atomic, use expression emission,
670 // which translates to objc_storeStrong. This isn't required, but
671 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000672 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000673 // Using standard expression emission for the setter is only
674 // acceptable if the ivar is __strong, which won't be true if
675 // the property is annotated with __attribute__((NSObject)).
676 // TODO: falling all the way back to objc_setProperty here is
677 // just laziness, though; we could still use objc_storeStrong
678 // if we hacked it right.
679 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
680 Kind = Expression;
681 else
682 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000683 return;
684
685 // Otherwise, we need to at least use setProperty. However, if
686 // the property isn't atomic, we can use normal expression
687 // emission for the getter.
688 } else if (!IsAtomic) {
689 Kind = SetPropertyAndExpressionGet;
690 return;
691
692 // Otherwise, we have to use both setProperty and getProperty.
693 } else {
694 Kind = GetSetProperty;
695 return;
696 }
697 }
698
699 // If we're not atomic, just use expression accesses.
700 if (!IsAtomic) {
701 Kind = Expression;
702 return;
703 }
704
John McCall0e5c0862011-09-13 05:36:29 +0000705 // Properties on bitfield ivars need to be emitted using expression
706 // accesses even if they're nominally atomic.
707 if (ivar->isBitField()) {
708 Kind = Expression;
709 return;
710 }
711
John McCallf4528ae2011-09-13 03:34:09 +0000712 // GC-qualified or ARC-qualified ivars need to be emitted as
713 // expressions. This actually works out to being atomic anyway,
714 // except for ARC __strong, but that should trigger the above code.
715 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000716 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000717 CGM.getContext().getObjCGCAttrKind(ivarType))) {
718 Kind = Expression;
719 return;
720 }
721
722 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000723 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000724 if (const RecordType *recordType = ivarType->getAs<RecordType>())
725 HasStrong = recordType->getDecl()->hasObjectMember();
726
727 // We can never access structs with object members with a native
728 // access, because we need to use write barriers. This is what
729 // objc_copyStruct is for.
730 if (HasStrong) {
731 Kind = CopyStruct;
732 return;
733 }
734
735 // Otherwise, this is target-dependent and based on the size and
736 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000737
738 // If the size of the ivar is not a power of two, give up. We don't
739 // want to get into the business of doing compare-and-swaps.
740 if (!IvarSize.isPowerOfTwo()) {
741 Kind = CopyStruct;
742 return;
743 }
744
John McCallf4528ae2011-09-13 03:34:09 +0000745 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000746 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000747
748 // Most architectures require memory to fit within a single cache
749 // line, so the alignment has to be at least the size of the access.
750 // Otherwise we have to grab a lock.
751 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
752 Kind = CopyStruct;
753 return;
754 }
755
756 // If the ivar's size exceeds the architecture's maximum atomic
757 // access size, we have to use CopyStruct.
758 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
759 Kind = CopyStruct;
760 return;
761 }
762
763 // Otherwise, we can use native loads and stores.
764 Kind = Native;
765}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000766
James Dennettbe302452012-06-15 22:10:14 +0000767/// \brief Generate an Objective-C property getter function.
768///
769/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000770/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000771void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
772 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000773 llvm::Constant *AtomicHelperFn =
774 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000775 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
776 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
777 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000778 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000779
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000780 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000781
782 FinishFunction();
783}
784
John McCallbdd81852011-09-13 06:00:03 +0000785static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
786 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000787 if (!getter) return true;
788
789 // Sema only makes only of these when the ivar has a C++ class type,
790 // so the form is pretty constrained.
791
John McCallbdd81852011-09-13 06:00:03 +0000792 // If the property has a reference type, we might just be binding a
793 // reference, in which case the result will be a gl-value. We should
794 // treat this as a non-trivial operation.
795 if (getter->isGLValue())
796 return false;
797
John McCallf4528ae2011-09-13 03:34:09 +0000798 // If we selected a trivial copy-constructor, we're okay.
799 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
800 return (construct->getConstructor()->isTrivial());
801
802 // The constructor might require cleanups (in which case it's never
803 // trivial).
804 assert(isa<ExprWithCleanups>(getter));
805 return false;
806}
807
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000808/// emitCPPObjectAtomicGetterCall - Call the runtime function to
809/// copy the ivar into the resturn slot.
810static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
811 llvm::Value *returnAddr,
812 ObjCIvarDecl *ivar,
813 llvm::Constant *AtomicHelperFn) {
814 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
815 // AtomicHelperFn);
816 CallArgList args;
817
818 // The 1st argument is the return Slot.
819 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
820
821 // The 2nd argument is the address of the ivar.
822 llvm::Value *ivarAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000823 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
824 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000825 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
826 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
827
828 // Third argument is the helper function.
829 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
830
831 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000832 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000833 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
834 args,
835 FunctionType::ExtInfo(),
836 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000837 copyCppAtomicObjectFn, ReturnValueSlot(), args);
838}
839
John McCallf4528ae2011-09-13 03:34:09 +0000840void
841CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000842 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000843 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000844 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000845 // If there's a non-trivial 'get' expression, we just have to emit that.
846 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000847 if (!AtomicHelperFn) {
848 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000849 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000850 EmitReturnStmt(ret);
851 }
852 else {
853 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f416cc2015-09-08 08:05:57 +0000854 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000855 ivar, AtomicHelperFn);
856 }
John McCallf4528ae2011-09-13 03:34:09 +0000857 return;
858 }
859
860 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
861 QualType propType = prop->getType();
862 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
863
864 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
865
866 // Pick an implementation strategy.
867 PropertyImplStrategy strategy(CGM, propImpl);
868 switch (strategy.getKind()) {
869 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000870 // We don't need to do anything for a zero-size struct.
871 if (strategy.getIvarSize().isZero())
872 return;
873
John McCallf4528ae2011-09-13 03:34:09 +0000874 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
875
876 // Currently, all atomic accesses have to be through integer
877 // types, so there's no point in trying to pick a prettier type.
878 llvm::Type *bitcastType =
879 llvm::Type::getIntNTy(getLLVMContext(),
880 getContext().toBits(strategy.getIvarSize()));
881 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
882
883 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +0000884 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +0000885 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
886 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
John McCallf4528ae2011-09-13 03:34:09 +0000887 load->setAtomic(llvm::Unordered);
888
889 // Store that value into the return address. Doing this with a
890 // bitcast is likely to produce some pretty ugly IR, but it's not
891 // the *most* terrible thing in the world.
892 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
893
894 // Make sure we don't do an autorelease.
895 AutoreleaseResult = false;
896 return;
897 }
898
899 case PropertyImplStrategy::GetSetProperty: {
900 llvm::Value *getPropertyFn =
901 CGM.getObjCRuntime().GetPropertyGetFunction();
902 if (!getPropertyFn) {
903 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000904 return;
905 }
906
907 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
908 // FIXME: Can't this be simpler? This might even be worse than the
909 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000910 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +0000911 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +0000912 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
913 llvm::Value *ivarOffset =
914 EmitIvarOffset(classImpl->getClassInterface(), ivar);
915
916 CallArgList args;
917 args.add(RValue::get(self), getContext().getObjCIdType());
918 args.add(RValue::get(cmd), getContext().getObjCSelType());
919 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000920 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
921 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000922
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000923 // FIXME: We shouldn't need to get the function info here, the
924 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000925 llvm::Instruction *CallInstruction;
John McCall8dda7b22012-07-07 06:41:13 +0000926 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
927 FunctionType::ExtInfo(),
928 RequiredArgs::All),
Craig Topper8a13c412014-05-21 05:09:00 +0000929 getPropertyFn, ReturnValueSlot(), args, nullptr,
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000930 &CallInstruction);
931 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
932 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000933
Daniel Dunbara08dff12008-09-24 04:04:31 +0000934 // We need to fix the type here. Ivars with copy & retain are
935 // always objects so we don't need to worry about complex or
936 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000937 RV = RValue::get(Builder.CreateBitCast(
938 RV.getScalarVal(),
939 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000940
941 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000942
943 // objc_getProperty does an autorelease, so we should suppress ours.
944 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000945
John McCallf4528ae2011-09-13 03:34:09 +0000946 return;
947 }
948
949 case PropertyImplStrategy::CopyStruct:
950 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
951 strategy.hasStrongMember());
952 return;
953
954 case PropertyImplStrategy::Expression:
955 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
956 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
957
958 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000959 switch (getEvaluationKind(ivarType)) {
960 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000961 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +0000962 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +0000963 /*init*/ true);
964 return;
965 }
966 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000967 // The return value slot is guaranteed to not be aliased, but
968 // that's not necessarily the same as "on the stack", so
969 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000970 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000971 return;
972 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000973 llvm::Value *value;
974 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000975 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +0000976 } else {
977 // We want to load and autoreleaseReturnValue ARC __weak ivars.
978 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000979 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000980
981 // Otherwise we want to do a simple load, suppressing the
982 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000983 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000984 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000985 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000986 }
John McCall31168b02011-06-15 23:02:42 +0000987
John McCall24fada12011-07-22 05:23:13 +0000988 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +0000989 value = Builder.CreateBitCast(
990 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +0000991 }
992
993 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000994 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000995 }
John McCall47fb9502013-03-07 21:37:08 +0000996 }
997 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000998 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000999
John McCallf4528ae2011-09-13 03:34:09 +00001000 }
1001 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001002}
1003
John McCallb923ece2011-09-12 23:06:44 +00001004/// emitStructSetterCall - Call the runtime function to store the value
1005/// from the first formal parameter into the given ivar.
1006static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1007 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001008 // objc_copyStruct (&structIvar, &Arg,
1009 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001010 CallArgList args;
1011
1012 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001013 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1014 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001015 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001016 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1017 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001018
1019 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001020 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001021 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +00001022 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001023 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001024 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1025 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001026
1027 // The third argument is the sizeof the type.
1028 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001029 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1030 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001031
John McCallb923ece2011-09-12 23:06:44 +00001032 // The fourth argument is the 'isAtomic' flag.
1033 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001034
John McCallb923ece2011-09-12 23:06:44 +00001035 // The fifth argument is the 'hasStrong' flag.
1036 // FIXME: should this really always be false?
1037 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1038
1039 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001040 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1041 args,
1042 FunctionType::ExtInfo(),
1043 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001044 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001045}
1046
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001047/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1048/// the value from the first formal parameter into the given ivar, using
1049/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1050static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1051 ObjCMethodDecl *OMD,
1052 ObjCIvarDecl *ivar,
1053 llvm::Constant *AtomicHelperFn) {
1054 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1055 // AtomicHelperFn);
1056 CallArgList args;
1057
1058 // The first argument is the address of the ivar.
1059 llvm::Value *ivarAddr =
1060 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001061 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001062 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1063 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1064
1065 // The second argument is the address of the parameter variable.
1066 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001067 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001068 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001069 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001070 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1071 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1072
1073 // Third argument is the helper function.
1074 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1075
1076 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001077 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001078 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1079 args,
1080 FunctionType::ExtInfo(),
1081 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001082 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001083}
1084
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001085
John McCallf4528ae2011-09-13 03:34:09 +00001086static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1087 Expr *setter = PID->getSetterCXXAssignment();
1088 if (!setter) return true;
1089
1090 // Sema only makes only of these when the ivar has a C++ class type,
1091 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001092
1093 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001094 // This also implies that there's nothing non-trivial going on with
1095 // the arguments, because operator= can only be trivial if it's a
1096 // synthesized assignment operator and therefore both parameters are
1097 // references.
1098 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001099 if (const FunctionDecl *callee
1100 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1101 if (callee->isTrivial())
1102 return true;
1103 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001104 }
John McCall7f16c422011-09-10 09:17:20 +00001105
John McCallf4528ae2011-09-13 03:34:09 +00001106 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001107 return false;
1108}
1109
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001110static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001111 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001112 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001113 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001114}
1115
John McCall7f16c422011-09-10 09:17:20 +00001116void
1117CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001118 const ObjCPropertyImplDecl *propImpl,
1119 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001120 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001121 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001122 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001123
1124 // Just use the setter expression if Sema gave us one and it's
1125 // non-trivial.
1126 if (!hasTrivialSetExpr(propImpl)) {
1127 if (!AtomicHelperFn)
1128 // If non-atomic, assignment is called directly.
1129 EmitStmt(propImpl->getSetterCXXAssignment());
1130 else
1131 // If atomic, assignment is called via a locking api.
1132 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1133 AtomicHelperFn);
1134 return;
1135 }
John McCall7f16c422011-09-10 09:17:20 +00001136
John McCallf4528ae2011-09-13 03:34:09 +00001137 PropertyImplStrategy strategy(CGM, propImpl);
1138 switch (strategy.getKind()) {
1139 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001140 // We don't need to do anything for a zero-size struct.
1141 if (strategy.getIvarSize().isZero())
1142 return;
1143
John McCall7f416cc2015-09-08 08:05:57 +00001144 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001145
John McCallf4528ae2011-09-13 03:34:09 +00001146 LValue ivarLValue =
1147 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001148 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001149
John McCallf4528ae2011-09-13 03:34:09 +00001150 // Currently, all atomic accesses have to be through integer
1151 // types, so there's no point in trying to pick a prettier type.
1152 llvm::Type *bitcastType =
1153 llvm::Type::getIntNTy(getLLVMContext(),
1154 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001155
1156 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001157 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1158 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001159
1160 // This bitcast load is likely to cause some nasty IR.
1161 llvm::Value *load = Builder.CreateLoad(argAddr);
1162
1163 // Perform an atomic store. There are no memory ordering requirements.
1164 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
John McCallf4528ae2011-09-13 03:34:09 +00001165 store->setAtomic(llvm::Unordered);
1166 return;
1167 }
1168
1169 case PropertyImplStrategy::GetSetProperty:
1170 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001171
1172 llvm::Value *setOptimizedPropertyFn = nullptr;
1173 llvm::Value *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001174 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001175 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001176 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001177 CGM.getObjCRuntime()
1178 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1179 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001180 if (!setOptimizedPropertyFn) {
1181 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1182 return;
1183 }
John McCall7f16c422011-09-10 09:17:20 +00001184 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001185 else {
1186 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1187 if (!setPropertyFn) {
1188 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1189 return;
1190 }
1191 }
1192
John McCall7f16c422011-09-10 09:17:20 +00001193 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1194 // <is-atomic>, <is-copy>).
1195 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001196 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001197 llvm::Value *self =
1198 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1199 llvm::Value *ivarOffset =
1200 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001201 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1202 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1203 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001204
1205 CallArgList args;
1206 args.add(RValue::get(self), getContext().getObjCIdType());
1207 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001208 if (setOptimizedPropertyFn) {
1209 args.add(RValue::get(arg), getContext().getObjCIdType());
1210 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001211 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1212 FunctionType::ExtInfo(),
1213 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001214 setOptimizedPropertyFn, ReturnValueSlot(), args);
1215 } else {
1216 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1217 args.add(RValue::get(arg), getContext().getObjCIdType());
1218 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1219 getContext().BoolTy);
1220 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1221 getContext().BoolTy);
1222 // FIXME: We shouldn't need to get the function info here, the runtime
1223 // already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001224 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1225 FunctionType::ExtInfo(),
1226 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001227 setPropertyFn, ReturnValueSlot(), args);
1228 }
1229
John McCall7f16c422011-09-10 09:17:20 +00001230 return;
1231 }
1232
John McCallf4528ae2011-09-13 03:34:09 +00001233 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001234 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001235 return;
John McCallf4528ae2011-09-13 03:34:09 +00001236
1237 case PropertyImplStrategy::Expression:
1238 break;
John McCall7f16c422011-09-10 09:17:20 +00001239 }
1240
1241 // Otherwise, fake up some ASTs and emit a normal assignment.
1242 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001243 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1244 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001245 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1246 selfDecl->getType(), CK_LValueToRValue, &self,
1247 VK_RValue);
1248 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001249 SourceLocation(), SourceLocation(),
1250 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001251
1252 ParmVarDecl *argDecl = *setterMethod->param_begin();
1253 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001254 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001255 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1256 argType.getUnqualifiedType(), CK_LValueToRValue,
1257 &arg, VK_RValue);
1258
1259 // The property type can differ from the ivar type in some situations with
1260 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1261 // The following absurdity is just to ensure well-formed IR.
1262 CastKind argCK = CK_NoOp;
1263 if (ivarRef.getType()->isObjCObjectPointerType()) {
1264 if (argLoad.getType()->isObjCObjectPointerType())
1265 argCK = CK_BitCast;
1266 else if (argLoad.getType()->isBlockPointerType())
1267 argCK = CK_BlockPointerToObjCPointerCast;
1268 else
1269 argCK = CK_CPointerToObjCPointerCast;
1270 } else if (ivarRef.getType()->isBlockPointerType()) {
1271 if (argLoad.getType()->isBlockPointerType())
1272 argCK = CK_BitCast;
1273 else
1274 argCK = CK_AnyPointerToBlockPointerCast;
1275 } else if (ivarRef.getType()->isPointerType()) {
1276 argCK = CK_BitCast;
1277 }
1278 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1279 ivarRef.getType(), argCK, &argLoad,
1280 VK_RValue);
1281 Expr *finalArg = &argLoad;
1282 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1283 argLoad.getType()))
1284 finalArg = &argCast;
1285
1286
1287 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1288 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001289 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001290 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001291}
1292
James Dennettbe302452012-06-15 22:10:14 +00001293/// \brief Generate an Objective-C property setter function.
1294///
1295/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001296/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001297void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1298 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001299 llvm::Constant *AtomicHelperFn =
1300 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001301 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1302 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1303 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001304 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001305
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001306 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001307
1308 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001309}
1310
John McCall6a4fa522011-03-22 07:05:39 +00001311namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001312 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001313 private:
1314 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001315 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001316 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001317 bool useEHCleanupForArray;
1318 public:
1319 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1320 CodeGenFunction::Destroyer *destroyer,
1321 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001322 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001323 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001324
Craig Topper4f12f102014-03-12 06:41:41 +00001325 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001326 LValue lvalue
1327 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1328 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001329 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001330 }
1331 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001332}
John McCall6a4fa522011-03-22 07:05:39 +00001333
John McCall4bd0fb12011-07-12 16:41:08 +00001334/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1335static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001336 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001337 QualType type) {
1338 llvm::Value *null = getNullForVariable(addr);
1339 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1340}
John McCall31168b02011-06-15 23:02:42 +00001341
John McCall6a4fa522011-03-22 07:05:39 +00001342static void emitCXXDestructMethod(CodeGenFunction &CGF,
1343 ObjCImplementationDecl *impl) {
1344 CodeGenFunction::RunCleanupsScope scope(CGF);
1345
1346 llvm::Value *self = CGF.LoadObjCSelf();
1347
Jordy Rosea91768e2011-07-22 02:08:32 +00001348 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1349 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001350 ivar; ivar = ivar->getNextIvar()) {
1351 QualType type = ivar->getType();
1352
John McCall6a4fa522011-03-22 07:05:39 +00001353 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001354 QualType::DestructionKind dtorKind = type.isDestructedType();
1355 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001356
Craig Topper8a13c412014-05-21 05:09:00 +00001357 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001358
John McCall4bd0fb12011-07-12 16:41:08 +00001359 // Use a call to objc_storeStrong to destroy strong ivars, for the
1360 // general benefit of the tools.
1361 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001362 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001363
John McCall4bd0fb12011-07-12 16:41:08 +00001364 // Otherwise use the default for the destruction kind.
1365 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001366 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001367 }
John McCall4bd0fb12011-07-12 16:41:08 +00001368
1369 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1370
1371 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1372 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001373 }
1374
1375 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1376}
1377
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001378void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1379 ObjCMethodDecl *MD,
1380 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001381 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001382 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001383
1384 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001385 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001386 // Suppress the final autorelease in ARC.
1387 AutoreleaseResult = false;
1388
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001389 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001390 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001391 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001392 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1393 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001394 EmitAggExpr(IvarInit->getInit(),
1395 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001396 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001397 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001398 }
1399 // constructor returns 'self'.
1400 CodeGenTypes &Types = CGM.getTypes();
1401 QualType IdTy(CGM.getContext().getObjCIdType());
1402 llvm::Value *SelfAsId =
1403 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1404 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001405
1406 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001407 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001408 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001409 }
1410 FinishFunction();
1411}
1412
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001413bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1414 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1415 it++; it++;
1416 const ABIArgInfo &AI = it->info;
1417 // FIXME. Is this sufficient check?
1418 return (AI.getKind() == ABIArgInfo::Indirect);
1419}
1420
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001421bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001422 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001423 return false;
1424 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1425 return FDTTy->getDecl()->hasObjectMember();
1426 return false;
1427}
1428
Daniel Dunbara08dff12008-09-24 04:04:31 +00001429llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001430 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1431 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1432 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001433 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001434}
1435
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001436QualType CodeGenFunction::TypeOfSelfObject() {
1437 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1438 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001439 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1440 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001441 return PTy->getPointeeType();
1442}
1443
Chris Lattnerd4808922009-03-22 21:03:39 +00001444void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001445 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001446 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001447
Daniel Dunbara08dff12008-09-24 04:04:31 +00001448 if (!EnumerationMutationFn) {
1449 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1450 return;
1451 }
1452
Devang Pateld2d66652011-01-19 01:36:36 +00001453 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001454 if (DI)
1455 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001456
Devang Patel297207f2011-06-13 23:15:32 +00001457 // The local variable comes into scope immediately.
1458 AutoVarEmission variable = AutoVarEmission::invalid();
1459 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1460 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1461
John McCall1c926b72011-01-07 01:49:06 +00001462 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001463
Anders Carlsson75658592008-08-31 02:33:12 +00001464 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001465 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001466 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001467 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Anders Carlsson75658592008-08-31 02:33:12 +00001469 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001470 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001471
John McCall1c926b72011-01-07 01:49:06 +00001472 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001473 IdentifierInfo *II[] = {
1474 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1475 &CGM.getContext().Idents.get("objects"),
1476 &CGM.getContext().Idents.get("count")
1477 };
1478 Selector FastEnumSel =
1479 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001480
1481 QualType ItemsTy =
1482 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001483 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001484 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001485 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001486
John McCall53848232011-07-27 01:07:15 +00001487 // Emit the collection pointer. In ARC, we do a retain.
1488 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001489 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001490 Collection = EmitARCRetainScalarExpr(S.getCollection());
1491
1492 // Enter a cleanup to do the release.
1493 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1494 } else {
1495 Collection = EmitScalarExpr(S.getCollection());
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
John McCall91e82dd2011-08-05 00:14:38 +00001498 // The 'continue' label needs to appear within the cleanup for the
1499 // collection object.
1500 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1501
John McCall1c926b72011-01-07 01:49:06 +00001502 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001503 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001504
1505 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001506 Args.add(RValue::get(StatePtr.getPointer()),
1507 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001508
John McCall1c926b72011-01-07 01:49:06 +00001509 // The second argument is a temporary array with space for NumItems
1510 // pointers. We'll actually be loading elements from the array
1511 // pointer written into the control state; this buffer is so that
1512 // collections that *aren't* backed by arrays can still queue up
1513 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001514 Args.add(RValue::get(ItemsPtr.getPointer()),
1515 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001516
John McCall1c926b72011-01-07 01:49:06 +00001517 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001518 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001519 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001520 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001521
John McCall1c926b72011-01-07 01:49:06 +00001522 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001523 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001524 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001525 getContext().UnsignedLongTy,
1526 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001527 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001528
John McCall1c926b72011-01-07 01:49:06 +00001529 // The initial number of objects that were returned in the buffer.
1530 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001531
John McCall1c926b72011-01-07 01:49:06 +00001532 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1533 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001534
John McCall1c926b72011-01-07 01:49:06 +00001535 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001536
John McCall1c926b72011-01-07 01:49:06 +00001537 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001538 // empty; skip all this. Set the branch weight assuming this has the same
1539 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001540 uint64_t EntryCount = getCurrentProfileCount();
1541 Builder.CreateCondBr(
1542 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1543 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001544 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001545
John McCall1c926b72011-01-07 01:49:06 +00001546 // Otherwise, initialize the loop.
1547 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCall1c926b72011-01-07 01:49:06 +00001549 // Save the initial mutations value. This is the value at an
1550 // address that was written into the state object by
1551 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001552 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1553 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1554 llvm::Value *StateMutationsPtr
1555 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001556
John McCall1c926b72011-01-07 01:49:06 +00001557 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001558 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1559 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCall1c926b72011-01-07 01:49:06 +00001561 // Start looping. This is the point we return to whenever we have a
1562 // fresh, non-empty batch of objects.
1563 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1564 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001565
John McCall1c926b72011-01-07 01:49:06 +00001566 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001567 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001568 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001569
John McCall1c926b72011-01-07 01:49:06 +00001570 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001571 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001572 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Justin Bogner66242d62015-04-23 23:06:47 +00001574 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001575
John McCall1c926b72011-01-07 01:49:06 +00001576 // Check whether the mutations value has changed from where it was
1577 // at start. StateMutationsPtr should actually be invariant between
1578 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001579 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001580 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001581 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1582 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001583
John McCall1c926b72011-01-07 01:49:06 +00001584 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001585 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall1c926b72011-01-07 01:49:06 +00001587 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1588 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001589
John McCall1c926b72011-01-07 01:49:06 +00001590 // If so, call the enumeration-mutation function.
1591 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001592 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001593 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001594 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001595 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001596 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001597 // FIXME: We shouldn't need to get the function info here, the runtime already
1598 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001599 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1600 FunctionType::ExtInfo(),
1601 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001602 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001603
John McCall1c926b72011-01-07 01:49:06 +00001604 // Otherwise, or if the mutation function returns, just continue.
1605 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001606
John McCall1c926b72011-01-07 01:49:06 +00001607 // Initialize the element variable.
1608 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001609 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001610 LValue elementLValue;
1611 QualType elementType;
1612 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001613 // Initialize the variable, in case it's a __block variable or something.
1614 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001615
John McCall9e2e22f2011-02-22 07:16:58 +00001616 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001617 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001618 VK_LValue, SourceLocation());
1619 elementLValue = EmitLValue(&tempDRE);
1620 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001621 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001622
1623 if (D->isARCPseudoStrong())
1624 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001625 } else {
1626 elementLValue = LValue(); // suppress warning
1627 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001628 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001629 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001630 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001631
1632 // Fetch the buffer out of the enumeration state.
1633 // TODO: this pointer should actually be invariant between
1634 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001635 Address StateItemsPtr = Builder.CreateStructGEP(
1636 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001637 llvm::Value *EnumStateItems =
1638 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001639
John McCall1c926b72011-01-07 01:49:06 +00001640 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001641 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001642 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001643 llvm::Value *CurrentItem =
1644 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001645
John McCall1c926b72011-01-07 01:49:06 +00001646 // Cast that value to the right type.
1647 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1648 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001649
John McCall1c926b72011-01-07 01:49:06 +00001650 // Make sure we have an l-value. Yes, this gets evaluated every
1651 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001652 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001653 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001654 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001655 } else {
1656 EmitScalarInit(CurrentItem, elementLValue);
1657 }
Mike Stump11289f42009-09-09 15:08:12 +00001658
John McCall9e2e22f2011-02-22 07:16:58 +00001659 // If we do have an element variable, this assignment is the end of
1660 // its initialization.
1661 if (elementIsVariable)
1662 EmitAutoVarCleanups(variable);
1663
John McCall1c926b72011-01-07 01:49:06 +00001664 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001665 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001666 {
1667 RunCleanupsScope Scope(*this);
1668 EmitStmt(S.getBody());
1669 }
Anders Carlsson75658592008-08-31 02:33:12 +00001670 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001671
John McCall1c926b72011-01-07 01:49:06 +00001672 // Destroy the element variable now.
1673 elementVariableScope.ForceCleanup();
1674
1675 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001676 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001677
John McCall1c926b72011-01-07 01:49:06 +00001678 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001679
John McCall1c926b72011-01-07 01:49:06 +00001680 // First we check in the local buffer.
1681 llvm::Value *indexPlusOne
1682 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001683
John McCall1c926b72011-01-07 01:49:06 +00001684 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001685 // Set the branch weights based on the simplifying assumption that this is
1686 // like a while-loop, i.e., ignoring that the false branch fetches more
1687 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001688 Builder.CreateCondBr(
1689 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001690 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001691
1692 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1693 count->addIncoming(count, AfterBody.getBlock());
1694
1695 // Otherwise, we have to fetch more elements.
1696 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001697
1698 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001699 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001700 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001701 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001702 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001703
John McCall1c926b72011-01-07 01:49:06 +00001704 // If we got a zero count, we're done.
1705 llvm::Value *refetchCount = CountRV.getScalarVal();
1706
1707 // (note that the message send might split FetchMoreBB)
1708 index->addIncoming(zero, Builder.GetInsertBlock());
1709 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1710
1711 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1712 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Anders Carlsson75658592008-08-31 02:33:12 +00001714 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001715 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001716
John McCall9e2e22f2011-02-22 07:16:58 +00001717 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001718 // If the element was not a declaration, set it to be null.
1719
John McCall1c926b72011-01-07 01:49:06 +00001720 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1721 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001722 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001723 }
1724
Eric Christopher7cdf9482011-10-13 21:45:18 +00001725 if (DI)
1726 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001727
John McCall53848232011-07-27 01:07:15 +00001728 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001729 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001730 PopCleanupBlock();
1731
John McCallad5d61e2010-07-23 21:56:41 +00001732 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001733}
1734
Mike Stump11289f42009-09-09 15:08:12 +00001735void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001736 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001737}
1738
Mike Stump11289f42009-09-09 15:08:12 +00001739void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001740 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1741}
1742
Chris Lattnere132e242008-11-15 21:26:17 +00001743void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001744 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001745 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001746}
1747
John McCall2d637d22011-09-10 06:18:15 +00001748/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001749/// primitive retain.
1750llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1751 llvm::Value *value) {
1752 return EmitARCRetain(type, value);
1753}
1754
1755namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001756 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001757 CallObjCRelease(llvm::Value *object) : object(object) {}
1758 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001759
Craig Topper4f12f102014-03-12 06:41:41 +00001760 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001761 // Releases at the end of the full-expression are imprecise.
1762 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001763 }
1764 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001765}
John McCall31168b02011-06-15 23:02:42 +00001766
John McCall2d637d22011-09-10 06:18:15 +00001767/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001768/// release at the end of the full-expression.
1769llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1770 llvm::Value *object) {
1771 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001772 // conditional.
1773 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001774 return object;
1775}
1776
1777llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1778 llvm::Value *value) {
1779 return EmitARCRetainAutorelease(type, value);
1780}
1781
John McCalleff18842013-03-23 02:35:54 +00001782/// Given a number of pointers, inform the optimizer that they're
1783/// being intrinsically used up until this point in the program.
1784void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1785 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1786 if (!fn) {
1787 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001788 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001789 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1790 }
1791
1792 // This isn't really a "runtime" function, but as an intrinsic it
1793 // doesn't really matter as long as we align things up.
1794 EmitNounwindRuntimeCall(fn, values);
1795}
1796
John McCall31168b02011-06-15 23:02:42 +00001797
1798static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001799 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001800 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001801 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1802
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001803 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001804 // If the target runtime doesn't naturally support ARC, emit weak
1805 // references to the runtime support library. We don't really
1806 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001807 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001808 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001809 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1810 // If we have Native ARC, set nonlazybind attribute for these APIs for
1811 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001812 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001813 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001814 }
John McCall31168b02011-06-15 23:02:42 +00001815
1816 return fn;
1817}
1818
1819/// Perform an operation having the signature
1820/// i8* (i8*)
1821/// where a null input causes a no-op and returns null.
1822static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1823 llvm::Value *value,
1824 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001825 StringRef fnName,
1826 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001827 if (isa<llvm::ConstantPointerNull>(value)) return value;
1828
1829 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001830 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001831 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001832 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1833 }
1834
1835 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001836 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001837 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1838
1839 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001840 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001841 if (isTailCall)
1842 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001843
1844 // Cast the result back to the original type.
1845 return CGF.Builder.CreateBitCast(call, origType);
1846}
1847
1848/// Perform an operation having the following signature:
1849/// i8* (i8**)
1850static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001851 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001852 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001853 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001854 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001855 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001856 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001857 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1858 }
1859
1860 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001861 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001862 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1863
1864 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001865 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001866
1867 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001868 if (origType != CGF.Int8PtrTy)
1869 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001870
1871 return result;
1872}
1873
1874/// Perform an operation having the following signature:
1875/// i8* (i8**, i8*)
1876static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001877 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001878 llvm::Value *value,
1879 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001880 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001881 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001882 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001883
1884 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001885 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001886
Chris Lattner2192fe52011-07-18 04:24:23 +00001887 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001888 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1889 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1890 }
1891
Chris Lattner2192fe52011-07-18 04:24:23 +00001892 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001893
John McCall882987f2013-02-28 19:01:20 +00001894 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001895 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001896 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1897 };
1898 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001899
Craig Topper8a13c412014-05-21 05:09:00 +00001900 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001901
1902 return CGF.Builder.CreateBitCast(result, origType);
1903}
1904
1905/// Perform an operation having the following signature:
1906/// void (i8**, i8**)
1907static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001908 Address dst,
1909 Address src,
John McCall31168b02011-06-15 23:02:42 +00001910 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001911 StringRef fnName) {
John McCall7f416cc2015-09-08 08:05:57 +00001912 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00001913
1914 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001915 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1916
Chris Lattner2192fe52011-07-18 04:24:23 +00001917 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001918 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1919 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1920 }
1921
John McCall882987f2013-02-28 19:01:20 +00001922 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001923 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1924 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00001925 };
1926 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001927}
1928
1929/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001930/// call i8* \@objc_retain(i8* %value)
1931/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001932llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1933 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001934 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001935 else
1936 return EmitARCRetainNonBlock(value);
1937}
1938
1939/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001940/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001941llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1942 return emitARCValueOperation(*this, value,
1943 CGM.getARCEntrypoints().objc_retain,
1944 "objc_retain");
1945}
1946
1947/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001948/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001949///
1950/// \param mandatory - If false, emit the call with metadata
1951/// indicating that it's okay for the optimizer to eliminate this call
1952/// if it can prove that the block never escapes except down the stack.
1953llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1954 bool mandatory) {
1955 llvm::Value *result
1956 = emitARCValueOperation(*this, value,
1957 CGM.getARCEntrypoints().objc_retainBlock,
1958 "objc_retainBlock");
1959
1960 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1961 // tell the optimizer that it doesn't need to do this copy if the
1962 // block doesn't escape, where being passed as an argument doesn't
1963 // count as escaping.
1964 if (!mandatory && isa<llvm::Instruction>(result)) {
1965 llvm::CallInst *call
1966 = cast<llvm::CallInst>(result->stripPointerCasts());
1967 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1968
John McCallff613032011-10-04 06:23:45 +00001969 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001970 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00001971 }
1972
1973 return result;
John McCall31168b02011-06-15 23:02:42 +00001974}
1975
1976/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001977/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001978///
1979/// Yes, this function name is one character away from a different
1980/// call with completely different semantics.
1981llvm::Value *
1982CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1983 // Fetch the void(void) inline asm which marks that we're going to
1984 // retain the autoreleased return value.
1985 llvm::InlineAsm *&marker
1986 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1987 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001988 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001989 = CGM.getTargetCodeGenInfo()
1990 .getARCRetainAutoreleasedReturnValueMarker();
1991
1992 // If we have an empty assembly string, there's nothing to do.
1993 if (assembly.empty()) {
1994
1995 // Otherwise, at -O0, build an inline asm that we're going to call
1996 // in a moment.
1997 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1998 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001999 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00002000
2001 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2002
2003 // If we're at -O1 and above, we don't want to litter the code
2004 // with this marker yet, so leave a breadcrumb for the ARC
2005 // optimizer to pick up.
2006 } else {
2007 llvm::NamedMDNode *metadata =
2008 CGM.getModule().getOrInsertNamedMetadata(
2009 "clang.arc.retainAutoreleasedReturnValueMarker");
2010 assert(metadata->getNumOperands() <= 1);
2011 if (metadata->getNumOperands() == 0) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002012 metadata->addOperand(llvm::MDNode::get(
2013 getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
John McCall31168b02011-06-15 23:02:42 +00002014 }
2015 }
2016 }
2017
2018 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002019 if (marker)
David Blaikie4ba525b2015-07-14 17:27:39 +00002020 Builder.CreateCall(marker);
John McCall31168b02011-06-15 23:02:42 +00002021
2022 return emitARCValueOperation(*this, value,
2023 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
2024 "objc_retainAutoreleasedReturnValue");
2025}
2026
2027/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002028/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002029void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2030 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002031 if (isa<llvm::ConstantPointerNull>(value)) return;
2032
2033 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2034 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002035 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002036 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002037 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2038 }
2039
2040 // Cast the argument to 'id'.
2041 value = Builder.CreateBitCast(value, Int8PtrTy);
2042
2043 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002044 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002045
John McCallcdda29c2013-03-13 03:10:54 +00002046 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002047 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002048 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002049 }
2050}
2051
John McCalle68b8f42012-10-17 02:28:37 +00002052/// Destroy a __strong variable.
2053///
2054/// At -O0, emit a call to store 'null' into the address;
2055/// instrumenting tools prefer this because the address is exposed,
2056/// but it's relatively cumbersome to optimize.
2057///
2058/// At -O1 and above, just load and call objc_release.
2059///
2060/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002061void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002062 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002063 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002064 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002065 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2066 return;
2067 }
2068
2069 llvm::Value *value = Builder.CreateLoad(addr);
2070 EmitARCRelease(value, precise);
2071}
2072
John McCall31168b02011-06-15 23:02:42 +00002073/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002074/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002075llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002076 llvm::Value *value,
2077 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002078 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002079
2080 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2081 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002082 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002083 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002084 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2085 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2086 }
2087
John McCall882987f2013-02-28 19:01:20 +00002088 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002089 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002090 Builder.CreateBitCast(value, Int8PtrTy)
2091 };
2092 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002093
Craig Topper8a13c412014-05-21 05:09:00 +00002094 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002095 return value;
2096}
2097
2098/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002099/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002100/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002101llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002102 llvm::Value *newValue,
2103 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002104 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002105 bool isBlock = type->isBlockPointerType();
2106
2107 // Use a store barrier at -O0 unless this is a block type or the
2108 // lvalue is inadequately aligned.
2109 if (shouldUseFusedARCCalls() &&
2110 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002111 (dst.getAlignment().isZero() ||
2112 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002113 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2114 }
2115
2116 // Otherwise, split it out.
2117
2118 // Retain the new value.
2119 newValue = EmitARCRetain(type, newValue);
2120
2121 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002122 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002123
2124 // Store. We do this before the release so that any deallocs won't
2125 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002126 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002127
2128 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002129 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002130
2131 return newValue;
2132}
2133
2134/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002135/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002136llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2137 return emitARCValueOperation(*this, value,
2138 CGM.getARCEntrypoints().objc_autorelease,
2139 "objc_autorelease");
2140}
2141
2142/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002143/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002144llvm::Value *
2145CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2146 return emitARCValueOperation(*this, value,
2147 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002148 "objc_autoreleaseReturnValue",
2149 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002150}
2151
2152/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002153/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002154llvm::Value *
2155CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2156 return emitARCValueOperation(*this, value,
2157 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002158 "objc_retainAutoreleaseReturnValue",
2159 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002160}
2161
2162/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002163/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002164/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002165/// %retain = call i8* \@objc_retainBlock(i8* %value)
2166/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002167llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2168 llvm::Value *value) {
2169 if (!type->isBlockPointerType())
2170 return EmitARCRetainAutoreleaseNonBlock(value);
2171
2172 if (isa<llvm::ConstantPointerNull>(value)) return value;
2173
Chris Lattner2192fe52011-07-18 04:24:23 +00002174 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002175 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002176 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002177 value = EmitARCAutorelease(value);
2178 return Builder.CreateBitCast(value, origType);
2179}
2180
2181/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002182/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002183llvm::Value *
2184CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2185 return emitARCValueOperation(*this, value,
2186 CGM.getARCEntrypoints().objc_retainAutorelease,
2187 "objc_retainAutorelease");
2188}
2189
James Dennett14c41ea2012-06-22 05:41:30 +00002190/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002191/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
John McCall7f416cc2015-09-08 08:05:57 +00002192llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002193 return emitARCLoadOperation(*this, addr,
2194 CGM.getARCEntrypoints().objc_loadWeak,
2195 "objc_loadWeak");
2196}
2197
James Dennett14c41ea2012-06-22 05:41:30 +00002198/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002199llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002200 return emitARCLoadOperation(*this, addr,
2201 CGM.getARCEntrypoints().objc_loadWeakRetained,
2202 "objc_loadWeakRetained");
2203}
2204
James Dennett14c41ea2012-06-22 05:41:30 +00002205/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002206/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002207llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002208 llvm::Value *value,
2209 bool ignored) {
2210 return emitARCStoreOperation(*this, addr, value,
2211 CGM.getARCEntrypoints().objc_storeWeak,
2212 "objc_storeWeak", ignored);
2213}
2214
James Dennett14c41ea2012-06-22 05:41:30 +00002215/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002216/// Returns %value. %addr is known to not have a current weak entry.
2217/// Essentially equivalent to:
2218/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002219void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002220 // If we're initializing to null, just write null to memory; no need
2221 // to get the runtime involved. But don't do this if optimization
2222 // is enabled, because accounting for this would make the optimizer
2223 // much more complicated.
2224 if (isa<llvm::ConstantPointerNull>(value) &&
2225 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2226 Builder.CreateStore(value, addr);
2227 return;
2228 }
2229
2230 emitARCStoreOperation(*this, addr, value,
2231 CGM.getARCEntrypoints().objc_initWeak,
2232 "objc_initWeak", /*ignored*/ true);
2233}
2234
James Dennett14c41ea2012-06-22 05:41:30 +00002235/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002236/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002237void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002238 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2239 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002240 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002241 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002242 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2243 }
2244
2245 // Cast the argument to 'id*'.
2246 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2247
John McCall7f416cc2015-09-08 08:05:57 +00002248 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002249}
2250
James Dennett14c41ea2012-06-22 05:41:30 +00002251/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002252/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2253/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002254void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002255 emitARCCopyOperation(*this, dst, src,
2256 CGM.getARCEntrypoints().objc_moveWeak,
2257 "objc_moveWeak");
2258}
2259
James Dennett14c41ea2012-06-22 05:41:30 +00002260/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002261/// Disregards the current value in %dest. Essentially
2262/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002263void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002264 emitARCCopyOperation(*this, dst, src,
2265 CGM.getARCEntrypoints().objc_copyWeak,
2266 "objc_copyWeak");
2267}
2268
2269/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002270/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002271llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2272 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2273 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002274 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002275 llvm::FunctionType::get(Int8PtrTy, false);
2276 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2277 }
2278
John McCall882987f2013-02-28 19:01:20 +00002279 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002280}
2281
2282/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002283/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002284void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2285 assert(value->getType() == Int8PtrTy);
2286
2287 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2288 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002289 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002290 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002291
2292 // We don't want to use a weak import here; instead we should not
2293 // fall into this path.
2294 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2295 }
2296
John McCallb7ff6db2013-04-16 21:29:40 +00002297 // objc_autoreleasePoolPop can throw.
2298 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002299}
2300
2301/// Produce the code to do an MRR version objc_autoreleasepool_push.
2302/// Which is: [[NSAutoreleasePool alloc] init];
2303/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2304/// init is declared as: - (id) init; in its NSObject super class.
2305///
2306llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2307 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002308 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002309 // [NSAutoreleasePool alloc]
2310 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2311 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2312 CallArgList Args;
2313 RValue AllocRV =
2314 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2315 getContext().getObjCIdType(),
2316 AllocSel, Receiver, Args);
2317
2318 // [Receiver init]
2319 Receiver = AllocRV.getScalarVal();
2320 II = &CGM.getContext().Idents.get("init");
2321 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2322 RValue InitRV =
2323 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2324 getContext().getObjCIdType(),
2325 InitSel, Receiver, Args);
2326 return InitRV.getScalarVal();
2327}
2328
2329/// Produce the code to do a primitive release.
2330/// [tmp drain];
2331void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2332 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2333 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2334 CallArgList Args;
2335 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2336 getContext().VoidTy, DrainSel, Arg, Args);
2337}
2338
John McCall82fe67b2011-07-09 01:37:26 +00002339void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002340 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002341 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002342 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002343}
2344
2345void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002346 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002347 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002348 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002349}
2350
2351void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002352 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002353 QualType type) {
2354 CGF.EmitARCDestroyWeak(addr);
2355}
2356
John McCall31168b02011-06-15 23:02:42 +00002357namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002358 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002359 llvm::Value *Token;
2360
2361 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2362
Craig Topper4f12f102014-03-12 06:41:41 +00002363 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002364 CGF.EmitObjCAutoreleasePoolPop(Token);
2365 }
2366 };
David Blaikie7e70d682015-08-18 22:40:54 +00002367 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002368 llvm::Value *Token;
2369
2370 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2371
Craig Topper4f12f102014-03-12 06:41:41 +00002372 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002373 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2374 }
2375 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002376}
John McCall31168b02011-06-15 23:02:42 +00002377
2378void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002379 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002380 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2381 else
2382 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2383}
2384
John McCall31168b02011-06-15 23:02:42 +00002385static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2386 LValue lvalue,
2387 QualType type) {
2388 switch (type.getObjCLifetime()) {
2389 case Qualifiers::OCL_None:
2390 case Qualifiers::OCL_ExplicitNone:
2391 case Qualifiers::OCL_Strong:
2392 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002393 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2394 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002395 false);
2396
2397 case Qualifiers::OCL_Weak:
2398 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2399 true);
2400 }
2401
2402 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002403}
2404
2405static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2406 const Expr *e) {
2407 e = e->IgnoreParens();
2408 QualType type = e->getType();
2409
John McCall154a2fd2011-08-30 00:57:29 +00002410 // If we're loading retained from a __strong xvalue, we can avoid
2411 // an extra retain/release pair by zeroing out the source of this
2412 // "move" operation.
2413 if (e->isXValue() &&
2414 !type.isConstQualified() &&
2415 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2416 // Emit the lvalue.
2417 LValue lv = CGF.EmitLValue(e);
2418
2419 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002420 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2421 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002422
2423 // Set the source pointer to NULL.
2424 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2425
2426 return TryEmitResult(result, true);
2427 }
2428
John McCall31168b02011-06-15 23:02:42 +00002429 // As a very special optimization, in ARC++, if the l-value is the
2430 // result of a non-volatile assignment, do a simple retain of the
2431 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002432 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002433 !type.isVolatileQualified() &&
2434 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2435 isa<BinaryOperator>(e) &&
2436 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2437 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2438
2439 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2440}
2441
2442static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2443 llvm::Value *value);
2444
2445/// Given that the given expression is some sort of call (which does
2446/// not return retained), emit a retain following it.
2447static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2448 llvm::Value *value = CGF.EmitScalarExpr(e);
2449 return emitARCRetainAfterCall(CGF, value);
2450}
2451
2452static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2453 llvm::Value *value) {
2454 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2455 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2456
2457 // Place the retain immediately following the call.
2458 CGF.Builder.SetInsertPoint(call->getParent(),
2459 ++llvm::BasicBlock::iterator(call));
2460 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2461
2462 CGF.Builder.restoreIP(ip);
2463 return value;
2464 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2465 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2466
2467 // Place the retain at the beginning of the normal destination block.
2468 llvm::BasicBlock *BB = invoke->getNormalDest();
2469 CGF.Builder.SetInsertPoint(BB, BB->begin());
2470 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2471
2472 CGF.Builder.restoreIP(ip);
2473 return value;
2474
2475 // Bitcasts can arise because of related-result returns. Rewrite
2476 // the operand.
2477 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2478 llvm::Value *operand = bitcast->getOperand(0);
2479 operand = emitARCRetainAfterCall(CGF, operand);
2480 bitcast->setOperand(0, operand);
2481 return bitcast;
2482
2483 // Generic fall-back case.
2484 } else {
2485 // Retain using the non-block variant: we never need to do a copy
2486 // of a block that's been returned to us.
2487 return CGF.EmitARCRetainNonBlock(value);
2488 }
2489}
2490
John McCallcd78e802011-09-10 01:16:55 +00002491/// Determine whether it might be important to emit a separate
2492/// objc_retain_block on the result of the given expression, or
2493/// whether it's okay to just emit it in a +1 context.
2494static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2495 assert(e->getType()->isBlockPointerType());
2496 e = e->IgnoreParens();
2497
2498 // For future goodness, emit block expressions directly in +1
2499 // contexts if we can.
2500 if (isa<BlockExpr>(e))
2501 return false;
2502
2503 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2504 switch (cast->getCastKind()) {
2505 // Emitting these operations in +1 contexts is goodness.
2506 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002507 case CK_ARCReclaimReturnedObject:
2508 case CK_ARCConsumeObject:
2509 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002510 return false;
2511
2512 // These operations preserve a block type.
2513 case CK_NoOp:
2514 case CK_BitCast:
2515 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2516
2517 // These operations are known to be bad (or haven't been considered).
2518 case CK_AnyPointerToBlockPointerCast:
2519 default:
2520 return true;
2521 }
2522 }
2523
2524 return true;
2525}
2526
John McCallfe96e0b2011-11-06 09:01:30 +00002527/// Try to emit a PseudoObjectExpr at +1.
2528///
2529/// This massively duplicates emitPseudoObjectRValue.
2530static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2531 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002532 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002533
2534 // Find the result expression.
2535 const Expr *resultExpr = E->getResultExpr();
2536 assert(resultExpr);
2537 TryEmitResult result;
2538
2539 for (PseudoObjectExpr::const_semantics_iterator
2540 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2541 const Expr *semantic = *i;
2542
2543 // If this semantic expression is an opaque value, bind it
2544 // to the result of its source expression.
2545 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2546 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2547 OVMA opaqueData;
2548
2549 // If this semantic is the result of the pseudo-object
2550 // expression, try to evaluate the source as +1.
2551 if (ov == resultExpr) {
2552 assert(!OVMA::shouldBindAsLValue(ov));
2553 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2554 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2555
2556 // Otherwise, just bind it.
2557 } else {
2558 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2559 }
2560 opaques.push_back(opaqueData);
2561
2562 // Otherwise, if the expression is the result, evaluate it
2563 // and remember the result.
2564 } else if (semantic == resultExpr) {
2565 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2566
2567 // Otherwise, evaluate the expression in an ignored context.
2568 } else {
2569 CGF.EmitIgnoredExpr(semantic);
2570 }
2571 }
2572
2573 // Unbind all the opaques now.
2574 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2575 opaques[i].unbind(CGF);
2576
2577 return result;
2578}
2579
John McCall31168b02011-06-15 23:02:42 +00002580static TryEmitResult
2581tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002582 // We should *never* see a nested full-expression here, because if
2583 // we fail to emit at +1, our caller must not retain after we close
2584 // out the full-expression.
2585 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002586
John McCall31168b02011-06-15 23:02:42 +00002587 // The desired result type, if it differs from the type of the
2588 // ultimate opaque expression.
Craig Topper8a13c412014-05-21 05:09:00 +00002589 llvm::Type *resultType = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002590
2591 while (true) {
2592 e = e->IgnoreParens();
2593
2594 // There's a break at the end of this if-chain; anything
2595 // that wants to keep looping has to explicitly continue.
2596 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2597 switch (ce->getCastKind()) {
2598 // No-op casts don't change the type, so we just ignore them.
2599 case CK_NoOp:
2600 e = ce->getSubExpr();
2601 continue;
2602
2603 case CK_LValueToRValue: {
2604 TryEmitResult loadResult
2605 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2606 if (resultType) {
2607 llvm::Value *value = loadResult.getPointer();
2608 value = CGF.Builder.CreateBitCast(value, resultType);
2609 loadResult.setPointer(value);
2610 }
2611 return loadResult;
2612 }
2613
2614 // These casts can change the type, so remember that and
2615 // soldier on. We only need to remember the outermost such
2616 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002617 case CK_CPointerToObjCPointerCast:
2618 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002619 case CK_AnyPointerToBlockPointerCast:
2620 case CK_BitCast:
2621 if (!resultType)
2622 resultType = CGF.ConvertType(ce->getType());
2623 e = ce->getSubExpr();
2624 assert(e->getType()->hasPointerRepresentation());
2625 continue;
2626
2627 // For consumptions, just emit the subexpression and thus elide
2628 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002629 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002630 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2631 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2632 return TryEmitResult(result, true);
2633 }
2634
John McCallcd78e802011-09-10 01:16:55 +00002635 // Block extends are net +0. Naively, we could just recurse on
2636 // the subexpression, but actually we need to ensure that the
2637 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002638 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002639 llvm::Value *result; // will be a +0 value
2640
2641 // If we can't safely assume the sub-expression will produce a
2642 // block-copied value, emit the sub-expression at +0.
2643 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2644 result = CGF.EmitScalarExpr(ce->getSubExpr());
2645
2646 // Otherwise, try to emit the sub-expression at +1 recursively.
2647 } else {
2648 TryEmitResult subresult
2649 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2650 result = subresult.getPointer();
2651
2652 // If that produced a retained value, just use that,
2653 // possibly casting down.
2654 if (subresult.getInt()) {
2655 if (resultType)
2656 result = CGF.Builder.CreateBitCast(result, resultType);
2657 return TryEmitResult(result, true);
2658 }
2659
2660 // Otherwise it's +0.
2661 }
2662
2663 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002664 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002665 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2666 return TryEmitResult(result, true);
2667 }
2668
John McCall4db5c3c2011-07-07 06:58:02 +00002669 // For reclaims, emit the subexpression as a retained call and
2670 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002671 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002672 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2673 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2674 return TryEmitResult(result, true);
2675 }
2676
John McCall31168b02011-06-15 23:02:42 +00002677 default:
2678 break;
2679 }
2680
2681 // Skip __extension__.
2682 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2683 if (op->getOpcode() == UO_Extension) {
2684 e = op->getSubExpr();
2685 continue;
2686 }
2687
2688 // For calls and message sends, use the retained-call logic.
2689 // Delegate inits are a special case in that they're the only
2690 // returns-retained expression that *isn't* surrounded by
2691 // a consume.
2692 } else if (isa<CallExpr>(e) ||
2693 (isa<ObjCMessageExpr>(e) &&
2694 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2695 llvm::Value *result = emitARCRetainCall(CGF, e);
2696 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2697 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002698
2699 // Look through pseudo-object expressions.
2700 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2701 TryEmitResult result
2702 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2703 if (resultType) {
2704 llvm::Value *value = result.getPointer();
2705 value = CGF.Builder.CreateBitCast(value, resultType);
2706 result.setPointer(value);
2707 }
2708 return result;
John McCall31168b02011-06-15 23:02:42 +00002709 }
2710
2711 // Conservatively halt the search at any other expression kind.
2712 break;
2713 }
2714
2715 // We didn't find an obvious production, so emit what we've got and
2716 // tell the caller that we didn't manage to retain.
2717 llvm::Value *result = CGF.EmitScalarExpr(e);
2718 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2719 return TryEmitResult(result, false);
2720}
2721
2722static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2723 LValue lvalue,
2724 QualType type) {
2725 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2726 llvm::Value *value = result.getPointer();
2727 if (!result.getInt())
2728 value = CGF.EmitARCRetain(type, value);
2729 return value;
2730}
2731
2732/// EmitARCRetainScalarExpr - Semantically equivalent to
2733/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2734/// best-effort attempt to peephole expressions that naturally produce
2735/// retained objects.
2736llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002737 // The retain needs to happen within the full-expression.
2738 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2739 enterFullExpression(cleanups);
2740 RunCleanupsScope scope(*this);
2741 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2742 }
2743
John McCall31168b02011-06-15 23:02:42 +00002744 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2745 llvm::Value *value = result.getPointer();
2746 if (!result.getInt())
2747 value = EmitARCRetain(e->getType(), value);
2748 return value;
2749}
2750
2751llvm::Value *
2752CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002753 // The retain needs to happen within the full-expression.
2754 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2755 enterFullExpression(cleanups);
2756 RunCleanupsScope scope(*this);
2757 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2758 }
2759
John McCall31168b02011-06-15 23:02:42 +00002760 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2761 llvm::Value *value = result.getPointer();
2762 if (result.getInt())
2763 value = EmitARCAutorelease(value);
2764 else
2765 value = EmitARCRetainAutorelease(e->getType(), value);
2766 return value;
2767}
2768
John McCallff613032011-10-04 06:23:45 +00002769llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2770 llvm::Value *result;
2771 bool doRetain;
2772
2773 if (shouldEmitSeparateBlockRetain(e)) {
2774 result = EmitScalarExpr(e);
2775 doRetain = true;
2776 } else {
2777 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2778 result = subresult.getPointer();
2779 doRetain = !subresult.getInt();
2780 }
2781
2782 if (doRetain)
2783 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2784 return EmitObjCConsumeObject(e->getType(), result);
2785}
2786
John McCall248512a2011-10-01 10:32:24 +00002787llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2788 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002789 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002790 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002791 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002792 return EmitARCRetainAutoreleaseScalarExpr(expr);
2793 }
2794
2795 // Otherwise, use the normal scalar-expression emission. The
2796 // exception machinery doesn't do anything special with the
2797 // exception like retaining it, so there's no safety associated with
2798 // only running cleanups after the throw has started, and when it
2799 // matters it tends to be substantially inferior code.
2800 return EmitScalarExpr(expr);
2801}
2802
John McCall31168b02011-06-15 23:02:42 +00002803std::pair<LValue,llvm::Value*>
2804CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2805 bool ignored) {
2806 // Evaluate the RHS first.
2807 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2808 llvm::Value *value = result.getPointer();
2809
John McCallb726a552011-07-28 07:23:35 +00002810 bool hasImmediateRetain = result.getInt();
2811
2812 // If we didn't emit a retained object, and the l-value is of block
2813 // type, then we need to emit the block-retain immediately in case
2814 // it invalidates the l-value.
2815 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002816 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002817 hasImmediateRetain = true;
2818 }
2819
John McCall31168b02011-06-15 23:02:42 +00002820 LValue lvalue = EmitLValue(e->getLHS());
2821
2822 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002823 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002824 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002825 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002826 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002827 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002828 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002829 }
2830
2831 return std::pair<LValue,llvm::Value*>(lvalue, value);
2832}
2833
2834std::pair<LValue,llvm::Value*>
2835CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2836 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2837 LValue lvalue = EmitLValue(e->getLHS());
2838
Eli Friedmana0544d62011-12-03 04:14:32 +00002839 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002840
2841 return std::pair<LValue,llvm::Value*>(lvalue, value);
2842}
2843
2844void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002845 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002846 const Stmt *subStmt = ARPS.getSubStmt();
2847 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2848
2849 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002850 if (DI)
2851 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002852
2853 // Keep track of the current cleanup stack depth.
2854 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002855 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002856 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2857 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2858 } else {
2859 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2860 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2861 }
2862
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00002863 for (const auto *I : S.body())
2864 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00002865
Eric Christopher7cdf9482011-10-13 21:45:18 +00002866 if (DI)
2867 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002868}
John McCall1bd25562011-06-24 23:21:27 +00002869
2870/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2871/// make sure it survives garbage collection until this point.
2872void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2873 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002874 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002875 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002876 llvm::Value *extender
2877 = llvm::InlineAsm::get(extenderType,
2878 /* assembly */ "",
2879 /* constraints */ "r",
2880 /* side effects */ true);
2881
2882 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00002883 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00002884}
2885
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002886/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002887/// non-trivial copy assignment function, produce following helper function.
2888/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2889///
2890llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002891CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2892 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002893 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002894 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002895 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002896 QualType Ty = PID->getPropertyIvarDecl()->getType();
2897 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002898 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002899 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002900 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002901 return nullptr;
2902 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002903 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002904 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002905 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2906 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2907 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002908
2909 ASTContext &C = getContext();
2910 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002911 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002912 FunctionDecl *FD = FunctionDecl::Create(C,
2913 C.getTranslationUnitDecl(),
2914 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002915 SourceLocation(), II, C.VoidTy,
2916 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002917 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002918 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002919
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002920 QualType DestTy = C.getPointerType(Ty);
2921 QualType SrcTy = Ty;
2922 SrcTy.addConst();
2923 SrcTy = C.getPointerType(SrcTy);
2924
2925 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002926 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002927 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002928 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002929 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002930
2931 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2932 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2933
John McCalla729c622012-02-17 03:33:10 +00002934 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002935
2936 llvm::Function *Fn =
2937 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002938 "__assign_helper_atomic_property_",
2939 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002940
Adrian Prantl22e66b42014-04-11 01:13:04 +00002941 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002942
John McCall113bee02012-03-10 09:33:50 +00002943 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2944 VK_RValue, SourceLocation());
2945 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2946 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002947
John McCall113bee02012-03-10 09:33:50 +00002948 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2949 VK_RValue, SourceLocation());
2950 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2951 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002952
John McCall113bee02012-03-10 09:33:50 +00002953 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002954 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002955 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002956 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002957 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002958
2959 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002960
2961 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002962 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002963 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002964 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002965}
2966
2967llvm::Constant *
2968CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2969 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002970 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002971 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002972 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002973 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2974 QualType Ty = PD->getType();
2975 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002976 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002977 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002978 return nullptr;
2979 llvm::Constant *HelperFn = nullptr;
2980
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002981 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002982 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002983 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2984 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2985 return HelperFn;
2986
2987
2988 ASTContext &C = getContext();
2989 IdentifierInfo *II
2990 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2991 FunctionDecl *FD = FunctionDecl::Create(C,
2992 C.getTranslationUnitDecl(),
2993 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002994 SourceLocation(), II, C.VoidTy,
2995 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002996 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002997 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002998
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002999 QualType DestTy = C.getPointerType(Ty);
3000 QualType SrcTy = Ty;
3001 SrcTy.addConst();
3002 SrcTy = C.getPointerType(SrcTy);
3003
3004 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00003005 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003006 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00003007 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003008 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003009
3010 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3011 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
3012
John McCalla729c622012-02-17 03:33:10 +00003013 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003014
3015 llvm::Function *Fn =
3016 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3017 "__copy_helper_atomic_property_", &CGM.getModule());
3018
Adrian Prantl22e66b42014-04-11 01:13:04 +00003019 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003020
John McCall113bee02012-03-10 09:33:50 +00003021 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003022 VK_RValue, SourceLocation());
3023
John McCall113bee02012-03-10 09:33:50 +00003024 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3025 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003026
3027 CXXConstructExpr *CXXConstExpr =
3028 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3029
3030 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003031 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003032 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3033 CXXConstExpr->arg_end());
3034
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003035 CXXConstructExpr *TheCXXConstructExpr =
3036 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3037 CXXConstExpr->getConstructor(),
3038 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003039 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003040 CXXConstExpr->hadMultipleCandidates(),
3041 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003042 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003043 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003044 CXXConstExpr->getConstructionKind(),
3045 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003046
John McCall113bee02012-03-10 09:33:50 +00003047 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3048 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003049
John McCall113bee02012-03-10 09:33:50 +00003050 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003051 CharUnits Alignment
3052 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003053 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003054 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3055 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003056 AggValueSlot::IsDestructed,
3057 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003058 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003059
3060 FinishFunction();
3061 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3062 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3063 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003064}
3065
Eli Friedmanec75fec2012-02-28 01:08:45 +00003066llvm::Value *
3067CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3068 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003069 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3070 Selector CopySelector =
3071 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003072 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3073 Selector AutoreleaseSelector =
3074 getContext().Selectors.getNullarySelector(AutoreleaseID);
3075
3076 // Emit calls to retain/autorelease.
3077 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3078 llvm::Value *Val = Block;
3079 RValue Result;
3080 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003081 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003082 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003083 Val = Result.getScalarVal();
3084 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3085 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003086 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003087 Val = Result.getScalarVal();
3088 return Val;
3089}
3090
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003091
Ted Kremenek43e06332008-04-09 15:51:31 +00003092CGObjCRuntime::~CGObjCRuntime() {}