blob: 242b3d5a73596292ea4b0b816a14080fcab4a416 [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();
276 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
277 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
278 receiver = ice->getSubExpr()->IgnoreParens();
279
280 // Only __strong variables.
281 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
282 return true;
283
284 // All ivars and fields have precise lifetime.
285 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
286 return false;
287
288 // Otherwise, check for variables.
289 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
290 if (!declRef) return true;
291 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
292 if (!var) return true;
293
294 // All variables have precise lifetime except local variables with
295 // automatic storage duration that aren't specially marked.
296 return (var->hasLocalStorage() &&
297 !var->hasAttr<ObjCPreciseLifetimeAttr>());
298 }
299
300 case ObjCMessageExpr::Class:
301 case ObjCMessageExpr::SuperClass:
302 // It's never necessary for class objects.
303 return false;
304
305 case ObjCMessageExpr::SuperInstance:
306 // We generally assume that 'self' lives throughout a method call.
307 return false;
308 }
309
310 llvm_unreachable("invalid receiver kind");
311}
312
John McCall78a15112010-05-22 01:48:05 +0000313RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
314 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000315 // Only the lookup mechanism and first two arguments of the method
316 // implementation vary between runtimes. We can get the receiver and
317 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000318
John McCall31168b02011-06-15 23:02:42 +0000319 bool isDelegateInit = E->isDelegateInitCall();
320
John McCallcf166702011-07-22 08:53:00 +0000321 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000322
John McCall31168b02011-06-15 23:02:42 +0000323 // We don't retain the receiver in delegate init calls, and this is
324 // safe because the receiver value is always loaded from 'self',
325 // which we zero out. We don't want to Block_copy block receivers,
326 // though.
327 bool retainSelf =
328 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000329 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000330 method &&
331 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000332
Daniel Dunbar8d480592008-08-11 18:12:00 +0000333 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000334 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000335 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000336 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000337 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000338 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000339 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000340 switch (E->getReceiverKind()) {
341 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000342 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000343 if (retainSelf) {
344 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
345 E->getInstanceReceiver());
346 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000347 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000348 } else
349 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000350 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000351
Douglas Gregor9a129192010-04-21 00:45:42 +0000352 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000353 ReceiverType = E->getClassReceiver();
354 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000355 assert(ObjTy && "Invalid Objective-C class message send");
356 OID = ObjTy->getInterface();
357 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000358 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000359 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000360 break;
361 }
362
363 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000364 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000365 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000366 isSuperMessage = true;
367 break;
368
369 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000370 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000371 Receiver = LoadObjCSelf();
372 isSuperMessage = true;
373 isClassMessage = true;
374 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000375 }
376
John McCallcf166702011-07-22 08:53:00 +0000377 if (retainSelf)
378 Receiver = EmitARCRetainNonBlock(Receiver);
379
380 // In ARC, we sometimes want to "extend the lifetime"
381 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
382 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000383 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000384 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
385 shouldExtendReceiverForInnerPointerMessage(E))
386 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
387
Alp Toker314cc812014-01-25 16:55:45 +0000388 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000389
Daniel Dunbarc722b852008-08-30 03:02:31 +0000390 CallArgList Args;
David Blaikief05779e2015-07-21 18:37:18 +0000391 EmitCallArgs(Args, method, E->arguments());
Mike Stump11289f42009-09-09 15:08:12 +0000392
John McCall31168b02011-06-15 23:02:42 +0000393 // For delegate init calls in ARC, do an unsafe store of null into
394 // self. This represents the call taking direct ownership of that
395 // value. We have to do this after emitting the other call
396 // arguments because they might also reference self, but we don't
397 // have to worry about any of them modifying self because that would
398 // be an undefined read and write of an object in unordered
399 // expressions.
400 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000401 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000402 "delegate init calls should only be marked in ARC");
403
404 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000405 Address selfAddr =
406 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000407 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
408 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000409
Douglas Gregor33823722011-06-11 01:09:30 +0000410 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000411 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000412 // super is only valid in an Objective-C method
413 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000414 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000415 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
416 E->getSelector(),
417 OMD->getClassInterface(),
418 isCategoryImpl,
419 Receiver,
420 isClassMessage,
421 Args,
John McCallcf166702011-07-22 08:53:00 +0000422 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000423 } else {
424 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
425 E->getSelector(),
426 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000427 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000428 }
John McCall31168b02011-06-15 23:02:42 +0000429
430 // For delegate init calls in ARC, implicitly store the result of
431 // the call back into self. This takes ownership of the value.
432 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000433 Address selfAddr =
434 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000435 llvm::Value *newSelf = result.getScalarVal();
436
437 // The delegate return type isn't necessarily a matching type; in
438 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000439 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000440 newSelf = Builder.CreateBitCast(newSelf, selfTy);
441
442 Builder.CreateStore(newSelf, selfAddr);
443 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000444
Douglas Gregore83b9562015-07-07 03:57:53 +0000445 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000446}
447
John McCall31168b02011-06-15 23:02:42 +0000448namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000449struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000450 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000451 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000452
453 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000454 const ObjCInterfaceDecl *iface = impl->getClassInterface();
455 if (!iface->getSuperClass()) return;
456
John McCalldffafde2011-07-13 18:26:47 +0000457 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
458
John McCall31168b02011-06-15 23:02:42 +0000459 // Call [super dealloc] if we have a superclass.
460 llvm::Value *self = CGF.LoadObjCSelf();
461
462 CallArgList args;
463 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
464 CGF.getContext().VoidTy,
465 method->getSelector(),
466 iface,
John McCalldffafde2011-07-13 18:26:47 +0000467 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000468 self,
469 /*is class msg*/ false,
470 args,
471 method);
472 }
473};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000474}
John McCall31168b02011-06-15 23:02:42 +0000475
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000476/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
477/// the LLVM function and sets the other context used by
478/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000479void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000480 const ObjCContainerDecl *CD) {
481 SourceLocation StartLoc = OMD->getLocStart();
John McCalla738c252011-03-09 04:27:21 +0000482 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000483 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000484 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000485 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000486
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000487 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000488
John McCalla729c622012-02-17 03:33:10 +0000489 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000490 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000491
John McCalla738c252011-03-09 04:27:21 +0000492 args.push_back(OMD->getSelfDecl());
493 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000494
Benjamin Kramerf9890422015-02-17 16:48:30 +0000495 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000496
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000497 CurGD = OMD;
David Blaikie47d28e02015-01-14 07:10:46 +0000498 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000499
Adrian Prantl42d71b92014-04-10 23:21:53 +0000500 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
501 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000502
503 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000505 OMD->isInstanceMethod() &&
506 OMD->getSelector().isUnarySelector()) {
507 const IdentifierInfo *ident =
508 OMD->getSelector().getIdentifierInfoForSlot(0);
509 if (ident->isStr("dealloc"))
510 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
511 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000512}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000513
John McCall31168b02011-06-15 23:02:42 +0000514static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
515 LValue lvalue, QualType type);
516
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000517/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000518/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000519void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000520 StartObjCMethod(OMD, OMD->getClassInterface());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000521 PGO.assignRegionCounters(OMD, CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000522 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000523 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000524 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000525 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000526}
527
John McCallb923ece2011-09-12 23:06:44 +0000528/// emitStructGetterCall - Call the runtime function to load a property
529/// into the return value slot.
530static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
531 bool isAtomic, bool hasStrong) {
532 ASTContext &Context = CGF.getContext();
533
John McCall7f416cc2015-09-08 08:05:57 +0000534 Address src =
535 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
536 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000537
538 // objc_copyStruct (ReturnValue, &structIvar,
539 // sizeof (Type of Ivar), isAtomic, false);
540 CallArgList args;
541
John McCall7f416cc2015-09-08 08:05:57 +0000542 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
543 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000544
545 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000546 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000547
548 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
549 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
550 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
551 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
552
553 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000554 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
555 FunctionType::ExtInfo(),
556 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000557 fn, ReturnValueSlot(), args);
558}
559
John McCallf4528ae2011-09-13 03:34:09 +0000560/// Determine whether the given architecture supports unaligned atomic
561/// accesses. They don't have to be fast, just faster than a function
562/// call and a mutex.
563static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000564 // FIXME: Allow unaligned atomic load/store on x86. (It is not
565 // currently supported by the backend.)
566 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000567}
568
569/// Return the maximum size that permits atomic accesses for the given
570/// architecture.
571static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
572 llvm::Triple::ArchType arch) {
573 // ARM has 8-byte atomic accesses, but it's not clear whether we
574 // want to rely on them here.
575
576 // In the default case, just assume that any size up to a pointer is
577 // fine given adequate alignment.
578 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
579}
580
581namespace {
582 class PropertyImplStrategy {
583 public:
584 enum StrategyKind {
585 /// The 'native' strategy is to use the architecture's provided
586 /// reads and writes.
587 Native,
588
589 /// Use objc_setProperty and objc_getProperty.
590 GetSetProperty,
591
592 /// Use objc_setProperty for the setter, but use expression
593 /// evaluation for the getter.
594 SetPropertyAndExpressionGet,
595
596 /// Use objc_copyStruct.
597 CopyStruct,
598
599 /// The 'expression' strategy is to emit normal assignment or
600 /// lvalue-to-rvalue expressions.
601 Expression
602 };
603
604 StrategyKind getKind() const { return StrategyKind(Kind); }
605
606 bool hasStrongMember() const { return HasStrong; }
607 bool isAtomic() const { return IsAtomic; }
608 bool isCopy() const { return IsCopy; }
609
610 CharUnits getIvarSize() const { return IvarSize; }
611 CharUnits getIvarAlignment() const { return IvarAlignment; }
612
613 PropertyImplStrategy(CodeGenModule &CGM,
614 const ObjCPropertyImplDecl *propImpl);
615
616 private:
617 unsigned Kind : 8;
618 unsigned IsAtomic : 1;
619 unsigned IsCopy : 1;
620 unsigned HasStrong : 1;
621
622 CharUnits IvarSize;
623 CharUnits IvarAlignment;
624 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000625}
John McCallf4528ae2011-09-13 03:34:09 +0000626
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000627/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000628PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
629 const ObjCPropertyImplDecl *propImpl) {
630 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000631 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000632
John McCall43192862011-09-13 18:31:23 +0000633 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
634 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000635 HasStrong = false; // doesn't matter here.
636
637 // Evaluate the ivar's size and alignment.
638 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
639 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000640 std::tie(IvarSize, IvarAlignment) =
641 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000642
643 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000644 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000645 if (IsCopy) {
646 Kind = GetSetProperty;
647 return;
648 }
649
John McCall43192862011-09-13 18:31:23 +0000650 // Handle retain.
651 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000652 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000653 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000654 // fallthrough
655
656 // In ARC, if the property is non-atomic, use expression emission,
657 // which translates to objc_storeStrong. This isn't required, but
658 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000659 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000660 // Using standard expression emission for the setter is only
661 // acceptable if the ivar is __strong, which won't be true if
662 // the property is annotated with __attribute__((NSObject)).
663 // TODO: falling all the way back to objc_setProperty here is
664 // just laziness, though; we could still use objc_storeStrong
665 // if we hacked it right.
666 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
667 Kind = Expression;
668 else
669 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000670 return;
671
672 // Otherwise, we need to at least use setProperty. However, if
673 // the property isn't atomic, we can use normal expression
674 // emission for the getter.
675 } else if (!IsAtomic) {
676 Kind = SetPropertyAndExpressionGet;
677 return;
678
679 // Otherwise, we have to use both setProperty and getProperty.
680 } else {
681 Kind = GetSetProperty;
682 return;
683 }
684 }
685
686 // If we're not atomic, just use expression accesses.
687 if (!IsAtomic) {
688 Kind = Expression;
689 return;
690 }
691
John McCall0e5c0862011-09-13 05:36:29 +0000692 // Properties on bitfield ivars need to be emitted using expression
693 // accesses even if they're nominally atomic.
694 if (ivar->isBitField()) {
695 Kind = Expression;
696 return;
697 }
698
John McCallf4528ae2011-09-13 03:34:09 +0000699 // GC-qualified or ARC-qualified ivars need to be emitted as
700 // expressions. This actually works out to being atomic anyway,
701 // except for ARC __strong, but that should trigger the above code.
702 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000703 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000704 CGM.getContext().getObjCGCAttrKind(ivarType))) {
705 Kind = Expression;
706 return;
707 }
708
709 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000710 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000711 if (const RecordType *recordType = ivarType->getAs<RecordType>())
712 HasStrong = recordType->getDecl()->hasObjectMember();
713
714 // We can never access structs with object members with a native
715 // access, because we need to use write barriers. This is what
716 // objc_copyStruct is for.
717 if (HasStrong) {
718 Kind = CopyStruct;
719 return;
720 }
721
722 // Otherwise, this is target-dependent and based on the size and
723 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000724
725 // If the size of the ivar is not a power of two, give up. We don't
726 // want to get into the business of doing compare-and-swaps.
727 if (!IvarSize.isPowerOfTwo()) {
728 Kind = CopyStruct;
729 return;
730 }
731
John McCallf4528ae2011-09-13 03:34:09 +0000732 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000733 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000734
735 // Most architectures require memory to fit within a single cache
736 // line, so the alignment has to be at least the size of the access.
737 // Otherwise we have to grab a lock.
738 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
739 Kind = CopyStruct;
740 return;
741 }
742
743 // If the ivar's size exceeds the architecture's maximum atomic
744 // access size, we have to use CopyStruct.
745 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
746 Kind = CopyStruct;
747 return;
748 }
749
750 // Otherwise, we can use native loads and stores.
751 Kind = Native;
752}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000753
James Dennettbe302452012-06-15 22:10:14 +0000754/// \brief Generate an Objective-C property getter function.
755///
756/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000757/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000758void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
759 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000760 llvm::Constant *AtomicHelperFn =
761 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000762 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
763 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
764 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000765 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000766
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000767 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000768
769 FinishFunction();
770}
771
John McCallbdd81852011-09-13 06:00:03 +0000772static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
773 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000774 if (!getter) return true;
775
776 // Sema only makes only of these when the ivar has a C++ class type,
777 // so the form is pretty constrained.
778
John McCallbdd81852011-09-13 06:00:03 +0000779 // If the property has a reference type, we might just be binding a
780 // reference, in which case the result will be a gl-value. We should
781 // treat this as a non-trivial operation.
782 if (getter->isGLValue())
783 return false;
784
John McCallf4528ae2011-09-13 03:34:09 +0000785 // If we selected a trivial copy-constructor, we're okay.
786 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
787 return (construct->getConstructor()->isTrivial());
788
789 // The constructor might require cleanups (in which case it's never
790 // trivial).
791 assert(isa<ExprWithCleanups>(getter));
792 return false;
793}
794
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000795/// emitCPPObjectAtomicGetterCall - Call the runtime function to
796/// copy the ivar into the resturn slot.
797static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
798 llvm::Value *returnAddr,
799 ObjCIvarDecl *ivar,
800 llvm::Constant *AtomicHelperFn) {
801 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
802 // AtomicHelperFn);
803 CallArgList args;
804
805 // The 1st argument is the return Slot.
806 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
807
808 // The 2nd argument is the address of the ivar.
809 llvm::Value *ivarAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000810 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
811 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000812 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
813 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
814
815 // Third argument is the helper function.
816 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
817
818 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000819 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000820 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
821 args,
822 FunctionType::ExtInfo(),
823 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000824 copyCppAtomicObjectFn, ReturnValueSlot(), args);
825}
826
John McCallf4528ae2011-09-13 03:34:09 +0000827void
828CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000829 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000830 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000831 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000832 // If there's a non-trivial 'get' expression, we just have to emit that.
833 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000834 if (!AtomicHelperFn) {
835 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000836 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000837 EmitReturnStmt(ret);
838 }
839 else {
840 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f416cc2015-09-08 08:05:57 +0000841 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000842 ivar, AtomicHelperFn);
843 }
John McCallf4528ae2011-09-13 03:34:09 +0000844 return;
845 }
846
847 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
848 QualType propType = prop->getType();
849 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
850
851 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
852
853 // Pick an implementation strategy.
854 PropertyImplStrategy strategy(CGM, propImpl);
855 switch (strategy.getKind()) {
856 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000857 // We don't need to do anything for a zero-size struct.
858 if (strategy.getIvarSize().isZero())
859 return;
860
John McCallf4528ae2011-09-13 03:34:09 +0000861 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
862
863 // Currently, all atomic accesses have to be through integer
864 // types, so there's no point in trying to pick a prettier type.
865 llvm::Type *bitcastType =
866 llvm::Type::getIntNTy(getLLVMContext(),
867 getContext().toBits(strategy.getIvarSize()));
868 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
869
870 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +0000871 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +0000872 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
873 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
John McCallf4528ae2011-09-13 03:34:09 +0000874 load->setAtomic(llvm::Unordered);
875
876 // Store that value into the return address. Doing this with a
877 // bitcast is likely to produce some pretty ugly IR, but it's not
878 // the *most* terrible thing in the world.
879 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
880
881 // Make sure we don't do an autorelease.
882 AutoreleaseResult = false;
883 return;
884 }
885
886 case PropertyImplStrategy::GetSetProperty: {
887 llvm::Value *getPropertyFn =
888 CGM.getObjCRuntime().GetPropertyGetFunction();
889 if (!getPropertyFn) {
890 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000891 return;
892 }
893
894 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
895 // FIXME: Can't this be simpler? This might even be worse than the
896 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000897 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +0000898 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +0000899 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
900 llvm::Value *ivarOffset =
901 EmitIvarOffset(classImpl->getClassInterface(), ivar);
902
903 CallArgList args;
904 args.add(RValue::get(self), getContext().getObjCIdType());
905 args.add(RValue::get(cmd), getContext().getObjCSelType());
906 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000907 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
908 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000909
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000910 // FIXME: We shouldn't need to get the function info here, the
911 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000912 llvm::Instruction *CallInstruction;
John McCall8dda7b22012-07-07 06:41:13 +0000913 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
914 FunctionType::ExtInfo(),
915 RequiredArgs::All),
Craig Topper8a13c412014-05-21 05:09:00 +0000916 getPropertyFn, ReturnValueSlot(), args, nullptr,
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000917 &CallInstruction);
918 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
919 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000920
Daniel Dunbara08dff12008-09-24 04:04:31 +0000921 // We need to fix the type here. Ivars with copy & retain are
922 // always objects so we don't need to worry about complex or
923 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000924 RV = RValue::get(Builder.CreateBitCast(
925 RV.getScalarVal(),
926 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000927
928 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000929
930 // objc_getProperty does an autorelease, so we should suppress ours.
931 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000932
John McCallf4528ae2011-09-13 03:34:09 +0000933 return;
934 }
935
936 case PropertyImplStrategy::CopyStruct:
937 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
938 strategy.hasStrongMember());
939 return;
940
941 case PropertyImplStrategy::Expression:
942 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
943 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
944
945 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000946 switch (getEvaluationKind(ivarType)) {
947 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000948 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +0000949 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +0000950 /*init*/ true);
951 return;
952 }
953 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000954 // The return value slot is guaranteed to not be aliased, but
955 // that's not necessarily the same as "on the stack", so
956 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000957 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000958 return;
959 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000960 llvm::Value *value;
961 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000962 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +0000963 } else {
964 // We want to load and autoreleaseReturnValue ARC __weak ivars.
965 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000966 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000967
968 // Otherwise we want to do a simple load, suppressing the
969 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000970 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000971 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000972 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000973 }
John McCall31168b02011-06-15 23:02:42 +0000974
John McCall24fada12011-07-22 05:23:13 +0000975 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +0000976 value = Builder.CreateBitCast(
977 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +0000978 }
979
980 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000981 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000982 }
John McCall47fb9502013-03-07 21:37:08 +0000983 }
984 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000985 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000986
John McCallf4528ae2011-09-13 03:34:09 +0000987 }
988 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000989}
990
John McCallb923ece2011-09-12 23:06:44 +0000991/// emitStructSetterCall - Call the runtime function to store the value
992/// from the first formal parameter into the given ivar.
993static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
994 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000995 // objc_copyStruct (&structIvar, &Arg,
996 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000997 CallArgList args;
998
999 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001000 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1001 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001002 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001003 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1004 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001005
1006 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001007 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001008 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +00001009 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001010 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001011 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1012 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001013
1014 // The third argument is the sizeof the type.
1015 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001016 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1017 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001018
John McCallb923ece2011-09-12 23:06:44 +00001019 // The fourth argument is the 'isAtomic' flag.
1020 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001021
John McCallb923ece2011-09-12 23:06:44 +00001022 // The fifth argument is the 'hasStrong' flag.
1023 // FIXME: should this really always be false?
1024 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1025
1026 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001027 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1028 args,
1029 FunctionType::ExtInfo(),
1030 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001031 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001032}
1033
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001034/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1035/// the value from the first formal parameter into the given ivar, using
1036/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1037static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1038 ObjCMethodDecl *OMD,
1039 ObjCIvarDecl *ivar,
1040 llvm::Constant *AtomicHelperFn) {
1041 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1042 // AtomicHelperFn);
1043 CallArgList args;
1044
1045 // The first argument is the address of the ivar.
1046 llvm::Value *ivarAddr =
1047 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001048 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001049 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1050 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1051
1052 // The second argument is the address of the parameter variable.
1053 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001054 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001055 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001056 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001057 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1058 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1059
1060 // Third argument is the helper function.
1061 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1062
1063 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001064 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001065 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1066 args,
1067 FunctionType::ExtInfo(),
1068 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001069 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001070}
1071
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001072
John McCallf4528ae2011-09-13 03:34:09 +00001073static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1074 Expr *setter = PID->getSetterCXXAssignment();
1075 if (!setter) return true;
1076
1077 // Sema only makes only of these when the ivar has a C++ class type,
1078 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001079
1080 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001081 // This also implies that there's nothing non-trivial going on with
1082 // the arguments, because operator= can only be trivial if it's a
1083 // synthesized assignment operator and therefore both parameters are
1084 // references.
1085 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001086 if (const FunctionDecl *callee
1087 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1088 if (callee->isTrivial())
1089 return true;
1090 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001091 }
John McCall7f16c422011-09-10 09:17:20 +00001092
John McCallf4528ae2011-09-13 03:34:09 +00001093 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001094 return false;
1095}
1096
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001097static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001098 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001099 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001100 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001101}
1102
John McCall7f16c422011-09-10 09:17:20 +00001103void
1104CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001105 const ObjCPropertyImplDecl *propImpl,
1106 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001107 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001108 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001109 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001110
1111 // Just use the setter expression if Sema gave us one and it's
1112 // non-trivial.
1113 if (!hasTrivialSetExpr(propImpl)) {
1114 if (!AtomicHelperFn)
1115 // If non-atomic, assignment is called directly.
1116 EmitStmt(propImpl->getSetterCXXAssignment());
1117 else
1118 // If atomic, assignment is called via a locking api.
1119 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1120 AtomicHelperFn);
1121 return;
1122 }
John McCall7f16c422011-09-10 09:17:20 +00001123
John McCallf4528ae2011-09-13 03:34:09 +00001124 PropertyImplStrategy strategy(CGM, propImpl);
1125 switch (strategy.getKind()) {
1126 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001127 // We don't need to do anything for a zero-size struct.
1128 if (strategy.getIvarSize().isZero())
1129 return;
1130
John McCall7f416cc2015-09-08 08:05:57 +00001131 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001132
John McCallf4528ae2011-09-13 03:34:09 +00001133 LValue ivarLValue =
1134 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001135 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001136
John McCallf4528ae2011-09-13 03:34:09 +00001137 // Currently, all atomic accesses have to be through integer
1138 // types, so there's no point in trying to pick a prettier type.
1139 llvm::Type *bitcastType =
1140 llvm::Type::getIntNTy(getLLVMContext(),
1141 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001142
1143 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001144 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1145 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001146
1147 // This bitcast load is likely to cause some nasty IR.
1148 llvm::Value *load = Builder.CreateLoad(argAddr);
1149
1150 // Perform an atomic store. There are no memory ordering requirements.
1151 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
John McCallf4528ae2011-09-13 03:34:09 +00001152 store->setAtomic(llvm::Unordered);
1153 return;
1154 }
1155
1156 case PropertyImplStrategy::GetSetProperty:
1157 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001158
1159 llvm::Value *setOptimizedPropertyFn = nullptr;
1160 llvm::Value *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001161 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001162 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001163 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001164 CGM.getObjCRuntime()
1165 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1166 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001167 if (!setOptimizedPropertyFn) {
1168 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1169 return;
1170 }
John McCall7f16c422011-09-10 09:17:20 +00001171 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001172 else {
1173 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1174 if (!setPropertyFn) {
1175 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1176 return;
1177 }
1178 }
1179
John McCall7f16c422011-09-10 09:17:20 +00001180 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1181 // <is-atomic>, <is-copy>).
1182 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001183 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001184 llvm::Value *self =
1185 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1186 llvm::Value *ivarOffset =
1187 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001188 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1189 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1190 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001191
1192 CallArgList args;
1193 args.add(RValue::get(self), getContext().getObjCIdType());
1194 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001195 if (setOptimizedPropertyFn) {
1196 args.add(RValue::get(arg), getContext().getObjCIdType());
1197 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001198 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1199 FunctionType::ExtInfo(),
1200 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001201 setOptimizedPropertyFn, ReturnValueSlot(), args);
1202 } else {
1203 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1204 args.add(RValue::get(arg), getContext().getObjCIdType());
1205 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1206 getContext().BoolTy);
1207 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1208 getContext().BoolTy);
1209 // FIXME: We shouldn't need to get the function info here, the runtime
1210 // already should have computed it to build the function.
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 setPropertyFn, ReturnValueSlot(), args);
1215 }
1216
John McCall7f16c422011-09-10 09:17:20 +00001217 return;
1218 }
1219
John McCallf4528ae2011-09-13 03:34:09 +00001220 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001221 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001222 return;
John McCallf4528ae2011-09-13 03:34:09 +00001223
1224 case PropertyImplStrategy::Expression:
1225 break;
John McCall7f16c422011-09-10 09:17:20 +00001226 }
1227
1228 // Otherwise, fake up some ASTs and emit a normal assignment.
1229 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001230 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1231 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001232 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1233 selfDecl->getType(), CK_LValueToRValue, &self,
1234 VK_RValue);
1235 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001236 SourceLocation(), SourceLocation(),
1237 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001238
1239 ParmVarDecl *argDecl = *setterMethod->param_begin();
1240 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001241 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001242 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1243 argType.getUnqualifiedType(), CK_LValueToRValue,
1244 &arg, VK_RValue);
1245
1246 // The property type can differ from the ivar type in some situations with
1247 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1248 // The following absurdity is just to ensure well-formed IR.
1249 CastKind argCK = CK_NoOp;
1250 if (ivarRef.getType()->isObjCObjectPointerType()) {
1251 if (argLoad.getType()->isObjCObjectPointerType())
1252 argCK = CK_BitCast;
1253 else if (argLoad.getType()->isBlockPointerType())
1254 argCK = CK_BlockPointerToObjCPointerCast;
1255 else
1256 argCK = CK_CPointerToObjCPointerCast;
1257 } else if (ivarRef.getType()->isBlockPointerType()) {
1258 if (argLoad.getType()->isBlockPointerType())
1259 argCK = CK_BitCast;
1260 else
1261 argCK = CK_AnyPointerToBlockPointerCast;
1262 } else if (ivarRef.getType()->isPointerType()) {
1263 argCK = CK_BitCast;
1264 }
1265 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1266 ivarRef.getType(), argCK, &argLoad,
1267 VK_RValue);
1268 Expr *finalArg = &argLoad;
1269 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1270 argLoad.getType()))
1271 finalArg = &argCast;
1272
1273
1274 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1275 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001276 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001277 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001278}
1279
James Dennettbe302452012-06-15 22:10:14 +00001280/// \brief Generate an Objective-C property setter function.
1281///
1282/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001283/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001284void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1285 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001286 llvm::Constant *AtomicHelperFn =
1287 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001288 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1289 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1290 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001291 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001292
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001293 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001294
1295 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001296}
1297
John McCall6a4fa522011-03-22 07:05:39 +00001298namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001299 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001300 private:
1301 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001302 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001303 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001304 bool useEHCleanupForArray;
1305 public:
1306 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1307 CodeGenFunction::Destroyer *destroyer,
1308 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001309 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001310 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001311
Craig Topper4f12f102014-03-12 06:41:41 +00001312 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001313 LValue lvalue
1314 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1315 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001316 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001317 }
1318 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001319}
John McCall6a4fa522011-03-22 07:05:39 +00001320
John McCall4bd0fb12011-07-12 16:41:08 +00001321/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1322static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001323 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001324 QualType type) {
1325 llvm::Value *null = getNullForVariable(addr);
1326 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1327}
John McCall31168b02011-06-15 23:02:42 +00001328
John McCall6a4fa522011-03-22 07:05:39 +00001329static void emitCXXDestructMethod(CodeGenFunction &CGF,
1330 ObjCImplementationDecl *impl) {
1331 CodeGenFunction::RunCleanupsScope scope(CGF);
1332
1333 llvm::Value *self = CGF.LoadObjCSelf();
1334
Jordy Rosea91768e2011-07-22 02:08:32 +00001335 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1336 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001337 ivar; ivar = ivar->getNextIvar()) {
1338 QualType type = ivar->getType();
1339
John McCall6a4fa522011-03-22 07:05:39 +00001340 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001341 QualType::DestructionKind dtorKind = type.isDestructedType();
1342 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001343
Craig Topper8a13c412014-05-21 05:09:00 +00001344 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001345
John McCall4bd0fb12011-07-12 16:41:08 +00001346 // Use a call to objc_storeStrong to destroy strong ivars, for the
1347 // general benefit of the tools.
1348 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001349 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001350
John McCall4bd0fb12011-07-12 16:41:08 +00001351 // Otherwise use the default for the destruction kind.
1352 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001353 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001354 }
John McCall4bd0fb12011-07-12 16:41:08 +00001355
1356 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1357
1358 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1359 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001360 }
1361
1362 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1363}
1364
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001365void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1366 ObjCMethodDecl *MD,
1367 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001368 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001369 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001370
1371 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001372 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001373 // Suppress the final autorelease in ARC.
1374 AutoreleaseResult = false;
1375
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001376 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001377 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001378 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001379 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1380 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001381 EmitAggExpr(IvarInit->getInit(),
1382 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001383 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001384 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001385 }
1386 // constructor returns 'self'.
1387 CodeGenTypes &Types = CGM.getTypes();
1388 QualType IdTy(CGM.getContext().getObjCIdType());
1389 llvm::Value *SelfAsId =
1390 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1391 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001392
1393 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001394 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001395 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001396 }
1397 FinishFunction();
1398}
1399
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001400bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1401 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1402 it++; it++;
1403 const ABIArgInfo &AI = it->info;
1404 // FIXME. Is this sufficient check?
1405 return (AI.getKind() == ABIArgInfo::Indirect);
1406}
1407
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001408bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001409 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001410 return false;
1411 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1412 return FDTTy->getDecl()->hasObjectMember();
1413 return false;
1414}
1415
Daniel Dunbara08dff12008-09-24 04:04:31 +00001416llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001417 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1418 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1419 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001420 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001421}
1422
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001423QualType CodeGenFunction::TypeOfSelfObject() {
1424 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1425 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001426 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1427 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001428 return PTy->getPointeeType();
1429}
1430
Chris Lattnerd4808922009-03-22 21:03:39 +00001431void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001432 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001433 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001434
Daniel Dunbara08dff12008-09-24 04:04:31 +00001435 if (!EnumerationMutationFn) {
1436 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1437 return;
1438 }
1439
Devang Pateld2d66652011-01-19 01:36:36 +00001440 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001441 if (DI)
1442 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001443
Devang Patel297207f2011-06-13 23:15:32 +00001444 // The local variable comes into scope immediately.
1445 AutoVarEmission variable = AutoVarEmission::invalid();
1446 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1447 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1448
John McCall1c926b72011-01-07 01:49:06 +00001449 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001450
Anders Carlsson75658592008-08-31 02:33:12 +00001451 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001452 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001453 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001454 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001455
Anders Carlsson75658592008-08-31 02:33:12 +00001456 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001457 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001458
John McCall1c926b72011-01-07 01:49:06 +00001459 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001460 IdentifierInfo *II[] = {
1461 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1462 &CGM.getContext().Idents.get("objects"),
1463 &CGM.getContext().Idents.get("count")
1464 };
1465 Selector FastEnumSel =
1466 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001467
1468 QualType ItemsTy =
1469 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001470 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001471 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001472 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001473
John McCall53848232011-07-27 01:07:15 +00001474 // Emit the collection pointer. In ARC, we do a retain.
1475 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001476 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001477 Collection = EmitARCRetainScalarExpr(S.getCollection());
1478
1479 // Enter a cleanup to do the release.
1480 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1481 } else {
1482 Collection = EmitScalarExpr(S.getCollection());
1483 }
Mike Stump11289f42009-09-09 15:08:12 +00001484
John McCall91e82dd2011-08-05 00:14:38 +00001485 // The 'continue' label needs to appear within the cleanup for the
1486 // collection object.
1487 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1488
John McCall1c926b72011-01-07 01:49:06 +00001489 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001490 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001491
1492 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001493 Args.add(RValue::get(StatePtr.getPointer()),
1494 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001495
John McCall1c926b72011-01-07 01:49:06 +00001496 // The second argument is a temporary array with space for NumItems
1497 // pointers. We'll actually be loading elements from the array
1498 // pointer written into the control state; this buffer is so that
1499 // collections that *aren't* backed by arrays can still queue up
1500 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001501 Args.add(RValue::get(ItemsPtr.getPointer()),
1502 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001503
John McCall1c926b72011-01-07 01:49:06 +00001504 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001505 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001506 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001507 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001508
John McCall1c926b72011-01-07 01:49:06 +00001509 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001510 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001511 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001512 getContext().UnsignedLongTy,
1513 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001514 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001515
John McCall1c926b72011-01-07 01:49:06 +00001516 // The initial number of objects that were returned in the buffer.
1517 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCall1c926b72011-01-07 01:49:06 +00001519 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1520 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001521
John McCall1c926b72011-01-07 01:49:06 +00001522 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001523
John McCall1c926b72011-01-07 01:49:06 +00001524 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001525 // empty; skip all this. Set the branch weight assuming this has the same
1526 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001527 uint64_t EntryCount = getCurrentProfileCount();
1528 Builder.CreateCondBr(
1529 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1530 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001531 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001532
John McCall1c926b72011-01-07 01:49:06 +00001533 // Otherwise, initialize the loop.
1534 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001535
John McCall1c926b72011-01-07 01:49:06 +00001536 // Save the initial mutations value. This is the value at an
1537 // address that was written into the state object by
1538 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001539 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1540 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1541 llvm::Value *StateMutationsPtr
1542 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001543
John McCall1c926b72011-01-07 01:49:06 +00001544 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001545 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1546 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001547
John McCall1c926b72011-01-07 01:49:06 +00001548 // Start looping. This is the point we return to whenever we have a
1549 // fresh, non-empty batch of objects.
1550 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1551 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001552
John McCall1c926b72011-01-07 01:49:06 +00001553 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001554 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001555 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001556
John McCall1c926b72011-01-07 01:49:06 +00001557 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001558 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001559 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001560
Justin Bogner66242d62015-04-23 23:06:47 +00001561 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001562
John McCall1c926b72011-01-07 01:49:06 +00001563 // Check whether the mutations value has changed from where it was
1564 // at start. StateMutationsPtr should actually be invariant between
1565 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001566 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001567 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001568 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1569 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001570
John McCall1c926b72011-01-07 01:49:06 +00001571 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001572 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001573
John McCall1c926b72011-01-07 01:49:06 +00001574 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1575 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001576
John McCall1c926b72011-01-07 01:49:06 +00001577 // If so, call the enumeration-mutation function.
1578 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001579 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001580 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001581 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001582 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001583 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001584 // FIXME: We shouldn't need to get the function info here, the runtime already
1585 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001586 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1587 FunctionType::ExtInfo(),
1588 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001589 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001590
John McCall1c926b72011-01-07 01:49:06 +00001591 // Otherwise, or if the mutation function returns, just continue.
1592 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001593
John McCall1c926b72011-01-07 01:49:06 +00001594 // Initialize the element variable.
1595 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001596 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001597 LValue elementLValue;
1598 QualType elementType;
1599 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001600 // Initialize the variable, in case it's a __block variable or something.
1601 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001602
John McCall9e2e22f2011-02-22 07:16:58 +00001603 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001604 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001605 VK_LValue, SourceLocation());
1606 elementLValue = EmitLValue(&tempDRE);
1607 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001608 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001609
1610 if (D->isARCPseudoStrong())
1611 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001612 } else {
1613 elementLValue = LValue(); // suppress warning
1614 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001615 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001616 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001617 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001618
1619 // Fetch the buffer out of the enumeration state.
1620 // TODO: this pointer should actually be invariant between
1621 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001622 Address StateItemsPtr = Builder.CreateStructGEP(
1623 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001624 llvm::Value *EnumStateItems =
1625 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001626
John McCall1c926b72011-01-07 01:49:06 +00001627 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001628 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001629 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001630 llvm::Value *CurrentItem =
1631 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001632
John McCall1c926b72011-01-07 01:49:06 +00001633 // Cast that value to the right type.
1634 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1635 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001636
John McCall1c926b72011-01-07 01:49:06 +00001637 // Make sure we have an l-value. Yes, this gets evaluated every
1638 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001639 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001640 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001641 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001642 } else {
1643 EmitScalarInit(CurrentItem, elementLValue);
1644 }
Mike Stump11289f42009-09-09 15:08:12 +00001645
John McCall9e2e22f2011-02-22 07:16:58 +00001646 // If we do have an element variable, this assignment is the end of
1647 // its initialization.
1648 if (elementIsVariable)
1649 EmitAutoVarCleanups(variable);
1650
John McCall1c926b72011-01-07 01:49:06 +00001651 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001652 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001653 {
1654 RunCleanupsScope Scope(*this);
1655 EmitStmt(S.getBody());
1656 }
Anders Carlsson75658592008-08-31 02:33:12 +00001657 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001658
John McCall1c926b72011-01-07 01:49:06 +00001659 // Destroy the element variable now.
1660 elementVariableScope.ForceCleanup();
1661
1662 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001663 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001664
John McCall1c926b72011-01-07 01:49:06 +00001665 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001666
John McCall1c926b72011-01-07 01:49:06 +00001667 // First we check in the local buffer.
1668 llvm::Value *indexPlusOne
1669 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001670
John McCall1c926b72011-01-07 01:49:06 +00001671 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001672 // Set the branch weights based on the simplifying assumption that this is
1673 // like a while-loop, i.e., ignoring that the false branch fetches more
1674 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001675 Builder.CreateCondBr(
1676 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001677 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001678
1679 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1680 count->addIncoming(count, AfterBody.getBlock());
1681
1682 // Otherwise, we have to fetch more elements.
1683 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001684
1685 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001686 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001687 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001688 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001689 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001690
John McCall1c926b72011-01-07 01:49:06 +00001691 // If we got a zero count, we're done.
1692 llvm::Value *refetchCount = CountRV.getScalarVal();
1693
1694 // (note that the message send might split FetchMoreBB)
1695 index->addIncoming(zero, Builder.GetInsertBlock());
1696 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1697
1698 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1699 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001700
Anders Carlsson75658592008-08-31 02:33:12 +00001701 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001702 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001703
John McCall9e2e22f2011-02-22 07:16:58 +00001704 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001705 // If the element was not a declaration, set it to be null.
1706
John McCall1c926b72011-01-07 01:49:06 +00001707 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1708 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001709 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001710 }
1711
Eric Christopher7cdf9482011-10-13 21:45:18 +00001712 if (DI)
1713 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001714
John McCall53848232011-07-27 01:07:15 +00001715 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001716 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001717 PopCleanupBlock();
1718
John McCallad5d61e2010-07-23 21:56:41 +00001719 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001720}
1721
Mike Stump11289f42009-09-09 15:08:12 +00001722void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001723 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001724}
1725
Mike Stump11289f42009-09-09 15:08:12 +00001726void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001727 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1728}
1729
Chris Lattnere132e242008-11-15 21:26:17 +00001730void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001731 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001732 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001733}
1734
John McCall2d637d22011-09-10 06:18:15 +00001735/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001736/// primitive retain.
1737llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1738 llvm::Value *value) {
1739 return EmitARCRetain(type, value);
1740}
1741
1742namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001743 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001744 CallObjCRelease(llvm::Value *object) : object(object) {}
1745 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001746
Craig Topper4f12f102014-03-12 06:41:41 +00001747 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001748 // Releases at the end of the full-expression are imprecise.
1749 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001750 }
1751 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001752}
John McCall31168b02011-06-15 23:02:42 +00001753
John McCall2d637d22011-09-10 06:18:15 +00001754/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001755/// release at the end of the full-expression.
1756llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1757 llvm::Value *object) {
1758 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001759 // conditional.
1760 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001761 return object;
1762}
1763
1764llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1765 llvm::Value *value) {
1766 return EmitARCRetainAutorelease(type, value);
1767}
1768
John McCalleff18842013-03-23 02:35:54 +00001769/// Given a number of pointers, inform the optimizer that they're
1770/// being intrinsically used up until this point in the program.
1771void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1772 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1773 if (!fn) {
1774 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001775 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001776 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1777 }
1778
1779 // This isn't really a "runtime" function, but as an intrinsic it
1780 // doesn't really matter as long as we align things up.
1781 EmitNounwindRuntimeCall(fn, values);
1782}
1783
John McCall31168b02011-06-15 23:02:42 +00001784
1785static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001786 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001787 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001788 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1789
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001790 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001791 // If the target runtime doesn't naturally support ARC, emit weak
1792 // references to the runtime support library. We don't really
1793 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001794 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001795 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001796 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1797 // If we have Native ARC, set nonlazybind attribute for these APIs for
1798 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001799 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001800 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001801 }
John McCall31168b02011-06-15 23:02:42 +00001802
1803 return fn;
1804}
1805
1806/// Perform an operation having the signature
1807/// i8* (i8*)
1808/// where a null input causes a no-op and returns null.
1809static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1810 llvm::Value *value,
1811 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001812 StringRef fnName,
1813 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001814 if (isa<llvm::ConstantPointerNull>(value)) return value;
1815
1816 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001817 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001818 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001819 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1820 }
1821
1822 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001823 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001824 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1825
1826 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001827 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001828 if (isTailCall)
1829 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001830
1831 // Cast the result back to the original type.
1832 return CGF.Builder.CreateBitCast(call, origType);
1833}
1834
1835/// Perform an operation having the following signature:
1836/// i8* (i8**)
1837static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001838 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001839 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001840 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001841 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001842 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001843 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001844 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1845 }
1846
1847 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001848 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001849 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1850
1851 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001852 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001853
1854 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001855 if (origType != CGF.Int8PtrTy)
1856 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001857
1858 return result;
1859}
1860
1861/// Perform an operation having the following signature:
1862/// i8* (i8**, i8*)
1863static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001864 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001865 llvm::Value *value,
1866 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001867 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001868 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001869 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001870
1871 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001872 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001873
Chris Lattner2192fe52011-07-18 04:24:23 +00001874 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001875 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1876 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1877 }
1878
Chris Lattner2192fe52011-07-18 04:24:23 +00001879 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001880
John McCall882987f2013-02-28 19:01:20 +00001881 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001882 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001883 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1884 };
1885 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001886
Craig Topper8a13c412014-05-21 05:09:00 +00001887 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001888
1889 return CGF.Builder.CreateBitCast(result, origType);
1890}
1891
1892/// Perform an operation having the following signature:
1893/// void (i8**, i8**)
1894static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001895 Address dst,
1896 Address src,
John McCall31168b02011-06-15 23:02:42 +00001897 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001898 StringRef fnName) {
John McCall7f416cc2015-09-08 08:05:57 +00001899 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00001900
1901 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001902 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1903
Chris Lattner2192fe52011-07-18 04:24:23 +00001904 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001905 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1906 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1907 }
1908
John McCall882987f2013-02-28 19:01:20 +00001909 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001910 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1911 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00001912 };
1913 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001914}
1915
1916/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001917/// call i8* \@objc_retain(i8* %value)
1918/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001919llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1920 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001921 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001922 else
1923 return EmitARCRetainNonBlock(value);
1924}
1925
1926/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001927/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001928llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1929 return emitARCValueOperation(*this, value,
1930 CGM.getARCEntrypoints().objc_retain,
1931 "objc_retain");
1932}
1933
1934/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001935/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001936///
1937/// \param mandatory - If false, emit the call with metadata
1938/// indicating that it's okay for the optimizer to eliminate this call
1939/// if it can prove that the block never escapes except down the stack.
1940llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1941 bool mandatory) {
1942 llvm::Value *result
1943 = emitARCValueOperation(*this, value,
1944 CGM.getARCEntrypoints().objc_retainBlock,
1945 "objc_retainBlock");
1946
1947 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1948 // tell the optimizer that it doesn't need to do this copy if the
1949 // block doesn't escape, where being passed as an argument doesn't
1950 // count as escaping.
1951 if (!mandatory && isa<llvm::Instruction>(result)) {
1952 llvm::CallInst *call
1953 = cast<llvm::CallInst>(result->stripPointerCasts());
1954 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1955
John McCallff613032011-10-04 06:23:45 +00001956 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001957 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00001958 }
1959
1960 return result;
John McCall31168b02011-06-15 23:02:42 +00001961}
1962
1963/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001964/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001965///
1966/// Yes, this function name is one character away from a different
1967/// call with completely different semantics.
1968llvm::Value *
1969CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1970 // Fetch the void(void) inline asm which marks that we're going to
1971 // retain the autoreleased return value.
1972 llvm::InlineAsm *&marker
1973 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1974 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001975 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001976 = CGM.getTargetCodeGenInfo()
1977 .getARCRetainAutoreleasedReturnValueMarker();
1978
1979 // If we have an empty assembly string, there's nothing to do.
1980 if (assembly.empty()) {
1981
1982 // Otherwise, at -O0, build an inline asm that we're going to call
1983 // in a moment.
1984 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1985 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001986 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001987
1988 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1989
1990 // If we're at -O1 and above, we don't want to litter the code
1991 // with this marker yet, so leave a breadcrumb for the ARC
1992 // optimizer to pick up.
1993 } else {
1994 llvm::NamedMDNode *metadata =
1995 CGM.getModule().getOrInsertNamedMetadata(
1996 "clang.arc.retainAutoreleasedReturnValueMarker");
1997 assert(metadata->getNumOperands() <= 1);
1998 if (metadata->getNumOperands() == 0) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001999 metadata->addOperand(llvm::MDNode::get(
2000 getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
John McCall31168b02011-06-15 23:02:42 +00002001 }
2002 }
2003 }
2004
2005 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002006 if (marker)
David Blaikie4ba525b2015-07-14 17:27:39 +00002007 Builder.CreateCall(marker);
John McCall31168b02011-06-15 23:02:42 +00002008
2009 return emitARCValueOperation(*this, value,
2010 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
2011 "objc_retainAutoreleasedReturnValue");
2012}
2013
2014/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002015/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002016void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2017 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002018 if (isa<llvm::ConstantPointerNull>(value)) return;
2019
2020 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2021 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002022 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002023 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002024 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2025 }
2026
2027 // Cast the argument to 'id'.
2028 value = Builder.CreateBitCast(value, Int8PtrTy);
2029
2030 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002031 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002032
John McCallcdda29c2013-03-13 03:10:54 +00002033 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002034 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002035 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002036 }
2037}
2038
John McCalle68b8f42012-10-17 02:28:37 +00002039/// Destroy a __strong variable.
2040///
2041/// At -O0, emit a call to store 'null' into the address;
2042/// instrumenting tools prefer this because the address is exposed,
2043/// but it's relatively cumbersome to optimize.
2044///
2045/// At -O1 and above, just load and call objc_release.
2046///
2047/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002048void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002049 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002050 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002051 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002052 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2053 return;
2054 }
2055
2056 llvm::Value *value = Builder.CreateLoad(addr);
2057 EmitARCRelease(value, precise);
2058}
2059
John McCall31168b02011-06-15 23:02:42 +00002060/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002061/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002062llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002063 llvm::Value *value,
2064 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002065 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002066
2067 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2068 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002069 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002070 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002071 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2072 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2073 }
2074
John McCall882987f2013-02-28 19:01:20 +00002075 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002076 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002077 Builder.CreateBitCast(value, Int8PtrTy)
2078 };
2079 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002080
Craig Topper8a13c412014-05-21 05:09:00 +00002081 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002082 return value;
2083}
2084
2085/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002086/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002087/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002088llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002089 llvm::Value *newValue,
2090 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002091 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002092 bool isBlock = type->isBlockPointerType();
2093
2094 // Use a store barrier at -O0 unless this is a block type or the
2095 // lvalue is inadequately aligned.
2096 if (shouldUseFusedARCCalls() &&
2097 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002098 (dst.getAlignment().isZero() ||
2099 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002100 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2101 }
2102
2103 // Otherwise, split it out.
2104
2105 // Retain the new value.
2106 newValue = EmitARCRetain(type, newValue);
2107
2108 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002109 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002110
2111 // Store. We do this before the release so that any deallocs won't
2112 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002113 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002114
2115 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002116 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002117
2118 return newValue;
2119}
2120
2121/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002122/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002123llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2124 return emitARCValueOperation(*this, value,
2125 CGM.getARCEntrypoints().objc_autorelease,
2126 "objc_autorelease");
2127}
2128
2129/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002130/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002131llvm::Value *
2132CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2133 return emitARCValueOperation(*this, value,
2134 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002135 "objc_autoreleaseReturnValue",
2136 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002137}
2138
2139/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002140/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002141llvm::Value *
2142CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2143 return emitARCValueOperation(*this, value,
2144 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002145 "objc_retainAutoreleaseReturnValue",
2146 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002147}
2148
2149/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002150/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002151/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002152/// %retain = call i8* \@objc_retainBlock(i8* %value)
2153/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002154llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2155 llvm::Value *value) {
2156 if (!type->isBlockPointerType())
2157 return EmitARCRetainAutoreleaseNonBlock(value);
2158
2159 if (isa<llvm::ConstantPointerNull>(value)) return value;
2160
Chris Lattner2192fe52011-07-18 04:24:23 +00002161 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002162 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002163 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002164 value = EmitARCAutorelease(value);
2165 return Builder.CreateBitCast(value, origType);
2166}
2167
2168/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002169/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002170llvm::Value *
2171CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2172 return emitARCValueOperation(*this, value,
2173 CGM.getARCEntrypoints().objc_retainAutorelease,
2174 "objc_retainAutorelease");
2175}
2176
James Dennett14c41ea2012-06-22 05:41:30 +00002177/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002178/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
John McCall7f416cc2015-09-08 08:05:57 +00002179llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002180 return emitARCLoadOperation(*this, addr,
2181 CGM.getARCEntrypoints().objc_loadWeak,
2182 "objc_loadWeak");
2183}
2184
James Dennett14c41ea2012-06-22 05:41:30 +00002185/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002186llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002187 return emitARCLoadOperation(*this, addr,
2188 CGM.getARCEntrypoints().objc_loadWeakRetained,
2189 "objc_loadWeakRetained");
2190}
2191
James Dennett14c41ea2012-06-22 05:41:30 +00002192/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002193/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002194llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002195 llvm::Value *value,
2196 bool ignored) {
2197 return emitARCStoreOperation(*this, addr, value,
2198 CGM.getARCEntrypoints().objc_storeWeak,
2199 "objc_storeWeak", ignored);
2200}
2201
James Dennett14c41ea2012-06-22 05:41:30 +00002202/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002203/// Returns %value. %addr is known to not have a current weak entry.
2204/// Essentially equivalent to:
2205/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002206void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002207 // If we're initializing to null, just write null to memory; no need
2208 // to get the runtime involved. But don't do this if optimization
2209 // is enabled, because accounting for this would make the optimizer
2210 // much more complicated.
2211 if (isa<llvm::ConstantPointerNull>(value) &&
2212 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2213 Builder.CreateStore(value, addr);
2214 return;
2215 }
2216
2217 emitARCStoreOperation(*this, addr, value,
2218 CGM.getARCEntrypoints().objc_initWeak,
2219 "objc_initWeak", /*ignored*/ true);
2220}
2221
James Dennett14c41ea2012-06-22 05:41:30 +00002222/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002223/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002224void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002225 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2226 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002227 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002228 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002229 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2230 }
2231
2232 // Cast the argument to 'id*'.
2233 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2234
John McCall7f416cc2015-09-08 08:05:57 +00002235 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002236}
2237
James Dennett14c41ea2012-06-22 05:41:30 +00002238/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002239/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2240/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002241void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002242 emitARCCopyOperation(*this, dst, src,
2243 CGM.getARCEntrypoints().objc_moveWeak,
2244 "objc_moveWeak");
2245}
2246
James Dennett14c41ea2012-06-22 05:41:30 +00002247/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002248/// Disregards the current value in %dest. Essentially
2249/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002250void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002251 emitARCCopyOperation(*this, dst, src,
2252 CGM.getARCEntrypoints().objc_copyWeak,
2253 "objc_copyWeak");
2254}
2255
2256/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002257/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002258llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2259 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2260 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002261 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002262 llvm::FunctionType::get(Int8PtrTy, false);
2263 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2264 }
2265
John McCall882987f2013-02-28 19:01:20 +00002266 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002267}
2268
2269/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002270/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002271void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2272 assert(value->getType() == Int8PtrTy);
2273
2274 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2275 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002276 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002277 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002278
2279 // We don't want to use a weak import here; instead we should not
2280 // fall into this path.
2281 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2282 }
2283
John McCallb7ff6db2013-04-16 21:29:40 +00002284 // objc_autoreleasePoolPop can throw.
2285 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002286}
2287
2288/// Produce the code to do an MRR version objc_autoreleasepool_push.
2289/// Which is: [[NSAutoreleasePool alloc] init];
2290/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2291/// init is declared as: - (id) init; in its NSObject super class.
2292///
2293llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2294 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002295 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002296 // [NSAutoreleasePool alloc]
2297 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2298 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2299 CallArgList Args;
2300 RValue AllocRV =
2301 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2302 getContext().getObjCIdType(),
2303 AllocSel, Receiver, Args);
2304
2305 // [Receiver init]
2306 Receiver = AllocRV.getScalarVal();
2307 II = &CGM.getContext().Idents.get("init");
2308 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2309 RValue InitRV =
2310 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2311 getContext().getObjCIdType(),
2312 InitSel, Receiver, Args);
2313 return InitRV.getScalarVal();
2314}
2315
2316/// Produce the code to do a primitive release.
2317/// [tmp drain];
2318void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2319 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2320 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2321 CallArgList Args;
2322 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2323 getContext().VoidTy, DrainSel, Arg, Args);
2324}
2325
John McCall82fe67b2011-07-09 01:37:26 +00002326void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002327 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002328 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002329 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002330}
2331
2332void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002333 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002334 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002335 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002336}
2337
2338void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002339 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002340 QualType type) {
2341 CGF.EmitARCDestroyWeak(addr);
2342}
2343
John McCall31168b02011-06-15 23:02:42 +00002344namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002345 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002346 llvm::Value *Token;
2347
2348 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2349
Craig Topper4f12f102014-03-12 06:41:41 +00002350 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002351 CGF.EmitObjCAutoreleasePoolPop(Token);
2352 }
2353 };
David Blaikie7e70d682015-08-18 22:40:54 +00002354 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002355 llvm::Value *Token;
2356
2357 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2358
Craig Topper4f12f102014-03-12 06:41:41 +00002359 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002360 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2361 }
2362 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002363}
John McCall31168b02011-06-15 23:02:42 +00002364
2365void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002366 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002367 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2368 else
2369 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2370}
2371
John McCall31168b02011-06-15 23:02:42 +00002372static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2373 LValue lvalue,
2374 QualType type) {
2375 switch (type.getObjCLifetime()) {
2376 case Qualifiers::OCL_None:
2377 case Qualifiers::OCL_ExplicitNone:
2378 case Qualifiers::OCL_Strong:
2379 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002380 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2381 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002382 false);
2383
2384 case Qualifiers::OCL_Weak:
2385 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2386 true);
2387 }
2388
2389 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002390}
2391
2392static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2393 const Expr *e) {
2394 e = e->IgnoreParens();
2395 QualType type = e->getType();
2396
John McCall154a2fd2011-08-30 00:57:29 +00002397 // If we're loading retained from a __strong xvalue, we can avoid
2398 // an extra retain/release pair by zeroing out the source of this
2399 // "move" operation.
2400 if (e->isXValue() &&
2401 !type.isConstQualified() &&
2402 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2403 // Emit the lvalue.
2404 LValue lv = CGF.EmitLValue(e);
2405
2406 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002407 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2408 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002409
2410 // Set the source pointer to NULL.
2411 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2412
2413 return TryEmitResult(result, true);
2414 }
2415
John McCall31168b02011-06-15 23:02:42 +00002416 // As a very special optimization, in ARC++, if the l-value is the
2417 // result of a non-volatile assignment, do a simple retain of the
2418 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002419 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002420 !type.isVolatileQualified() &&
2421 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2422 isa<BinaryOperator>(e) &&
2423 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2424 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2425
2426 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2427}
2428
2429static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2430 llvm::Value *value);
2431
2432/// Given that the given expression is some sort of call (which does
2433/// not return retained), emit a retain following it.
2434static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2435 llvm::Value *value = CGF.EmitScalarExpr(e);
2436 return emitARCRetainAfterCall(CGF, value);
2437}
2438
2439static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2440 llvm::Value *value) {
2441 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2442 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2443
2444 // Place the retain immediately following the call.
2445 CGF.Builder.SetInsertPoint(call->getParent(),
2446 ++llvm::BasicBlock::iterator(call));
2447 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2448
2449 CGF.Builder.restoreIP(ip);
2450 return value;
2451 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2452 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2453
2454 // Place the retain at the beginning of the normal destination block.
2455 llvm::BasicBlock *BB = invoke->getNormalDest();
2456 CGF.Builder.SetInsertPoint(BB, BB->begin());
2457 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2458
2459 CGF.Builder.restoreIP(ip);
2460 return value;
2461
2462 // Bitcasts can arise because of related-result returns. Rewrite
2463 // the operand.
2464 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2465 llvm::Value *operand = bitcast->getOperand(0);
2466 operand = emitARCRetainAfterCall(CGF, operand);
2467 bitcast->setOperand(0, operand);
2468 return bitcast;
2469
2470 // Generic fall-back case.
2471 } else {
2472 // Retain using the non-block variant: we never need to do a copy
2473 // of a block that's been returned to us.
2474 return CGF.EmitARCRetainNonBlock(value);
2475 }
2476}
2477
John McCallcd78e802011-09-10 01:16:55 +00002478/// Determine whether it might be important to emit a separate
2479/// objc_retain_block on the result of the given expression, or
2480/// whether it's okay to just emit it in a +1 context.
2481static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2482 assert(e->getType()->isBlockPointerType());
2483 e = e->IgnoreParens();
2484
2485 // For future goodness, emit block expressions directly in +1
2486 // contexts if we can.
2487 if (isa<BlockExpr>(e))
2488 return false;
2489
2490 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2491 switch (cast->getCastKind()) {
2492 // Emitting these operations in +1 contexts is goodness.
2493 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002494 case CK_ARCReclaimReturnedObject:
2495 case CK_ARCConsumeObject:
2496 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002497 return false;
2498
2499 // These operations preserve a block type.
2500 case CK_NoOp:
2501 case CK_BitCast:
2502 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2503
2504 // These operations are known to be bad (or haven't been considered).
2505 case CK_AnyPointerToBlockPointerCast:
2506 default:
2507 return true;
2508 }
2509 }
2510
2511 return true;
2512}
2513
John McCallfe96e0b2011-11-06 09:01:30 +00002514/// Try to emit a PseudoObjectExpr at +1.
2515///
2516/// This massively duplicates emitPseudoObjectRValue.
2517static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2518 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002519 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002520
2521 // Find the result expression.
2522 const Expr *resultExpr = E->getResultExpr();
2523 assert(resultExpr);
2524 TryEmitResult result;
2525
2526 for (PseudoObjectExpr::const_semantics_iterator
2527 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2528 const Expr *semantic = *i;
2529
2530 // If this semantic expression is an opaque value, bind it
2531 // to the result of its source expression.
2532 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2533 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2534 OVMA opaqueData;
2535
2536 // If this semantic is the result of the pseudo-object
2537 // expression, try to evaluate the source as +1.
2538 if (ov == resultExpr) {
2539 assert(!OVMA::shouldBindAsLValue(ov));
2540 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2541 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2542
2543 // Otherwise, just bind it.
2544 } else {
2545 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2546 }
2547 opaques.push_back(opaqueData);
2548
2549 // Otherwise, if the expression is the result, evaluate it
2550 // and remember the result.
2551 } else if (semantic == resultExpr) {
2552 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2553
2554 // Otherwise, evaluate the expression in an ignored context.
2555 } else {
2556 CGF.EmitIgnoredExpr(semantic);
2557 }
2558 }
2559
2560 // Unbind all the opaques now.
2561 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2562 opaques[i].unbind(CGF);
2563
2564 return result;
2565}
2566
John McCall31168b02011-06-15 23:02:42 +00002567static TryEmitResult
2568tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002569 // We should *never* see a nested full-expression here, because if
2570 // we fail to emit at +1, our caller must not retain after we close
2571 // out the full-expression.
2572 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002573
John McCall31168b02011-06-15 23:02:42 +00002574 // The desired result type, if it differs from the type of the
2575 // ultimate opaque expression.
Craig Topper8a13c412014-05-21 05:09:00 +00002576 llvm::Type *resultType = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002577
2578 while (true) {
2579 e = e->IgnoreParens();
2580
2581 // There's a break at the end of this if-chain; anything
2582 // that wants to keep looping has to explicitly continue.
2583 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2584 switch (ce->getCastKind()) {
2585 // No-op casts don't change the type, so we just ignore them.
2586 case CK_NoOp:
2587 e = ce->getSubExpr();
2588 continue;
2589
2590 case CK_LValueToRValue: {
2591 TryEmitResult loadResult
2592 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2593 if (resultType) {
2594 llvm::Value *value = loadResult.getPointer();
2595 value = CGF.Builder.CreateBitCast(value, resultType);
2596 loadResult.setPointer(value);
2597 }
2598 return loadResult;
2599 }
2600
2601 // These casts can change the type, so remember that and
2602 // soldier on. We only need to remember the outermost such
2603 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002604 case CK_CPointerToObjCPointerCast:
2605 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002606 case CK_AnyPointerToBlockPointerCast:
2607 case CK_BitCast:
2608 if (!resultType)
2609 resultType = CGF.ConvertType(ce->getType());
2610 e = ce->getSubExpr();
2611 assert(e->getType()->hasPointerRepresentation());
2612 continue;
2613
2614 // For consumptions, just emit the subexpression and thus elide
2615 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002616 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002617 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2618 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2619 return TryEmitResult(result, true);
2620 }
2621
John McCallcd78e802011-09-10 01:16:55 +00002622 // Block extends are net +0. Naively, we could just recurse on
2623 // the subexpression, but actually we need to ensure that the
2624 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002625 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002626 llvm::Value *result; // will be a +0 value
2627
2628 // If we can't safely assume the sub-expression will produce a
2629 // block-copied value, emit the sub-expression at +0.
2630 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2631 result = CGF.EmitScalarExpr(ce->getSubExpr());
2632
2633 // Otherwise, try to emit the sub-expression at +1 recursively.
2634 } else {
2635 TryEmitResult subresult
2636 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2637 result = subresult.getPointer();
2638
2639 // If that produced a retained value, just use that,
2640 // possibly casting down.
2641 if (subresult.getInt()) {
2642 if (resultType)
2643 result = CGF.Builder.CreateBitCast(result, resultType);
2644 return TryEmitResult(result, true);
2645 }
2646
2647 // Otherwise it's +0.
2648 }
2649
2650 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002651 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002652 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2653 return TryEmitResult(result, true);
2654 }
2655
John McCall4db5c3c2011-07-07 06:58:02 +00002656 // For reclaims, emit the subexpression as a retained call and
2657 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002658 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002659 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2660 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2661 return TryEmitResult(result, true);
2662 }
2663
John McCall31168b02011-06-15 23:02:42 +00002664 default:
2665 break;
2666 }
2667
2668 // Skip __extension__.
2669 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2670 if (op->getOpcode() == UO_Extension) {
2671 e = op->getSubExpr();
2672 continue;
2673 }
2674
2675 // For calls and message sends, use the retained-call logic.
2676 // Delegate inits are a special case in that they're the only
2677 // returns-retained expression that *isn't* surrounded by
2678 // a consume.
2679 } else if (isa<CallExpr>(e) ||
2680 (isa<ObjCMessageExpr>(e) &&
2681 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2682 llvm::Value *result = emitARCRetainCall(CGF, e);
2683 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2684 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002685
2686 // Look through pseudo-object expressions.
2687 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2688 TryEmitResult result
2689 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2690 if (resultType) {
2691 llvm::Value *value = result.getPointer();
2692 value = CGF.Builder.CreateBitCast(value, resultType);
2693 result.setPointer(value);
2694 }
2695 return result;
John McCall31168b02011-06-15 23:02:42 +00002696 }
2697
2698 // Conservatively halt the search at any other expression kind.
2699 break;
2700 }
2701
2702 // We didn't find an obvious production, so emit what we've got and
2703 // tell the caller that we didn't manage to retain.
2704 llvm::Value *result = CGF.EmitScalarExpr(e);
2705 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2706 return TryEmitResult(result, false);
2707}
2708
2709static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2710 LValue lvalue,
2711 QualType type) {
2712 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2713 llvm::Value *value = result.getPointer();
2714 if (!result.getInt())
2715 value = CGF.EmitARCRetain(type, value);
2716 return value;
2717}
2718
2719/// EmitARCRetainScalarExpr - Semantically equivalent to
2720/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2721/// best-effort attempt to peephole expressions that naturally produce
2722/// retained objects.
2723llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002724 // The retain needs to happen within the full-expression.
2725 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2726 enterFullExpression(cleanups);
2727 RunCleanupsScope scope(*this);
2728 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2729 }
2730
John McCall31168b02011-06-15 23:02:42 +00002731 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2732 llvm::Value *value = result.getPointer();
2733 if (!result.getInt())
2734 value = EmitARCRetain(e->getType(), value);
2735 return value;
2736}
2737
2738llvm::Value *
2739CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002740 // The retain needs to happen within the full-expression.
2741 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2742 enterFullExpression(cleanups);
2743 RunCleanupsScope scope(*this);
2744 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2745 }
2746
John McCall31168b02011-06-15 23:02:42 +00002747 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2748 llvm::Value *value = result.getPointer();
2749 if (result.getInt())
2750 value = EmitARCAutorelease(value);
2751 else
2752 value = EmitARCRetainAutorelease(e->getType(), value);
2753 return value;
2754}
2755
John McCallff613032011-10-04 06:23:45 +00002756llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2757 llvm::Value *result;
2758 bool doRetain;
2759
2760 if (shouldEmitSeparateBlockRetain(e)) {
2761 result = EmitScalarExpr(e);
2762 doRetain = true;
2763 } else {
2764 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2765 result = subresult.getPointer();
2766 doRetain = !subresult.getInt();
2767 }
2768
2769 if (doRetain)
2770 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2771 return EmitObjCConsumeObject(e->getType(), result);
2772}
2773
John McCall248512a2011-10-01 10:32:24 +00002774llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2775 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002776 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002777 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002778 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002779 return EmitARCRetainAutoreleaseScalarExpr(expr);
2780 }
2781
2782 // Otherwise, use the normal scalar-expression emission. The
2783 // exception machinery doesn't do anything special with the
2784 // exception like retaining it, so there's no safety associated with
2785 // only running cleanups after the throw has started, and when it
2786 // matters it tends to be substantially inferior code.
2787 return EmitScalarExpr(expr);
2788}
2789
John McCall31168b02011-06-15 23:02:42 +00002790std::pair<LValue,llvm::Value*>
2791CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2792 bool ignored) {
2793 // Evaluate the RHS first.
2794 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2795 llvm::Value *value = result.getPointer();
2796
John McCallb726a552011-07-28 07:23:35 +00002797 bool hasImmediateRetain = result.getInt();
2798
2799 // If we didn't emit a retained object, and the l-value is of block
2800 // type, then we need to emit the block-retain immediately in case
2801 // it invalidates the l-value.
2802 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002803 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002804 hasImmediateRetain = true;
2805 }
2806
John McCall31168b02011-06-15 23:02:42 +00002807 LValue lvalue = EmitLValue(e->getLHS());
2808
2809 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002810 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002811 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002812 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002813 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002814 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002815 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002816 }
2817
2818 return std::pair<LValue,llvm::Value*>(lvalue, value);
2819}
2820
2821std::pair<LValue,llvm::Value*>
2822CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2823 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2824 LValue lvalue = EmitLValue(e->getLHS());
2825
Eli Friedmana0544d62011-12-03 04:14:32 +00002826 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002827
2828 return std::pair<LValue,llvm::Value*>(lvalue, value);
2829}
2830
2831void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002832 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002833 const Stmt *subStmt = ARPS.getSubStmt();
2834 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2835
2836 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002837 if (DI)
2838 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002839
2840 // Keep track of the current cleanup stack depth.
2841 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002842 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002843 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2844 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2845 } else {
2846 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2847 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2848 }
2849
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00002850 for (const auto *I : S.body())
2851 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00002852
Eric Christopher7cdf9482011-10-13 21:45:18 +00002853 if (DI)
2854 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002855}
John McCall1bd25562011-06-24 23:21:27 +00002856
2857/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2858/// make sure it survives garbage collection until this point.
2859void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2860 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002861 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002862 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002863 llvm::Value *extender
2864 = llvm::InlineAsm::get(extenderType,
2865 /* assembly */ "",
2866 /* constraints */ "r",
2867 /* side effects */ true);
2868
2869 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00002870 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00002871}
2872
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002873/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002874/// non-trivial copy assignment function, produce following helper function.
2875/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2876///
2877llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002878CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2879 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002880 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002881 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002882 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002883 QualType Ty = PID->getPropertyIvarDecl()->getType();
2884 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002885 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002886 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002887 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002888 return nullptr;
2889 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002890 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002891 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002892 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2893 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2894 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002895
2896 ASTContext &C = getContext();
2897 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002898 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002899 FunctionDecl *FD = FunctionDecl::Create(C,
2900 C.getTranslationUnitDecl(),
2901 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002902 SourceLocation(), II, C.VoidTy,
2903 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002904 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002905 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002906
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002907 QualType DestTy = C.getPointerType(Ty);
2908 QualType SrcTy = Ty;
2909 SrcTy.addConst();
2910 SrcTy = C.getPointerType(SrcTy);
2911
2912 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002913 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002914 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002915 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002916 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002917
2918 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2919 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2920
John McCalla729c622012-02-17 03:33:10 +00002921 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002922
2923 llvm::Function *Fn =
2924 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002925 "__assign_helper_atomic_property_",
2926 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002927
Adrian Prantl22e66b42014-04-11 01:13:04 +00002928 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002929
John McCall113bee02012-03-10 09:33:50 +00002930 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2931 VK_RValue, SourceLocation());
2932 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2933 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002934
John McCall113bee02012-03-10 09:33:50 +00002935 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2936 VK_RValue, SourceLocation());
2937 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2938 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002939
John McCall113bee02012-03-10 09:33:50 +00002940 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002941 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002942 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002943 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002944 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002945
2946 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002947
2948 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002949 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002950 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002951 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002952}
2953
2954llvm::Constant *
2955CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2956 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002957 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002958 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002959 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002960 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2961 QualType Ty = PD->getType();
2962 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002963 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002964 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002965 return nullptr;
2966 llvm::Constant *HelperFn = nullptr;
2967
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002968 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002969 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002970 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2971 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2972 return HelperFn;
2973
2974
2975 ASTContext &C = getContext();
2976 IdentifierInfo *II
2977 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2978 FunctionDecl *FD = FunctionDecl::Create(C,
2979 C.getTranslationUnitDecl(),
2980 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002981 SourceLocation(), II, C.VoidTy,
2982 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002983 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002984 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002985
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002986 QualType DestTy = C.getPointerType(Ty);
2987 QualType SrcTy = Ty;
2988 SrcTy.addConst();
2989 SrcTy = C.getPointerType(SrcTy);
2990
2991 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002992 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002993 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002994 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002995 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002996
2997 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2998 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2999
John McCalla729c622012-02-17 03:33:10 +00003000 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003001
3002 llvm::Function *Fn =
3003 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3004 "__copy_helper_atomic_property_", &CGM.getModule());
3005
Adrian Prantl22e66b42014-04-11 01:13:04 +00003006 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003007
John McCall113bee02012-03-10 09:33:50 +00003008 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003009 VK_RValue, SourceLocation());
3010
John McCall113bee02012-03-10 09:33:50 +00003011 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3012 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003013
3014 CXXConstructExpr *CXXConstExpr =
3015 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3016
3017 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003018 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003019 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3020 CXXConstExpr->arg_end());
3021
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003022 CXXConstructExpr *TheCXXConstructExpr =
3023 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3024 CXXConstExpr->getConstructor(),
3025 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003026 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003027 CXXConstExpr->hadMultipleCandidates(),
3028 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003029 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003030 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003031 CXXConstExpr->getConstructionKind(),
3032 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003033
John McCall113bee02012-03-10 09:33:50 +00003034 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3035 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003036
John McCall113bee02012-03-10 09:33:50 +00003037 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003038 CharUnits Alignment
3039 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003040 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003041 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3042 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003043 AggValueSlot::IsDestructed,
3044 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003045 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003046
3047 FinishFunction();
3048 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3049 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3050 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003051}
3052
Eli Friedmanec75fec2012-02-28 01:08:45 +00003053llvm::Value *
3054CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3055 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003056 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3057 Selector CopySelector =
3058 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003059 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3060 Selector AutoreleaseSelector =
3061 getContext().Selectors.getNullarySelector(AutoreleaseID);
3062
3063 // Emit calls to retain/autorelease.
3064 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3065 llvm::Value *Val = Block;
3066 RValue Result;
3067 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003068 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003069 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003070 Val = Result.getScalarVal();
3071 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3072 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003073 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003074 Val = Result.getScalarVal();
3075 return Val;
3076}
3077
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003078
Ted Kremenek43e06332008-04-09 15:51:31 +00003079CGObjCRuntime::~CGObjCRuntime() {}