blob: 785a12665b9508b4854c746ead0e50d9b862349f [file] [log] [blame]
Erik Pilkington9227e102017-02-21 20:31:01 +00001//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
Anders Carlsson76f4a902007-08-21 17:43:55 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson76f4a902007-08-21 17:43:55 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Objective-C code as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
Devang Pateld2d66652011-01-19 01:36:36 +000013#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000014#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000017#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000021#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000022#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000032static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
33 QualType ET,
34 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000035
36/// Given the address of a variable of pointer type, find the correct
37/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000038static llvm::Constant *getNullForVariable(Address addr) {
39 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000040 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
41}
42
Chris Lattnerb1d329d2008-06-24 17:04:18 +000043/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000044llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000045{
Fangrui Song6907ce22018-07-30 19:24:48 +000046 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000047 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000048 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000049 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000050}
51
Patrick Beard0caa3942012-04-19 00:25:12 +000052/// EmitObjCBoxedExpr - This routine generates code to call
53/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000054/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
55/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000056///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000057llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000058CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000059 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000060 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000061 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000062 const Expr *SubExpr = E->getSubExpr();
Patrick Beard0caa3942012-04-19 00:25:12 +000063 assert(BoxingMethod && "BoxingMethod is null");
64 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
65 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000066
Ted Kremeneke65b0862012-03-06 20:05:56 +000067 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000068 // Assumes that the method was introduced in the class that should be
69 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000070 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000071 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000072 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000073
Ted Kremeneke65b0862012-03-06 20:05:56 +000074 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000075 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
76 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000077
78 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000079 // via [NSValue valueWithBytes:objCType:]
80 const QualType ValueType(SubExpr->getType().getCanonicalType());
81 if (ValueType->isObjCBoxableRecordType()) {
82 // Emit CodeGen for first parameter
83 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000084 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000085 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000086 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
87 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000088
89 // Create char array to store type encoding
90 std::string Str;
91 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000092 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +000093
Alex Denisovfde64952015-06-26 05:28:36 +000094 // Cast type encoding to correct type
95 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
96 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
97 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
98
99 Args.add(RValue::get(Cast), EncodingQT);
100 } else {
101 Args.add(EmitAnyExpr(SubExpr), ArgQT);
102 }
Alp Toker314cc812014-01-25 16:55:45 +0000103
104 RValue result = Runtime.GenerateMessageSend(
105 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
106 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000107 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000108 ConvertType(E->getType()));
109}
110
111llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000112 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000113 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000114 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
116 if (!ALE)
117 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000118
119 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000120 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000122 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
123 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
124 QualType IdTy(CGM.getContext().getObjCIdType());
125 llvm::Constant *Constant =
126 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000127 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000128 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000129 cast<llvm::LoadInst>(Ptr)->setMetadata(
130 CGM.getModule().getMDKindID("invariant.load"),
131 llvm::MDNode::get(getLLVMContext(), None));
132 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000133 }
134
135 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000136 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
137 NumElements);
138 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 QualType ElementArrayType
140 = Context.getConstantArrayType(ElementType, APNumElements,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141 ArrayType::Normal, /*IndexTypeQuals=*/0);
142
143 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000144 Address Objects = CreateMemTemp(ElementArrayType, "objects");
145 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000146 if (DLE)
147 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
John McCall770a4c12013-04-04 00:20:38 +0000149 // In ARC, we may need to do extra work to keep all the keys and
150 // values alive until after the call.
151 SmallVector<llvm::Value *, 16> NeededObjects;
152 bool TrackNeededObjects =
153 (getLangOpts().ObjCAutoRefCount &&
154 CGM.getCodeGenOpts().OptimizationLevel != 0);
155
Ted Kremeneke65b0862012-03-06 20:05:56 +0000156 // Perform the actual initialialization of the array(s).
157 for (uint64_t i = 0; i < NumElements; i++) {
158 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000159 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000160 const Expr *Rhs = ALE->getElement(i);
James Y Knight751fe282019-02-09 22:22:28 +0000161 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
162 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000163
164 llvm::Value *value = EmitScalarExpr(Rhs);
165 EmitStoreThroughLValue(RValue::get(value), LV, true);
166 if (TrackNeededObjects) {
167 NeededObjects.push_back(value);
168 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000169 } else {
John McCall770a4c12013-04-04 00:20:38 +0000170 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171 const Expr *Key = DLE->getKeyValueElement(i).Key;
James Y Knight751fe282019-02-09 22:22:28 +0000172 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
173 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000174 llvm::Value *keyValue = EmitScalarExpr(Key);
175 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000176
John McCall770a4c12013-04-04 00:20:38 +0000177 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000178 const Expr *Value = DLE->getKeyValueElement(i).Value;
James Y Knight751fe282019-02-09 22:22:28 +0000179 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
180 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000181 llvm::Value *valueValue = EmitScalarExpr(Value);
182 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
183 if (TrackNeededObjects) {
184 NeededObjects.push_back(keyValue);
185 NeededObjects.push_back(valueValue);
186 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000187 }
188 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000189
Ted Kremeneke65b0862012-03-06 20:05:56 +0000190 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000191 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000192 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
193 const ParmVarDecl *argDecl = *PI++;
194 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000195 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000196 if (DLE) {
197 argDecl = *PI++;
198 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000199 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000200 }
201 argDecl = *PI;
202 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000203 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000204 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
205 Args.add(RValue::get(Count), ArgQT);
206
207 // Generate a reference to the class pointer, which will be the receiver.
208 Selector Sel = MethodWithObjects->getSelector();
209 QualType ResultType = E->getType();
210 const ObjCObjectPointerType *InterfacePointerType
211 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000212 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000213 = InterfacePointerType->getObjectType()->getInterface();
214 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000215 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000216
217 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000218 RValue result = Runtime.GenerateMessageSend(
219 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
220 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000221
222 // The above message send needs these objects, but in ARC they are
223 // passed in a buffer that is essentially __unsafe_unretained.
224 // Therefore we must prevent the optimizer from releasing them until
225 // after the call.
226 if (TrackNeededObjects) {
227 EmitARCIntrinsicUse(NeededObjects);
228 }
229
Fangrui Song6907ce22018-07-30 19:24:48 +0000230 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000231 ConvertType(E->getType()));
232}
233
234llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000235 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000236}
237
238llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
239 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000240 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000241}
242
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000243/// Emit a selector.
244llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
245 // Untyped selector.
246 // Note that this implementation allows for non-constant strings to be passed
247 // as arguments to @selector(). Currently, the only thing preventing this
248 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000249 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000250}
251
Daniel Dunbar66912a12008-08-20 00:28:19 +0000252llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
253 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000254 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000255}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000257/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000258/// to type erasure at various points, e.g., related result types or the use
259/// of parameterized classes.
260static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
261 RValue Result) {
262 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000263 return Result;
John McCall31168b02011-06-15 23:02:42 +0000264
Douglas Gregore83b9562015-07-07 03:57:53 +0000265 // If the converted types are the same, we're done.
266 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
267 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000268 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000269
270 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000271 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000272 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000273}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000274
John McCallcf166702011-07-22 08:53:00 +0000275/// Decide whether to extend the lifetime of the receiver of a
276/// returns-inner-pointer message.
277static bool
278shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
279 switch (message->getReceiverKind()) {
280
281 // For a normal instance message, we should extend unless the
282 // receiver is loaded from a variable with precise lifetime.
283 case ObjCMessageExpr::Instance: {
284 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000285
286 // Look through OVEs.
287 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
288 if (opaque->getSourceExpr())
289 receiver = opaque->getSourceExpr()->IgnoreParens();
290 }
291
John McCallcf166702011-07-22 08:53:00 +0000292 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
293 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
294 receiver = ice->getSubExpr()->IgnoreParens();
295
John McCall6380a282015-09-09 23:37:17 +0000296 // Look through OVEs.
297 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
298 if (opaque->getSourceExpr())
299 receiver = opaque->getSourceExpr()->IgnoreParens();
300 }
301
John McCallcf166702011-07-22 08:53:00 +0000302 // Only __strong variables.
303 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
304 return true;
305
306 // All ivars and fields have precise lifetime.
307 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
308 return false;
309
310 // Otherwise, check for variables.
311 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
312 if (!declRef) return true;
313 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
314 if (!var) return true;
315
316 // All variables have precise lifetime except local variables with
317 // automatic storage duration that aren't specially marked.
318 return (var->hasLocalStorage() &&
319 !var->hasAttr<ObjCPreciseLifetimeAttr>());
320 }
321
322 case ObjCMessageExpr::Class:
323 case ObjCMessageExpr::SuperClass:
324 // It's never necessary for class objects.
325 return false;
326
327 case ObjCMessageExpr::SuperInstance:
328 // We generally assume that 'self' lives throughout a method call.
329 return false;
330 }
331
332 llvm_unreachable("invalid receiver kind");
333}
334
John McCall460ce582015-10-22 18:38:17 +0000335/// Given an expression of ObjC pointer type, check whether it was
336/// immediately loaded from an ARC __weak l-value.
337static const Expr *findWeakLValue(const Expr *E) {
338 assert(E->getType()->isObjCRetainableType());
339 E = E->IgnoreParens();
340 if (auto CE = dyn_cast<CastExpr>(E)) {
341 if (CE->getCastKind() == CK_LValueToRValue) {
342 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
343 return CE->getSubExpr();
344 }
345 }
346
347 return nullptr;
348}
349
Pete Coopere3886802018-12-08 05:13:50 +0000350/// The ObjC runtime may provide entrypoints that are likely to be faster
351/// than an ordinary message send of the appropriate selector.
352///
353/// The entrypoints are guaranteed to be equivalent to just sending the
354/// corresponding message. If the entrypoint is implemented naively as just a
355/// message send, using it is a trade-off: it sacrifices a few cycles of
356/// overhead to save a small amount of code. However, it's possible for
357/// runtimes to detect and special-case classes that use "standard"
358/// behavior; if that's dynamically a large proportion of all objects, using
359/// the entrypoint will also be faster than using a message send.
360///
361/// If the runtime does support a required entrypoint, then this method will
362/// generate a call and return the resulting value. Otherwise it will return
363/// None and the caller can generate a msgSend instead.
364static Optional<llvm::Value *>
365tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
366 llvm::Value *Receiver,
367 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000368 const ObjCMethodDecl *method,
369 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000370 auto &CGM = CGF.CGM;
371 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
372 return None;
373
374 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
375 switch (Sel.getMethodFamily()) {
376 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000377 if (isClassMessage &&
378 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000379 ResultType->isObjCObjectPointerType()) {
380 // [Foo alloc] -> objc_alloc(Foo)
381 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
382 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
383 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
384 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
385 Args.size() == 1 && Args.front().getType()->isPointerType() &&
386 Sel.getNameForSlot(0) == "allocWithZone") {
387 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
388 if (isa<llvm::ConstantPointerNull>(arg))
389 return CGF.EmitObjCAllocWithZone(Receiver,
390 CGF.ConvertType(ResultType));
391 return None;
392 }
393 }
394 break;
395
Pete Coopere5b64ea2018-12-21 21:00:32 +0000396 case OMF_autorelease:
397 if (ResultType->isObjCObjectPointerType() &&
398 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
399 Runtime.shouldUseARCFunctionsForRetainRelease())
400 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
401 break;
402
403 case OMF_retain:
404 if (ResultType->isObjCObjectPointerType() &&
405 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
406 Runtime.shouldUseARCFunctionsForRetainRelease())
407 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
408 break;
409
410 case OMF_release:
411 if (ResultType->isVoidType() &&
412 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
413 Runtime.shouldUseARCFunctionsForRetainRelease()) {
414 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
415 return nullptr;
416 }
417 break;
418
Pete Coopere3886802018-12-08 05:13:50 +0000419 default:
420 break;
421 }
422 return None;
423}
424
John McCall78a15112010-05-22 01:48:05 +0000425RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
426 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000427 // Only the lookup mechanism and first two arguments of the method
428 // implementation vary between runtimes. We can get the receiver and
429 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000430
John McCall31168b02011-06-15 23:02:42 +0000431 bool isDelegateInit = E->isDelegateInitCall();
432
John McCallcf166702011-07-22 08:53:00 +0000433 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000434
John McCall460ce582015-10-22 18:38:17 +0000435 // If the method is -retain, and the receiver's being loaded from
436 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
437 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
438 method->getMethodFamily() == OMF_retain) {
439 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
440 LValue lvalue = EmitLValue(lvalueExpr);
441 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
442 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
443 }
444 }
445
John McCall31168b02011-06-15 23:02:42 +0000446 // We don't retain the receiver in delegate init calls, and this is
447 // safe because the receiver value is always loaded from 'self',
448 // which we zero out. We don't want to Block_copy block receivers,
449 // though.
450 bool retainSelf =
451 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000452 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000453 method &&
454 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000455
Daniel Dunbar8d480592008-08-11 18:12:00 +0000456 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000457 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000458 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000459 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000460 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000461 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000462 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000463 switch (E->getReceiverKind()) {
464 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000465 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000466 if (retainSelf) {
467 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
468 E->getInstanceReceiver());
469 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000470 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000471 } else
472 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000473 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000474
Douglas Gregor9a129192010-04-21 00:45:42 +0000475 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000476 ReceiverType = E->getClassReceiver();
477 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000478 assert(ObjTy && "Invalid Objective-C class message send");
479 OID = ObjTy->getInterface();
480 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000481 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000482 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000483 break;
484 }
485
486 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000487 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000488 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000489 isSuperMessage = true;
490 break;
491
492 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000493 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000494 Receiver = LoadObjCSelf();
495 isSuperMessage = true;
496 isClassMessage = true;
497 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000498 }
499
John McCallcf166702011-07-22 08:53:00 +0000500 if (retainSelf)
501 Receiver = EmitARCRetainNonBlock(Receiver);
502
503 // In ARC, we sometimes want to "extend the lifetime"
504 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
505 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000506 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000507 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
508 shouldExtendReceiverForInnerPointerMessage(E))
509 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
510
Alp Toker314cc812014-01-25 16:55:45 +0000511 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000512
Daniel Dunbarc722b852008-08-30 03:02:31 +0000513 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000514 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000515
John McCall31168b02011-06-15 23:02:42 +0000516 // For delegate init calls in ARC, do an unsafe store of null into
517 // self. This represents the call taking direct ownership of that
518 // value. We have to do this after emitting the other call
519 // arguments because they might also reference self, but we don't
520 // have to worry about any of them modifying self because that would
521 // be an undefined read and write of an object in unordered
522 // expressions.
523 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000524 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000525 "delegate init calls should only be marked in ARC");
526
527 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000528 Address selfAddr =
529 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000530 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
531 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000532
Douglas Gregor33823722011-06-11 01:09:30 +0000533 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000534 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000535 // super is only valid in an Objective-C method
536 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000537 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000538 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
539 E->getSelector(),
540 OMD->getClassInterface(),
541 isCategoryImpl,
542 Receiver,
543 isClassMessage,
544 Args,
John McCallcf166702011-07-22 08:53:00 +0000545 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000546 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000547 // Call runtime methods directly if we can.
548 if (Optional<llvm::Value *> SpecializedResult =
549 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000550 E->getSelector(), method,
551 isClassMessage)) {
Pete Coopere3886802018-12-08 05:13:50 +0000552 result = RValue::get(SpecializedResult.getValue());
553 } else {
554 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
555 E->getSelector(), Receiver, Args,
556 OID, method);
557 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000558 }
John McCall31168b02011-06-15 23:02:42 +0000559
560 // For delegate init calls in ARC, implicitly store the result of
561 // the call back into self. This takes ownership of the value.
562 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000563 Address selfAddr =
564 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000565 llvm::Value *newSelf = result.getScalarVal();
566
567 // The delegate return type isn't necessarily a matching type; in
568 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000569 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000570 newSelf = Builder.CreateBitCast(newSelf, selfTy);
571
572 Builder.CreateStore(newSelf, selfAddr);
573 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000574
Douglas Gregore83b9562015-07-07 03:57:53 +0000575 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000576}
577
John McCall31168b02011-06-15 23:02:42 +0000578namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000579struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000580 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000581 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000582
583 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000584 const ObjCInterfaceDecl *iface = impl->getClassInterface();
585 if (!iface->getSuperClass()) return;
586
John McCalldffafde2011-07-13 18:26:47 +0000587 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
588
John McCall31168b02011-06-15 23:02:42 +0000589 // Call [super dealloc] if we have a superclass.
590 llvm::Value *self = CGF.LoadObjCSelf();
591
592 CallArgList args;
593 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
594 CGF.getContext().VoidTy,
595 method->getSelector(),
596 iface,
John McCalldffafde2011-07-13 18:26:47 +0000597 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000598 self,
599 /*is class msg*/ false,
600 args,
601 method);
602 }
603};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000604}
John McCall31168b02011-06-15 23:02:42 +0000605
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000606/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
607/// the LLVM function and sets the other context used by
608/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000609void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000610 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000611 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000612 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000613 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000614 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000615 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000616
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000617 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000618
John McCalla729c622012-02-17 03:33:10 +0000619 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000620 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000621
John McCalla738c252011-03-09 04:27:21 +0000622 args.push_back(OMD->getSelfDecl());
623 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000624
Benjamin Kramerf9890422015-02-17 16:48:30 +0000625 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000626
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000627 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000628 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000629
Adrian Prantl42d71b92014-04-10 23:21:53 +0000630 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
631 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000632
633 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000634 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000635 OMD->isInstanceMethod() &&
636 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000637 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000638 OMD->getSelector().getIdentifierInfoForSlot(0);
639 if (ident->isStr("dealloc"))
640 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
641 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000642}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000643
John McCall31168b02011-06-15 23:02:42 +0000644static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
645 LValue lvalue, QualType type);
646
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000647/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000648/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000649void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000650 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000651 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000652 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000653 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000654 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000655 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000656}
657
John McCallb923ece2011-09-12 23:06:44 +0000658/// emitStructGetterCall - Call the runtime function to load a property
659/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000660static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000661 bool isAtomic, bool hasStrong) {
662 ASTContext &Context = CGF.getContext();
663
John McCall7f416cc2015-09-08 08:05:57 +0000664 Address src =
665 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
666 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000667
Fangrui Song6907ce22018-07-30 19:24:48 +0000668 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000669 // sizeof (Type of Ivar), isAtomic, false);
670 CallArgList args;
671
John McCall7f416cc2015-09-08 08:05:57 +0000672 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
673 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000674
675 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000676 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000677
678 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
679 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
680 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
681 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
682
James Y Knight9871db02019-02-05 16:42:33 +0000683 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000684 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000685 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000686 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000687}
688
John McCallf4528ae2011-09-13 03:34:09 +0000689/// Determine whether the given architecture supports unaligned atomic
690/// accesses. They don't have to be fast, just faster than a function
691/// call and a mutex.
692static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000693 // FIXME: Allow unaligned atomic load/store on x86. (It is not
694 // currently supported by the backend.)
695 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000696}
697
698/// Return the maximum size that permits atomic accesses for the given
699/// architecture.
700static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
701 llvm::Triple::ArchType arch) {
702 // ARM has 8-byte atomic accesses, but it's not clear whether we
703 // want to rely on them here.
704
705 // In the default case, just assume that any size up to a pointer is
706 // fine given adequate alignment.
707 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
708}
709
710namespace {
711 class PropertyImplStrategy {
712 public:
713 enum StrategyKind {
714 /// The 'native' strategy is to use the architecture's provided
715 /// reads and writes.
716 Native,
717
718 /// Use objc_setProperty and objc_getProperty.
719 GetSetProperty,
720
721 /// Use objc_setProperty for the setter, but use expression
722 /// evaluation for the getter.
723 SetPropertyAndExpressionGet,
724
725 /// Use objc_copyStruct.
726 CopyStruct,
727
728 /// The 'expression' strategy is to emit normal assignment or
729 /// lvalue-to-rvalue expressions.
730 Expression
731 };
732
733 StrategyKind getKind() const { return StrategyKind(Kind); }
734
735 bool hasStrongMember() const { return HasStrong; }
736 bool isAtomic() const { return IsAtomic; }
737 bool isCopy() const { return IsCopy; }
738
739 CharUnits getIvarSize() const { return IvarSize; }
740 CharUnits getIvarAlignment() const { return IvarAlignment; }
741
742 PropertyImplStrategy(CodeGenModule &CGM,
743 const ObjCPropertyImplDecl *propImpl);
744
745 private:
746 unsigned Kind : 8;
747 unsigned IsAtomic : 1;
748 unsigned IsCopy : 1;
749 unsigned HasStrong : 1;
750
751 CharUnits IvarSize;
752 CharUnits IvarAlignment;
753 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000754}
John McCallf4528ae2011-09-13 03:34:09 +0000755
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000756/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000757PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
758 const ObjCPropertyImplDecl *propImpl) {
759 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000760 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000761
John McCall43192862011-09-13 18:31:23 +0000762 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
763 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000764 HasStrong = false; // doesn't matter here.
765
766 // Evaluate the ivar's size and alignment.
767 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
768 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000769 std::tie(IvarSize, IvarAlignment) =
770 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000771
772 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000773 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000774 if (IsCopy) {
775 Kind = GetSetProperty;
776 return;
777 }
778
John McCall43192862011-09-13 18:31:23 +0000779 // Handle retain.
780 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000781 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000782 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000783 // fallthrough
784
785 // In ARC, if the property is non-atomic, use expression emission,
786 // which translates to objc_storeStrong. This isn't required, but
787 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000788 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000789 // Using standard expression emission for the setter is only
790 // acceptable if the ivar is __strong, which won't be true if
791 // the property is annotated with __attribute__((NSObject)).
792 // TODO: falling all the way back to objc_setProperty here is
793 // just laziness, though; we could still use objc_storeStrong
794 // if we hacked it right.
795 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
796 Kind = Expression;
797 else
798 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000799 return;
800
801 // Otherwise, we need to at least use setProperty. However, if
802 // the property isn't atomic, we can use normal expression
803 // emission for the getter.
804 } else if (!IsAtomic) {
805 Kind = SetPropertyAndExpressionGet;
806 return;
807
808 // Otherwise, we have to use both setProperty and getProperty.
809 } else {
810 Kind = GetSetProperty;
811 return;
812 }
813 }
814
815 // If we're not atomic, just use expression accesses.
816 if (!IsAtomic) {
817 Kind = Expression;
818 return;
819 }
820
John McCall0e5c0862011-09-13 05:36:29 +0000821 // Properties on bitfield ivars need to be emitted using expression
822 // accesses even if they're nominally atomic.
823 if (ivar->isBitField()) {
824 Kind = Expression;
825 return;
826 }
827
John McCallf4528ae2011-09-13 03:34:09 +0000828 // GC-qualified or ARC-qualified ivars need to be emitted as
829 // expressions. This actually works out to being atomic anyway,
830 // except for ARC __strong, but that should trigger the above code.
831 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000833 CGM.getContext().getObjCGCAttrKind(ivarType))) {
834 Kind = Expression;
835 return;
836 }
837
838 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000839 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000840 if (const RecordType *recordType = ivarType->getAs<RecordType>())
841 HasStrong = recordType->getDecl()->hasObjectMember();
842
843 // We can never access structs with object members with a native
844 // access, because we need to use write barriers. This is what
845 // objc_copyStruct is for.
846 if (HasStrong) {
847 Kind = CopyStruct;
848 return;
849 }
850
851 // Otherwise, this is target-dependent and based on the size and
852 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000853
854 // If the size of the ivar is not a power of two, give up. We don't
855 // want to get into the business of doing compare-and-swaps.
856 if (!IvarSize.isPowerOfTwo()) {
857 Kind = CopyStruct;
858 return;
859 }
860
John McCallf4528ae2011-09-13 03:34:09 +0000861 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000862 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000863
864 // Most architectures require memory to fit within a single cache
865 // line, so the alignment has to be at least the size of the access.
866 // Otherwise we have to grab a lock.
867 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
868 Kind = CopyStruct;
869 return;
870 }
871
872 // If the ivar's size exceeds the architecture's maximum atomic
873 // access size, we have to use CopyStruct.
874 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
875 Kind = CopyStruct;
876 return;
877 }
878
879 // Otherwise, we can use native loads and stores.
880 Kind = Native;
881}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000882
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000883/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000884///
885/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000886/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000887void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
888 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000889 llvm::Constant *AtomicHelperFn =
890 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000891 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
892 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
893 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000894 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000895
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000896 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000897
898 FinishFunction();
899}
900
John McCallbdd81852011-09-13 06:00:03 +0000901static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
902 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000903 if (!getter) return true;
904
905 // Sema only makes only of these when the ivar has a C++ class type,
906 // so the form is pretty constrained.
907
John McCallbdd81852011-09-13 06:00:03 +0000908 // If the property has a reference type, we might just be binding a
909 // reference, in which case the result will be a gl-value. We should
910 // treat this as a non-trivial operation.
911 if (getter->isGLValue())
912 return false;
913
John McCallf4528ae2011-09-13 03:34:09 +0000914 // If we selected a trivial copy-constructor, we're okay.
915 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
916 return (construct->getConstructor()->isTrivial());
917
918 // The constructor might require cleanups (in which case it's never
919 // trivial).
920 assert(isa<ExprWithCleanups>(getter));
921 return false;
922}
923
Fangrui Song6907ce22018-07-30 19:24:48 +0000924/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000925/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000926static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000927 llvm::Value *returnAddr,
928 ObjCIvarDecl *ivar,
929 llvm::Constant *AtomicHelperFn) {
930 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
931 // AtomicHelperFn);
932 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000933
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000934 // The 1st argument is the return Slot.
935 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000936
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000937 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +0000938 llvm::Value *ivarAddr =
939 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +0000940 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000941 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
942 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000943
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000944 // Third argument is the helper function.
945 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000946
James Y Knight9871db02019-02-05 16:42:33 +0000947 llvm::FunctionCallee copyCppAtomicObjectFn =
948 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000949 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000950 CGF.EmitCall(
951 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000952 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000953}
954
John McCallf4528ae2011-09-13 03:34:09 +0000955void
956CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000957 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000958 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000959 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000960 // If there's a non-trivial 'get' expression, we just have to emit that.
961 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000962 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +0000963 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
964 propImpl->getGetterCXXConstructor(),
965 /* NRVOCandidate=*/nullptr);
966 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000967 }
968 else {
969 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000970 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000971 ivar, AtomicHelperFn);
972 }
John McCallf4528ae2011-09-13 03:34:09 +0000973 return;
974 }
975
976 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
977 QualType propType = prop->getType();
978 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
979
Fangrui Song6907ce22018-07-30 19:24:48 +0000980 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +0000981
982 // Pick an implementation strategy.
983 PropertyImplStrategy strategy(CGM, propImpl);
984 switch (strategy.getKind()) {
985 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000986 // We don't need to do anything for a zero-size struct.
987 if (strategy.getIvarSize().isZero())
988 return;
989
John McCallf4528ae2011-09-13 03:34:09 +0000990 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
991
992 // Currently, all atomic accesses have to be through integer
993 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000994 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
995 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +0000996 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
997
998 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +0000999 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +00001000 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1001 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001002 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001003
1004 // Store that value into the return address. Doing this with a
1005 // bitcast is likely to produce some pretty ugly IR, but it's not
1006 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001007 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1008 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1009 llvm::Value *ivarVal = load;
1010 if (ivarSize > retTySize) {
1011 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1012 ivarVal = Builder.CreateTrunc(load, newTy);
1013 bitcastType = newTy->getPointerTo();
1014 }
1015 Builder.CreateStore(ivarVal,
1016 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001017
1018 // Make sure we don't do an autorelease.
1019 AutoreleaseResult = false;
1020 return;
1021 }
1022
1023 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001024 llvm::FunctionCallee getPropertyFn =
1025 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001026 if (!getPropertyFn) {
1027 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001028 return;
1029 }
John McCallb92ab1a2016-10-26 23:46:34 +00001030 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001031
1032 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1033 // FIXME: Can't this be simpler? This might even be worse than the
1034 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001035 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001036 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001037 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1038 llvm::Value *ivarOffset =
1039 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1040
1041 CallArgList args;
1042 args.add(RValue::get(self), getContext().getObjCIdType());
1043 args.add(RValue::get(cmd), getContext().getObjCSelType());
1044 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001045 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1046 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001047
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001048 // FIXME: We shouldn't need to get the function info here, the
1049 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001050 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001051 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1052 getContext().getObjCIdType(), args),
1053 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001054 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1055 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001056
Daniel Dunbara08dff12008-09-24 04:04:31 +00001057 // We need to fix the type here. Ivars with copy & retain are
1058 // always objects so we don't need to worry about complex or
1059 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001060 RV = RValue::get(Builder.CreateBitCast(
1061 RV.getScalarVal(),
1062 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001063
1064 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001065
1066 // objc_getProperty does an autorelease, so we should suppress ours.
1067 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001068
John McCallf4528ae2011-09-13 03:34:09 +00001069 return;
1070 }
1071
1072 case PropertyImplStrategy::CopyStruct:
1073 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1074 strategy.hasStrongMember());
1075 return;
1076
1077 case PropertyImplStrategy::Expression:
1078 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1079 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1080
1081 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001082 switch (getEvaluationKind(ivarType)) {
1083 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001084 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001085 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001086 /*init*/ true);
1087 return;
1088 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001089 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001090 // The return value slot is guaranteed to not be aliased, but
1091 // that's not necessarily the same as "on the stack", so
1092 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001093 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smithe78fac52018-04-05 20:52:58 +00001094 /* Src= */ LV, ivarType, overlapForReturnValue());
1095 return;
1096 }
John McCall47fb9502013-03-07 21:37:08 +00001097 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001098 llvm::Value *value;
1099 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001100 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001101 } else {
1102 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1103 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001104 if (getLangOpts().ObjCAutoRefCount) {
1105 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1106 } else {
1107 value = EmitARCLoadWeak(LV.getAddress());
1108 }
John McCall24fada12011-07-22 05:23:13 +00001109
1110 // Otherwise we want to do a simple load, suppressing the
1111 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001112 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001113 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001114 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001115 }
John McCall31168b02011-06-15 23:02:42 +00001116
Alp Toker314cc812014-01-25 16:55:45 +00001117 value = Builder.CreateBitCast(
1118 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001119 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001120
John McCall24fada12011-07-22 05:23:13 +00001121 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001122 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001123 }
John McCall47fb9502013-03-07 21:37:08 +00001124 }
1125 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001126 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001127
John McCallf4528ae2011-09-13 03:34:09 +00001128 }
1129 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001130}
1131
John McCallb923ece2011-09-12 23:06:44 +00001132/// emitStructSetterCall - Call the runtime function to store the value
1133/// from the first formal parameter into the given ivar.
1134static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1135 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001136 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001137 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001138 CallArgList args;
1139
1140 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001141 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1142 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001143 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001144 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1145 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001146
1147 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001148 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001149 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1150 argVar->getType().getNonReferenceType(), VK_LValue,
1151 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001152 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001153 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1154 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001155
1156 // The third argument is the sizeof the type.
1157 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001158 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1159 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001160
John McCallb923ece2011-09-12 23:06:44 +00001161 // The fourth argument is the 'isAtomic' flag.
1162 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001163
John McCallb923ece2011-09-12 23:06:44 +00001164 // The fifth argument is the 'hasStrong' flag.
1165 // FIXME: should this really always be false?
1166 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1167
James Y Knight9871db02019-02-05 16:42:33 +00001168 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001169 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001170 CGF.EmitCall(
1171 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001172 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001173}
1174
Fangrui Song6907ce22018-07-30 19:24:48 +00001175/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1176/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001177/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001178static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001179 ObjCMethodDecl *OMD,
1180 ObjCIvarDecl *ivar,
1181 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001182 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001183 // AtomicHelperFn);
1184 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001185
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001186 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001187 llvm::Value *ivarAddr =
1188 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001189 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001190 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1191 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001192
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001193 // The second argument is the address of the parameter variable.
1194 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001195 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1196 argVar->getType().getNonReferenceType(), VK_LValue,
1197 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001198 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001199 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1200 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001201
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001202 // Third argument is the helper function.
1203 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001204
James Y Knight9871db02019-02-05 16:42:33 +00001205 llvm::FunctionCallee fn =
1206 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001207 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001208 CGF.EmitCall(
1209 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001210 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001211}
1212
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001213
John McCallf4528ae2011-09-13 03:34:09 +00001214static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1215 Expr *setter = PID->getSetterCXXAssignment();
1216 if (!setter) return true;
1217
1218 // Sema only makes only of these when the ivar has a C++ class type,
1219 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001220
1221 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001222 // This also implies that there's nothing non-trivial going on with
1223 // the arguments, because operator= can only be trivial if it's a
1224 // synthesized assignment operator and therefore both parameters are
1225 // references.
1226 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001227 if (const FunctionDecl *callee
1228 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1229 if (callee->isTrivial())
1230 return true;
1231 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001232 }
John McCall7f16c422011-09-10 09:17:20 +00001233
John McCallf4528ae2011-09-13 03:34:09 +00001234 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001235 return false;
1236}
1237
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001238static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001239 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001240 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001241 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001242}
1243
John McCall7f16c422011-09-10 09:17:20 +00001244void
1245CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001246 const ObjCPropertyImplDecl *propImpl,
1247 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001248 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001249 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001250 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001251
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001252 // Just use the setter expression if Sema gave us one and it's
1253 // non-trivial.
1254 if (!hasTrivialSetExpr(propImpl)) {
1255 if (!AtomicHelperFn)
1256 // If non-atomic, assignment is called directly.
1257 EmitStmt(propImpl->getSetterCXXAssignment());
1258 else
1259 // If atomic, assignment is called via a locking api.
1260 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1261 AtomicHelperFn);
1262 return;
1263 }
John McCall7f16c422011-09-10 09:17:20 +00001264
John McCallf4528ae2011-09-13 03:34:09 +00001265 PropertyImplStrategy strategy(CGM, propImpl);
1266 switch (strategy.getKind()) {
1267 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001268 // We don't need to do anything for a zero-size struct.
1269 if (strategy.getIvarSize().isZero())
1270 return;
1271
John McCall7f416cc2015-09-08 08:05:57 +00001272 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001273
John McCallf4528ae2011-09-13 03:34:09 +00001274 LValue ivarLValue =
1275 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001276 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001277
John McCallf4528ae2011-09-13 03:34:09 +00001278 // Currently, all atomic accesses have to be through integer
1279 // types, so there's no point in trying to pick a prettier type.
1280 llvm::Type *bitcastType =
1281 llvm::Type::getIntNTy(getLLVMContext(),
1282 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001283
1284 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001285 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1286 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001287
1288 // This bitcast load is likely to cause some nasty IR.
1289 llvm::Value *load = Builder.CreateLoad(argAddr);
1290
1291 // Perform an atomic store. There are no memory ordering requirements.
1292 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001293 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001294 return;
1295 }
1296
1297 case PropertyImplStrategy::GetSetProperty:
1298 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001299
James Y Knight9871db02019-02-05 16:42:33 +00001300 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1301 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001302 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001303 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001304 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001305 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1306 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001307 if (!setOptimizedPropertyFn) {
1308 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1309 return;
1310 }
John McCall7f16c422011-09-10 09:17:20 +00001311 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001312 else {
1313 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1314 if (!setPropertyFn) {
1315 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1316 return;
1317 }
1318 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001319
John McCall7f16c422011-09-10 09:17:20 +00001320 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1321 // <is-atomic>, <is-copy>).
1322 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001323 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001324 llvm::Value *self =
1325 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1326 llvm::Value *ivarOffset =
1327 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001328 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1329 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1330 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001331
1332 CallArgList args;
1333 args.add(RValue::get(self), getContext().getObjCIdType());
1334 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001335 if (setOptimizedPropertyFn) {
1336 args.add(RValue::get(arg), getContext().getObjCIdType());
1337 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001338 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001339 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001340 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001341 } else {
1342 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1343 args.add(RValue::get(arg), getContext().getObjCIdType());
1344 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1345 getContext().BoolTy);
1346 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1347 getContext().BoolTy);
1348 // FIXME: We shouldn't need to get the function info here, the runtime
1349 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001350 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001351 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001352 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001353 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001354
John McCall7f16c422011-09-10 09:17:20 +00001355 return;
1356 }
1357
John McCallf4528ae2011-09-13 03:34:09 +00001358 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001359 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001360 return;
John McCallf4528ae2011-09-13 03:34:09 +00001361
1362 case PropertyImplStrategy::Expression:
1363 break;
John McCall7f16c422011-09-10 09:17:20 +00001364 }
1365
1366 // Otherwise, fake up some ASTs and emit a normal assignment.
1367 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001368 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001369 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001370 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1371 selfDecl->getType(), CK_LValueToRValue, &self,
1372 VK_RValue);
1373 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001374 SourceLocation(), SourceLocation(),
1375 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001376
1377 ParmVarDecl *argDecl = *setterMethod->param_begin();
1378 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001379 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1380 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001381 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1382 argType.getUnqualifiedType(), CK_LValueToRValue,
1383 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001384
John McCall7f16c422011-09-10 09:17:20 +00001385 // The property type can differ from the ivar type in some situations with
1386 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1387 // The following absurdity is just to ensure well-formed IR.
1388 CastKind argCK = CK_NoOp;
1389 if (ivarRef.getType()->isObjCObjectPointerType()) {
1390 if (argLoad.getType()->isObjCObjectPointerType())
1391 argCK = CK_BitCast;
1392 else if (argLoad.getType()->isBlockPointerType())
1393 argCK = CK_BlockPointerToObjCPointerCast;
1394 else
1395 argCK = CK_CPointerToObjCPointerCast;
1396 } else if (ivarRef.getType()->isBlockPointerType()) {
1397 if (argLoad.getType()->isBlockPointerType())
1398 argCK = CK_BitCast;
1399 else
1400 argCK = CK_AnyPointerToBlockPointerCast;
1401 } else if (ivarRef.getType()->isPointerType()) {
1402 argCK = CK_BitCast;
1403 }
1404 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1405 ivarRef.getType(), argCK, &argLoad,
1406 VK_RValue);
1407 Expr *finalArg = &argLoad;
1408 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1409 argLoad.getType()))
1410 finalArg = &argCast;
1411
1412
1413 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1414 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001415 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001416 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001417}
1418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001419/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001420///
1421/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001422/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001423void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1424 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001425 llvm::Constant *AtomicHelperFn =
1426 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001427 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1428 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1429 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001430 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001431
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001432 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001433
1434 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001435}
1436
John McCall6a4fa522011-03-22 07:05:39 +00001437namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001438 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001439 private:
1440 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001441 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001442 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001443 bool useEHCleanupForArray;
1444 public:
1445 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1446 CodeGenFunction::Destroyer *destroyer,
1447 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001448 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001449 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001450
Craig Topper4f12f102014-03-12 06:41:41 +00001451 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001452 LValue lvalue
1453 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1454 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001455 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001456 }
1457 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001458}
John McCall6a4fa522011-03-22 07:05:39 +00001459
John McCall4bd0fb12011-07-12 16:41:08 +00001460/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1461static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001462 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001463 QualType type) {
1464 llvm::Value *null = getNullForVariable(addr);
1465 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1466}
John McCall31168b02011-06-15 23:02:42 +00001467
John McCall6a4fa522011-03-22 07:05:39 +00001468static void emitCXXDestructMethod(CodeGenFunction &CGF,
1469 ObjCImplementationDecl *impl) {
1470 CodeGenFunction::RunCleanupsScope scope(CGF);
1471
1472 llvm::Value *self = CGF.LoadObjCSelf();
1473
Jordy Rosea91768e2011-07-22 02:08:32 +00001474 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1475 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001476 ivar; ivar = ivar->getNextIvar()) {
1477 QualType type = ivar->getType();
1478
John McCall6a4fa522011-03-22 07:05:39 +00001479 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001480 QualType::DestructionKind dtorKind = type.isDestructedType();
1481 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001482
Craig Topper8a13c412014-05-21 05:09:00 +00001483 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001484
John McCall4bd0fb12011-07-12 16:41:08 +00001485 // Use a call to objc_storeStrong to destroy strong ivars, for the
1486 // general benefit of the tools.
1487 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001488 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001489
John McCall4bd0fb12011-07-12 16:41:08 +00001490 // Otherwise use the default for the destruction kind.
1491 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001492 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001493 }
John McCall4bd0fb12011-07-12 16:41:08 +00001494
1495 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1496
1497 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1498 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001499 }
1500
1501 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1502}
1503
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001504void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1505 ObjCMethodDecl *MD,
1506 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001507 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001508 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001509
1510 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001511 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001512 // Suppress the final autorelease in ARC.
1513 AutoreleaseResult = false;
1514
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001515 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001516 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001517 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001518 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001519 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001520 EmitAggExpr(IvarInit->getInit(),
1521 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001522 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001523 AggValueSlot::IsNotAliased,
1524 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001525 }
1526 // constructor returns 'self'.
1527 CodeGenTypes &Types = CGM.getTypes();
1528 QualType IdTy(CGM.getContext().getObjCIdType());
1529 llvm::Value *SelfAsId =
1530 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1531 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001532
1533 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001534 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001535 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001536 }
1537 FinishFunction();
1538}
1539
Daniel Dunbara08dff12008-09-24 04:04:31 +00001540llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001541 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001542 DeclRefExpr DRE(getContext(), Self,
1543 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001544 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001545 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001546}
1547
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001548QualType CodeGenFunction::TypeOfSelfObject() {
1549 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1550 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001551 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1552 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001553 return PTy->getPointeeType();
1554}
1555
Chris Lattnerd4808922009-03-22 21:03:39 +00001556void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001557 llvm::FunctionCallee EnumerationMutationFnPtr =
1558 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001559 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001560 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1561 return;
1562 }
John McCallb92ab1a2016-10-26 23:46:34 +00001563 CGCallee EnumerationMutationFn =
1564 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001565
Devang Pateld2d66652011-01-19 01:36:36 +00001566 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001567 if (DI)
1568 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001569
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001570 RunCleanupsScope ForScope(*this);
1571
Kuba Mracek82c21752017-04-14 01:00:03 +00001572 // The local variable comes into scope immediately.
1573 AutoVarEmission variable = AutoVarEmission::invalid();
1574 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1575 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1576
John McCall1c926b72011-01-07 01:49:06 +00001577 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001578
Anders Carlsson75658592008-08-31 02:33:12 +00001579 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001580 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001581 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001582 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001583
Anders Carlsson75658592008-08-31 02:33:12 +00001584 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001585 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall1c926b72011-01-07 01:49:06 +00001587 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001588 IdentifierInfo *II[] = {
1589 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1590 &CGM.getContext().Idents.get("objects"),
1591 &CGM.getContext().Idents.get("count")
1592 };
1593 Selector FastEnumSel =
1594 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001595
1596 QualType ItemsTy =
1597 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001598 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001599 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001600 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001601
John McCall53848232011-07-27 01:07:15 +00001602 // Emit the collection pointer. In ARC, we do a retain.
1603 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001604 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001605 Collection = EmitARCRetainScalarExpr(S.getCollection());
1606
1607 // Enter a cleanup to do the release.
1608 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1609 } else {
1610 Collection = EmitScalarExpr(S.getCollection());
1611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
John McCall91e82dd2011-08-05 00:14:38 +00001613 // The 'continue' label needs to appear within the cleanup for the
1614 // collection object.
1615 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1616
John McCall1c926b72011-01-07 01:49:06 +00001617 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001618 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001619
1620 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001621 Args.add(RValue::get(StatePtr.getPointer()),
1622 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001623
John McCall1c926b72011-01-07 01:49:06 +00001624 // The second argument is a temporary array with space for NumItems
1625 // pointers. We'll actually be loading elements from the array
1626 // pointer written into the control state; this buffer is so that
1627 // collections that *aren't* backed by arrays can still queue up
1628 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001629 Args.add(RValue::get(ItemsPtr.getPointer()),
1630 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001631
John McCall1c926b72011-01-07 01:49:06 +00001632 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001633 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1634 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1635 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001636
John McCall1c926b72011-01-07 01:49:06 +00001637 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001638 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001639 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1640 getContext().getNSUIntegerType(),
1641 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001642
John McCall1c926b72011-01-07 01:49:06 +00001643 // The initial number of objects that were returned in the buffer.
1644 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001645
John McCall1c926b72011-01-07 01:49:06 +00001646 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1647 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001648
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001649 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001650
John McCall1c926b72011-01-07 01:49:06 +00001651 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001652 // empty; skip all this. Set the branch weight assuming this has the same
1653 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001654 uint64_t EntryCount = getCurrentProfileCount();
1655 Builder.CreateCondBr(
1656 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1657 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001658 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001659
John McCall1c926b72011-01-07 01:49:06 +00001660 // Otherwise, initialize the loop.
1661 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001662
John McCall1c926b72011-01-07 01:49:06 +00001663 // Save the initial mutations value. This is the value at an
1664 // address that was written into the state object by
1665 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001666 Address StateMutationsPtrPtr =
1667 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001668 llvm::Value *StateMutationsPtr
1669 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001670
John McCall1c926b72011-01-07 01:49:06 +00001671 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001672 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1673 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001674
John McCall1c926b72011-01-07 01:49:06 +00001675 // Start looping. This is the point we return to whenever we have a
1676 // fresh, non-empty batch of objects.
1677 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1678 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001679
John McCall1c926b72011-01-07 01:49:06 +00001680 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001681 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001682 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001683
John McCall1c926b72011-01-07 01:49:06 +00001684 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001685 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001686 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001687
Justin Bogner66242d62015-04-23 23:06:47 +00001688 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001689
John McCall1c926b72011-01-07 01:49:06 +00001690 // Check whether the mutations value has changed from where it was
1691 // at start. StateMutationsPtr should actually be invariant between
1692 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001693 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001694 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001695 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1696 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001697
John McCall1c926b72011-01-07 01:49:06 +00001698 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001699 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001700
John McCall1c926b72011-01-07 01:49:06 +00001701 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1702 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001703
John McCall1c926b72011-01-07 01:49:06 +00001704 // If so, call the enumeration-mutation function.
1705 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001706 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001707 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001708 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001709 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001710 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001711 // FIXME: We shouldn't need to get the function info here, the runtime already
1712 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001713 EmitCall(
1714 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001715 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001716
John McCall1c926b72011-01-07 01:49:06 +00001717 // Otherwise, or if the mutation function returns, just continue.
1718 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001719
John McCall1c926b72011-01-07 01:49:06 +00001720 // Initialize the element variable.
1721 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001722 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001723 LValue elementLValue;
1724 QualType elementType;
1725 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001726 // Initialize the variable, in case it's a __block variable or something.
1727 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001728
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001729 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1730 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1731 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001732 elementLValue = EmitLValue(&tempDRE);
1733 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001734 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001735
1736 if (D->isARCPseudoStrong())
1737 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001738 } else {
1739 elementLValue = LValue(); // suppress warning
1740 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001741 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001742 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001743 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001744
1745 // Fetch the buffer out of the enumeration state.
1746 // TODO: this pointer should actually be invariant between
1747 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001748 Address StateItemsPtr =
1749 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001750 llvm::Value *EnumStateItems =
1751 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001752
John McCall1c926b72011-01-07 01:49:06 +00001753 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001754 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001755 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001756 llvm::Value *CurrentItem =
1757 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001758
John McCall1c926b72011-01-07 01:49:06 +00001759 // Cast that value to the right type.
1760 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1761 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001762
John McCall1c926b72011-01-07 01:49:06 +00001763 // Make sure we have an l-value. Yes, this gets evaluated every
1764 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001765 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001766 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001767 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001768 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001769 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1770 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
John McCall9e2e22f2011-02-22 07:16:58 +00001773 // If we do have an element variable, this assignment is the end of
1774 // its initialization.
1775 if (elementIsVariable)
1776 EmitAutoVarCleanups(variable);
1777
John McCall1c926b72011-01-07 01:49:06 +00001778 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001779 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001780 {
1781 RunCleanupsScope Scope(*this);
1782 EmitStmt(S.getBody());
1783 }
Anders Carlsson75658592008-08-31 02:33:12 +00001784 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001785
John McCall1c926b72011-01-07 01:49:06 +00001786 // Destroy the element variable now.
1787 elementVariableScope.ForceCleanup();
1788
1789 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001790 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001791
John McCall1c926b72011-01-07 01:49:06 +00001792 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001793
John McCall1c926b72011-01-07 01:49:06 +00001794 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001795 llvm::Value *indexPlusOne =
1796 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001797
John McCall1c926b72011-01-07 01:49:06 +00001798 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001799 // Set the branch weights based on the simplifying assumption that this is
1800 // like a while-loop, i.e., ignoring that the false branch fetches more
1801 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001802 Builder.CreateCondBr(
1803 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001804 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001805
1806 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1807 count->addIncoming(count, AfterBody.getBlock());
1808
1809 // Otherwise, we have to fetch more elements.
1810 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001811
1812 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001813 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1814 getContext().getNSUIntegerType(),
1815 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001816
John McCall1c926b72011-01-07 01:49:06 +00001817 // If we got a zero count, we're done.
1818 llvm::Value *refetchCount = CountRV.getScalarVal();
1819
1820 // (note that the message send might split FetchMoreBB)
1821 index->addIncoming(zero, Builder.GetInsertBlock());
1822 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1823
1824 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1825 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001826
Anders Carlsson75658592008-08-31 02:33:12 +00001827 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001828 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001829
John McCall9e2e22f2011-02-22 07:16:58 +00001830 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001831 // If the element was not a declaration, set it to be null.
1832
John McCall1c926b72011-01-07 01:49:06 +00001833 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1834 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001835 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001836 }
1837
Eric Christopher7cdf9482011-10-13 21:45:18 +00001838 if (DI)
1839 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001840
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001841 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001842 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001843}
1844
Mike Stump11289f42009-09-09 15:08:12 +00001845void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001846 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001847}
1848
Mike Stump11289f42009-09-09 15:08:12 +00001849void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001850 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1851}
1852
Chris Lattnere132e242008-11-15 21:26:17 +00001853void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001854 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001855 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001856}
1857
John McCall31168b02011-06-15 23:02:42 +00001858namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001859 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001860 CallObjCRelease(llvm::Value *object) : object(object) {}
1861 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001862
Craig Topper4f12f102014-03-12 06:41:41 +00001863 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001864 // Releases at the end of the full-expression are imprecise.
1865 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001866 }
1867 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001868}
John McCall31168b02011-06-15 23:02:42 +00001869
John McCall2d637d22011-09-10 06:18:15 +00001870/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001871/// release at the end of the full-expression.
1872llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1873 llvm::Value *object) {
1874 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001875 // conditional.
1876 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001877 return object;
1878}
1879
1880llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1881 llvm::Value *value) {
1882 return EmitARCRetainAutorelease(type, value);
1883}
1884
John McCalleff18842013-03-23 02:35:54 +00001885/// Given a number of pointers, inform the optimizer that they're
1886/// being intrinsically used up until this point in the program.
1887void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001888 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001889 if (!fn)
1890 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001891
1892 // This isn't really a "runtime" function, but as an intrinsic it
1893 // doesn't really matter as long as we align things up.
1894 EmitNounwindRuntimeCall(fn, values);
1895}
1896
James Y Knight9871db02019-02-05 16:42:33 +00001897static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001898 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001899 // If the target runtime doesn't naturally support ARC, emit weak
1900 // references to the runtime support library. We don't really
1901 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001902 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1903 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001904 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001905 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001906 }
John McCall31168b02011-06-15 23:02:42 +00001907}
1908
James Y Knight9871db02019-02-05 16:42:33 +00001909static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1910 llvm::FunctionCallee RTF) {
1911 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1912}
1913
John McCall31168b02011-06-15 23:02:42 +00001914/// Perform an operation having the signature
1915/// i8* (i8*)
1916/// where a null input causes a no-op and returns null.
James Y Knight9871db02019-02-05 16:42:33 +00001917static llvm::Value *
1918emitARCValueOperation(CodeGenFunction &CGF, llvm::Value *value,
1919 llvm::Type *returnType, llvm::Function *&fn,
1920 llvm::Intrinsic::ID IntID, bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001921 if (isa<llvm::ConstantPointerNull>(value))
1922 return value;
John McCall31168b02011-06-15 23:02:42 +00001923
1924 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001925 fn = CGF.CGM.getIntrinsic(IntID);
1926 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001927 }
1928
1929 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001930 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001931 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1932
1933 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001934 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001935 if (isTailCall)
1936 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001937
1938 // Cast the result back to the original type.
1939 return CGF.Builder.CreateBitCast(call, origType);
1940}
1941
1942/// Perform an operation having the following signature:
1943/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00001944static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
1945 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001946 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00001947 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001948 fn = CGF.CGM.getIntrinsic(IntID);
1949 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001950 }
1951
1952 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001953 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001954 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1955
1956 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001957 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001958
1959 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001960 if (origType != CGF.Int8PtrTy)
1961 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001962
1963 return result;
1964}
1965
1966/// Perform an operation having the following signature:
1967/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00001968static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00001969 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00001970 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001971 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00001972 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001973 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001974
1975 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001976 fn = CGF.CGM.getIntrinsic(IntID);
1977 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001978 }
1979
Chris Lattner2192fe52011-07-18 04:24:23 +00001980 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001981
John McCall882987f2013-02-28 19:01:20 +00001982 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001983 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001984 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1985 };
1986 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001987
Craig Topper8a13c412014-05-21 05:09:00 +00001988 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001989
1990 return CGF.Builder.CreateBitCast(result, origType);
1991}
1992
1993/// Perform an operation having the following signature:
1994/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00001995static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
1996 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001997 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00001998 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00001999
2000 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002001 fn = CGF.CGM.getIntrinsic(IntID);
2002 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002003 }
2004
John McCall882987f2013-02-28 19:01:20 +00002005 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002006 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2007 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002008 };
2009 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002010}
2011
Pete Cooper2cd35962018-12-18 20:33:00 +00002012/// Perform an operation having the signature
2013/// i8* (i8*)
2014/// where a null input causes a no-op and returns null.
2015static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2016 llvm::Value *value,
2017 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002018 llvm::FunctionCallee &fn,
2019 StringRef fnName, bool MayThrow) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002020 if (isa<llvm::ConstantPointerNull>(value))
2021 return value;
2022
2023 if (!fn) {
2024 llvm::FunctionType *fnType =
2025 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2026 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002027
2028 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002029 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002030 if (fnName == "objc_retain")
2031 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002032 }
2033
2034 // Cast the argument to 'id'.
2035 llvm::Type *origType = returnType ? returnType : value->getType();
2036 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2037
2038 // Call the function.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002039 llvm::CallBase *Inst = nullptr;
2040 if (MayThrow)
2041 Inst = CGF.EmitCallOrInvoke(fn, value);
2042 else
2043 Inst = CGF.EmitNounwindRuntimeCall(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002044
2045 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002046 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002047}
2048
John McCall31168b02011-06-15 23:02:42 +00002049/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002050/// call i8* \@objc_retain(i8* %value)
2051/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002052llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2053 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002054 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002055 else
2056 return EmitARCRetainNonBlock(value);
2057}
2058
2059/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002060/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002061llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002062 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002063 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002064 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002065}
2066
2067/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002068/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002069///
2070/// \param mandatory - If false, emit the call with metadata
2071/// indicating that it's okay for the optimizer to eliminate this call
2072/// if it can prove that the block never escapes except down the stack.
2073llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2074 bool mandatory) {
2075 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002076 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002077 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002078 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002079
2080 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2081 // tell the optimizer that it doesn't need to do this copy if the
2082 // block doesn't escape, where being passed as an argument doesn't
2083 // count as escaping.
2084 if (!mandatory && isa<llvm::Instruction>(result)) {
2085 llvm::CallInst *call
2086 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002087 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002088
John McCallff613032011-10-04 06:23:45 +00002089 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002090 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002091 }
2092
2093 return result;
John McCall31168b02011-06-15 23:02:42 +00002094}
2095
John McCalle399e5b2016-01-27 18:32:30 +00002096static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002097 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002098 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002099 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002100 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002101 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002102 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002103 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002104 .getARCRetainAutoreleasedReturnValueMarker();
2105
2106 // If we have an empty assembly string, there's nothing to do.
2107 if (assembly.empty()) {
2108
2109 // Otherwise, at -O0, build an inline asm that we're going to call
2110 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002111 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002112 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002113 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002114
John McCall31168b02011-06-15 23:02:42 +00002115 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2116
2117 // If we're at -O1 and above, we don't want to litter the code
2118 // with this marker yet, so leave a breadcrumb for the ARC
2119 // optimizer to pick up.
2120 } else {
2121 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002122 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002123 "clang.arc.retainAutoreleasedReturnValueMarker");
2124 assert(metadata->getNumOperands() <= 1);
2125 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002126 auto &ctx = CGF.getLLVMContext();
2127 metadata->addOperand(llvm::MDNode::get(ctx,
2128 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002129 }
2130 }
2131 }
2132
2133 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002134 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002135 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002136}
John McCall31168b02011-06-15 23:02:42 +00002137
John McCalle399e5b2016-01-27 18:32:30 +00002138/// Retain the given object which is the result of a function call.
2139/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2140///
2141/// Yes, this function name is one character away from a different
2142/// call with completely different semantics.
2143llvm::Value *
2144CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2145 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002146 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002147 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002148 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
John McCall31168b02011-06-15 23:02:42 +00002149}
2150
John McCalle399e5b2016-01-27 18:32:30 +00002151/// Claim a possibly-autoreleased return value at +0. This is only
2152/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002153/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002154/// the value is ignored, or when it is being assigned to an
2155/// __unsafe_unretained variable.
2156///
2157/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2158llvm::Value *
2159CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2160 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002161 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002162 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002163 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002164}
2165
John McCall31168b02011-06-15 23:02:42 +00002166/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002167/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002168void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2169 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002170 if (isa<llvm::ConstantPointerNull>(value)) return;
2171
James Y Knight9871db02019-02-05 16:42:33 +00002172 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002173 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002174 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2175 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002176 }
2177
2178 // Cast the argument to 'id'.
2179 value = Builder.CreateBitCast(value, Int8PtrTy);
2180
2181 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002182 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002183
John McCallcdda29c2013-03-13 03:10:54 +00002184 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002185 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002186 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002187 }
2188}
2189
John McCalle68b8f42012-10-17 02:28:37 +00002190/// Destroy a __strong variable.
2191///
2192/// At -O0, emit a call to store 'null' into the address;
2193/// instrumenting tools prefer this because the address is exposed,
2194/// but it's relatively cumbersome to optimize.
2195///
2196/// At -O1 and above, just load and call objc_release.
2197///
2198/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002199void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002200 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002201 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002202 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002203 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2204 return;
2205 }
2206
2207 llvm::Value *value = Builder.CreateLoad(addr);
2208 EmitARCRelease(value, precise);
2209}
2210
John McCall31168b02011-06-15 23:02:42 +00002211/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002212/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002213llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002214 llvm::Value *value,
2215 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002216 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002217
James Y Knight9871db02019-02-05 16:42:33 +00002218 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002219 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002220 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2221 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002222 }
2223
John McCall882987f2013-02-28 19:01:20 +00002224 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002225 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002226 Builder.CreateBitCast(value, Int8PtrTy)
2227 };
2228 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002229
Craig Topper8a13c412014-05-21 05:09:00 +00002230 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002231 return value;
2232}
2233
2234/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002235/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002236/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002237llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002238 llvm::Value *newValue,
2239 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002240 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002241 bool isBlock = type->isBlockPointerType();
2242
2243 // Use a store barrier at -O0 unless this is a block type or the
2244 // lvalue is inadequately aligned.
2245 if (shouldUseFusedARCCalls() &&
2246 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002247 (dst.getAlignment().isZero() ||
2248 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002249 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2250 }
2251
2252 // Otherwise, split it out.
2253
2254 // Retain the new value.
2255 newValue = EmitARCRetain(type, newValue);
2256
2257 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002258 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002259
2260 // Store. We do this before the release so that any deallocs won't
2261 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002262 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002263
2264 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002265 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002266
2267 return newValue;
2268}
2269
2270/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002271/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002272llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002273 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002274 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002275 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002276}
2277
2278/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002279/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002280llvm::Value *
2281CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002282 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002283 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002284 llvm::Intrinsic::objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002285 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002286}
2287
2288/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002289/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002290llvm::Value *
2291CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002292 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002293 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002294 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002295 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002296}
2297
2298/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002299/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002300/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002301/// %retain = call i8* \@objc_retainBlock(i8* %value)
2302/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002303llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2304 llvm::Value *value) {
2305 if (!type->isBlockPointerType())
2306 return EmitARCRetainAutoreleaseNonBlock(value);
2307
2308 if (isa<llvm::ConstantPointerNull>(value)) return value;
2309
Chris Lattner2192fe52011-07-18 04:24:23 +00002310 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002311 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002312 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002313 value = EmitARCAutorelease(value);
2314 return Builder.CreateBitCast(value, origType);
2315}
2316
2317/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002318/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002319llvm::Value *
2320CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002321 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002322 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002323 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002324}
2325
John McCallb04ecb72015-10-21 18:06:43 +00002326/// i8* \@objc_loadWeak(i8** %addr)
2327/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2328llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2329 return emitARCLoadOperation(*this, addr,
2330 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002331 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002332}
2333
James Dennett14c41ea2012-06-22 05:41:30 +00002334/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002335llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002336 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002337 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002338 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002339}
2340
James Dennett14c41ea2012-06-22 05:41:30 +00002341/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002342/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002343llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002344 llvm::Value *value,
2345 bool ignored) {
2346 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002347 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002348 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002349}
2350
James Dennett14c41ea2012-06-22 05:41:30 +00002351/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002352/// Returns %value. %addr is known to not have a current weak entry.
2353/// Essentially equivalent to:
2354/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002355void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002356 // If we're initializing to null, just write null to memory; no need
2357 // to get the runtime involved. But don't do this if optimization
2358 // is enabled, because accounting for this would make the optimizer
2359 // much more complicated.
2360 if (isa<llvm::ConstantPointerNull>(value) &&
2361 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2362 Builder.CreateStore(value, addr);
2363 return;
2364 }
2365
2366 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002367 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002368 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002369}
2370
James Dennett14c41ea2012-06-22 05:41:30 +00002371/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002372/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002373void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002374 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002375 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002376 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2377 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002378 }
2379
2380 // Cast the argument to 'id*'.
2381 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2382
John McCall7f416cc2015-09-08 08:05:57 +00002383 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002384}
2385
James Dennett14c41ea2012-06-22 05:41:30 +00002386/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002387/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2388/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002389void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002390 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002391 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002392 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002393}
2394
James Dennett14c41ea2012-06-22 05:41:30 +00002395/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002396/// Disregards the current value in %dest. Essentially
2397/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002398void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002399 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002400 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002401 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002402}
2403
Akira Hatanakad791e922018-03-19 17:38:40 +00002404void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2405 Address SrcAddr) {
2406 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2407 Object = EmitObjCConsumeObject(Ty, Object);
2408 EmitARCStoreWeak(DstAddr, Object, false);
2409}
2410
2411void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2412 Address SrcAddr) {
2413 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2414 Object = EmitObjCConsumeObject(Ty, Object);
2415 EmitARCStoreWeak(DstAddr, Object, false);
2416 EmitARCDestroyWeak(SrcAddr);
2417}
2418
John McCall31168b02011-06-15 23:02:42 +00002419/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002420/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002421llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002422 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002423 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002424 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2425 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002426 }
2427
John McCall882987f2013-02-28 19:01:20 +00002428 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002429}
2430
2431/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002432/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002433void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2434 assert(value->getType() == Int8PtrTy);
2435
Pete Cooper2cd35962018-12-18 20:33:00 +00002436 if (getInvokeDest()) {
2437 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002438 llvm::FunctionCallee &fn =
2439 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002440 if (!fn) {
2441 llvm::FunctionType *fnType =
2442 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2443 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2444 setARCRuntimeFunctionLinkage(CGM, fn);
2445 }
John McCall31168b02011-06-15 23:02:42 +00002446
Pete Cooper2cd35962018-12-18 20:33:00 +00002447 // objc_autoreleasePoolPop can throw.
2448 EmitRuntimeCallOrInvoke(fn, value);
2449 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002450 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002451 if (!fn) {
2452 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2453 setARCRuntimeFunctionLinkage(CGM, fn);
2454 }
2455
2456 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002457 }
John McCall31168b02011-06-15 23:02:42 +00002458}
2459
2460/// Produce the code to do an MRR version objc_autoreleasepool_push.
2461/// Which is: [[NSAutoreleasePool alloc] init];
2462/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2463/// init is declared as: - (id) init; in its NSObject super class.
2464///
2465llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2466 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002467 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002468 // [NSAutoreleasePool alloc]
2469 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2470 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2471 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002472 RValue AllocRV =
2473 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002474 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002475 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002476
2477 // [Receiver init]
2478 Receiver = AllocRV.getScalarVal();
2479 II = &CGM.getContext().Idents.get("init");
2480 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2481 RValue InitRV =
2482 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2483 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002484 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002485 return InitRV.getScalarVal();
2486}
2487
Pete Coopere3886802018-12-08 05:13:50 +00002488/// Allocate the given objc object.
2489/// call i8* \@objc_alloc(i8* %value)
2490llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2491 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002492 return emitObjCValueOperation(*this, value, resultType,
2493 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002494 "objc_alloc", /*MayThrow=*/true);
Pete Coopere3886802018-12-08 05:13:50 +00002495}
2496
2497/// Allocate the given objc object.
2498/// call i8* \@objc_allocWithZone(i8* %value)
2499llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2500 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002501 return emitObjCValueOperation(*this, value, resultType,
2502 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002503 "objc_allocWithZone", /*MayThrow=*/true);
Pete Coopere3886802018-12-08 05:13:50 +00002504}
2505
John McCall31168b02011-06-15 23:02:42 +00002506/// Produce the code to do a primitive release.
2507/// [tmp drain];
2508void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2509 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2510 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2511 CallArgList Args;
2512 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002513 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002514}
2515
John McCall82fe67b2011-07-09 01:37:26 +00002516void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002517 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002518 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002519 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002520}
2521
2522void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002523 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002524 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002525 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002526}
2527
2528void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002529 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002530 QualType type) {
2531 CGF.EmitARCDestroyWeak(addr);
2532}
2533
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002534void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2535 QualType type) {
2536 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2537 CGF.EmitARCIntrinsicUse(value);
2538}
2539
Pete Coopere5b64ea2018-12-21 21:00:32 +00002540/// Autorelease the given object.
2541/// call i8* \@objc_autorelease(i8* %value)
2542llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2543 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002544 return emitObjCValueOperation(
2545 *this, value, returnType,
2546 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2547 "objc_autorelease", /*MayThrow=*/false);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002548}
2549
2550/// Retain the given object, with normal retain semantics.
2551/// call i8* \@objc_retain(i8* %value)
2552llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2553 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002554 return emitObjCValueOperation(
2555 *this, value, returnType,
2556 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain",
2557 /*MayThrow=*/false);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002558}
2559
2560/// Release the given object.
2561/// call void \@objc_release(i8* %value)
2562void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2563 ARCPreciseLifetime_t precise) {
2564 if (isa<llvm::ConstantPointerNull>(value)) return;
2565
James Y Knight9871db02019-02-05 16:42:33 +00002566 llvm::FunctionCallee &fn =
2567 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002568 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002569 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002570 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002571 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2572 setARCRuntimeFunctionLinkage(CGM, fn);
2573 // We have Native ARC, so set nonlazybind attribute for performance
2574 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2575 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002576 }
2577
2578 // Cast the argument to 'id'.
2579 value = Builder.CreateBitCast(value, Int8PtrTy);
2580
2581 // Call objc_release.
2582 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2583
2584 if (precise == ARCImpreciseLifetime) {
2585 call->setMetadata("clang.imprecise_release",
2586 llvm::MDNode::get(Builder.getContext(), None));
2587 }
2588}
2589
John McCall31168b02011-06-15 23:02:42 +00002590namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002591 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002592 llvm::Value *Token;
2593
2594 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2595
Craig Topper4f12f102014-03-12 06:41:41 +00002596 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002597 CGF.EmitObjCAutoreleasePoolPop(Token);
2598 }
2599 };
David Blaikie7e70d682015-08-18 22:40:54 +00002600 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002601 llvm::Value *Token;
2602
2603 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2604
Craig Topper4f12f102014-03-12 06:41:41 +00002605 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002606 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2607 }
2608 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002609}
John McCall31168b02011-06-15 23:02:42 +00002610
2611void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002612 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002613 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2614 else
2615 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2616}
2617
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002618static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2619 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002620 case Qualifiers::OCL_None:
2621 case Qualifiers::OCL_ExplicitNone:
2622 case Qualifiers::OCL_Strong:
2623 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002624 return true;
John McCall31168b02011-06-15 23:02:42 +00002625
2626 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002627 return false;
John McCall31168b02011-06-15 23:02:42 +00002628 }
2629
2630 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002631}
2632
2633static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002634 LValue lvalue,
2635 QualType type) {
2636 llvm::Value *result;
2637 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2638 if (shouldRetain) {
2639 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2640 } else {
2641 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2642 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2643 }
2644 return TryEmitResult(result, !shouldRetain);
2645}
2646
2647static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002648 const Expr *e) {
2649 e = e->IgnoreParens();
2650 QualType type = e->getType();
2651
Fangrui Song6907ce22018-07-30 19:24:48 +00002652 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002653 // an extra retain/release pair by zeroing out the source of this
2654 // "move" operation.
2655 if (e->isXValue() &&
2656 !type.isConstQualified() &&
2657 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2658 // Emit the lvalue.
2659 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002660
John McCall154a2fd2011-08-30 00:57:29 +00002661 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002662 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2663 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002664
John McCall154a2fd2011-08-30 00:57:29 +00002665 // Set the source pointer to NULL.
2666 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002667
John McCall154a2fd2011-08-30 00:57:29 +00002668 return TryEmitResult(result, true);
2669 }
2670
John McCall31168b02011-06-15 23:02:42 +00002671 // As a very special optimization, in ARC++, if the l-value is the
2672 // result of a non-volatile assignment, do a simple retain of the
2673 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002674 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002675 !type.isVolatileQualified() &&
2676 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2677 isa<BinaryOperator>(e) &&
2678 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2679 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2680
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002681 // Try to emit code for scalar constant instead of emitting LValue and
2682 // loading it because we are not guaranteed to have an l-value. One of such
2683 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2684 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2685 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2686 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2687 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2688 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2689 }
2690
John McCall31168b02011-06-15 23:02:42 +00002691 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2692}
2693
John McCalle399e5b2016-01-27 18:32:30 +00002694typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2695 llvm::Value *value)>
2696 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002697
John McCalle399e5b2016-01-27 18:32:30 +00002698/// Insert code immediately after a call.
2699static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2700 llvm::Value *value,
2701 ValueTransform doAfterCall,
2702 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002703 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2704 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2705
2706 // Place the retain immediately following the call.
2707 CGF.Builder.SetInsertPoint(call->getParent(),
2708 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002709 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002710
2711 CGF.Builder.restoreIP(ip);
2712 return value;
2713 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2714 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2715
2716 // Place the retain at the beginning of the normal destination block.
2717 llvm::BasicBlock *BB = invoke->getNormalDest();
2718 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002719 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002720
2721 CGF.Builder.restoreIP(ip);
2722 return value;
2723
2724 // Bitcasts can arise because of related-result returns. Rewrite
2725 // the operand.
2726 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2727 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002728 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002729 bitcast->setOperand(0, operand);
2730 return bitcast;
2731
2732 // Generic fall-back case.
2733 } else {
2734 // Retain using the non-block variant: we never need to do a copy
2735 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002736 return doFallback(CGF, value);
2737 }
2738}
2739
2740/// Given that the given expression is some sort of call (which does
2741/// not return retained), emit a retain following it.
2742static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2743 const Expr *e) {
2744 llvm::Value *value = CGF.EmitScalarExpr(e);
2745 return emitARCOperationAfterCall(CGF, value,
2746 [](CodeGenFunction &CGF, llvm::Value *value) {
2747 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2748 },
2749 [](CodeGenFunction &CGF, llvm::Value *value) {
2750 return CGF.EmitARCRetainNonBlock(value);
2751 });
2752}
2753
2754/// Given that the given expression is some sort of call (which does
2755/// not return retained), perform an unsafeClaim following it.
2756static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2757 const Expr *e) {
2758 llvm::Value *value = CGF.EmitScalarExpr(e);
2759 return emitARCOperationAfterCall(CGF, value,
2760 [](CodeGenFunction &CGF, llvm::Value *value) {
2761 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2762 },
2763 [](CodeGenFunction &CGF, llvm::Value *value) {
2764 return value;
2765 });
2766}
2767
2768llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2769 bool allowUnsafeClaim) {
2770 if (allowUnsafeClaim &&
2771 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2772 return emitARCUnsafeClaimCallResult(*this, E);
2773 } else {
2774 llvm::Value *value = emitARCRetainCallResult(*this, E);
2775 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002776 }
2777}
2778
John McCallcd78e802011-09-10 01:16:55 +00002779/// Determine whether it might be important to emit a separate
2780/// objc_retain_block on the result of the given expression, or
2781/// whether it's okay to just emit it in a +1 context.
2782static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2783 assert(e->getType()->isBlockPointerType());
2784 e = e->IgnoreParens();
2785
2786 // For future goodness, emit block expressions directly in +1
2787 // contexts if we can.
2788 if (isa<BlockExpr>(e))
2789 return false;
2790
2791 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2792 switch (cast->getCastKind()) {
2793 // Emitting these operations in +1 contexts is goodness.
2794 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002795 case CK_ARCReclaimReturnedObject:
2796 case CK_ARCConsumeObject:
2797 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002798 return false;
2799
2800 // These operations preserve a block type.
2801 case CK_NoOp:
2802 case CK_BitCast:
2803 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2804
2805 // These operations are known to be bad (or haven't been considered).
2806 case CK_AnyPointerToBlockPointerCast:
2807 default:
2808 return true;
2809 }
2810 }
2811
2812 return true;
2813}
2814
John McCalle399e5b2016-01-27 18:32:30 +00002815namespace {
2816/// A CRTP base class for emitting expressions of retainable object
2817/// pointer type in ARC.
2818template <typename Impl, typename Result> class ARCExprEmitter {
2819protected:
2820 CodeGenFunction &CGF;
2821 Impl &asImpl() { return *static_cast<Impl*>(this); }
2822
2823 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2824
2825public:
2826 Result visit(const Expr *e);
2827 Result visitCastExpr(const CastExpr *e);
2828 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2829 Result visitBinaryOperator(const BinaryOperator *e);
2830 Result visitBinAssign(const BinaryOperator *e);
2831 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2832 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2833 Result visitBinAssignWeak(const BinaryOperator *e);
2834 Result visitBinAssignStrong(const BinaryOperator *e);
2835
2836 // Minimal implementation:
2837 // Result visitLValueToRValue(const Expr *e)
2838 // Result visitConsumeObject(const Expr *e)
2839 // Result visitExtendBlockObject(const Expr *e)
2840 // Result visitReclaimReturnedObject(const Expr *e)
2841 // Result visitCall(const Expr *e)
2842 // Result visitExpr(const Expr *e)
2843 //
2844 // Result emitBitCast(Result result, llvm::Type *resultType)
2845 // llvm::Value *getValueOfResult(Result result)
2846};
2847}
2848
2849/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002850///
2851/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002852template <typename Impl, typename Result>
2853Result
2854ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002855 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002856
2857 // Find the result expression.
2858 const Expr *resultExpr = E->getResultExpr();
2859 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002860 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002861
2862 for (PseudoObjectExpr::const_semantics_iterator
2863 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2864 const Expr *semantic = *i;
2865
2866 // If this semantic expression is an opaque value, bind it
2867 // to the result of its source expression.
2868 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2869 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2870 OVMA opaqueData;
2871
2872 // If this semantic is the result of the pseudo-object
2873 // expression, try to evaluate the source as +1.
2874 if (ov == resultExpr) {
2875 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002876 result = asImpl().visit(ov->getSourceExpr());
2877 opaqueData = OVMA::bind(CGF, ov,
2878 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002879
2880 // Otherwise, just bind it.
2881 } else {
2882 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2883 }
2884 opaques.push_back(opaqueData);
2885
2886 // Otherwise, if the expression is the result, evaluate it
2887 // and remember the result.
2888 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002889 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002890
2891 // Otherwise, evaluate the expression in an ignored context.
2892 } else {
2893 CGF.EmitIgnoredExpr(semantic);
2894 }
2895 }
2896
2897 // Unbind all the opaques now.
2898 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2899 opaques[i].unbind(CGF);
2900
2901 return result;
2902}
2903
John McCalle399e5b2016-01-27 18:32:30 +00002904template <typename Impl, typename Result>
2905Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2906 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002907
John McCalle399e5b2016-01-27 18:32:30 +00002908 // No-op casts don't change the type, so we just ignore them.
2909 case CK_NoOp:
2910 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002911
John McCalle399e5b2016-01-27 18:32:30 +00002912 // These casts can change the type.
2913 case CK_CPointerToObjCPointerCast:
2914 case CK_BlockPointerToObjCPointerCast:
2915 case CK_AnyPointerToBlockPointerCast:
2916 case CK_BitCast: {
2917 llvm::Type *resultType = CGF.ConvertType(e->getType());
2918 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2919 Result result = asImpl().visit(e->getSubExpr());
2920 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002921 }
2922
John McCalle399e5b2016-01-27 18:32:30 +00002923 // Handle some casts specially.
2924 case CK_LValueToRValue:
2925 return asImpl().visitLValueToRValue(e->getSubExpr());
2926 case CK_ARCConsumeObject:
2927 return asImpl().visitConsumeObject(e->getSubExpr());
2928 case CK_ARCExtendBlockObject:
2929 return asImpl().visitExtendBlockObject(e->getSubExpr());
2930 case CK_ARCReclaimReturnedObject:
2931 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2932
2933 // Otherwise, use the default logic.
2934 default:
2935 return asImpl().visitExpr(e);
2936 }
2937}
2938
2939template <typename Impl, typename Result>
2940Result
2941ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2942 switch (e->getOpcode()) {
2943 case BO_Comma:
2944 CGF.EmitIgnoredExpr(e->getLHS());
2945 CGF.EnsureInsertPoint();
2946 return asImpl().visit(e->getRHS());
2947
2948 case BO_Assign:
2949 return asImpl().visitBinAssign(e);
2950
2951 default:
2952 return asImpl().visitExpr(e);
2953 }
2954}
2955
2956template <typename Impl, typename Result>
2957Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2958 switch (e->getLHS()->getType().getObjCLifetime()) {
2959 case Qualifiers::OCL_ExplicitNone:
2960 return asImpl().visitBinAssignUnsafeUnretained(e);
2961
2962 case Qualifiers::OCL_Weak:
2963 return asImpl().visitBinAssignWeak(e);
2964
2965 case Qualifiers::OCL_Autoreleasing:
2966 return asImpl().visitBinAssignAutoreleasing(e);
2967
2968 case Qualifiers::OCL_Strong:
2969 return asImpl().visitBinAssignStrong(e);
2970
2971 case Qualifiers::OCL_None:
2972 return asImpl().visitExpr(e);
2973 }
2974 llvm_unreachable("bad ObjC ownership qualifier");
2975}
2976
2977/// The default rule for __unsafe_unretained emits the RHS recursively,
2978/// stores into the unsafe variable, and propagates the result outward.
2979template <typename Impl, typename Result>
2980Result ARCExprEmitter<Impl,Result>::
2981 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2982 // Recursively emit the RHS.
2983 // For __block safety, do this before emitting the LHS.
2984 Result result = asImpl().visit(e->getRHS());
2985
2986 // Perform the store.
2987 LValue lvalue =
2988 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2989 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2990 lvalue);
2991
2992 return result;
2993}
2994
2995template <typename Impl, typename Result>
2996Result
2997ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2998 return asImpl().visitExpr(e);
2999}
3000
3001template <typename Impl, typename Result>
3002Result
3003ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3004 return asImpl().visitExpr(e);
3005}
3006
3007template <typename Impl, typename Result>
3008Result
3009ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3010 return asImpl().visitExpr(e);
3011}
3012
3013/// The general expression-emission logic.
3014template <typename Impl, typename Result>
3015Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3016 // We should *never* see a nested full-expression here, because if
3017 // we fail to emit at +1, our caller must not retain after we close
3018 // out the full-expression. This isn't as important in the unsafe
3019 // emitter.
3020 assert(!isa<ExprWithCleanups>(e));
3021
3022 // Look through parens, __extension__, generic selection, etc.
3023 e = e->IgnoreParens();
3024
3025 // Handle certain kinds of casts.
3026 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3027 return asImpl().visitCastExpr(ce);
3028
3029 // Handle the comma operator.
3030 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3031 return asImpl().visitBinaryOperator(op);
3032
3033 // TODO: handle conditional operators here
3034
3035 // For calls and message sends, use the retained-call logic.
3036 // Delegate inits are a special case in that they're the only
3037 // returns-retained expression that *isn't* surrounded by
3038 // a consume.
3039 } else if (isa<CallExpr>(e) ||
3040 (isa<ObjCMessageExpr>(e) &&
3041 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3042 return asImpl().visitCall(e);
3043
3044 // Look through pseudo-object expressions.
3045 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3046 return asImpl().visitPseudoObjectExpr(pseudo);
3047 }
3048
3049 return asImpl().visitExpr(e);
3050}
3051
3052namespace {
3053
3054/// An emitter for +1 results.
3055struct ARCRetainExprEmitter :
3056 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3057
3058 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3059
3060 llvm::Value *getValueOfResult(TryEmitResult result) {
3061 return result.getPointer();
3062 }
3063
3064 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3065 llvm::Value *value = result.getPointer();
3066 value = CGF.Builder.CreateBitCast(value, resultType);
3067 result.setPointer(value);
3068 return result;
3069 }
3070
3071 TryEmitResult visitLValueToRValue(const Expr *e) {
3072 return tryEmitARCRetainLoadOfScalar(CGF, e);
3073 }
3074
3075 /// For consumptions, just emit the subexpression and thus elide
3076 /// the retain/release pair.
3077 TryEmitResult visitConsumeObject(const Expr *e) {
3078 llvm::Value *result = CGF.EmitScalarExpr(e);
3079 return TryEmitResult(result, true);
3080 }
3081
3082 /// Block extends are net +0. Naively, we could just recurse on
3083 /// the subexpression, but actually we need to ensure that the
3084 /// value is copied as a block, so there's a little filter here.
3085 TryEmitResult visitExtendBlockObject(const Expr *e) {
3086 llvm::Value *result; // will be a +0 value
3087
3088 // If we can't safely assume the sub-expression will produce a
3089 // block-copied value, emit the sub-expression at +0.
3090 if (shouldEmitSeparateBlockRetain(e)) {
3091 result = CGF.EmitScalarExpr(e);
3092
3093 // Otherwise, try to emit the sub-expression at +1 recursively.
3094 } else {
3095 TryEmitResult subresult = asImpl().visit(e);
3096
3097 // If that produced a retained value, just use that.
3098 if (subresult.getInt()) {
3099 return subresult;
3100 }
3101
3102 // Otherwise it's +0.
3103 result = subresult.getPointer();
3104 }
3105
3106 // Retain the object as a block.
3107 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3108 return TryEmitResult(result, true);
3109 }
3110
3111 /// For reclaims, emit the subexpression as a retained call and
3112 /// skip the consumption.
3113 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3114 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3115 return TryEmitResult(result, true);
3116 }
3117
3118 /// When we have an undecorated call, retroactively do a claim.
3119 TryEmitResult visitCall(const Expr *e) {
3120 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3121 return TryEmitResult(result, true);
3122 }
3123
3124 // TODO: maybe special-case visitBinAssignWeak?
3125
3126 TryEmitResult visitExpr(const Expr *e) {
3127 // We didn't find an obvious production, so emit what we've got and
3128 // tell the caller that we didn't manage to retain.
3129 llvm::Value *result = CGF.EmitScalarExpr(e);
3130 return TryEmitResult(result, false);
3131 }
3132};
3133}
3134
3135static TryEmitResult
3136tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3137 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003138}
3139
3140static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3141 LValue lvalue,
3142 QualType type) {
3143 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3144 llvm::Value *value = result.getPointer();
3145 if (!result.getInt())
3146 value = CGF.EmitARCRetain(type, value);
3147 return value;
3148}
3149
3150/// EmitARCRetainScalarExpr - Semantically equivalent to
3151/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3152/// best-effort attempt to peephole expressions that naturally produce
3153/// retained objects.
3154llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003155 // The retain needs to happen within the full-expression.
3156 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3157 enterFullExpression(cleanups);
3158 RunCleanupsScope scope(*this);
3159 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3160 }
3161
John McCall31168b02011-06-15 23:02:42 +00003162 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3163 llvm::Value *value = result.getPointer();
3164 if (!result.getInt())
3165 value = EmitARCRetain(e->getType(), value);
3166 return value;
3167}
3168
3169llvm::Value *
3170CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003171 // The retain needs to happen within the full-expression.
3172 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3173 enterFullExpression(cleanups);
3174 RunCleanupsScope scope(*this);
3175 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3176 }
3177
John McCall31168b02011-06-15 23:02:42 +00003178 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3179 llvm::Value *value = result.getPointer();
3180 if (result.getInt())
3181 value = EmitARCAutorelease(value);
3182 else
3183 value = EmitARCRetainAutorelease(e->getType(), value);
3184 return value;
3185}
3186
John McCallff613032011-10-04 06:23:45 +00003187llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3188 llvm::Value *result;
3189 bool doRetain;
3190
3191 if (shouldEmitSeparateBlockRetain(e)) {
3192 result = EmitScalarExpr(e);
3193 doRetain = true;
3194 } else {
3195 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3196 result = subresult.getPointer();
3197 doRetain = !subresult.getInt();
3198 }
3199
3200 if (doRetain)
3201 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3202 return EmitObjCConsumeObject(e->getType(), result);
3203}
3204
John McCall248512a2011-10-01 10:32:24 +00003205llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3206 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003207 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003208 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003209 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003210 return EmitARCRetainAutoreleaseScalarExpr(expr);
3211 }
3212
3213 // Otherwise, use the normal scalar-expression emission. The
3214 // exception machinery doesn't do anything special with the
3215 // exception like retaining it, so there's no safety associated with
3216 // only running cleanups after the throw has started, and when it
3217 // matters it tends to be substantially inferior code.
3218 return EmitScalarExpr(expr);
3219}
3220
John McCalle399e5b2016-01-27 18:32:30 +00003221namespace {
3222
3223/// An emitter for assigning into an __unsafe_unretained context.
3224struct ARCUnsafeUnretainedExprEmitter :
3225 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3226
3227 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3228
3229 llvm::Value *getValueOfResult(llvm::Value *value) {
3230 return value;
3231 }
3232
3233 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3234 return CGF.Builder.CreateBitCast(value, resultType);
3235 }
3236
3237 llvm::Value *visitLValueToRValue(const Expr *e) {
3238 return CGF.EmitScalarExpr(e);
3239 }
3240
3241 /// For consumptions, just emit the subexpression and perform the
3242 /// consumption like normal.
3243 llvm::Value *visitConsumeObject(const Expr *e) {
3244 llvm::Value *value = CGF.EmitScalarExpr(e);
3245 return CGF.EmitObjCConsumeObject(e->getType(), value);
3246 }
3247
3248 /// No special logic for block extensions. (This probably can't
3249 /// actually happen in this emitter, though.)
3250 llvm::Value *visitExtendBlockObject(const Expr *e) {
3251 return CGF.EmitARCExtendBlockObject(e);
3252 }
3253
3254 /// For reclaims, perform an unsafeClaim if that's enabled.
3255 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3256 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3257 }
3258
3259 /// When we have an undecorated call, just emit it without adding
3260 /// the unsafeClaim.
3261 llvm::Value *visitCall(const Expr *e) {
3262 return CGF.EmitScalarExpr(e);
3263 }
3264
3265 /// Just do normal scalar emission in the default case.
3266 llvm::Value *visitExpr(const Expr *e) {
3267 return CGF.EmitScalarExpr(e);
3268 }
3269};
3270}
3271
3272static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3273 const Expr *e) {
3274 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3275}
3276
3277/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3278/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3279/// avoiding any spurious retains, including by performing reclaims
3280/// with objc_unsafeClaimAutoreleasedReturnValue.
3281llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3282 // Look through full-expressions.
3283 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3284 enterFullExpression(cleanups);
3285 RunCleanupsScope scope(*this);
3286 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3287 }
3288
3289 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3290}
3291
3292std::pair<LValue,llvm::Value*>
3293CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3294 bool ignored) {
3295 // Evaluate the RHS first. If we're ignoring the result, assume
3296 // that we can emit at an unsafe +0.
3297 llvm::Value *value;
3298 if (ignored) {
3299 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3300 } else {
3301 value = EmitScalarExpr(e->getRHS());
3302 }
3303
3304 // Emit the LHS and perform the store.
3305 LValue lvalue = EmitLValue(e->getLHS());
3306 EmitStoreOfScalar(value, lvalue);
3307
3308 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3309}
3310
John McCall31168b02011-06-15 23:02:42 +00003311std::pair<LValue,llvm::Value*>
3312CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3313 bool ignored) {
3314 // Evaluate the RHS first.
3315 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3316 llvm::Value *value = result.getPointer();
3317
John McCallb726a552011-07-28 07:23:35 +00003318 bool hasImmediateRetain = result.getInt();
3319
3320 // If we didn't emit a retained object, and the l-value is of block
3321 // type, then we need to emit the block-retain immediately in case
3322 // it invalidates the l-value.
3323 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003324 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003325 hasImmediateRetain = true;
3326 }
3327
John McCall31168b02011-06-15 23:02:42 +00003328 LValue lvalue = EmitLValue(e->getLHS());
3329
3330 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003331 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003332 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003333 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003334 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003335 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003336 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003337 }
3338
3339 return std::pair<LValue,llvm::Value*>(lvalue, value);
3340}
3341
3342std::pair<LValue,llvm::Value*>
3343CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3344 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3345 LValue lvalue = EmitLValue(e->getLHS());
3346
Eli Friedmana0544d62011-12-03 04:14:32 +00003347 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003348
3349 return std::pair<LValue,llvm::Value*>(lvalue, value);
3350}
3351
3352void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003353 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003354 const Stmt *subStmt = ARPS.getSubStmt();
3355 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3356
3357 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003358 if (DI)
3359 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003360
3361 // Keep track of the current cleanup stack depth.
3362 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003363 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003364 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3365 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3366 } else {
3367 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3368 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3369 }
3370
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003371 for (const auto *I : S.body())
3372 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003373
Eric Christopher7cdf9482011-10-13 21:45:18 +00003374 if (DI)
3375 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003376}
John McCall1bd25562011-06-24 23:21:27 +00003377
3378/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3379/// make sure it survives garbage collection until this point.
3380void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3381 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003382 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003383 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003384 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3385 /* assembly */ "",
3386 /* constraints */ "r",
3387 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003388
3389 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003390 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003391}
3392
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003393/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003394/// non-trivial copy assignment function, produce following helper function.
3395/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3396///
3397llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003398CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3399 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003400 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003401 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003402 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003403 QualType Ty = PID->getPropertyIvarDecl()->getType();
3404 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003405 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003406 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003407 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003408 return nullptr;
3409 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003410 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003411 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003412 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3413 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3414 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003415
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003416 ASTContext &C = getContext();
3417 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003418 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003419
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003420 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003421 QualType DestTy = C.getPointerType(Ty);
3422 QualType SrcTy = Ty;
3423 SrcTy.addConst();
3424 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003425
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003426 SmallVector<QualType, 2> ArgTys;
3427 ArgTys.push_back(DestTy);
3428 ArgTys.push_back(SrcTy);
3429 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3430
3431 FunctionDecl *FD = FunctionDecl::Create(
3432 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3433 FunctionTy, nullptr, SC_Static, false, false);
3434
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003435 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003436 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3437 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003438 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003439 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3440 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003441 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003442
John McCallc56a8b32016-03-11 04:30:31 +00003443 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003444 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003445
John McCalla729c622012-02-17 03:33:10 +00003446 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003447
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003448 llvm::Function *Fn =
3449 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003450 "__assign_helper_atomic_property_",
3451 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003452
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003453 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003454
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003455 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003456
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003457 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3458 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003459 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003460 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003461
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003462 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3463 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003464 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003465 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003466
John McCall113bee02012-03-10 09:33:50 +00003467 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003468 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003469 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3470 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3471 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003472
Bruno Riccic5885cf2018-12-21 15:20:32 +00003473 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003474
3475 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003476 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003477 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003478 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003479}
3480
3481llvm::Constant *
3482CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3483 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003484 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003485 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003486 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003487 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3488 QualType Ty = PD->getType();
3489 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003490 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003491 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003492 return nullptr;
3493 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003494 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003495 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003496 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3497 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3498 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003499
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003500 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003501 IdentifierInfo *II =
3502 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003503
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003504 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003505 QualType DestTy = C.getPointerType(Ty);
3506 QualType SrcTy = Ty;
3507 SrcTy.addConst();
3508 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003509
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003510 SmallVector<QualType, 2> ArgTys;
3511 ArgTys.push_back(DestTy);
3512 ArgTys.push_back(SrcTy);
3513 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3514
3515 FunctionDecl *FD = FunctionDecl::Create(
3516 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3517 FunctionTy, nullptr, SC_Static, false, false);
3518
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003519 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003520 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3521 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003522 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003523 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3524 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003525 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003526
John McCallc56a8b32016-03-11 04:30:31 +00003527 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003528 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003529
John McCalla729c622012-02-17 03:33:10 +00003530 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003531
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003532 llvm::Function *Fn = llvm::Function::Create(
3533 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3534 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003535
3536 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003537
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003538 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003539
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003540 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3541 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003542
John McCall113bee02012-03-10 09:33:50 +00003543 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003544 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003545
3546 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003547 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003548
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003549 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003550 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003551 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3552 CXXConstExpr->arg_end());
3553
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003554 CXXConstructExpr *TheCXXConstructExpr =
3555 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3556 CXXConstExpr->getConstructor(),
3557 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003558 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003559 CXXConstExpr->hadMultipleCandidates(),
3560 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003561 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003562 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003563 CXXConstExpr->getConstructionKind(),
3564 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003565
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003566 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3567 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003568
John McCall113bee02012-03-10 09:33:50 +00003569 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003570 CharUnits Alignment
3571 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003572 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003573 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3574 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003575 AggValueSlot::IsDestructed,
3576 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003577 AggValueSlot::IsNotAliased,
3578 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003579
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003580 FinishFunction();
3581 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3582 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3583 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003584}
3585
Eli Friedmanec75fec2012-02-28 01:08:45 +00003586llvm::Value *
3587CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3588 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003589 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3590 Selector CopySelector =
3591 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003592 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3593 Selector AutoreleaseSelector =
3594 getContext().Selectors.getNullarySelector(AutoreleaseID);
3595
3596 // Emit calls to retain/autorelease.
3597 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3598 llvm::Value *Val = Block;
3599 RValue Result;
3600 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003601 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003602 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003603 Val = Result.getScalarVal();
3604 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3605 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003606 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003607 Val = Result.getScalarVal();
3608 return Val;
3609}
3610
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003611llvm::Value *
3612CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3613 assert(Args.size() == 3 && "Expected 3 argument here!");
3614
3615 if (!CGM.IsOSVersionAtLeastFn) {
3616 llvm::FunctionType *FTy =
3617 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3618 CGM.IsOSVersionAtLeastFn =
3619 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3620 }
3621
3622 llvm::Value *CallRes =
3623 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3624
3625 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3626}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003627
Alex Lorenza8fbef42017-03-23 11:14:27 +00003628void CodeGenModule::emitAtAvailableLinkGuard() {
3629 if (!IsOSVersionAtLeastFn)
3630 return;
3631 // @available requires CoreFoundation only on Darwin.
3632 if (!Target.getTriple().isOSDarwin())
3633 return;
3634 // Add -framework CoreFoundation to the linker commands. We still want to
3635 // emit the core foundation reference down below because otherwise if
3636 // CoreFoundation is not used in the code, the linker won't link the
3637 // framework.
3638 auto &Context = getLLVMContext();
3639 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3640 llvm::MDString::get(Context, "CoreFoundation")};
3641 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3642 // Emit a reference to a symbol from CoreFoundation to ensure that
3643 // CoreFoundation is linked into the final binary.
3644 llvm::FunctionType *FTy =
3645 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003646 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003647 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3648
3649 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003650 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3651 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
3652 llvm::AttributeList(), /*IsLocal=*/true);
3653 llvm::Function *CFLinkCheckFunc =
3654 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3655 if (CFLinkCheckFunc->empty()) {
3656 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3657 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3658 CodeGenFunction CGF(*this);
3659 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3660 CGF.EmitNounwindRuntimeCall(CFFunc,
3661 llvm::Constant::getNullValue(VoidPtrTy));
3662 CGF.Builder.CreateUnreachable();
3663 addCompilerUsedGlobal(CFLinkCheckFunc);
3664 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003665}
3666
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003667CGObjCRuntime::~CGObjCRuntime() {}