blob: 1fa72678081af5123d014a8fa011d253e693d427 [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"
Akira Hatanaka1488ee42019-03-08 04:45:37 +000017#include "ConstantEmitter.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall31168b02011-06-15 23:02:42 +000030typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
31static TryEmitResult
32tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000033static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
34 QualType ET,
35 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000039static llvm::Constant *getNullForVariable(Address addr) {
40 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000041 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
42}
43
Chris Lattnerb1d329d2008-06-24 17:04:18 +000044/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000045llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000046{
Fangrui Song6907ce22018-07-30 19:24:48 +000047 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000048 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000049 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000050 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000051}
52
Patrick Beard0caa3942012-04-19 00:25:12 +000053/// EmitObjCBoxedExpr - This routine generates code to call
54/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000055/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
56/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000057///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000058llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000062 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000063 const Expr *SubExpr = E->getSubExpr();
Akira Hatanaka1488ee42019-03-08 04:45:37 +000064
65 if (E->isExpressibleAsConstantInitializer()) {
66 ConstantEmitter ConstEmitter(CGM);
67 return ConstEmitter.tryEmitAbstract(E, E->getType());
68 }
69
Patrick Beard0caa3942012-04-19 00:25:12 +000070 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
71 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000072
Ted Kremeneke65b0862012-03-06 20:05:56 +000073 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000074 // Assumes that the method was introduced in the class that should be
75 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000077 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000078 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000079
Ted Kremeneke65b0862012-03-06 20:05:56 +000080 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000081 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
82 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000083
84 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000085 // via [NSValue valueWithBytes:objCType:]
86 const QualType ValueType(SubExpr->getType().getCanonicalType());
87 if (ValueType->isObjCBoxableRecordType()) {
88 // Emit CodeGen for first parameter
89 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000090 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000091 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000092 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
93 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000094
95 // Create char array to store type encoding
96 std::string Str;
97 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000098 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +000099
Alex Denisovfde64952015-06-26 05:28:36 +0000100 // Cast type encoding to correct type
101 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
102 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
103 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
104
105 Args.add(RValue::get(Cast), EncodingQT);
106 } else {
107 Args.add(EmitAnyExpr(SubExpr), ArgQT);
108 }
Alp Toker314cc812014-01-25 16:55:45 +0000109
110 RValue result = Runtime.GenerateMessageSend(
111 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
112 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000113 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000114 ConvertType(E->getType()));
115}
116
117llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000118 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000120 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
122 if (!ALE)
123 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000124
125 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000126 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000127 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000128 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
129 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
130 QualType IdTy(CGM.getContext().getObjCIdType());
131 llvm::Constant *Constant =
132 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000133 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000134 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000135 cast<llvm::LoadInst>(Ptr)->setMetadata(
136 CGM.getModule().getMDKindID("invariant.load"),
137 llvm::MDNode::get(getLLVMContext(), None));
138 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000139 }
140
141 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000142 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
143 NumElements);
144 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000145 QualType ElementArrayType
Richard Smith772e2662019-10-04 01:25:59 +0000146 = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000147 ArrayType::Normal, /*IndexTypeQuals=*/0);
148
149 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000150 Address Objects = CreateMemTemp(ElementArrayType, "objects");
151 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000152 if (DLE)
153 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000154
John McCall770a4c12013-04-04 00:20:38 +0000155 // In ARC, we may need to do extra work to keep all the keys and
156 // values alive until after the call.
157 SmallVector<llvm::Value *, 16> NeededObjects;
158 bool TrackNeededObjects =
159 (getLangOpts().ObjCAutoRefCount &&
160 CGM.getCodeGenOpts().OptimizationLevel != 0);
161
Ted Kremeneke65b0862012-03-06 20:05:56 +0000162 // Perform the actual initialialization of the array(s).
163 for (uint64_t i = 0; i < NumElements; i++) {
164 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000165 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000166 const Expr *Rhs = ALE->getElement(i);
James Y Knight751fe282019-02-09 22:22:28 +0000167 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
168 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000169
170 llvm::Value *value = EmitScalarExpr(Rhs);
171 EmitStoreThroughLValue(RValue::get(value), LV, true);
172 if (TrackNeededObjects) {
173 NeededObjects.push_back(value);
174 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000175 } else {
John McCall770a4c12013-04-04 00:20:38 +0000176 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000177 const Expr *Key = DLE->getKeyValueElement(i).Key;
James Y Knight751fe282019-02-09 22:22:28 +0000178 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
179 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000180 llvm::Value *keyValue = EmitScalarExpr(Key);
181 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000182
John McCall770a4c12013-04-04 00:20:38 +0000183 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000184 const Expr *Value = DLE->getKeyValueElement(i).Value;
James Y Knight751fe282019-02-09 22:22:28 +0000185 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
186 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000187 llvm::Value *valueValue = EmitScalarExpr(Value);
188 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
189 if (TrackNeededObjects) {
190 NeededObjects.push_back(keyValue);
191 NeededObjects.push_back(valueValue);
192 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000193 }
194 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000195
Ted Kremeneke65b0862012-03-06 20:05:56 +0000196 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000197 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000198 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
199 const ParmVarDecl *argDecl = *PI++;
200 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000201 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000202 if (DLE) {
203 argDecl = *PI++;
204 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000205 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000206 }
207 argDecl = *PI;
208 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000209 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000210 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
211 Args.add(RValue::get(Count), ArgQT);
212
213 // Generate a reference to the class pointer, which will be the receiver.
214 Selector Sel = MethodWithObjects->getSelector();
215 QualType ResultType = E->getType();
216 const ObjCObjectPointerType *InterfacePointerType
217 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000218 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000219 = InterfacePointerType->getObjectType()->getInterface();
220 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000221 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000222
223 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000224 RValue result = Runtime.GenerateMessageSend(
225 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
226 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000227
228 // The above message send needs these objects, but in ARC they are
229 // passed in a buffer that is essentially __unsafe_unretained.
230 // Therefore we must prevent the optimizer from releasing them until
231 // after the call.
232 if (TrackNeededObjects) {
233 EmitARCIntrinsicUse(NeededObjects);
234 }
235
Fangrui Song6907ce22018-07-30 19:24:48 +0000236 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000237 ConvertType(E->getType()));
238}
239
240llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000241 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000242}
243
244llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
245 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000246 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000247}
248
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000249/// Emit a selector.
250llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
251 // Untyped selector.
252 // Note that this implementation allows for non-constant strings to be passed
253 // as arguments to @selector(). Currently, the only thing preventing this
254 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000255 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000256}
257
Daniel Dunbar66912a12008-08-20 00:28:19 +0000258llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
259 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000260 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000261}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000263/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000264/// to type erasure at various points, e.g., related result types or the use
265/// of parameterized classes.
266static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
267 RValue Result) {
268 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000269 return Result;
John McCall31168b02011-06-15 23:02:42 +0000270
Douglas Gregore83b9562015-07-07 03:57:53 +0000271 // If the converted types are the same, we're done.
272 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
273 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000274 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000275
276 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000277 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000278 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000279}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000280
John McCallcf166702011-07-22 08:53:00 +0000281/// Decide whether to extend the lifetime of the receiver of a
282/// returns-inner-pointer message.
283static bool
284shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
285 switch (message->getReceiverKind()) {
286
287 // For a normal instance message, we should extend unless the
288 // receiver is loaded from a variable with precise lifetime.
289 case ObjCMessageExpr::Instance: {
290 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000291
292 // Look through OVEs.
293 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
294 if (opaque->getSourceExpr())
295 receiver = opaque->getSourceExpr()->IgnoreParens();
296 }
297
John McCallcf166702011-07-22 08:53:00 +0000298 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
299 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
300 receiver = ice->getSubExpr()->IgnoreParens();
301
John McCall6380a282015-09-09 23:37:17 +0000302 // Look through OVEs.
303 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
304 if (opaque->getSourceExpr())
305 receiver = opaque->getSourceExpr()->IgnoreParens();
306 }
307
John McCallcf166702011-07-22 08:53:00 +0000308 // Only __strong variables.
309 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
310 return true;
311
312 // All ivars and fields have precise lifetime.
313 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
314 return false;
315
316 // Otherwise, check for variables.
317 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
318 if (!declRef) return true;
319 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
320 if (!var) return true;
321
322 // All variables have precise lifetime except local variables with
323 // automatic storage duration that aren't specially marked.
324 return (var->hasLocalStorage() &&
325 !var->hasAttr<ObjCPreciseLifetimeAttr>());
326 }
327
328 case ObjCMessageExpr::Class:
329 case ObjCMessageExpr::SuperClass:
330 // It's never necessary for class objects.
331 return false;
332
333 case ObjCMessageExpr::SuperInstance:
334 // We generally assume that 'self' lives throughout a method call.
335 return false;
336 }
337
338 llvm_unreachable("invalid receiver kind");
339}
340
John McCall460ce582015-10-22 18:38:17 +0000341/// Given an expression of ObjC pointer type, check whether it was
342/// immediately loaded from an ARC __weak l-value.
343static const Expr *findWeakLValue(const Expr *E) {
344 assert(E->getType()->isObjCRetainableType());
345 E = E->IgnoreParens();
346 if (auto CE = dyn_cast<CastExpr>(E)) {
347 if (CE->getCastKind() == CK_LValueToRValue) {
348 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
349 return CE->getSubExpr();
350 }
351 }
352
353 return nullptr;
354}
355
Pete Coopere3886802018-12-08 05:13:50 +0000356/// The ObjC runtime may provide entrypoints that are likely to be faster
357/// than an ordinary message send of the appropriate selector.
358///
359/// The entrypoints are guaranteed to be equivalent to just sending the
360/// corresponding message. If the entrypoint is implemented naively as just a
361/// message send, using it is a trade-off: it sacrifices a few cycles of
362/// overhead to save a small amount of code. However, it's possible for
363/// runtimes to detect and special-case classes that use "standard"
364/// behavior; if that's dynamically a large proportion of all objects, using
365/// the entrypoint will also be faster than using a message send.
366///
367/// If the runtime does support a required entrypoint, then this method will
368/// generate a call and return the resulting value. Otherwise it will return
369/// None and the caller can generate a msgSend instead.
370static Optional<llvm::Value *>
371tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
372 llvm::Value *Receiver,
373 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000374 const ObjCMethodDecl *method,
375 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000376 auto &CGM = CGF.CGM;
377 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
378 return None;
379
380 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
381 switch (Sel.getMethodFamily()) {
382 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000383 if (isClassMessage &&
384 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000385 ResultType->isObjCObjectPointerType()) {
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000386 // [Foo alloc] -> objc_alloc(Foo) or
387 // [self alloc] -> objc_alloc(self)
Pete Coopere3886802018-12-08 05:13:50 +0000388 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
389 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000390 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
391 // [self allocWithZone:nil] -> objc_allocWithZone(self)
Pete Coopere3886802018-12-08 05:13:50 +0000392 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
393 Args.size() == 1 && Args.front().getType()->isPointerType() &&
394 Sel.getNameForSlot(0) == "allocWithZone") {
395 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
396 if (isa<llvm::ConstantPointerNull>(arg))
397 return CGF.EmitObjCAllocWithZone(Receiver,
398 CGF.ConvertType(ResultType));
399 return None;
400 }
401 }
402 break;
403
Pete Coopere5b64ea2018-12-21 21:00:32 +0000404 case OMF_autorelease:
405 if (ResultType->isObjCObjectPointerType() &&
406 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
407 Runtime.shouldUseARCFunctionsForRetainRelease())
408 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
409 break;
410
411 case OMF_retain:
412 if (ResultType->isObjCObjectPointerType() &&
413 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
414 Runtime.shouldUseARCFunctionsForRetainRelease())
415 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
416 break;
417
418 case OMF_release:
419 if (ResultType->isVoidType() &&
420 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
421 Runtime.shouldUseARCFunctionsForRetainRelease()) {
422 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
423 return nullptr;
424 }
425 break;
426
Pete Coopere3886802018-12-08 05:13:50 +0000427 default:
428 break;
429 }
430 return None;
431}
432
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000433/// Instead of '[[MyClass alloc] init]', try to generate
434/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
435/// caller side, as well as the optimized objc_alloc.
436static Optional<llvm::Value *>
437tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
438 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
439 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
440 return None;
441
442 // Match the exact pattern '[[MyClass alloc] init]'.
443 Selector Sel = OME->getSelector();
Erik Pilkington55e703a2019-02-25 21:35:14 +0000444 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
445 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
446 Sel.getNameForSlot(0) != "init")
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000447 return None;
448
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000449 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]' or
450 // we are in an ObjC class method and 'receiver' is '[self alloc]'.
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000451 auto *SubOME =
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000452 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000453 if (!SubOME)
454 return None;
455 Selector SubSel = SubOME->getSelector();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000456
457 // Check if we are in an ObjC class method and the receiver expression is
458 // 'self'.
459 const Expr *SelfInClassMethod = nullptr;
460 if (const auto *CurMD = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
461 if (CurMD->isClassMethod())
462 if ((SelfInClassMethod = SubOME->getInstanceReceiver()))
463 if (!SelfInClassMethod->isObjCSelfExpr())
464 SelfInClassMethod = nullptr;
465
466 if ((SubOME->getReceiverKind() != ObjCMessageExpr::Class &&
467 !SelfInClassMethod) || !SubOME->getType()->isObjCObjectPointerType() ||
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000468 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
469 return None;
470
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000471 llvm::Value *Receiver;
472 if (SelfInClassMethod) {
473 Receiver = CGF.EmitScalarExpr(SelfInClassMethod);
474 } else {
475 QualType ReceiverType = SubOME->getClassReceiver();
476 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
477 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
478 assert(ID && "null interface should be impossible here");
479 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
480 }
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000481 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
482}
483
John McCall78a15112010-05-22 01:48:05 +0000484RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
485 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000486 // Only the lookup mechanism and first two arguments of the method
487 // implementation vary between runtimes. We can get the receiver and
488 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000489
John McCall31168b02011-06-15 23:02:42 +0000490 bool isDelegateInit = E->isDelegateInitCall();
491
John McCallcf166702011-07-22 08:53:00 +0000492 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000493
John McCall460ce582015-10-22 18:38:17 +0000494 // If the method is -retain, and the receiver's being loaded from
495 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
496 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
497 method->getMethodFamily() == OMF_retain) {
498 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
499 LValue lvalue = EmitLValue(lvalueExpr);
500 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
501 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
502 }
503 }
504
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000505 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
506 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
507
John McCall31168b02011-06-15 23:02:42 +0000508 // We don't retain the receiver in delegate init calls, and this is
509 // safe because the receiver value is always loaded from 'self',
510 // which we zero out. We don't want to Block_copy block receivers,
511 // though.
512 bool retainSelf =
513 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000514 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000515 method &&
516 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000517
Daniel Dunbar8d480592008-08-11 18:12:00 +0000518 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000519 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000520 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000521 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000522 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000523 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000524 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000525 switch (E->getReceiverKind()) {
526 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000527 ReceiverType = E->getInstanceReceiver()->getType();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000528 if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl))
529 if (OMD->isClassMethod())
530 if (E->getInstanceReceiver()->isObjCSelfExpr())
531 isClassMessage = true;
John McCall31168b02011-06-15 23:02:42 +0000532 if (retainSelf) {
533 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
534 E->getInstanceReceiver());
535 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000536 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000537 } else
538 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000539 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000540
Douglas Gregor9a129192010-04-21 00:45:42 +0000541 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000542 ReceiverType = E->getClassReceiver();
543 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000544 assert(ObjTy && "Invalid Objective-C class message send");
545 OID = ObjTy->getInterface();
546 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000547 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000548 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000549 break;
550 }
551
552 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000553 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000554 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000555 isSuperMessage = true;
556 break;
557
558 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000559 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000560 Receiver = LoadObjCSelf();
561 isSuperMessage = true;
562 isClassMessage = true;
563 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000564 }
565
John McCallcf166702011-07-22 08:53:00 +0000566 if (retainSelf)
567 Receiver = EmitARCRetainNonBlock(Receiver);
568
569 // In ARC, we sometimes want to "extend the lifetime"
570 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
571 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000572 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000573 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
574 shouldExtendReceiverForInnerPointerMessage(E))
575 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
576
Alp Toker314cc812014-01-25 16:55:45 +0000577 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000578
Daniel Dunbarc722b852008-08-30 03:02:31 +0000579 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000580 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000581
John McCall31168b02011-06-15 23:02:42 +0000582 // For delegate init calls in ARC, do an unsafe store of null into
583 // self. This represents the call taking direct ownership of that
584 // value. We have to do this after emitting the other call
585 // arguments because they might also reference self, but we don't
586 // have to worry about any of them modifying self because that would
587 // be an undefined read and write of an object in unordered
588 // expressions.
589 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000590 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000591 "delegate init calls should only be marked in ARC");
592
593 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000594 Address selfAddr =
595 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000596 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
597 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000598
Douglas Gregor33823722011-06-11 01:09:30 +0000599 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000600 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000601 // super is only valid in an Objective-C method
602 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000603 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000604 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
605 E->getSelector(),
606 OMD->getClassInterface(),
607 isCategoryImpl,
608 Receiver,
609 isClassMessage,
610 Args,
John McCallcf166702011-07-22 08:53:00 +0000611 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000612 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000613 // Call runtime methods directly if we can.
614 if (Optional<llvm::Value *> SpecializedResult =
615 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000616 E->getSelector(), method,
617 isClassMessage)) {
Pete Coopere3886802018-12-08 05:13:50 +0000618 result = RValue::get(SpecializedResult.getValue());
619 } else {
620 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
621 E->getSelector(), Receiver, Args,
622 OID, method);
623 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000624 }
John McCall31168b02011-06-15 23:02:42 +0000625
626 // For delegate init calls in ARC, implicitly store the result of
627 // the call back into self. This takes ownership of the value.
628 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000629 Address selfAddr =
630 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000631 llvm::Value *newSelf = result.getScalarVal();
632
633 // The delegate return type isn't necessarily a matching type; in
634 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000635 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000636 newSelf = Builder.CreateBitCast(newSelf, selfTy);
637
638 Builder.CreateStore(newSelf, selfAddr);
639 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000640
Douglas Gregore83b9562015-07-07 03:57:53 +0000641 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000642}
643
John McCall31168b02011-06-15 23:02:42 +0000644namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000645struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000646 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000647 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000648
649 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000650 const ObjCInterfaceDecl *iface = impl->getClassInterface();
651 if (!iface->getSuperClass()) return;
652
John McCalldffafde2011-07-13 18:26:47 +0000653 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
654
John McCall31168b02011-06-15 23:02:42 +0000655 // Call [super dealloc] if we have a superclass.
656 llvm::Value *self = CGF.LoadObjCSelf();
657
658 CallArgList args;
659 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
660 CGF.getContext().VoidTy,
661 method->getSelector(),
662 iface,
John McCalldffafde2011-07-13 18:26:47 +0000663 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000664 self,
665 /*is class msg*/ false,
666 args,
667 method);
668 }
669};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000670}
John McCall31168b02011-06-15 23:02:42 +0000671
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000672/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
673/// the LLVM function and sets the other context used by
674/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000675void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000676 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000677 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000678 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000679 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000680 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000681 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000682
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000683 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000684
John McCalla729c622012-02-17 03:33:10 +0000685 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000686 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000687
John McCalla738c252011-03-09 04:27:21 +0000688 args.push_back(OMD->getSelfDecl());
689 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000690
Benjamin Kramerf9890422015-02-17 16:48:30 +0000691 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000692
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000693 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000694 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000695
Adrian Prantl42d71b92014-04-10 23:21:53 +0000696 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
697 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000698
699 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000700 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000701 OMD->isInstanceMethod() &&
702 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000703 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000704 OMD->getSelector().getIdentifierInfoForSlot(0);
705 if (ident->isStr("dealloc"))
706 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
707 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000708}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000709
John McCall31168b02011-06-15 23:02:42 +0000710static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
711 LValue lvalue, QualType type);
712
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000713/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000714/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000715void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000716 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000717 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000718 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000719 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000720 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000721 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000722}
723
John McCallb923ece2011-09-12 23:06:44 +0000724/// emitStructGetterCall - Call the runtime function to load a property
725/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000726static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000727 bool isAtomic, bool hasStrong) {
728 ASTContext &Context = CGF.getContext();
729
John McCall7f416cc2015-09-08 08:05:57 +0000730 Address src =
731 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
732 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000733
Fangrui Song6907ce22018-07-30 19:24:48 +0000734 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000735 // sizeof (Type of Ivar), isAtomic, false);
736 CallArgList args;
737
John McCall7f416cc2015-09-08 08:05:57 +0000738 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
739 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000740
741 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000742 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000743
744 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
745 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
746 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
747 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
748
James Y Knight9871db02019-02-05 16:42:33 +0000749 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000750 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000751 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000752 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000753}
754
John McCallf4528ae2011-09-13 03:34:09 +0000755/// Determine whether the given architecture supports unaligned atomic
756/// accesses. They don't have to be fast, just faster than a function
757/// call and a mutex.
758static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000759 // FIXME: Allow unaligned atomic load/store on x86. (It is not
760 // currently supported by the backend.)
761 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000762}
763
764/// Return the maximum size that permits atomic accesses for the given
765/// architecture.
766static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
767 llvm::Triple::ArchType arch) {
768 // ARM has 8-byte atomic accesses, but it's not clear whether we
769 // want to rely on them here.
770
771 // In the default case, just assume that any size up to a pointer is
772 // fine given adequate alignment.
773 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
774}
775
776namespace {
777 class PropertyImplStrategy {
778 public:
779 enum StrategyKind {
780 /// The 'native' strategy is to use the architecture's provided
781 /// reads and writes.
782 Native,
783
784 /// Use objc_setProperty and objc_getProperty.
785 GetSetProperty,
786
787 /// Use objc_setProperty for the setter, but use expression
788 /// evaluation for the getter.
789 SetPropertyAndExpressionGet,
790
791 /// Use objc_copyStruct.
792 CopyStruct,
793
794 /// The 'expression' strategy is to emit normal assignment or
795 /// lvalue-to-rvalue expressions.
796 Expression
797 };
798
799 StrategyKind getKind() const { return StrategyKind(Kind); }
800
801 bool hasStrongMember() const { return HasStrong; }
802 bool isAtomic() const { return IsAtomic; }
803 bool isCopy() const { return IsCopy; }
804
805 CharUnits getIvarSize() const { return IvarSize; }
806 CharUnits getIvarAlignment() const { return IvarAlignment; }
807
808 PropertyImplStrategy(CodeGenModule &CGM,
809 const ObjCPropertyImplDecl *propImpl);
810
811 private:
812 unsigned Kind : 8;
813 unsigned IsAtomic : 1;
814 unsigned IsCopy : 1;
815 unsigned HasStrong : 1;
816
817 CharUnits IvarSize;
818 CharUnits IvarAlignment;
819 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000820}
John McCallf4528ae2011-09-13 03:34:09 +0000821
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000822/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000823PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
824 const ObjCPropertyImplDecl *propImpl) {
825 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000826 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000827
John McCall43192862011-09-13 18:31:23 +0000828 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
829 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000830 HasStrong = false; // doesn't matter here.
831
832 // Evaluate the ivar's size and alignment.
833 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
834 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000835 std::tie(IvarSize, IvarAlignment) =
836 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000837
838 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000839 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000840 if (IsCopy) {
841 Kind = GetSetProperty;
842 return;
843 }
844
John McCall43192862011-09-13 18:31:23 +0000845 // Handle retain.
846 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000847 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000848 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000849 // fallthrough
850
851 // In ARC, if the property is non-atomic, use expression emission,
852 // which translates to objc_storeStrong. This isn't required, but
853 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000854 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000855 // Using standard expression emission for the setter is only
856 // acceptable if the ivar is __strong, which won't be true if
857 // the property is annotated with __attribute__((NSObject)).
858 // TODO: falling all the way back to objc_setProperty here is
859 // just laziness, though; we could still use objc_storeStrong
860 // if we hacked it right.
861 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
862 Kind = Expression;
863 else
864 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000865 return;
866
867 // Otherwise, we need to at least use setProperty. However, if
868 // the property isn't atomic, we can use normal expression
869 // emission for the getter.
870 } else if (!IsAtomic) {
871 Kind = SetPropertyAndExpressionGet;
872 return;
873
874 // Otherwise, we have to use both setProperty and getProperty.
875 } else {
876 Kind = GetSetProperty;
877 return;
878 }
879 }
880
881 // If we're not atomic, just use expression accesses.
882 if (!IsAtomic) {
883 Kind = Expression;
884 return;
885 }
886
John McCall0e5c0862011-09-13 05:36:29 +0000887 // Properties on bitfield ivars need to be emitted using expression
888 // accesses even if they're nominally atomic.
889 if (ivar->isBitField()) {
890 Kind = Expression;
891 return;
892 }
893
John McCallf4528ae2011-09-13 03:34:09 +0000894 // GC-qualified or ARC-qualified ivars need to be emitted as
895 // expressions. This actually works out to being atomic anyway,
896 // except for ARC __strong, but that should trigger the above code.
897 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000898 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000899 CGM.getContext().getObjCGCAttrKind(ivarType))) {
900 Kind = Expression;
901 return;
902 }
903
904 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000905 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000906 if (const RecordType *recordType = ivarType->getAs<RecordType>())
907 HasStrong = recordType->getDecl()->hasObjectMember();
908
909 // We can never access structs with object members with a native
910 // access, because we need to use write barriers. This is what
911 // objc_copyStruct is for.
912 if (HasStrong) {
913 Kind = CopyStruct;
914 return;
915 }
916
917 // Otherwise, this is target-dependent and based on the size and
918 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000919
920 // If the size of the ivar is not a power of two, give up. We don't
921 // want to get into the business of doing compare-and-swaps.
922 if (!IvarSize.isPowerOfTwo()) {
923 Kind = CopyStruct;
924 return;
925 }
926
John McCallf4528ae2011-09-13 03:34:09 +0000927 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000928 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000929
930 // Most architectures require memory to fit within a single cache
931 // line, so the alignment has to be at least the size of the access.
932 // Otherwise we have to grab a lock.
933 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
934 Kind = CopyStruct;
935 return;
936 }
937
938 // If the ivar's size exceeds the architecture's maximum atomic
939 // access size, we have to use CopyStruct.
940 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
941 Kind = CopyStruct;
942 return;
943 }
944
945 // Otherwise, we can use native loads and stores.
946 Kind = Native;
947}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000949/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000950///
951/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000952/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000953void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
954 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000955 llvm::Constant *AtomicHelperFn =
956 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000957 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
958 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
959 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000960 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000961
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000962 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000963
964 FinishFunction();
965}
966
John McCallbdd81852011-09-13 06:00:03 +0000967static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
968 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000969 if (!getter) return true;
970
971 // Sema only makes only of these when the ivar has a C++ class type,
972 // so the form is pretty constrained.
973
John McCallbdd81852011-09-13 06:00:03 +0000974 // If the property has a reference type, we might just be binding a
975 // reference, in which case the result will be a gl-value. We should
976 // treat this as a non-trivial operation.
977 if (getter->isGLValue())
978 return false;
979
John McCallf4528ae2011-09-13 03:34:09 +0000980 // If we selected a trivial copy-constructor, we're okay.
981 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
982 return (construct->getConstructor()->isTrivial());
983
984 // The constructor might require cleanups (in which case it's never
985 // trivial).
986 assert(isa<ExprWithCleanups>(getter));
987 return false;
988}
989
Fangrui Song6907ce22018-07-30 19:24:48 +0000990/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000991/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000992static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000993 llvm::Value *returnAddr,
994 ObjCIvarDecl *ivar,
995 llvm::Constant *AtomicHelperFn) {
996 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
997 // AtomicHelperFn);
998 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000999
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001000 // The 1st argument is the return Slot.
1001 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001002
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001003 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001004 llvm::Value *ivarAddr =
1005 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001006 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001007 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1008 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001009
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001010 // Third argument is the helper function.
1011 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001012
James Y Knight9871db02019-02-05 16:42:33 +00001013 llvm::FunctionCallee copyCppAtomicObjectFn =
1014 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001015 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +00001016 CGF.EmitCall(
1017 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001018 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001019}
1020
John McCallf4528ae2011-09-13 03:34:09 +00001021void
1022CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001023 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001024 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001025 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +00001026 // If there's a non-trivial 'get' expression, we just have to emit that.
1027 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001028 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001029 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1030 propImpl->getGetterCXXConstructor(),
1031 /* NRVOCandidate=*/nullptr);
1032 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001033 }
1034 else {
1035 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001036 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001037 ivar, AtomicHelperFn);
1038 }
John McCallf4528ae2011-09-13 03:34:09 +00001039 return;
1040 }
1041
1042 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1043 QualType propType = prop->getType();
1044 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
1045
Fangrui Song6907ce22018-07-30 19:24:48 +00001046 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001047
1048 // Pick an implementation strategy.
1049 PropertyImplStrategy strategy(CGM, propImpl);
1050 switch (strategy.getKind()) {
1051 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001052 // We don't need to do anything for a zero-size struct.
1053 if (strategy.getIvarSize().isZero())
1054 return;
1055
John McCallf4528ae2011-09-13 03:34:09 +00001056 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1057
1058 // Currently, all atomic accesses have to be through integer
1059 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001060 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1061 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001062 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1063
1064 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +00001065 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +00001066 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1067 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001068 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001069
1070 // Store that value into the return address. Doing this with a
1071 // bitcast is likely to produce some pretty ugly IR, but it's not
1072 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001073 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1074 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1075 llvm::Value *ivarVal = load;
1076 if (ivarSize > retTySize) {
1077 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1078 ivarVal = Builder.CreateTrunc(load, newTy);
1079 bitcastType = newTy->getPointerTo();
1080 }
1081 Builder.CreateStore(ivarVal,
1082 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001083
1084 // Make sure we don't do an autorelease.
1085 AutoreleaseResult = false;
1086 return;
1087 }
1088
1089 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001090 llvm::FunctionCallee getPropertyFn =
1091 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001092 if (!getPropertyFn) {
1093 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001094 return;
1095 }
John McCallb92ab1a2016-10-26 23:46:34 +00001096 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001097
1098 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1099 // FIXME: Can't this be simpler? This might even be worse than the
1100 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001101 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001102 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001103 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1104 llvm::Value *ivarOffset =
1105 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1106
1107 CallArgList args;
1108 args.add(RValue::get(self), getContext().getObjCIdType());
1109 args.add(RValue::get(cmd), getContext().getObjCSelType());
1110 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001111 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1112 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001113
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001114 // FIXME: We shouldn't need to get the function info here, the
1115 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001116 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001117 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1118 getContext().getObjCIdType(), args),
1119 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001120 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1121 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001122
Daniel Dunbara08dff12008-09-24 04:04:31 +00001123 // We need to fix the type here. Ivars with copy & retain are
1124 // always objects so we don't need to worry about complex or
1125 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001126 RV = RValue::get(Builder.CreateBitCast(
1127 RV.getScalarVal(),
1128 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001129
1130 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001131
1132 // objc_getProperty does an autorelease, so we should suppress ours.
1133 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001134
John McCallf4528ae2011-09-13 03:34:09 +00001135 return;
1136 }
1137
1138 case PropertyImplStrategy::CopyStruct:
1139 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1140 strategy.hasStrongMember());
1141 return;
1142
1143 case PropertyImplStrategy::Expression:
1144 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1145 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1146
1147 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001148 switch (getEvaluationKind(ivarType)) {
1149 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001150 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001151 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001152 /*init*/ true);
1153 return;
1154 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001155 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001156 // The return value slot is guaranteed to not be aliased, but
1157 // that's not necessarily the same as "on the stack", so
1158 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001159 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smith8cca3a52019-06-20 20:56:20 +00001160 /* Src= */ LV, ivarType, getOverlapForReturnValue());
Richard Smithe78fac52018-04-05 20:52:58 +00001161 return;
1162 }
John McCall47fb9502013-03-07 21:37:08 +00001163 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001164 llvm::Value *value;
1165 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001166 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001167 } else {
1168 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1169 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001170 if (getLangOpts().ObjCAutoRefCount) {
1171 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1172 } else {
1173 value = EmitARCLoadWeak(LV.getAddress());
1174 }
John McCall24fada12011-07-22 05:23:13 +00001175
1176 // Otherwise we want to do a simple load, suppressing the
1177 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001178 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001179 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001180 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001181 }
John McCall31168b02011-06-15 23:02:42 +00001182
Alp Toker314cc812014-01-25 16:55:45 +00001183 value = Builder.CreateBitCast(
1184 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001185 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001186
John McCall24fada12011-07-22 05:23:13 +00001187 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001188 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001189 }
John McCall47fb9502013-03-07 21:37:08 +00001190 }
1191 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001192 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001193
John McCallf4528ae2011-09-13 03:34:09 +00001194 }
1195 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001196}
1197
John McCallb923ece2011-09-12 23:06:44 +00001198/// emitStructSetterCall - Call the runtime function to store the value
1199/// from the first formal parameter into the given ivar.
1200static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1201 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001202 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001203 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001204 CallArgList args;
1205
1206 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001207 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1208 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001209 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001210 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1211 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001212
1213 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001214 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001215 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1216 argVar->getType().getNonReferenceType(), VK_LValue,
1217 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001218 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001219 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1220 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001221
1222 // The third argument is the sizeof the type.
1223 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001224 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1225 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001226
John McCallb923ece2011-09-12 23:06:44 +00001227 // The fourth argument is the 'isAtomic' flag.
1228 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001229
John McCallb923ece2011-09-12 23:06:44 +00001230 // The fifth argument is the 'hasStrong' flag.
1231 // FIXME: should this really always be false?
1232 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1233
James Y Knight9871db02019-02-05 16:42:33 +00001234 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001235 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001236 CGF.EmitCall(
1237 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001238 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001239}
1240
Fangrui Song6907ce22018-07-30 19:24:48 +00001241/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1242/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001243/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001244static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001245 ObjCMethodDecl *OMD,
1246 ObjCIvarDecl *ivar,
1247 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001248 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001249 // AtomicHelperFn);
1250 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001251
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001252 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001253 llvm::Value *ivarAddr =
1254 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001255 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001256 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1257 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001258
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001259 // The second argument is the address of the parameter variable.
1260 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001261 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1262 argVar->getType().getNonReferenceType(), VK_LValue,
1263 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001264 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001265 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1266 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001267
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001268 // Third argument is the helper function.
1269 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001270
James Y Knight9871db02019-02-05 16:42:33 +00001271 llvm::FunctionCallee fn =
1272 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001273 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001274 CGF.EmitCall(
1275 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001276 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001277}
1278
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001279
John McCallf4528ae2011-09-13 03:34:09 +00001280static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1281 Expr *setter = PID->getSetterCXXAssignment();
1282 if (!setter) return true;
1283
1284 // Sema only makes only of these when the ivar has a C++ class type,
1285 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001286
1287 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001288 // This also implies that there's nothing non-trivial going on with
1289 // the arguments, because operator= can only be trivial if it's a
1290 // synthesized assignment operator and therefore both parameters are
1291 // references.
1292 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001293 if (const FunctionDecl *callee
1294 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1295 if (callee->isTrivial())
1296 return true;
1297 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001298 }
John McCall7f16c422011-09-10 09:17:20 +00001299
John McCallf4528ae2011-09-13 03:34:09 +00001300 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001301 return false;
1302}
1303
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001304static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001305 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001306 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001307 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001308}
1309
John McCall7f16c422011-09-10 09:17:20 +00001310void
1311CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001312 const ObjCPropertyImplDecl *propImpl,
1313 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001314 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001315 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001316 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001317
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001318 // Just use the setter expression if Sema gave us one and it's
1319 // non-trivial.
1320 if (!hasTrivialSetExpr(propImpl)) {
1321 if (!AtomicHelperFn)
1322 // If non-atomic, assignment is called directly.
1323 EmitStmt(propImpl->getSetterCXXAssignment());
1324 else
1325 // If atomic, assignment is called via a locking api.
1326 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1327 AtomicHelperFn);
1328 return;
1329 }
John McCall7f16c422011-09-10 09:17:20 +00001330
John McCallf4528ae2011-09-13 03:34:09 +00001331 PropertyImplStrategy strategy(CGM, propImpl);
1332 switch (strategy.getKind()) {
1333 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001334 // We don't need to do anything for a zero-size struct.
1335 if (strategy.getIvarSize().isZero())
1336 return;
1337
John McCall7f416cc2015-09-08 08:05:57 +00001338 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001339
John McCallf4528ae2011-09-13 03:34:09 +00001340 LValue ivarLValue =
1341 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001342 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001343
John McCallf4528ae2011-09-13 03:34:09 +00001344 // Currently, all atomic accesses have to be through integer
1345 // types, so there's no point in trying to pick a prettier type.
1346 llvm::Type *bitcastType =
1347 llvm::Type::getIntNTy(getLLVMContext(),
1348 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001349
1350 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001351 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1352 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001353
1354 // This bitcast load is likely to cause some nasty IR.
1355 llvm::Value *load = Builder.CreateLoad(argAddr);
1356
1357 // Perform an atomic store. There are no memory ordering requirements.
1358 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001359 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001360 return;
1361 }
1362
1363 case PropertyImplStrategy::GetSetProperty:
1364 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001365
James Y Knight9871db02019-02-05 16:42:33 +00001366 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1367 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001368 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001369 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001370 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001371 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1372 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001373 if (!setOptimizedPropertyFn) {
1374 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1375 return;
1376 }
John McCall7f16c422011-09-10 09:17:20 +00001377 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001378 else {
1379 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1380 if (!setPropertyFn) {
1381 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1382 return;
1383 }
1384 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001385
John McCall7f16c422011-09-10 09:17:20 +00001386 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1387 // <is-atomic>, <is-copy>).
1388 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001389 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001390 llvm::Value *self =
1391 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1392 llvm::Value *ivarOffset =
1393 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001394 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1395 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1396 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001397
1398 CallArgList args;
1399 args.add(RValue::get(self), getContext().getObjCIdType());
1400 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001401 if (setOptimizedPropertyFn) {
1402 args.add(RValue::get(arg), getContext().getObjCIdType());
1403 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001404 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001405 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001406 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001407 } else {
1408 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1409 args.add(RValue::get(arg), getContext().getObjCIdType());
1410 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1411 getContext().BoolTy);
1412 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1413 getContext().BoolTy);
1414 // FIXME: We shouldn't need to get the function info here, the runtime
1415 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001416 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001417 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001418 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001419 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001420
John McCall7f16c422011-09-10 09:17:20 +00001421 return;
1422 }
1423
John McCallf4528ae2011-09-13 03:34:09 +00001424 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001425 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001426 return;
John McCallf4528ae2011-09-13 03:34:09 +00001427
1428 case PropertyImplStrategy::Expression:
1429 break;
John McCall7f16c422011-09-10 09:17:20 +00001430 }
1431
1432 // Otherwise, fake up some ASTs and emit a normal assignment.
1433 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001434 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001435 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001436 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1437 selfDecl->getType(), CK_LValueToRValue, &self,
1438 VK_RValue);
1439 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001440 SourceLocation(), SourceLocation(),
1441 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001442
1443 ParmVarDecl *argDecl = *setterMethod->param_begin();
1444 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001445 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1446 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001447 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1448 argType.getUnqualifiedType(), CK_LValueToRValue,
1449 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001450
John McCall7f16c422011-09-10 09:17:20 +00001451 // The property type can differ from the ivar type in some situations with
1452 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1453 // The following absurdity is just to ensure well-formed IR.
1454 CastKind argCK = CK_NoOp;
1455 if (ivarRef.getType()->isObjCObjectPointerType()) {
1456 if (argLoad.getType()->isObjCObjectPointerType())
1457 argCK = CK_BitCast;
1458 else if (argLoad.getType()->isBlockPointerType())
1459 argCK = CK_BlockPointerToObjCPointerCast;
1460 else
1461 argCK = CK_CPointerToObjCPointerCast;
1462 } else if (ivarRef.getType()->isBlockPointerType()) {
1463 if (argLoad.getType()->isBlockPointerType())
1464 argCK = CK_BitCast;
1465 else
1466 argCK = CK_AnyPointerToBlockPointerCast;
1467 } else if (ivarRef.getType()->isPointerType()) {
1468 argCK = CK_BitCast;
1469 }
1470 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1471 ivarRef.getType(), argCK, &argLoad,
1472 VK_RValue);
1473 Expr *finalArg = &argLoad;
1474 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1475 argLoad.getType()))
1476 finalArg = &argCast;
1477
1478
1479 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1480 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001481 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001482 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001483}
1484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001485/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001486///
1487/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001488/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001489void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1490 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001491 llvm::Constant *AtomicHelperFn =
1492 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001493 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1494 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1495 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001496 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001497
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001498 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001499
1500 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001501}
1502
John McCall6a4fa522011-03-22 07:05:39 +00001503namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001504 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001505 private:
1506 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001507 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001508 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001509 bool useEHCleanupForArray;
1510 public:
1511 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1512 CodeGenFunction::Destroyer *destroyer,
1513 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001514 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001515 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001516
Craig Topper4f12f102014-03-12 06:41:41 +00001517 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001518 LValue lvalue
1519 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1520 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001521 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001522 }
1523 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001524}
John McCall6a4fa522011-03-22 07:05:39 +00001525
John McCall4bd0fb12011-07-12 16:41:08 +00001526/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1527static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001528 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001529 QualType type) {
1530 llvm::Value *null = getNullForVariable(addr);
1531 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1532}
John McCall31168b02011-06-15 23:02:42 +00001533
John McCall6a4fa522011-03-22 07:05:39 +00001534static void emitCXXDestructMethod(CodeGenFunction &CGF,
1535 ObjCImplementationDecl *impl) {
1536 CodeGenFunction::RunCleanupsScope scope(CGF);
1537
1538 llvm::Value *self = CGF.LoadObjCSelf();
1539
Jordy Rosea91768e2011-07-22 02:08:32 +00001540 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1541 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001542 ivar; ivar = ivar->getNextIvar()) {
1543 QualType type = ivar->getType();
1544
John McCall6a4fa522011-03-22 07:05:39 +00001545 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001546 QualType::DestructionKind dtorKind = type.isDestructedType();
1547 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001548
Craig Topper8a13c412014-05-21 05:09:00 +00001549 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001550
John McCall4bd0fb12011-07-12 16:41:08 +00001551 // Use a call to objc_storeStrong to destroy strong ivars, for the
1552 // general benefit of the tools.
1553 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001554 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001555
John McCall4bd0fb12011-07-12 16:41:08 +00001556 // Otherwise use the default for the destruction kind.
1557 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001558 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001559 }
John McCall4bd0fb12011-07-12 16:41:08 +00001560
1561 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1562
1563 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1564 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001565 }
1566
1567 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1568}
1569
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001570void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1571 ObjCMethodDecl *MD,
1572 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001573 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001574 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001575
1576 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001577 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001578 // Suppress the final autorelease in ARC.
1579 AutoreleaseResult = false;
1580
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001581 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001582 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001583 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001584 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001585 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001586 EmitAggExpr(IvarInit->getInit(),
1587 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001588 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001589 AggValueSlot::IsNotAliased,
1590 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001591 }
1592 // constructor returns 'self'.
1593 CodeGenTypes &Types = CGM.getTypes();
1594 QualType IdTy(CGM.getContext().getObjCIdType());
1595 llvm::Value *SelfAsId =
1596 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1597 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001598
1599 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001600 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001601 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001602 }
1603 FinishFunction();
1604}
1605
Daniel Dunbara08dff12008-09-24 04:04:31 +00001606llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001607 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001608 DeclRefExpr DRE(getContext(), Self,
1609 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001610 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001611 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001612}
1613
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001614QualType CodeGenFunction::TypeOfSelfObject() {
1615 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1616 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001617 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1618 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001619 return PTy->getPointeeType();
1620}
1621
Chris Lattnerd4808922009-03-22 21:03:39 +00001622void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001623 llvm::FunctionCallee EnumerationMutationFnPtr =
1624 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001625 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001626 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1627 return;
1628 }
John McCallb92ab1a2016-10-26 23:46:34 +00001629 CGCallee EnumerationMutationFn =
1630 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001631
Devang Pateld2d66652011-01-19 01:36:36 +00001632 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001633 if (DI)
1634 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001635
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001636 RunCleanupsScope ForScope(*this);
1637
Kuba Mracek82c21752017-04-14 01:00:03 +00001638 // The local variable comes into scope immediately.
1639 AutoVarEmission variable = AutoVarEmission::invalid();
1640 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1641 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1642
John McCall1c926b72011-01-07 01:49:06 +00001643 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001644
Anders Carlsson75658592008-08-31 02:33:12 +00001645 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001646 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001647 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001648 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001649
Anders Carlsson75658592008-08-31 02:33:12 +00001650 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001651 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001652
John McCall1c926b72011-01-07 01:49:06 +00001653 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001654 IdentifierInfo *II[] = {
1655 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1656 &CGM.getContext().Idents.get("objects"),
1657 &CGM.getContext().Idents.get("count")
1658 };
1659 Selector FastEnumSel =
1660 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001661
1662 QualType ItemsTy =
1663 getContext().getConstantArrayType(getContext().getObjCIdType(),
Richard Smith772e2662019-10-04 01:25:59 +00001664 llvm::APInt(32, NumItems), nullptr,
Anders Carlsson75658592008-08-31 02:33:12 +00001665 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001666 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001667
John McCall53848232011-07-27 01:07:15 +00001668 // Emit the collection pointer. In ARC, we do a retain.
1669 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001670 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001671 Collection = EmitARCRetainScalarExpr(S.getCollection());
1672
1673 // Enter a cleanup to do the release.
1674 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1675 } else {
1676 Collection = EmitScalarExpr(S.getCollection());
1677 }
Mike Stump11289f42009-09-09 15:08:12 +00001678
John McCall91e82dd2011-08-05 00:14:38 +00001679 // The 'continue' label needs to appear within the cleanup for the
1680 // collection object.
1681 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1682
John McCall1c926b72011-01-07 01:49:06 +00001683 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001684 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001685
1686 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001687 Args.add(RValue::get(StatePtr.getPointer()),
1688 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall1c926b72011-01-07 01:49:06 +00001690 // The second argument is a temporary array with space for NumItems
1691 // pointers. We'll actually be loading elements from the array
1692 // pointer written into the control state; this buffer is so that
1693 // collections that *aren't* backed by arrays can still queue up
1694 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001695 Args.add(RValue::get(ItemsPtr.getPointer()),
1696 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001697
John McCall1c926b72011-01-07 01:49:06 +00001698 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001699 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1700 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1701 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCall1c926b72011-01-07 01:49:06 +00001703 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001704 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001705 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1706 getContext().getNSUIntegerType(),
1707 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001708
John McCall1c926b72011-01-07 01:49:06 +00001709 // The initial number of objects that were returned in the buffer.
1710 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001711
John McCall1c926b72011-01-07 01:49:06 +00001712 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1713 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001714
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001715 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001716
John McCall1c926b72011-01-07 01:49:06 +00001717 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001718 // empty; skip all this. Set the branch weight assuming this has the same
1719 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001720 uint64_t EntryCount = getCurrentProfileCount();
1721 Builder.CreateCondBr(
1722 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1723 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001724 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001725
John McCall1c926b72011-01-07 01:49:06 +00001726 // Otherwise, initialize the loop.
1727 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001728
John McCall1c926b72011-01-07 01:49:06 +00001729 // Save the initial mutations value. This is the value at an
1730 // address that was written into the state object by
1731 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001732 Address StateMutationsPtrPtr =
1733 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001734 llvm::Value *StateMutationsPtr
1735 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001736
John McCall1c926b72011-01-07 01:49:06 +00001737 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001738 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1739 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001740
John McCall1c926b72011-01-07 01:49:06 +00001741 // Start looping. This is the point we return to whenever we have a
1742 // fresh, non-empty batch of objects.
1743 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1744 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001745
John McCall1c926b72011-01-07 01:49:06 +00001746 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001747 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001748 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001749
John McCall1c926b72011-01-07 01:49:06 +00001750 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001751 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001752 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001753
Justin Bogner66242d62015-04-23 23:06:47 +00001754 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001755
John McCall1c926b72011-01-07 01:49:06 +00001756 // Check whether the mutations value has changed from where it was
1757 // at start. StateMutationsPtr should actually be invariant between
1758 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001759 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001760 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001761 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1762 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001763
John McCall1c926b72011-01-07 01:49:06 +00001764 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001765 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001766
John McCall1c926b72011-01-07 01:49:06 +00001767 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1768 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001769
John McCall1c926b72011-01-07 01:49:06 +00001770 // If so, call the enumeration-mutation function.
1771 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001772 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001773 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001774 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001775 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001776 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001777 // FIXME: We shouldn't need to get the function info here, the runtime already
1778 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001779 EmitCall(
1780 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001781 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001782
John McCall1c926b72011-01-07 01:49:06 +00001783 // Otherwise, or if the mutation function returns, just continue.
1784 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001785
John McCall1c926b72011-01-07 01:49:06 +00001786 // Initialize the element variable.
1787 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001788 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001789 LValue elementLValue;
1790 QualType elementType;
1791 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001792 // Initialize the variable, in case it's a __block variable or something.
1793 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001794
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001795 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1796 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1797 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001798 elementLValue = EmitLValue(&tempDRE);
1799 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001800 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001801
1802 if (D->isARCPseudoStrong())
1803 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001804 } else {
1805 elementLValue = LValue(); // suppress warning
1806 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001807 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001808 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001809 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001810
1811 // Fetch the buffer out of the enumeration state.
1812 // TODO: this pointer should actually be invariant between
1813 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001814 Address StateItemsPtr =
1815 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001816 llvm::Value *EnumStateItems =
1817 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001818
John McCall1c926b72011-01-07 01:49:06 +00001819 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001820 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001821 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001822 llvm::Value *CurrentItem =
1823 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001824
John McCall1c926b72011-01-07 01:49:06 +00001825 // Cast that value to the right type.
1826 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1827 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001828
John McCall1c926b72011-01-07 01:49:06 +00001829 // Make sure we have an l-value. Yes, this gets evaluated every
1830 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001831 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001832 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001833 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001834 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001835 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1836 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001837 }
Mike Stump11289f42009-09-09 15:08:12 +00001838
John McCall9e2e22f2011-02-22 07:16:58 +00001839 // If we do have an element variable, this assignment is the end of
1840 // its initialization.
1841 if (elementIsVariable)
1842 EmitAutoVarCleanups(variable);
1843
John McCall1c926b72011-01-07 01:49:06 +00001844 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001845 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001846 {
1847 RunCleanupsScope Scope(*this);
1848 EmitStmt(S.getBody());
1849 }
Anders Carlsson75658592008-08-31 02:33:12 +00001850 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001851
John McCall1c926b72011-01-07 01:49:06 +00001852 // Destroy the element variable now.
1853 elementVariableScope.ForceCleanup();
1854
1855 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001856 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001857
John McCall1c926b72011-01-07 01:49:06 +00001858 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001859
John McCall1c926b72011-01-07 01:49:06 +00001860 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001861 llvm::Value *indexPlusOne =
1862 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001863
John McCall1c926b72011-01-07 01:49:06 +00001864 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001865 // Set the branch weights based on the simplifying assumption that this is
1866 // like a while-loop, i.e., ignoring that the false branch fetches more
1867 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001868 Builder.CreateCondBr(
1869 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001870 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001871
1872 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1873 count->addIncoming(count, AfterBody.getBlock());
1874
1875 // Otherwise, we have to fetch more elements.
1876 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001877
1878 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001879 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1880 getContext().getNSUIntegerType(),
1881 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001882
John McCall1c926b72011-01-07 01:49:06 +00001883 // If we got a zero count, we're done.
1884 llvm::Value *refetchCount = CountRV.getScalarVal();
1885
1886 // (note that the message send might split FetchMoreBB)
1887 index->addIncoming(zero, Builder.GetInsertBlock());
1888 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1889
1890 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1891 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001892
Anders Carlsson75658592008-08-31 02:33:12 +00001893 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001894 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001895
John McCall9e2e22f2011-02-22 07:16:58 +00001896 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001897 // If the element was not a declaration, set it to be null.
1898
John McCall1c926b72011-01-07 01:49:06 +00001899 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1900 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001901 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001902 }
1903
Eric Christopher7cdf9482011-10-13 21:45:18 +00001904 if (DI)
1905 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001906
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001907 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001908 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001909}
1910
Mike Stump11289f42009-09-09 15:08:12 +00001911void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001912 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001913}
1914
Mike Stump11289f42009-09-09 15:08:12 +00001915void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001916 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1917}
1918
Chris Lattnere132e242008-11-15 21:26:17 +00001919void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001920 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001921 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001922}
1923
John McCall31168b02011-06-15 23:02:42 +00001924namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001925 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001926 CallObjCRelease(llvm::Value *object) : object(object) {}
1927 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001928
Craig Topper4f12f102014-03-12 06:41:41 +00001929 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001930 // Releases at the end of the full-expression are imprecise.
1931 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001932 }
1933 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001934}
John McCall31168b02011-06-15 23:02:42 +00001935
John McCall2d637d22011-09-10 06:18:15 +00001936/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001937/// release at the end of the full-expression.
1938llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1939 llvm::Value *object) {
1940 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001941 // conditional.
1942 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001943 return object;
1944}
1945
1946llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1947 llvm::Value *value) {
1948 return EmitARCRetainAutorelease(type, value);
1949}
1950
John McCalleff18842013-03-23 02:35:54 +00001951/// Given a number of pointers, inform the optimizer that they're
1952/// being intrinsically used up until this point in the program.
1953void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001954 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001955 if (!fn)
1956 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001957
1958 // This isn't really a "runtime" function, but as an intrinsic it
1959 // doesn't really matter as long as we align things up.
1960 EmitNounwindRuntimeCall(fn, values);
1961}
1962
James Y Knight9871db02019-02-05 16:42:33 +00001963static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001964 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001965 // If the target runtime doesn't naturally support ARC, emit weak
1966 // references to the runtime support library. We don't really
1967 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001968 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1969 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001970 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001971 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001972 }
John McCall31168b02011-06-15 23:02:42 +00001973}
1974
James Y Knight9871db02019-02-05 16:42:33 +00001975static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1976 llvm::FunctionCallee RTF) {
1977 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1978}
1979
John McCall31168b02011-06-15 23:02:42 +00001980/// Perform an operation having the signature
1981/// i8* (i8*)
1982/// where a null input causes a no-op and returns null.
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00001983static llvm::Value *emitARCValueOperation(
1984 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
1985 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
1986 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001987 if (isa<llvm::ConstantPointerNull>(value))
1988 return value;
John McCall31168b02011-06-15 23:02:42 +00001989
1990 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001991 fn = CGF.CGM.getIntrinsic(IntID);
1992 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001993 }
1994
1995 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001996 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001997 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1998
1999 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00002000 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002001 call->setTailCallKind(tailKind);
John McCall31168b02011-06-15 23:02:42 +00002002
2003 // Cast the result back to the original type.
2004 return CGF.Builder.CreateBitCast(call, origType);
2005}
2006
2007/// Perform an operation having the following signature:
2008/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002009static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2010 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002011 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00002012 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002013 fn = CGF.CGM.getIntrinsic(IntID);
2014 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002015 }
2016
2017 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00002018 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00002019 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2020
2021 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002022 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002023
2024 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002025 if (origType != CGF.Int8PtrTy)
2026 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002027
2028 return result;
2029}
2030
2031/// Perform an operation having the following signature:
2032/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002033static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002034 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002035 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002036 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002037 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002038 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002039
2040 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002041 fn = CGF.CGM.getIntrinsic(IntID);
2042 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002043 }
2044
Chris Lattner2192fe52011-07-18 04:24:23 +00002045 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002046
John McCall882987f2013-02-28 19:01:20 +00002047 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002048 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002049 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2050 };
2051 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002052
Craig Topper8a13c412014-05-21 05:09:00 +00002053 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002054
2055 return CGF.Builder.CreateBitCast(result, origType);
2056}
2057
2058/// Perform an operation having the following signature:
2059/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002060static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2061 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002062 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002063 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002064
2065 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002066 fn = CGF.CGM.getIntrinsic(IntID);
2067 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002068 }
2069
John McCall882987f2013-02-28 19:01:20 +00002070 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002071 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2072 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002073 };
2074 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002075}
2076
Pete Cooper2cd35962018-12-18 20:33:00 +00002077/// Perform an operation having the signature
2078/// i8* (i8*)
2079/// where a null input causes a no-op and returns null.
2080static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2081 llvm::Value *value,
2082 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002083 llvm::FunctionCallee &fn,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002084 StringRef fnName) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002085 if (isa<llvm::ConstantPointerNull>(value))
2086 return value;
2087
2088 if (!fn) {
2089 llvm::FunctionType *fnType =
2090 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2091 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002092
2093 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002094 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002095 if (fnName == "objc_retain")
2096 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002097 }
2098
2099 // Cast the argument to 'id'.
2100 llvm::Type *origType = returnType ? returnType : value->getType();
2101 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2102
2103 // Call the function.
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002104 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002105
2106 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002107 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002108}
2109
John McCall31168b02011-06-15 23:02:42 +00002110/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002111/// call i8* \@objc_retain(i8* %value)
2112/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002113llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2114 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002115 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002116 else
2117 return EmitARCRetainNonBlock(value);
2118}
2119
2120/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002121/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002122llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002123 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002124 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002125 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002126}
2127
2128/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002129/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002130///
2131/// \param mandatory - If false, emit the call with metadata
2132/// indicating that it's okay for the optimizer to eliminate this call
2133/// if it can prove that the block never escapes except down the stack.
2134llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2135 bool mandatory) {
2136 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002137 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002138 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002139 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002140
2141 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2142 // tell the optimizer that it doesn't need to do this copy if the
2143 // block doesn't escape, where being passed as an argument doesn't
2144 // count as escaping.
2145 if (!mandatory && isa<llvm::Instruction>(result)) {
2146 llvm::CallInst *call
2147 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002148 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002149
John McCallff613032011-10-04 06:23:45 +00002150 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002151 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002152 }
2153
2154 return result;
John McCall31168b02011-06-15 23:02:42 +00002155}
2156
John McCalle399e5b2016-01-27 18:32:30 +00002157static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002158 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002159 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002160 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002161 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002162 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002163 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002164 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002165 .getARCRetainAutoreleasedReturnValueMarker();
2166
2167 // If we have an empty assembly string, there's nothing to do.
2168 if (assembly.empty()) {
2169
2170 // Otherwise, at -O0, build an inline asm that we're going to call
2171 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002172 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002173 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002174 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002175
John McCall31168b02011-06-15 23:02:42 +00002176 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2177
2178 // If we're at -O1 and above, we don't want to litter the code
2179 // with this marker yet, so leave a breadcrumb for the ARC
2180 // optimizer to pick up.
2181 } else {
Akira Hatanaka60c3a3b2019-04-10 06:20:23 +00002182 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2183 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2184 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2185 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
John McCall31168b02011-06-15 23:02:42 +00002186 }
2187 }
2188 }
2189
2190 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002191 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002192 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002193}
John McCall31168b02011-06-15 23:02:42 +00002194
John McCalle399e5b2016-01-27 18:32:30 +00002195/// Retain the given object which is the result of a function call.
2196/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2197///
2198/// Yes, this function name is one character away from a different
2199/// call with completely different semantics.
2200llvm::Value *
2201CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2202 emitAutoreleasedReturnValueMarker(*this);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002203 llvm::CallInst::TailCallKind tailKind =
2204 CGM.getTargetCodeGenInfo()
2205 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2206 ? llvm::CallInst::TCK_NoTail
2207 : llvm::CallInst::TCK_None;
2208 return emitARCValueOperation(
2209 *this, value, nullptr,
2210 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2211 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
John McCall31168b02011-06-15 23:02:42 +00002212}
2213
John McCalle399e5b2016-01-27 18:32:30 +00002214/// Claim a possibly-autoreleased return value at +0. This is only
2215/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002216/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002217/// the value is ignored, or when it is being assigned to an
2218/// __unsafe_unretained variable.
2219///
2220/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2221llvm::Value *
2222CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2223 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002224 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002225 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002226 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002227}
2228
John McCall31168b02011-06-15 23:02:42 +00002229/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002230/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002231void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2232 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002233 if (isa<llvm::ConstantPointerNull>(value)) return;
2234
James Y Knight9871db02019-02-05 16:42:33 +00002235 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002236 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002237 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2238 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002239 }
2240
2241 // Cast the argument to 'id'.
2242 value = Builder.CreateBitCast(value, Int8PtrTy);
2243
2244 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002245 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002246
John McCallcdda29c2013-03-13 03:10:54 +00002247 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002248 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002249 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002250 }
2251}
2252
John McCalle68b8f42012-10-17 02:28:37 +00002253/// Destroy a __strong variable.
2254///
2255/// At -O0, emit a call to store 'null' into the address;
2256/// instrumenting tools prefer this because the address is exposed,
2257/// but it's relatively cumbersome to optimize.
2258///
2259/// At -O1 and above, just load and call objc_release.
2260///
2261/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002262void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002263 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002264 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002265 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002266 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2267 return;
2268 }
2269
2270 llvm::Value *value = Builder.CreateLoad(addr);
2271 EmitARCRelease(value, precise);
2272}
2273
John McCall31168b02011-06-15 23:02:42 +00002274/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002275/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002276llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002277 llvm::Value *value,
2278 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002279 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002280
James Y Knight9871db02019-02-05 16:42:33 +00002281 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002282 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002283 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2284 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002285 }
2286
John McCall882987f2013-02-28 19:01:20 +00002287 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002288 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002289 Builder.CreateBitCast(value, Int8PtrTy)
2290 };
2291 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002292
Craig Topper8a13c412014-05-21 05:09:00 +00002293 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002294 return value;
2295}
2296
2297/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002298/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002299/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002300llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002301 llvm::Value *newValue,
2302 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002303 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002304 bool isBlock = type->isBlockPointerType();
2305
2306 // Use a store barrier at -O0 unless this is a block type or the
2307 // lvalue is inadequately aligned.
2308 if (shouldUseFusedARCCalls() &&
2309 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002310 (dst.getAlignment().isZero() ||
2311 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002312 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2313 }
2314
2315 // Otherwise, split it out.
2316
2317 // Retain the new value.
2318 newValue = EmitARCRetain(type, newValue);
2319
2320 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002321 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002322
2323 // Store. We do this before the release so that any deallocs won't
2324 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002325 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002326
2327 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002328 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002329
2330 return newValue;
2331}
2332
2333/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002334/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002335llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002336 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002337 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002338 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002339}
2340
2341/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002342/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002343llvm::Value *
2344CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002345 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002346 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002347 llvm::Intrinsic::objc_autoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002348 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002349}
2350
2351/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002352/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002353llvm::Value *
2354CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002355 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002356 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002357 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002358 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002359}
2360
2361/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002362/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002363/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002364/// %retain = call i8* \@objc_retainBlock(i8* %value)
2365/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002366llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2367 llvm::Value *value) {
2368 if (!type->isBlockPointerType())
2369 return EmitARCRetainAutoreleaseNonBlock(value);
2370
2371 if (isa<llvm::ConstantPointerNull>(value)) return value;
2372
Chris Lattner2192fe52011-07-18 04:24:23 +00002373 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002374 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002375 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002376 value = EmitARCAutorelease(value);
2377 return Builder.CreateBitCast(value, origType);
2378}
2379
2380/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002381/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002382llvm::Value *
2383CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002384 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002385 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002386 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002387}
2388
John McCallb04ecb72015-10-21 18:06:43 +00002389/// i8* \@objc_loadWeak(i8** %addr)
2390/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2391llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2392 return emitARCLoadOperation(*this, addr,
2393 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002394 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002395}
2396
James Dennett14c41ea2012-06-22 05:41:30 +00002397/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002398llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002399 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002400 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002401 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002402}
2403
James Dennett14c41ea2012-06-22 05:41:30 +00002404/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002405/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002406llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002407 llvm::Value *value,
2408 bool ignored) {
2409 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002410 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002411 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002412}
2413
James Dennett14c41ea2012-06-22 05:41:30 +00002414/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002415/// Returns %value. %addr is known to not have a current weak entry.
2416/// Essentially equivalent to:
2417/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002418void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002419 // If we're initializing to null, just write null to memory; no need
2420 // to get the runtime involved. But don't do this if optimization
2421 // is enabled, because accounting for this would make the optimizer
2422 // much more complicated.
2423 if (isa<llvm::ConstantPointerNull>(value) &&
2424 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2425 Builder.CreateStore(value, addr);
2426 return;
2427 }
2428
2429 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002430 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002431 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002432}
2433
James Dennett14c41ea2012-06-22 05:41:30 +00002434/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002435/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002436void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002437 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002438 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002439 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2440 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002441 }
2442
2443 // Cast the argument to 'id*'.
2444 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2445
John McCall7f416cc2015-09-08 08:05:57 +00002446 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002447}
2448
James Dennett14c41ea2012-06-22 05:41:30 +00002449/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002450/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2451/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002452void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002453 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002454 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002455 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002456}
2457
James Dennett14c41ea2012-06-22 05:41:30 +00002458/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002459/// Disregards the current value in %dest. Essentially
2460/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002461void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002462 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002463 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002464 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002465}
2466
Akira Hatanakad791e922018-03-19 17:38:40 +00002467void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2468 Address SrcAddr) {
2469 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2470 Object = EmitObjCConsumeObject(Ty, Object);
2471 EmitARCStoreWeak(DstAddr, Object, false);
2472}
2473
2474void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2475 Address SrcAddr) {
2476 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2477 Object = EmitObjCConsumeObject(Ty, Object);
2478 EmitARCStoreWeak(DstAddr, Object, false);
2479 EmitARCDestroyWeak(SrcAddr);
2480}
2481
John McCall31168b02011-06-15 23:02:42 +00002482/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002483/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002484llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002485 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002486 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002487 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2488 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002489 }
2490
John McCall882987f2013-02-28 19:01:20 +00002491 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002492}
2493
2494/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002495/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002496void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2497 assert(value->getType() == Int8PtrTy);
2498
Pete Cooper2cd35962018-12-18 20:33:00 +00002499 if (getInvokeDest()) {
2500 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002501 llvm::FunctionCallee &fn =
2502 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002503 if (!fn) {
2504 llvm::FunctionType *fnType =
2505 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2506 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2507 setARCRuntimeFunctionLinkage(CGM, fn);
2508 }
John McCall31168b02011-06-15 23:02:42 +00002509
Pete Cooper2cd35962018-12-18 20:33:00 +00002510 // objc_autoreleasePoolPop can throw.
2511 EmitRuntimeCallOrInvoke(fn, value);
2512 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002513 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002514 if (!fn) {
2515 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2516 setARCRuntimeFunctionLinkage(CGM, fn);
2517 }
2518
2519 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002520 }
John McCall31168b02011-06-15 23:02:42 +00002521}
2522
2523/// Produce the code to do an MRR version objc_autoreleasepool_push.
2524/// Which is: [[NSAutoreleasePool alloc] init];
2525/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2526/// init is declared as: - (id) init; in its NSObject super class.
2527///
2528llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2529 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002530 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002531 // [NSAutoreleasePool alloc]
2532 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2533 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2534 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002535 RValue AllocRV =
2536 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002537 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002538 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002539
2540 // [Receiver init]
2541 Receiver = AllocRV.getScalarVal();
2542 II = &CGM.getContext().Idents.get("init");
2543 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2544 RValue InitRV =
2545 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2546 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002547 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002548 return InitRV.getScalarVal();
2549}
2550
Pete Coopere3886802018-12-08 05:13:50 +00002551/// Allocate the given objc object.
2552/// call i8* \@objc_alloc(i8* %value)
2553llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2554 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002555 return emitObjCValueOperation(*this, value, resultType,
2556 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002557 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002558}
2559
2560/// Allocate the given objc object.
2561/// call i8* \@objc_allocWithZone(i8* %value)
2562llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2563 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002564 return emitObjCValueOperation(*this, value, resultType,
2565 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002566 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002567}
2568
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002569llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2570 llvm::Type *resultType) {
2571 return emitObjCValueOperation(*this, value, resultType,
2572 CGM.getObjCEntrypoints().objc_alloc_init,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002573 "objc_alloc_init");
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002574}
2575
John McCall31168b02011-06-15 23:02:42 +00002576/// Produce the code to do a primitive release.
2577/// [tmp drain];
2578void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2579 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2580 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2581 CallArgList Args;
2582 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002583 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002584}
2585
John McCall82fe67b2011-07-09 01:37:26 +00002586void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002587 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002588 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002589 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002590}
2591
2592void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002593 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002594 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002595 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002596}
2597
2598void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002599 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002600 QualType type) {
2601 CGF.EmitARCDestroyWeak(addr);
2602}
2603
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002604void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2605 QualType type) {
2606 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2607 CGF.EmitARCIntrinsicUse(value);
2608}
2609
Pete Coopere5b64ea2018-12-21 21:00:32 +00002610/// Autorelease the given object.
2611/// call i8* \@objc_autorelease(i8* %value)
2612llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2613 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002614 return emitObjCValueOperation(
2615 *this, value, returnType,
2616 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002617 "objc_autorelease");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002618}
2619
2620/// Retain the given object, with normal retain semantics.
2621/// call i8* \@objc_retain(i8* %value)
2622llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2623 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002624 return emitObjCValueOperation(
2625 *this, value, returnType,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002626 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002627}
2628
2629/// Release the given object.
2630/// call void \@objc_release(i8* %value)
2631void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2632 ARCPreciseLifetime_t precise) {
2633 if (isa<llvm::ConstantPointerNull>(value)) return;
2634
James Y Knight9871db02019-02-05 16:42:33 +00002635 llvm::FunctionCallee &fn =
2636 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002637 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002638 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002639 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002640 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2641 setARCRuntimeFunctionLinkage(CGM, fn);
2642 // We have Native ARC, so set nonlazybind attribute for performance
2643 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2644 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002645 }
2646
2647 // Cast the argument to 'id'.
2648 value = Builder.CreateBitCast(value, Int8PtrTy);
2649
2650 // Call objc_release.
Akira Hatanaka34d28cf2019-05-10 21:54:16 +00002651 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002652
2653 if (precise == ARCImpreciseLifetime) {
2654 call->setMetadata("clang.imprecise_release",
2655 llvm::MDNode::get(Builder.getContext(), None));
2656 }
2657}
2658
John McCall31168b02011-06-15 23:02:42 +00002659namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002660 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002661 llvm::Value *Token;
2662
2663 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2664
Craig Topper4f12f102014-03-12 06:41:41 +00002665 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002666 CGF.EmitObjCAutoreleasePoolPop(Token);
2667 }
2668 };
David Blaikie7e70d682015-08-18 22:40:54 +00002669 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002670 llvm::Value *Token;
2671
2672 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2673
Craig Topper4f12f102014-03-12 06:41:41 +00002674 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002675 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2676 }
2677 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002678}
John McCall31168b02011-06-15 23:02:42 +00002679
2680void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002681 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002682 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2683 else
2684 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2685}
2686
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002687static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2688 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002689 case Qualifiers::OCL_None:
2690 case Qualifiers::OCL_ExplicitNone:
2691 case Qualifiers::OCL_Strong:
2692 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002693 return true;
John McCall31168b02011-06-15 23:02:42 +00002694
2695 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002696 return false;
John McCall31168b02011-06-15 23:02:42 +00002697 }
2698
2699 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002700}
2701
2702static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002703 LValue lvalue,
2704 QualType type) {
2705 llvm::Value *result;
2706 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2707 if (shouldRetain) {
2708 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2709 } else {
2710 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2711 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2712 }
2713 return TryEmitResult(result, !shouldRetain);
2714}
2715
2716static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002717 const Expr *e) {
2718 e = e->IgnoreParens();
2719 QualType type = e->getType();
2720
Fangrui Song6907ce22018-07-30 19:24:48 +00002721 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002722 // an extra retain/release pair by zeroing out the source of this
2723 // "move" operation.
2724 if (e->isXValue() &&
2725 !type.isConstQualified() &&
2726 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2727 // Emit the lvalue.
2728 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002729
John McCall154a2fd2011-08-30 00:57:29 +00002730 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002731 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2732 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002733
John McCall154a2fd2011-08-30 00:57:29 +00002734 // Set the source pointer to NULL.
2735 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002736
John McCall154a2fd2011-08-30 00:57:29 +00002737 return TryEmitResult(result, true);
2738 }
2739
John McCall31168b02011-06-15 23:02:42 +00002740 // As a very special optimization, in ARC++, if the l-value is the
2741 // result of a non-volatile assignment, do a simple retain of the
2742 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002743 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002744 !type.isVolatileQualified() &&
2745 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2746 isa<BinaryOperator>(e) &&
2747 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2748 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2749
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002750 // Try to emit code for scalar constant instead of emitting LValue and
2751 // loading it because we are not guaranteed to have an l-value. One of such
2752 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2753 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2754 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2755 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2756 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2757 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2758 }
2759
John McCall31168b02011-06-15 23:02:42 +00002760 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2761}
2762
John McCalle399e5b2016-01-27 18:32:30 +00002763typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2764 llvm::Value *value)>
2765 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002766
John McCalle399e5b2016-01-27 18:32:30 +00002767/// Insert code immediately after a call.
2768static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2769 llvm::Value *value,
2770 ValueTransform doAfterCall,
2771 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002772 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2773 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2774
2775 // Place the retain immediately following the call.
2776 CGF.Builder.SetInsertPoint(call->getParent(),
2777 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002778 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002779
2780 CGF.Builder.restoreIP(ip);
2781 return value;
2782 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2783 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2784
2785 // Place the retain at the beginning of the normal destination block.
2786 llvm::BasicBlock *BB = invoke->getNormalDest();
2787 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002788 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002789
2790 CGF.Builder.restoreIP(ip);
2791 return value;
2792
2793 // Bitcasts can arise because of related-result returns. Rewrite
2794 // the operand.
2795 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2796 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002797 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002798 bitcast->setOperand(0, operand);
2799 return bitcast;
2800
2801 // Generic fall-back case.
2802 } else {
2803 // Retain using the non-block variant: we never need to do a copy
2804 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002805 return doFallback(CGF, value);
2806 }
2807}
2808
2809/// Given that the given expression is some sort of call (which does
2810/// not return retained), emit a retain following it.
2811static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2812 const Expr *e) {
2813 llvm::Value *value = CGF.EmitScalarExpr(e);
2814 return emitARCOperationAfterCall(CGF, value,
2815 [](CodeGenFunction &CGF, llvm::Value *value) {
2816 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2817 },
2818 [](CodeGenFunction &CGF, llvm::Value *value) {
2819 return CGF.EmitARCRetainNonBlock(value);
2820 });
2821}
2822
2823/// Given that the given expression is some sort of call (which does
2824/// not return retained), perform an unsafeClaim following it.
2825static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2826 const Expr *e) {
2827 llvm::Value *value = CGF.EmitScalarExpr(e);
2828 return emitARCOperationAfterCall(CGF, value,
2829 [](CodeGenFunction &CGF, llvm::Value *value) {
2830 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2831 },
2832 [](CodeGenFunction &CGF, llvm::Value *value) {
2833 return value;
2834 });
2835}
2836
2837llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2838 bool allowUnsafeClaim) {
2839 if (allowUnsafeClaim &&
2840 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2841 return emitARCUnsafeClaimCallResult(*this, E);
2842 } else {
2843 llvm::Value *value = emitARCRetainCallResult(*this, E);
2844 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002845 }
2846}
2847
John McCallcd78e802011-09-10 01:16:55 +00002848/// Determine whether it might be important to emit a separate
2849/// objc_retain_block on the result of the given expression, or
2850/// whether it's okay to just emit it in a +1 context.
2851static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2852 assert(e->getType()->isBlockPointerType());
2853 e = e->IgnoreParens();
2854
2855 // For future goodness, emit block expressions directly in +1
2856 // contexts if we can.
2857 if (isa<BlockExpr>(e))
2858 return false;
2859
2860 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2861 switch (cast->getCastKind()) {
2862 // Emitting these operations in +1 contexts is goodness.
2863 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002864 case CK_ARCReclaimReturnedObject:
2865 case CK_ARCConsumeObject:
2866 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002867 return false;
2868
2869 // These operations preserve a block type.
2870 case CK_NoOp:
2871 case CK_BitCast:
2872 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2873
2874 // These operations are known to be bad (or haven't been considered).
2875 case CK_AnyPointerToBlockPointerCast:
2876 default:
2877 return true;
2878 }
2879 }
2880
2881 return true;
2882}
2883
John McCalle399e5b2016-01-27 18:32:30 +00002884namespace {
2885/// A CRTP base class for emitting expressions of retainable object
2886/// pointer type in ARC.
2887template <typename Impl, typename Result> class ARCExprEmitter {
2888protected:
2889 CodeGenFunction &CGF;
2890 Impl &asImpl() { return *static_cast<Impl*>(this); }
2891
2892 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2893
2894public:
2895 Result visit(const Expr *e);
2896 Result visitCastExpr(const CastExpr *e);
2897 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002898 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002899 Result visitBinaryOperator(const BinaryOperator *e);
2900 Result visitBinAssign(const BinaryOperator *e);
2901 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2902 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2903 Result visitBinAssignWeak(const BinaryOperator *e);
2904 Result visitBinAssignStrong(const BinaryOperator *e);
2905
2906 // Minimal implementation:
2907 // Result visitLValueToRValue(const Expr *e)
2908 // Result visitConsumeObject(const Expr *e)
2909 // Result visitExtendBlockObject(const Expr *e)
2910 // Result visitReclaimReturnedObject(const Expr *e)
2911 // Result visitCall(const Expr *e)
2912 // Result visitExpr(const Expr *e)
2913 //
2914 // Result emitBitCast(Result result, llvm::Type *resultType)
2915 // llvm::Value *getValueOfResult(Result result)
2916};
2917}
2918
2919/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002920///
2921/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002922template <typename Impl, typename Result>
2923Result
2924ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002925 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002926
2927 // Find the result expression.
2928 const Expr *resultExpr = E->getResultExpr();
2929 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002930 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002931
2932 for (PseudoObjectExpr::const_semantics_iterator
2933 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2934 const Expr *semantic = *i;
2935
2936 // If this semantic expression is an opaque value, bind it
2937 // to the result of its source expression.
2938 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2939 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2940 OVMA opaqueData;
2941
2942 // If this semantic is the result of the pseudo-object
2943 // expression, try to evaluate the source as +1.
2944 if (ov == resultExpr) {
2945 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002946 result = asImpl().visit(ov->getSourceExpr());
2947 opaqueData = OVMA::bind(CGF, ov,
2948 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002949
2950 // Otherwise, just bind it.
2951 } else {
2952 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2953 }
2954 opaques.push_back(opaqueData);
2955
2956 // Otherwise, if the expression is the result, evaluate it
2957 // and remember the result.
2958 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002959 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002960
2961 // Otherwise, evaluate the expression in an ignored context.
2962 } else {
2963 CGF.EmitIgnoredExpr(semantic);
2964 }
2965 }
2966
2967 // Unbind all the opaques now.
2968 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2969 opaques[i].unbind(CGF);
2970
2971 return result;
2972}
2973
John McCalle399e5b2016-01-27 18:32:30 +00002974template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002975Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2976 // The default implementation just forwards the expression to visitExpr.
2977 return asImpl().visitExpr(e);
2978}
2979
2980template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00002981Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2982 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002983
John McCalle399e5b2016-01-27 18:32:30 +00002984 // No-op casts don't change the type, so we just ignore them.
2985 case CK_NoOp:
2986 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002987
John McCalle399e5b2016-01-27 18:32:30 +00002988 // These casts can change the type.
2989 case CK_CPointerToObjCPointerCast:
2990 case CK_BlockPointerToObjCPointerCast:
2991 case CK_AnyPointerToBlockPointerCast:
2992 case CK_BitCast: {
2993 llvm::Type *resultType = CGF.ConvertType(e->getType());
2994 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2995 Result result = asImpl().visit(e->getSubExpr());
2996 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002997 }
2998
John McCalle399e5b2016-01-27 18:32:30 +00002999 // Handle some casts specially.
3000 case CK_LValueToRValue:
3001 return asImpl().visitLValueToRValue(e->getSubExpr());
3002 case CK_ARCConsumeObject:
3003 return asImpl().visitConsumeObject(e->getSubExpr());
3004 case CK_ARCExtendBlockObject:
3005 return asImpl().visitExtendBlockObject(e->getSubExpr());
3006 case CK_ARCReclaimReturnedObject:
3007 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3008
3009 // Otherwise, use the default logic.
3010 default:
3011 return asImpl().visitExpr(e);
3012 }
3013}
3014
3015template <typename Impl, typename Result>
3016Result
3017ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3018 switch (e->getOpcode()) {
3019 case BO_Comma:
3020 CGF.EmitIgnoredExpr(e->getLHS());
3021 CGF.EnsureInsertPoint();
3022 return asImpl().visit(e->getRHS());
3023
3024 case BO_Assign:
3025 return asImpl().visitBinAssign(e);
3026
3027 default:
3028 return asImpl().visitExpr(e);
3029 }
3030}
3031
3032template <typename Impl, typename Result>
3033Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3034 switch (e->getLHS()->getType().getObjCLifetime()) {
3035 case Qualifiers::OCL_ExplicitNone:
3036 return asImpl().visitBinAssignUnsafeUnretained(e);
3037
3038 case Qualifiers::OCL_Weak:
3039 return asImpl().visitBinAssignWeak(e);
3040
3041 case Qualifiers::OCL_Autoreleasing:
3042 return asImpl().visitBinAssignAutoreleasing(e);
3043
3044 case Qualifiers::OCL_Strong:
3045 return asImpl().visitBinAssignStrong(e);
3046
3047 case Qualifiers::OCL_None:
3048 return asImpl().visitExpr(e);
3049 }
3050 llvm_unreachable("bad ObjC ownership qualifier");
3051}
3052
3053/// The default rule for __unsafe_unretained emits the RHS recursively,
3054/// stores into the unsafe variable, and propagates the result outward.
3055template <typename Impl, typename Result>
3056Result ARCExprEmitter<Impl,Result>::
3057 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3058 // Recursively emit the RHS.
3059 // For __block safety, do this before emitting the LHS.
3060 Result result = asImpl().visit(e->getRHS());
3061
3062 // Perform the store.
3063 LValue lvalue =
3064 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3065 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3066 lvalue);
3067
3068 return result;
3069}
3070
3071template <typename Impl, typename Result>
3072Result
3073ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3074 return asImpl().visitExpr(e);
3075}
3076
3077template <typename Impl, typename Result>
3078Result
3079ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3080 return asImpl().visitExpr(e);
3081}
3082
3083template <typename Impl, typename Result>
3084Result
3085ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3086 return asImpl().visitExpr(e);
3087}
3088
3089/// The general expression-emission logic.
3090template <typename Impl, typename Result>
3091Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3092 // We should *never* see a nested full-expression here, because if
3093 // we fail to emit at +1, our caller must not retain after we close
3094 // out the full-expression. This isn't as important in the unsafe
3095 // emitter.
3096 assert(!isa<ExprWithCleanups>(e));
3097
3098 // Look through parens, __extension__, generic selection, etc.
3099 e = e->IgnoreParens();
3100
3101 // Handle certain kinds of casts.
3102 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3103 return asImpl().visitCastExpr(ce);
3104
3105 // Handle the comma operator.
3106 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3107 return asImpl().visitBinaryOperator(op);
3108
3109 // TODO: handle conditional operators here
3110
3111 // For calls and message sends, use the retained-call logic.
3112 // Delegate inits are a special case in that they're the only
3113 // returns-retained expression that *isn't* surrounded by
3114 // a consume.
3115 } else if (isa<CallExpr>(e) ||
3116 (isa<ObjCMessageExpr>(e) &&
3117 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3118 return asImpl().visitCall(e);
3119
3120 // Look through pseudo-object expressions.
3121 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3122 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003123 } else if (auto *be = dyn_cast<BlockExpr>(e))
3124 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003125
3126 return asImpl().visitExpr(e);
3127}
3128
3129namespace {
3130
3131/// An emitter for +1 results.
3132struct ARCRetainExprEmitter :
3133 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3134
3135 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3136
3137 llvm::Value *getValueOfResult(TryEmitResult result) {
3138 return result.getPointer();
3139 }
3140
3141 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3142 llvm::Value *value = result.getPointer();
3143 value = CGF.Builder.CreateBitCast(value, resultType);
3144 result.setPointer(value);
3145 return result;
3146 }
3147
3148 TryEmitResult visitLValueToRValue(const Expr *e) {
3149 return tryEmitARCRetainLoadOfScalar(CGF, e);
3150 }
3151
3152 /// For consumptions, just emit the subexpression and thus elide
3153 /// the retain/release pair.
3154 TryEmitResult visitConsumeObject(const Expr *e) {
3155 llvm::Value *result = CGF.EmitScalarExpr(e);
3156 return TryEmitResult(result, true);
3157 }
3158
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003159 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3160 TryEmitResult result = visitExpr(e);
3161 // Avoid the block-retain if this is a block literal that doesn't need to be
3162 // copied to the heap.
3163 if (e->getBlockDecl()->canAvoidCopyToHeap())
3164 result.setInt(true);
3165 return result;
3166 }
3167
John McCalle399e5b2016-01-27 18:32:30 +00003168 /// Block extends are net +0. Naively, we could just recurse on
3169 /// the subexpression, but actually we need to ensure that the
3170 /// value is copied as a block, so there's a little filter here.
3171 TryEmitResult visitExtendBlockObject(const Expr *e) {
3172 llvm::Value *result; // will be a +0 value
3173
3174 // If we can't safely assume the sub-expression will produce a
3175 // block-copied value, emit the sub-expression at +0.
3176 if (shouldEmitSeparateBlockRetain(e)) {
3177 result = CGF.EmitScalarExpr(e);
3178
3179 // Otherwise, try to emit the sub-expression at +1 recursively.
3180 } else {
3181 TryEmitResult subresult = asImpl().visit(e);
3182
3183 // If that produced a retained value, just use that.
3184 if (subresult.getInt()) {
3185 return subresult;
3186 }
3187
3188 // Otherwise it's +0.
3189 result = subresult.getPointer();
3190 }
3191
3192 // Retain the object as a block.
3193 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3194 return TryEmitResult(result, true);
3195 }
3196
3197 /// For reclaims, emit the subexpression as a retained call and
3198 /// skip the consumption.
3199 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3200 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3201 return TryEmitResult(result, true);
3202 }
3203
3204 /// When we have an undecorated call, retroactively do a claim.
3205 TryEmitResult visitCall(const Expr *e) {
3206 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3207 return TryEmitResult(result, true);
3208 }
3209
3210 // TODO: maybe special-case visitBinAssignWeak?
3211
3212 TryEmitResult visitExpr(const Expr *e) {
3213 // We didn't find an obvious production, so emit what we've got and
3214 // tell the caller that we didn't manage to retain.
3215 llvm::Value *result = CGF.EmitScalarExpr(e);
3216 return TryEmitResult(result, false);
3217 }
3218};
3219}
3220
3221static TryEmitResult
3222tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3223 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003224}
3225
3226static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3227 LValue lvalue,
3228 QualType type) {
3229 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3230 llvm::Value *value = result.getPointer();
3231 if (!result.getInt())
3232 value = CGF.EmitARCRetain(type, value);
3233 return value;
3234}
3235
3236/// EmitARCRetainScalarExpr - Semantically equivalent to
3237/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3238/// best-effort attempt to peephole expressions that naturally produce
3239/// retained objects.
3240llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003241 // The retain needs to happen within the full-expression.
3242 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3243 enterFullExpression(cleanups);
3244 RunCleanupsScope scope(*this);
3245 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3246 }
3247
John McCall31168b02011-06-15 23:02:42 +00003248 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3249 llvm::Value *value = result.getPointer();
3250 if (!result.getInt())
3251 value = EmitARCRetain(e->getType(), value);
3252 return value;
3253}
3254
3255llvm::Value *
3256CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003257 // The retain needs to happen within the full-expression.
3258 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3259 enterFullExpression(cleanups);
3260 RunCleanupsScope scope(*this);
3261 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3262 }
3263
John McCall31168b02011-06-15 23:02:42 +00003264 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3265 llvm::Value *value = result.getPointer();
3266 if (result.getInt())
3267 value = EmitARCAutorelease(value);
3268 else
3269 value = EmitARCRetainAutorelease(e->getType(), value);
3270 return value;
3271}
3272
John McCallff613032011-10-04 06:23:45 +00003273llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3274 llvm::Value *result;
3275 bool doRetain;
3276
3277 if (shouldEmitSeparateBlockRetain(e)) {
3278 result = EmitScalarExpr(e);
3279 doRetain = true;
3280 } else {
3281 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3282 result = subresult.getPointer();
3283 doRetain = !subresult.getInt();
3284 }
3285
3286 if (doRetain)
3287 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3288 return EmitObjCConsumeObject(e->getType(), result);
3289}
3290
John McCall248512a2011-10-01 10:32:24 +00003291llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3292 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003293 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003294 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003295 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003296 return EmitARCRetainAutoreleaseScalarExpr(expr);
3297 }
3298
3299 // Otherwise, use the normal scalar-expression emission. The
3300 // exception machinery doesn't do anything special with the
3301 // exception like retaining it, so there's no safety associated with
3302 // only running cleanups after the throw has started, and when it
3303 // matters it tends to be substantially inferior code.
3304 return EmitScalarExpr(expr);
3305}
3306
John McCalle399e5b2016-01-27 18:32:30 +00003307namespace {
3308
3309/// An emitter for assigning into an __unsafe_unretained context.
3310struct ARCUnsafeUnretainedExprEmitter :
3311 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3312
3313 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3314
3315 llvm::Value *getValueOfResult(llvm::Value *value) {
3316 return value;
3317 }
3318
3319 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3320 return CGF.Builder.CreateBitCast(value, resultType);
3321 }
3322
3323 llvm::Value *visitLValueToRValue(const Expr *e) {
3324 return CGF.EmitScalarExpr(e);
3325 }
3326
3327 /// For consumptions, just emit the subexpression and perform the
3328 /// consumption like normal.
3329 llvm::Value *visitConsumeObject(const Expr *e) {
3330 llvm::Value *value = CGF.EmitScalarExpr(e);
3331 return CGF.EmitObjCConsumeObject(e->getType(), value);
3332 }
3333
3334 /// No special logic for block extensions. (This probably can't
3335 /// actually happen in this emitter, though.)
3336 llvm::Value *visitExtendBlockObject(const Expr *e) {
3337 return CGF.EmitARCExtendBlockObject(e);
3338 }
3339
3340 /// For reclaims, perform an unsafeClaim if that's enabled.
3341 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3342 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3343 }
3344
3345 /// When we have an undecorated call, just emit it without adding
3346 /// the unsafeClaim.
3347 llvm::Value *visitCall(const Expr *e) {
3348 return CGF.EmitScalarExpr(e);
3349 }
3350
3351 /// Just do normal scalar emission in the default case.
3352 llvm::Value *visitExpr(const Expr *e) {
3353 return CGF.EmitScalarExpr(e);
3354 }
3355};
3356}
3357
3358static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3359 const Expr *e) {
3360 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3361}
3362
3363/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3364/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3365/// avoiding any spurious retains, including by performing reclaims
3366/// with objc_unsafeClaimAutoreleasedReturnValue.
3367llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3368 // Look through full-expressions.
3369 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3370 enterFullExpression(cleanups);
3371 RunCleanupsScope scope(*this);
3372 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3373 }
3374
3375 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3376}
3377
3378std::pair<LValue,llvm::Value*>
3379CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3380 bool ignored) {
3381 // Evaluate the RHS first. If we're ignoring the result, assume
3382 // that we can emit at an unsafe +0.
3383 llvm::Value *value;
3384 if (ignored) {
3385 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3386 } else {
3387 value = EmitScalarExpr(e->getRHS());
3388 }
3389
3390 // Emit the LHS and perform the store.
3391 LValue lvalue = EmitLValue(e->getLHS());
3392 EmitStoreOfScalar(value, lvalue);
3393
3394 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3395}
3396
John McCall31168b02011-06-15 23:02:42 +00003397std::pair<LValue,llvm::Value*>
3398CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3399 bool ignored) {
3400 // Evaluate the RHS first.
3401 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3402 llvm::Value *value = result.getPointer();
3403
John McCallb726a552011-07-28 07:23:35 +00003404 bool hasImmediateRetain = result.getInt();
3405
3406 // If we didn't emit a retained object, and the l-value is of block
3407 // type, then we need to emit the block-retain immediately in case
3408 // it invalidates the l-value.
3409 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003410 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003411 hasImmediateRetain = true;
3412 }
3413
John McCall31168b02011-06-15 23:02:42 +00003414 LValue lvalue = EmitLValue(e->getLHS());
3415
3416 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003417 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003418 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003419 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003420 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003421 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003422 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003423 }
3424
3425 return std::pair<LValue,llvm::Value*>(lvalue, value);
3426}
3427
3428std::pair<LValue,llvm::Value*>
3429CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3430 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3431 LValue lvalue = EmitLValue(e->getLHS());
3432
Eli Friedmana0544d62011-12-03 04:14:32 +00003433 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003434
3435 return std::pair<LValue,llvm::Value*>(lvalue, value);
3436}
3437
3438void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003439 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003440 const Stmt *subStmt = ARPS.getSubStmt();
3441 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3442
3443 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003444 if (DI)
3445 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003446
3447 // Keep track of the current cleanup stack depth.
3448 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003449 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003450 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3451 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3452 } else {
3453 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3454 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3455 }
3456
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003457 for (const auto *I : S.body())
3458 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003459
Eric Christopher7cdf9482011-10-13 21:45:18 +00003460 if (DI)
3461 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003462}
John McCall1bd25562011-06-24 23:21:27 +00003463
3464/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3465/// make sure it survives garbage collection until this point.
3466void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3467 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003468 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003469 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003470 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3471 /* assembly */ "",
3472 /* constraints */ "r",
3473 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003474
3475 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003476 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003477}
3478
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003479/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003480/// non-trivial copy assignment function, produce following helper function.
3481/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3482///
3483llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003484CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3485 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003486 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003487 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003488 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003489 QualType Ty = PID->getPropertyIvarDecl()->getType();
3490 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003491 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003492 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003493 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003494 return nullptr;
3495 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003496 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003497 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003498 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3499 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3500 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003501
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003502 ASTContext &C = getContext();
3503 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003504 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003505
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003506 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003507 QualType DestTy = C.getPointerType(Ty);
3508 QualType SrcTy = Ty;
3509 SrcTy.addConst();
3510 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003511
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003512 SmallVector<QualType, 2> ArgTys;
3513 ArgTys.push_back(DestTy);
3514 ArgTys.push_back(SrcTy);
3515 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3516
3517 FunctionDecl *FD = FunctionDecl::Create(
3518 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3519 FunctionTy, nullptr, SC_Static, false, false);
3520
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003521 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003522 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3523 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003524 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003525 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3526 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003527 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003528
John McCallc56a8b32016-03-11 04:30:31 +00003529 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003530 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003531
John McCalla729c622012-02-17 03:33:10 +00003532 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003533
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003534 llvm::Function *Fn =
3535 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003536 "__assign_helper_atomic_property_",
3537 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003538
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003539 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003540
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003541 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003542
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003543 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3544 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003545 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003546 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003547
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003548 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3549 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003550 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003551 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003552
John McCall113bee02012-03-10 09:33:50 +00003553 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003554 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003555 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3556 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3557 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003558
Bruno Riccic5885cf2018-12-21 15:20:32 +00003559 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003560
3561 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003562 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003563 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003564 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003565}
3566
3567llvm::Constant *
3568CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3569 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003570 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003571 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003572 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003573 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3574 QualType Ty = PD->getType();
3575 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003576 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003577 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003578 return nullptr;
3579 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003580 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003581 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003582 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3583 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3584 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003585
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003586 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003587 IdentifierInfo *II =
3588 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003589
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003590 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003591 QualType DestTy = C.getPointerType(Ty);
3592 QualType SrcTy = Ty;
3593 SrcTy.addConst();
3594 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003595
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003596 SmallVector<QualType, 2> ArgTys;
3597 ArgTys.push_back(DestTy);
3598 ArgTys.push_back(SrcTy);
3599 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3600
3601 FunctionDecl *FD = FunctionDecl::Create(
3602 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3603 FunctionTy, nullptr, SC_Static, false, false);
3604
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003605 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003606 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3607 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003608 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003609 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3610 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003611 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003612
John McCallc56a8b32016-03-11 04:30:31 +00003613 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003614 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003615
John McCalla729c622012-02-17 03:33:10 +00003616 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003617
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003618 llvm::Function *Fn = llvm::Function::Create(
3619 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3620 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003621
3622 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003623
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003624 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003625
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003626 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3627 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003628
John McCall113bee02012-03-10 09:33:50 +00003629 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003630 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003631
3632 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003633 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003634
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003635 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003636 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003637 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3638 CXXConstExpr->arg_end());
3639
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003640 CXXConstructExpr *TheCXXConstructExpr =
3641 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3642 CXXConstExpr->getConstructor(),
3643 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003644 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003645 CXXConstExpr->hadMultipleCandidates(),
3646 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003647 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003648 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003649 CXXConstExpr->getConstructionKind(),
3650 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003651
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003652 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3653 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003654
John McCall113bee02012-03-10 09:33:50 +00003655 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003656 CharUnits Alignment
3657 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003658 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003659 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3660 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003661 AggValueSlot::IsDestructed,
3662 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003663 AggValueSlot::IsNotAliased,
3664 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003665
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003666 FinishFunction();
3667 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3668 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3669 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003670}
3671
Eli Friedmanec75fec2012-02-28 01:08:45 +00003672llvm::Value *
3673CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3674 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003675 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3676 Selector CopySelector =
3677 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003678 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3679 Selector AutoreleaseSelector =
3680 getContext().Selectors.getNullarySelector(AutoreleaseID);
3681
3682 // Emit calls to retain/autorelease.
3683 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3684 llvm::Value *Val = Block;
3685 RValue Result;
3686 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003687 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003688 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003689 Val = Result.getScalarVal();
3690 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3691 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003692 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003693 Val = Result.getScalarVal();
3694 return Val;
3695}
3696
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003697llvm::Value *
3698CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3699 assert(Args.size() == 3 && "Expected 3 argument here!");
3700
3701 if (!CGM.IsOSVersionAtLeastFn) {
3702 llvm::FunctionType *FTy =
3703 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3704 CGM.IsOSVersionAtLeastFn =
3705 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3706 }
3707
3708 llvm::Value *CallRes =
3709 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3710
3711 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3712}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003713
Alex Lorenza8fbef42017-03-23 11:14:27 +00003714void CodeGenModule::emitAtAvailableLinkGuard() {
3715 if (!IsOSVersionAtLeastFn)
3716 return;
3717 // @available requires CoreFoundation only on Darwin.
3718 if (!Target.getTriple().isOSDarwin())
3719 return;
3720 // Add -framework CoreFoundation to the linker commands. We still want to
3721 // emit the core foundation reference down below because otherwise if
3722 // CoreFoundation is not used in the code, the linker won't link the
3723 // framework.
3724 auto &Context = getLLVMContext();
3725 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3726 llvm::MDString::get(Context, "CoreFoundation")};
3727 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3728 // Emit a reference to a symbol from CoreFoundation to ensure that
3729 // CoreFoundation is linked into the final binary.
3730 llvm::FunctionType *FTy =
3731 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003732 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003733 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3734
3735 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003736 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3737 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003738 llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00003739 llvm::Function *CFLinkCheckFunc =
3740 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3741 if (CFLinkCheckFunc->empty()) {
3742 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3743 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3744 CodeGenFunction CGF(*this);
3745 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3746 CGF.EmitNounwindRuntimeCall(CFFunc,
3747 llvm::Constant::getNullValue(VoidPtrTy));
3748 CGF.Builder.CreateUnreachable();
3749 addCompilerUsedGlobal(CFLinkCheckFunc);
3750 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003751}
3752
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003753CGObjCRuntime::~CGObjCRuntime() {}