blob: 6db05391722d58f12fd2b28e9684bff2124f80c0 [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
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800433CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
434 CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
435 Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
436 const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
437 bool isClassMessage) {
438 if (Optional<llvm::Value *> SpecializedResult =
439 tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
440 Sel, Method, isClassMessage)) {
441 return RValue::get(SpecializedResult.getValue());
442 }
443 return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
444 Method);
445}
446
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000447/// Instead of '[[MyClass alloc] init]', try to generate
448/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
449/// caller side, as well as the optimized objc_alloc.
450static Optional<llvm::Value *>
451tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
452 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
453 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
454 return None;
455
456 // Match the exact pattern '[[MyClass alloc] init]'.
457 Selector Sel = OME->getSelector();
Erik Pilkington55e703a2019-02-25 21:35:14 +0000458 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
459 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
460 Sel.getNameForSlot(0) != "init")
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000461 return None;
462
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000463 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]' or
464 // we are in an ObjC class method and 'receiver' is '[self alloc]'.
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000465 auto *SubOME =
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000466 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000467 if (!SubOME)
468 return None;
469 Selector SubSel = SubOME->getSelector();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000470
471 // Check if we are in an ObjC class method and the receiver expression is
472 // 'self'.
473 const Expr *SelfInClassMethod = nullptr;
474 if (const auto *CurMD = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
475 if (CurMD->isClassMethod())
476 if ((SelfInClassMethod = SubOME->getInstanceReceiver()))
477 if (!SelfInClassMethod->isObjCSelfExpr())
478 SelfInClassMethod = nullptr;
479
480 if ((SubOME->getReceiverKind() != ObjCMessageExpr::Class &&
481 !SelfInClassMethod) || !SubOME->getType()->isObjCObjectPointerType() ||
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000482 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
483 return None;
484
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000485 llvm::Value *Receiver;
486 if (SelfInClassMethod) {
487 Receiver = CGF.EmitScalarExpr(SelfInClassMethod);
488 } else {
489 QualType ReceiverType = SubOME->getClassReceiver();
490 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
491 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
492 assert(ID && "null interface should be impossible here");
493 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
494 }
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000495 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
496}
497
John McCall78a15112010-05-22 01:48:05 +0000498RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
499 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000500 // Only the lookup mechanism and first two arguments of the method
501 // implementation vary between runtimes. We can get the receiver and
502 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000503
John McCall31168b02011-06-15 23:02:42 +0000504 bool isDelegateInit = E->isDelegateInitCall();
505
John McCallcf166702011-07-22 08:53:00 +0000506 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000507
John McCall460ce582015-10-22 18:38:17 +0000508 // If the method is -retain, and the receiver's being loaded from
509 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
510 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
511 method->getMethodFamily() == OMF_retain) {
512 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
513 LValue lvalue = EmitLValue(lvalueExpr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800514 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +0000515 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
516 }
517 }
518
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000519 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
520 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
521
John McCall31168b02011-06-15 23:02:42 +0000522 // We don't retain the receiver in delegate init calls, and this is
523 // safe because the receiver value is always loaded from 'self',
524 // which we zero out. We don't want to Block_copy block receivers,
525 // though.
526 bool retainSelf =
527 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000528 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000529 method &&
530 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000531
Daniel Dunbar8d480592008-08-11 18:12:00 +0000532 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000533 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000534 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000535 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000536 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000537 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000538 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000539 switch (E->getReceiverKind()) {
540 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000541 ReceiverType = E->getInstanceReceiver()->getType();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000542 if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl))
543 if (OMD->isClassMethod())
544 if (E->getInstanceReceiver()->isObjCSelfExpr())
545 isClassMessage = true;
John McCall31168b02011-06-15 23:02:42 +0000546 if (retainSelf) {
547 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
548 E->getInstanceReceiver());
549 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000550 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000551 } else
552 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000553 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000554
Douglas Gregor9a129192010-04-21 00:45:42 +0000555 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000556 ReceiverType = E->getClassReceiver();
557 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000558 assert(ObjTy && "Invalid Objective-C class message send");
559 OID = ObjTy->getInterface();
560 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000561 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000562 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000563 break;
564 }
565
566 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000567 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000568 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000569 isSuperMessage = true;
570 break;
571
572 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000573 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000574 Receiver = LoadObjCSelf();
575 isSuperMessage = true;
576 isClassMessage = true;
577 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000578 }
579
John McCallcf166702011-07-22 08:53:00 +0000580 if (retainSelf)
581 Receiver = EmitARCRetainNonBlock(Receiver);
582
583 // In ARC, we sometimes want to "extend the lifetime"
584 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
585 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000586 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000587 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
588 shouldExtendReceiverForInnerPointerMessage(E))
589 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
590
Alp Toker314cc812014-01-25 16:55:45 +0000591 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000592
Daniel Dunbarc722b852008-08-30 03:02:31 +0000593 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000594 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000595
John McCall31168b02011-06-15 23:02:42 +0000596 // For delegate init calls in ARC, do an unsafe store of null into
597 // self. This represents the call taking direct ownership of that
598 // value. We have to do this after emitting the other call
599 // arguments because they might also reference self, but we don't
600 // have to worry about any of them modifying self because that would
601 // be an undefined read and write of an object in unordered
602 // expressions.
603 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000604 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000605 "delegate init calls should only be marked in ARC");
606
607 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000608 Address selfAddr =
609 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000610 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
611 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000612
Douglas Gregor33823722011-06-11 01:09:30 +0000613 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000614 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000615 // super is only valid in an Objective-C method
616 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000617 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000618 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
619 E->getSelector(),
620 OMD->getClassInterface(),
621 isCategoryImpl,
622 Receiver,
623 isClassMessage,
624 Args,
John McCallcf166702011-07-22 08:53:00 +0000625 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000626 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000627 // Call runtime methods directly if we can.
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800628 result = Runtime.GeneratePossiblySpecializedMessageSend(
629 *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
630 method, isClassMessage);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000631 }
John McCall31168b02011-06-15 23:02:42 +0000632
633 // For delegate init calls in ARC, implicitly store the result of
634 // the call back into self. This takes ownership of the value.
635 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000636 Address selfAddr =
637 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000638 llvm::Value *newSelf = result.getScalarVal();
639
640 // The delegate return type isn't necessarily a matching type; in
641 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000642 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000643 newSelf = Builder.CreateBitCast(newSelf, selfTy);
644
645 Builder.CreateStore(newSelf, selfAddr);
646 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000647
Douglas Gregore83b9562015-07-07 03:57:53 +0000648 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000649}
650
John McCall31168b02011-06-15 23:02:42 +0000651namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000652struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000653 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000654 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000655
656 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000657 const ObjCInterfaceDecl *iface = impl->getClassInterface();
658 if (!iface->getSuperClass()) return;
659
John McCalldffafde2011-07-13 18:26:47 +0000660 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
661
John McCall31168b02011-06-15 23:02:42 +0000662 // Call [super dealloc] if we have a superclass.
663 llvm::Value *self = CGF.LoadObjCSelf();
664
665 CallArgList args;
666 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
667 CGF.getContext().VoidTy,
668 method->getSelector(),
669 iface,
John McCalldffafde2011-07-13 18:26:47 +0000670 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000671 self,
672 /*is class msg*/ false,
673 args,
674 method);
675 }
676};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000677}
John McCall31168b02011-06-15 23:02:42 +0000678
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000679/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
680/// the LLVM function and sets the other context used by
681/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000682void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000683 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000684 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000685 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000686 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000687 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000688 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000689
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000690 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000691
John McCalla729c622012-02-17 03:33:10 +0000692 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800693 if (OMD->isDirectMethod()) {
694 Fn->setVisibility(llvm::Function::HiddenVisibility);
695 CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
696 CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
697 } else {
698 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
699 }
Chris Lattner5696e7b2008-06-17 18:05:57 +0000700
John McCalla738c252011-03-09 04:27:21 +0000701 args.push_back(OMD->getSelfDecl());
702 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000703
Benjamin Kramerf9890422015-02-17 16:48:30 +0000704 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000705
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000706 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000707 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000708
Adrian Prantl42d71b92014-04-10 23:21:53 +0000709 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
710 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000711
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800712 if (OMD->isDirectMethod()) {
713 // This function is a direct call, it has to implement a nil check
714 // on entry.
715 //
716 // TODO: possibly have several entry points to elide the check
717 CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
718 }
719
John McCall31168b02011-06-15 23:02:42 +0000720 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000721 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000722 OMD->isInstanceMethod() &&
723 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000724 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000725 OMD->getSelector().getIdentifierInfoForSlot(0);
726 if (ident->isStr("dealloc"))
727 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
728 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000729}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000730
John McCall31168b02011-06-15 23:02:42 +0000731static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
732 LValue lvalue, QualType type);
733
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000734/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000735/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000736void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000737 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000738 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000739 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000740 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000741 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000742 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000743}
744
John McCallb923ece2011-09-12 23:06:44 +0000745/// emitStructGetterCall - Call the runtime function to load a property
746/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000747static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000748 bool isAtomic, bool hasStrong) {
749 ASTContext &Context = CGF.getContext();
750
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address src =
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800752 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
753 .getAddress(CGF);
John McCallb923ece2011-09-12 23:06:44 +0000754
Fangrui Song6907ce22018-07-30 19:24:48 +0000755 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000756 // sizeof (Type of Ivar), isAtomic, false);
757 CallArgList args;
758
John McCall7f416cc2015-09-08 08:05:57 +0000759 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
760 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000761
762 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000763 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000764
765 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
766 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
767 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
768 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
769
James Y Knight9871db02019-02-05 16:42:33 +0000770 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000771 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000772 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000773 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000774}
775
John McCallf4528ae2011-09-13 03:34:09 +0000776/// Determine whether the given architecture supports unaligned atomic
777/// accesses. They don't have to be fast, just faster than a function
778/// call and a mutex.
779static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000780 // FIXME: Allow unaligned atomic load/store on x86. (It is not
781 // currently supported by the backend.)
782 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000783}
784
785/// Return the maximum size that permits atomic accesses for the given
786/// architecture.
787static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
788 llvm::Triple::ArchType arch) {
789 // ARM has 8-byte atomic accesses, but it's not clear whether we
790 // want to rely on them here.
791
792 // In the default case, just assume that any size up to a pointer is
793 // fine given adequate alignment.
794 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
795}
796
797namespace {
798 class PropertyImplStrategy {
799 public:
800 enum StrategyKind {
801 /// The 'native' strategy is to use the architecture's provided
802 /// reads and writes.
803 Native,
804
805 /// Use objc_setProperty and objc_getProperty.
806 GetSetProperty,
807
808 /// Use objc_setProperty for the setter, but use expression
809 /// evaluation for the getter.
810 SetPropertyAndExpressionGet,
811
812 /// Use objc_copyStruct.
813 CopyStruct,
814
815 /// The 'expression' strategy is to emit normal assignment or
816 /// lvalue-to-rvalue expressions.
817 Expression
818 };
819
820 StrategyKind getKind() const { return StrategyKind(Kind); }
821
822 bool hasStrongMember() const { return HasStrong; }
823 bool isAtomic() const { return IsAtomic; }
824 bool isCopy() const { return IsCopy; }
825
826 CharUnits getIvarSize() const { return IvarSize; }
827 CharUnits getIvarAlignment() const { return IvarAlignment; }
828
829 PropertyImplStrategy(CodeGenModule &CGM,
830 const ObjCPropertyImplDecl *propImpl);
831
832 private:
833 unsigned Kind : 8;
834 unsigned IsAtomic : 1;
835 unsigned IsCopy : 1;
836 unsigned HasStrong : 1;
837
838 CharUnits IvarSize;
839 CharUnits IvarAlignment;
840 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000841}
John McCallf4528ae2011-09-13 03:34:09 +0000842
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000843/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000844PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
845 const ObjCPropertyImplDecl *propImpl) {
846 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000847 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000848
John McCall43192862011-09-13 18:31:23 +0000849 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
850 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000851 HasStrong = false; // doesn't matter here.
852
853 // Evaluate the ivar's size and alignment.
854 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
855 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000856 std::tie(IvarSize, IvarAlignment) =
857 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000858
859 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000860 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000861 if (IsCopy) {
862 Kind = GetSetProperty;
863 return;
864 }
865
John McCall43192862011-09-13 18:31:23 +0000866 // Handle retain.
867 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000868 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000870 // fallthrough
871
872 // In ARC, if the property is non-atomic, use expression emission,
873 // which translates to objc_storeStrong. This isn't required, but
874 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000875 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000876 // Using standard expression emission for the setter is only
877 // acceptable if the ivar is __strong, which won't be true if
878 // the property is annotated with __attribute__((NSObject)).
879 // TODO: falling all the way back to objc_setProperty here is
880 // just laziness, though; we could still use objc_storeStrong
881 // if we hacked it right.
882 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
883 Kind = Expression;
884 else
885 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000886 return;
887
888 // Otherwise, we need to at least use setProperty. However, if
889 // the property isn't atomic, we can use normal expression
890 // emission for the getter.
891 } else if (!IsAtomic) {
892 Kind = SetPropertyAndExpressionGet;
893 return;
894
895 // Otherwise, we have to use both setProperty and getProperty.
896 } else {
897 Kind = GetSetProperty;
898 return;
899 }
900 }
901
902 // If we're not atomic, just use expression accesses.
903 if (!IsAtomic) {
904 Kind = Expression;
905 return;
906 }
907
John McCall0e5c0862011-09-13 05:36:29 +0000908 // Properties on bitfield ivars need to be emitted using expression
909 // accesses even if they're nominally atomic.
910 if (ivar->isBitField()) {
911 Kind = Expression;
912 return;
913 }
914
John McCallf4528ae2011-09-13 03:34:09 +0000915 // GC-qualified or ARC-qualified ivars need to be emitted as
916 // expressions. This actually works out to being atomic anyway,
917 // except for ARC __strong, but that should trigger the above code.
918 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000919 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000920 CGM.getContext().getObjCGCAttrKind(ivarType))) {
921 Kind = Expression;
922 return;
923 }
924
925 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000926 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000927 if (const RecordType *recordType = ivarType->getAs<RecordType>())
928 HasStrong = recordType->getDecl()->hasObjectMember();
929
930 // We can never access structs with object members with a native
931 // access, because we need to use write barriers. This is what
932 // objc_copyStruct is for.
933 if (HasStrong) {
934 Kind = CopyStruct;
935 return;
936 }
937
938 // Otherwise, this is target-dependent and based on the size and
939 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000940
941 // If the size of the ivar is not a power of two, give up. We don't
942 // want to get into the business of doing compare-and-swaps.
943 if (!IvarSize.isPowerOfTwo()) {
944 Kind = CopyStruct;
945 return;
946 }
947
John McCallf4528ae2011-09-13 03:34:09 +0000948 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000949 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000950
951 // Most architectures require memory to fit within a single cache
952 // line, so the alignment has to be at least the size of the access.
953 // Otherwise we have to grab a lock.
954 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
955 Kind = CopyStruct;
956 return;
957 }
958
959 // If the ivar's size exceeds the architecture's maximum atomic
960 // access size, we have to use CopyStruct.
961 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
962 Kind = CopyStruct;
963 return;
964 }
965
966 // Otherwise, we can use native loads and stores.
967 Kind = Native;
968}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000969
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000970/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000971///
972/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000973/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000974void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
975 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000976 llvm::Constant *AtomicHelperFn =
977 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -0800978 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000979 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000980 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000981
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000982 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000983
Adrian Prantlce7d3592019-12-05 12:26:16 -0800984 FinishFunction(OMD->getEndLoc());
John McCallf4528ae2011-09-13 03:34:09 +0000985}
986
John McCallbdd81852011-09-13 06:00:03 +0000987static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
988 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000989 if (!getter) return true;
990
991 // Sema only makes only of these when the ivar has a C++ class type,
992 // so the form is pretty constrained.
993
John McCallbdd81852011-09-13 06:00:03 +0000994 // If the property has a reference type, we might just be binding a
995 // reference, in which case the result will be a gl-value. We should
996 // treat this as a non-trivial operation.
997 if (getter->isGLValue())
998 return false;
999
John McCallf4528ae2011-09-13 03:34:09 +00001000 // If we selected a trivial copy-constructor, we're okay.
1001 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1002 return (construct->getConstructor()->isTrivial());
1003
1004 // The constructor might require cleanups (in which case it's never
1005 // trivial).
1006 assert(isa<ExprWithCleanups>(getter));
1007 return false;
1008}
1009
Fangrui Song6907ce22018-07-30 19:24:48 +00001010/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001011/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +00001012static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001013 llvm::Value *returnAddr,
1014 ObjCIvarDecl *ivar,
1015 llvm::Constant *AtomicHelperFn) {
1016 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1017 // AtomicHelperFn);
1018 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001019
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001020 // The 1st argument is the return Slot.
1021 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001022
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001023 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001024 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001025 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1026 .getPointer(CGF);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001027 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1028 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001029
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001030 // Third argument is the helper function.
1031 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001032
James Y Knight9871db02019-02-05 16:42:33 +00001033 llvm::FunctionCallee copyCppAtomicObjectFn =
1034 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001035 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +00001036 CGF.EmitCall(
1037 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001038 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001039}
1040
John McCallf4528ae2011-09-13 03:34:09 +00001041void
1042CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001043 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001044 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001045 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +00001046 // If there's a non-trivial 'get' expression, we just have to emit that.
1047 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001048 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001049 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1050 propImpl->getGetterCXXConstructor(),
1051 /* NRVOCandidate=*/nullptr);
1052 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001053 }
1054 else {
1055 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001056 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001057 ivar, AtomicHelperFn);
1058 }
John McCallf4528ae2011-09-13 03:34:09 +00001059 return;
1060 }
1061
1062 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1063 QualType propType = prop->getType();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001064 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001065
Fangrui Song6907ce22018-07-30 19:24:48 +00001066 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001067
1068 // Pick an implementation strategy.
1069 PropertyImplStrategy strategy(CGM, propImpl);
1070 switch (strategy.getKind()) {
1071 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001072 // We don't need to do anything for a zero-size struct.
1073 if (strategy.getIvarSize().isZero())
1074 return;
1075
John McCallf4528ae2011-09-13 03:34:09 +00001076 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1077
1078 // Currently, all atomic accesses have to be through integer
1079 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001080 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1081 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001082 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1083
1084 // Perform an atomic load. This does not impose ordering constraints.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001085 Address ivarAddr = LV.getAddress(*this);
John McCallf4528ae2011-09-13 03:34:09 +00001086 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1087 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001088 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001089
1090 // Store that value into the return address. Doing this with a
1091 // bitcast is likely to produce some pretty ugly IR, but it's not
1092 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001093 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1094 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1095 llvm::Value *ivarVal = load;
1096 if (ivarSize > retTySize) {
1097 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1098 ivarVal = Builder.CreateTrunc(load, newTy);
1099 bitcastType = newTy->getPointerTo();
1100 }
1101 Builder.CreateStore(ivarVal,
1102 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001103
1104 // Make sure we don't do an autorelease.
1105 AutoreleaseResult = false;
1106 return;
1107 }
1108
1109 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001110 llvm::FunctionCallee getPropertyFn =
1111 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001112 if (!getPropertyFn) {
1113 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001114 return;
1115 }
John McCallb92ab1a2016-10-26 23:46:34 +00001116 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001117
1118 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1119 // FIXME: Can't this be simpler? This might even be worse than the
1120 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001121 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001122 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001123 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1124 llvm::Value *ivarOffset =
1125 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1126
1127 CallArgList args;
1128 args.add(RValue::get(self), getContext().getObjCIdType());
1129 args.add(RValue::get(cmd), getContext().getObjCSelType());
1130 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001131 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1132 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001133
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001134 // FIXME: We shouldn't need to get the function info here, the
1135 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001136 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001137 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1138 getContext().getObjCIdType(), args),
1139 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001140 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1141 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001142
Daniel Dunbara08dff12008-09-24 04:04:31 +00001143 // We need to fix the type here. Ivars with copy & retain are
1144 // always objects so we don't need to worry about complex or
1145 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001146 RV = RValue::get(Builder.CreateBitCast(
1147 RV.getScalarVal(),
1148 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001149
1150 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001151
1152 // objc_getProperty does an autorelease, so we should suppress ours.
1153 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001154
John McCallf4528ae2011-09-13 03:34:09 +00001155 return;
1156 }
1157
1158 case PropertyImplStrategy::CopyStruct:
1159 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1160 strategy.hasStrongMember());
1161 return;
1162
1163 case PropertyImplStrategy::Expression:
1164 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1165 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1166
1167 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001168 switch (getEvaluationKind(ivarType)) {
1169 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001170 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001171 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001172 /*init*/ true);
1173 return;
1174 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001175 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001176 // The return value slot is guaranteed to not be aliased, but
1177 // that's not necessarily the same as "on the stack", so
1178 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001179 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smith8cca3a52019-06-20 20:56:20 +00001180 /* Src= */ LV, ivarType, getOverlapForReturnValue());
Richard Smithe78fac52018-04-05 20:52:58 +00001181 return;
1182 }
John McCall47fb9502013-03-07 21:37:08 +00001183 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001184 llvm::Value *value;
1185 if (propType->isReferenceType()) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001186 value = LV.getAddress(*this).getPointer();
John McCall24fada12011-07-22 05:23:13 +00001187 } else {
1188 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1189 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001190 if (getLangOpts().ObjCAutoRefCount) {
1191 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1192 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001193 value = EmitARCLoadWeak(LV.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +00001194 }
John McCall24fada12011-07-22 05:23:13 +00001195
1196 // Otherwise we want to do a simple load, suppressing the
1197 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001198 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001199 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001200 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001201 }
John McCall31168b02011-06-15 23:02:42 +00001202
Alp Toker314cc812014-01-25 16:55:45 +00001203 value = Builder.CreateBitCast(
1204 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001205 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001206
John McCall24fada12011-07-22 05:23:13 +00001207 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001208 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001209 }
John McCall47fb9502013-03-07 21:37:08 +00001210 }
1211 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001212 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001213
John McCallf4528ae2011-09-13 03:34:09 +00001214 }
1215 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001216}
1217
John McCallb923ece2011-09-12 23:06:44 +00001218/// emitStructSetterCall - Call the runtime function to store the value
1219/// from the first formal parameter into the given ivar.
1220static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1221 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001222 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001223 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001224 CallArgList args;
1225
1226 // The first argument is the address of the ivar.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001227 llvm::Value *ivarAddr =
1228 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1229 .getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001230 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1231 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001232
1233 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001234 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001235 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1236 argVar->getType().getNonReferenceType(), VK_LValue,
1237 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001238 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001239 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1240 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001241
1242 // The third argument is the sizeof the type.
1243 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001244 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1245 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001246
John McCallb923ece2011-09-12 23:06:44 +00001247 // The fourth argument is the 'isAtomic' flag.
1248 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001249
John McCallb923ece2011-09-12 23:06:44 +00001250 // The fifth argument is the 'hasStrong' flag.
1251 // FIXME: should this really always be false?
1252 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1253
James Y Knight9871db02019-02-05 16:42:33 +00001254 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001255 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001256 CGF.EmitCall(
1257 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001258 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001259}
1260
Fangrui Song6907ce22018-07-30 19:24:48 +00001261/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1262/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001263/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001264static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001265 ObjCMethodDecl *OMD,
1266 ObjCIvarDecl *ivar,
1267 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001268 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001269 // AtomicHelperFn);
1270 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001271
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001272 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001273 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001274 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1275 .getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001276 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1277 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001278
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001279 // The second argument is the address of the parameter variable.
1280 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001281 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1282 argVar->getType().getNonReferenceType(), VK_LValue,
1283 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001284 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001285 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1286 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001287
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001288 // Third argument is the helper function.
1289 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001290
James Y Knight9871db02019-02-05 16:42:33 +00001291 llvm::FunctionCallee fn =
1292 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001293 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001294 CGF.EmitCall(
1295 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001296 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001297}
1298
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001299
John McCallf4528ae2011-09-13 03:34:09 +00001300static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1301 Expr *setter = PID->getSetterCXXAssignment();
1302 if (!setter) return true;
1303
1304 // Sema only makes only of these when the ivar has a C++ class type,
1305 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001306
1307 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001308 // This also implies that there's nothing non-trivial going on with
1309 // the arguments, because operator= can only be trivial if it's a
1310 // synthesized assignment operator and therefore both parameters are
1311 // references.
1312 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001313 if (const FunctionDecl *callee
1314 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1315 if (callee->isTrivial())
1316 return true;
1317 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001318 }
John McCall7f16c422011-09-10 09:17:20 +00001319
John McCallf4528ae2011-09-13 03:34:09 +00001320 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001321 return false;
1322}
1323
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001324static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001325 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001326 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001327 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001328}
1329
John McCall7f16c422011-09-10 09:17:20 +00001330void
1331CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001332 const ObjCPropertyImplDecl *propImpl,
1333 llvm::Constant *AtomicHelperFn) {
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001334 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001335 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001336
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001337 // Just use the setter expression if Sema gave us one and it's
1338 // non-trivial.
1339 if (!hasTrivialSetExpr(propImpl)) {
1340 if (!AtomicHelperFn)
1341 // If non-atomic, assignment is called directly.
1342 EmitStmt(propImpl->getSetterCXXAssignment());
1343 else
1344 // If atomic, assignment is called via a locking api.
1345 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1346 AtomicHelperFn);
1347 return;
1348 }
John McCall7f16c422011-09-10 09:17:20 +00001349
John McCallf4528ae2011-09-13 03:34:09 +00001350 PropertyImplStrategy strategy(CGM, propImpl);
1351 switch (strategy.getKind()) {
1352 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001353 // We don't need to do anything for a zero-size struct.
1354 if (strategy.getIvarSize().isZero())
1355 return;
1356
John McCall7f416cc2015-09-08 08:05:57 +00001357 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001358
John McCallf4528ae2011-09-13 03:34:09 +00001359 LValue ivarLValue =
1360 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001361 Address ivarAddr = ivarLValue.getAddress(*this);
John McCall7f16c422011-09-10 09:17:20 +00001362
John McCallf4528ae2011-09-13 03:34:09 +00001363 // Currently, all atomic accesses have to be through integer
1364 // types, so there's no point in trying to pick a prettier type.
1365 llvm::Type *bitcastType =
1366 llvm::Type::getIntNTy(getLLVMContext(),
1367 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001368
1369 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001370 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1371 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001372
1373 // This bitcast load is likely to cause some nasty IR.
1374 llvm::Value *load = Builder.CreateLoad(argAddr);
1375
1376 // Perform an atomic store. There are no memory ordering requirements.
1377 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001378 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001379 return;
1380 }
1381
1382 case PropertyImplStrategy::GetSetProperty:
1383 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001384
James Y Knight9871db02019-02-05 16:42:33 +00001385 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1386 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001387 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001388 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001389 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001390 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1391 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001392 if (!setOptimizedPropertyFn) {
1393 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1394 return;
1395 }
John McCall7f16c422011-09-10 09:17:20 +00001396 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001397 else {
1398 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1399 if (!setPropertyFn) {
1400 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1401 return;
1402 }
1403 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001404
John McCall7f16c422011-09-10 09:17:20 +00001405 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1406 // <is-atomic>, <is-copy>).
1407 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001408 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001409 llvm::Value *self =
1410 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1411 llvm::Value *ivarOffset =
1412 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001413 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1414 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1415 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001416
1417 CallArgList args;
1418 args.add(RValue::get(self), getContext().getObjCIdType());
1419 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001420 if (setOptimizedPropertyFn) {
1421 args.add(RValue::get(arg), getContext().getObjCIdType());
1422 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001423 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001424 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001425 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001426 } else {
1427 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1428 args.add(RValue::get(arg), getContext().getObjCIdType());
1429 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1430 getContext().BoolTy);
1431 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1432 getContext().BoolTy);
1433 // FIXME: We shouldn't need to get the function info here, the runtime
1434 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001435 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001436 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001437 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001438 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001439
John McCall7f16c422011-09-10 09:17:20 +00001440 return;
1441 }
1442
John McCallf4528ae2011-09-13 03:34:09 +00001443 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001444 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001445 return;
John McCallf4528ae2011-09-13 03:34:09 +00001446
1447 case PropertyImplStrategy::Expression:
1448 break;
John McCall7f16c422011-09-10 09:17:20 +00001449 }
1450
1451 // Otherwise, fake up some ASTs and emit a normal assignment.
1452 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001453 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001454 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001455 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1456 selfDecl->getType(), CK_LValueToRValue, &self,
1457 VK_RValue);
1458 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001459 SourceLocation(), SourceLocation(),
1460 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001461
1462 ParmVarDecl *argDecl = *setterMethod->param_begin();
1463 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001464 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1465 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001466 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1467 argType.getUnqualifiedType(), CK_LValueToRValue,
1468 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001469
John McCall7f16c422011-09-10 09:17:20 +00001470 // The property type can differ from the ivar type in some situations with
1471 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1472 // The following absurdity is just to ensure well-formed IR.
1473 CastKind argCK = CK_NoOp;
1474 if (ivarRef.getType()->isObjCObjectPointerType()) {
1475 if (argLoad.getType()->isObjCObjectPointerType())
1476 argCK = CK_BitCast;
1477 else if (argLoad.getType()->isBlockPointerType())
1478 argCK = CK_BlockPointerToObjCPointerCast;
1479 else
1480 argCK = CK_CPointerToObjCPointerCast;
1481 } else if (ivarRef.getType()->isBlockPointerType()) {
1482 if (argLoad.getType()->isBlockPointerType())
1483 argCK = CK_BitCast;
1484 else
1485 argCK = CK_AnyPointerToBlockPointerCast;
1486 } else if (ivarRef.getType()->isPointerType()) {
1487 argCK = CK_BitCast;
1488 }
1489 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1490 ivarRef.getType(), argCK, &argLoad,
1491 VK_RValue);
1492 Expr *finalArg = &argLoad;
1493 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1494 argLoad.getType()))
1495 finalArg = &argCast;
1496
1497
1498 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1499 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001500 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001501 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001502}
1503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001504/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001505///
1506/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001507/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001508void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1509 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001510 llvm::Constant *AtomicHelperFn =
1511 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -08001512 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001513 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001514 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001515
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001516 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001517
Adrian Prantlce7d3592019-12-05 12:26:16 -08001518 FinishFunction(OMD->getEndLoc());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001519}
1520
John McCall6a4fa522011-03-22 07:05:39 +00001521namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001522 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001523 private:
1524 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001525 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001526 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001527 bool useEHCleanupForArray;
1528 public:
1529 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1530 CodeGenFunction::Destroyer *destroyer,
1531 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001532 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001533 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001534
Craig Topper4f12f102014-03-12 06:41:41 +00001535 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001536 LValue lvalue
1537 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001538 CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001539 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001540 }
1541 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001542}
John McCall6a4fa522011-03-22 07:05:39 +00001543
John McCall4bd0fb12011-07-12 16:41:08 +00001544/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1545static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001546 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001547 QualType type) {
1548 llvm::Value *null = getNullForVariable(addr);
1549 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1550}
John McCall31168b02011-06-15 23:02:42 +00001551
John McCall6a4fa522011-03-22 07:05:39 +00001552static void emitCXXDestructMethod(CodeGenFunction &CGF,
1553 ObjCImplementationDecl *impl) {
1554 CodeGenFunction::RunCleanupsScope scope(CGF);
1555
1556 llvm::Value *self = CGF.LoadObjCSelf();
1557
Jordy Rosea91768e2011-07-22 02:08:32 +00001558 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1559 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001560 ivar; ivar = ivar->getNextIvar()) {
1561 QualType type = ivar->getType();
1562
John McCall6a4fa522011-03-22 07:05:39 +00001563 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001564 QualType::DestructionKind dtorKind = type.isDestructedType();
1565 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001566
Craig Topper8a13c412014-05-21 05:09:00 +00001567 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001568
John McCall4bd0fb12011-07-12 16:41:08 +00001569 // Use a call to objc_storeStrong to destroy strong ivars, for the
1570 // general benefit of the tools.
1571 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001572 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001573
John McCall4bd0fb12011-07-12 16:41:08 +00001574 // Otherwise use the default for the destruction kind.
1575 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001576 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001577 }
John McCall4bd0fb12011-07-12 16:41:08 +00001578
1579 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1580
1581 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1582 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001583 }
1584
1585 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1586}
1587
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001588void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1589 ObjCMethodDecl *MD,
1590 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001591 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001592 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001593
1594 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001595 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001596 // Suppress the final autorelease in ARC.
1597 AutoreleaseResult = false;
1598
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001599 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001600 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001601 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001602 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001603 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001604 EmitAggExpr(IvarInit->getInit(),
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001605 AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001606 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001607 AggValueSlot::IsNotAliased,
1608 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001609 }
1610 // constructor returns 'self'.
1611 CodeGenTypes &Types = CGM.getTypes();
1612 QualType IdTy(CGM.getContext().getObjCIdType());
1613 llvm::Value *SelfAsId =
1614 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1615 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001616
1617 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001618 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001619 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001620 }
1621 FinishFunction();
1622}
1623
Daniel Dunbara08dff12008-09-24 04:04:31 +00001624llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001625 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001626 DeclRefExpr DRE(getContext(), Self,
1627 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001628 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001629 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001630}
1631
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001632QualType CodeGenFunction::TypeOfSelfObject() {
1633 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1634 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001635 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1636 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001637 return PTy->getPointeeType();
1638}
1639
Chris Lattnerd4808922009-03-22 21:03:39 +00001640void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001641 llvm::FunctionCallee EnumerationMutationFnPtr =
1642 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001643 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001644 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1645 return;
1646 }
John McCallb92ab1a2016-10-26 23:46:34 +00001647 CGCallee EnumerationMutationFn =
1648 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001649
Devang Pateld2d66652011-01-19 01:36:36 +00001650 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001651 if (DI)
1652 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001653
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001654 RunCleanupsScope ForScope(*this);
1655
Kuba Mracek82c21752017-04-14 01:00:03 +00001656 // The local variable comes into scope immediately.
1657 AutoVarEmission variable = AutoVarEmission::invalid();
1658 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1659 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1660
John McCall1c926b72011-01-07 01:49:06 +00001661 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001662
Anders Carlsson75658592008-08-31 02:33:12 +00001663 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001664 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001665 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001666 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001667
Anders Carlsson75658592008-08-31 02:33:12 +00001668 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001669 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001670
John McCall1c926b72011-01-07 01:49:06 +00001671 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001672 IdentifierInfo *II[] = {
1673 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1674 &CGM.getContext().Idents.get("objects"),
1675 &CGM.getContext().Idents.get("count")
1676 };
1677 Selector FastEnumSel =
1678 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001679
1680 QualType ItemsTy =
1681 getContext().getConstantArrayType(getContext().getObjCIdType(),
Richard Smith772e2662019-10-04 01:25:59 +00001682 llvm::APInt(32, NumItems), nullptr,
Anders Carlsson75658592008-08-31 02:33:12 +00001683 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001684 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001685
John McCall53848232011-07-27 01:07:15 +00001686 // Emit the collection pointer. In ARC, we do a retain.
1687 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001688 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001689 Collection = EmitARCRetainScalarExpr(S.getCollection());
1690
1691 // Enter a cleanup to do the release.
1692 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1693 } else {
1694 Collection = EmitScalarExpr(S.getCollection());
1695 }
Mike Stump11289f42009-09-09 15:08:12 +00001696
John McCall91e82dd2011-08-05 00:14:38 +00001697 // The 'continue' label needs to appear within the cleanup for the
1698 // collection object.
1699 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1700
John McCall1c926b72011-01-07 01:49:06 +00001701 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001702 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001703
1704 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001705 Args.add(RValue::get(StatePtr.getPointer()),
1706 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001707
John McCall1c926b72011-01-07 01:49:06 +00001708 // The second argument is a temporary array with space for NumItems
1709 // pointers. We'll actually be loading elements from the array
1710 // pointer written into the control state; this buffer is so that
1711 // collections that *aren't* backed by arrays can still queue up
1712 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001713 Args.add(RValue::get(ItemsPtr.getPointer()),
1714 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001715
John McCall1c926b72011-01-07 01:49:06 +00001716 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001717 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1718 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1719 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001720
John McCall1c926b72011-01-07 01:49:06 +00001721 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001722 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001723 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1724 getContext().getNSUIntegerType(),
1725 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001726
John McCall1c926b72011-01-07 01:49:06 +00001727 // The initial number of objects that were returned in the buffer.
1728 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001729
John McCall1c926b72011-01-07 01:49:06 +00001730 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1731 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001732
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001733 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001734
John McCall1c926b72011-01-07 01:49:06 +00001735 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001736 // empty; skip all this. Set the branch weight assuming this has the same
1737 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001738 uint64_t EntryCount = getCurrentProfileCount();
1739 Builder.CreateCondBr(
1740 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1741 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001742 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001743
John McCall1c926b72011-01-07 01:49:06 +00001744 // Otherwise, initialize the loop.
1745 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001746
John McCall1c926b72011-01-07 01:49:06 +00001747 // Save the initial mutations value. This is the value at an
1748 // address that was written into the state object by
1749 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001750 Address StateMutationsPtrPtr =
1751 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001752 llvm::Value *StateMutationsPtr
1753 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001754
John McCall1c926b72011-01-07 01:49:06 +00001755 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001756 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1757 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001758
John McCall1c926b72011-01-07 01:49:06 +00001759 // Start looping. This is the point we return to whenever we have a
1760 // fresh, non-empty batch of objects.
1761 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1762 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001763
John McCall1c926b72011-01-07 01:49:06 +00001764 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001765 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001766 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001767
John McCall1c926b72011-01-07 01:49:06 +00001768 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001769 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001770 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001771
Justin Bogner66242d62015-04-23 23:06:47 +00001772 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001773
John McCall1c926b72011-01-07 01:49:06 +00001774 // Check whether the mutations value has changed from where it was
1775 // at start. StateMutationsPtr should actually be invariant between
1776 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001777 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001778 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001779 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1780 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001781
John McCall1c926b72011-01-07 01:49:06 +00001782 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001783 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001784
John McCall1c926b72011-01-07 01:49:06 +00001785 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1786 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001787
John McCall1c926b72011-01-07 01:49:06 +00001788 // If so, call the enumeration-mutation function.
1789 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001790 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001791 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001792 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001793 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001794 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001795 // FIXME: We shouldn't need to get the function info here, the runtime already
1796 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001797 EmitCall(
1798 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001799 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001800
John McCall1c926b72011-01-07 01:49:06 +00001801 // Otherwise, or if the mutation function returns, just continue.
1802 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001803
John McCall1c926b72011-01-07 01:49:06 +00001804 // Initialize the element variable.
1805 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001806 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001807 LValue elementLValue;
1808 QualType elementType;
1809 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001810 // Initialize the variable, in case it's a __block variable or something.
1811 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001812
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001813 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1814 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1815 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001816 elementLValue = EmitLValue(&tempDRE);
1817 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001818 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001819
1820 if (D->isARCPseudoStrong())
1821 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001822 } else {
1823 elementLValue = LValue(); // suppress warning
1824 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001825 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001826 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001827 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001828
1829 // Fetch the buffer out of the enumeration state.
1830 // TODO: this pointer should actually be invariant between
1831 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001832 Address StateItemsPtr =
1833 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001834 llvm::Value *EnumStateItems =
1835 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001836
John McCall1c926b72011-01-07 01:49:06 +00001837 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001838 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001839 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001840 llvm::Value *CurrentItem =
1841 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001842
John McCall1c926b72011-01-07 01:49:06 +00001843 // Cast that value to the right type.
1844 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1845 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001846
John McCall1c926b72011-01-07 01:49:06 +00001847 // Make sure we have an l-value. Yes, this gets evaluated every
1848 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001849 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001850 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001851 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001852 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001853 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1854 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001855 }
Mike Stump11289f42009-09-09 15:08:12 +00001856
John McCall9e2e22f2011-02-22 07:16:58 +00001857 // If we do have an element variable, this assignment is the end of
1858 // its initialization.
1859 if (elementIsVariable)
1860 EmitAutoVarCleanups(variable);
1861
John McCall1c926b72011-01-07 01:49:06 +00001862 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001863 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001864 {
1865 RunCleanupsScope Scope(*this);
1866 EmitStmt(S.getBody());
1867 }
Anders Carlsson75658592008-08-31 02:33:12 +00001868 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001869
John McCall1c926b72011-01-07 01:49:06 +00001870 // Destroy the element variable now.
1871 elementVariableScope.ForceCleanup();
1872
1873 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001874 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCall1c926b72011-01-07 01:49:06 +00001876 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001877
John McCall1c926b72011-01-07 01:49:06 +00001878 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001879 llvm::Value *indexPlusOne =
1880 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001881
John McCall1c926b72011-01-07 01:49:06 +00001882 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001883 // Set the branch weights based on the simplifying assumption that this is
1884 // like a while-loop, i.e., ignoring that the false branch fetches more
1885 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001886 Builder.CreateCondBr(
1887 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001888 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001889
1890 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1891 count->addIncoming(count, AfterBody.getBlock());
1892
1893 // Otherwise, we have to fetch more elements.
1894 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001895
1896 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001897 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1898 getContext().getNSUIntegerType(),
1899 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001900
John McCall1c926b72011-01-07 01:49:06 +00001901 // If we got a zero count, we're done.
1902 llvm::Value *refetchCount = CountRV.getScalarVal();
1903
1904 // (note that the message send might split FetchMoreBB)
1905 index->addIncoming(zero, Builder.GetInsertBlock());
1906 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1907
1908 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1909 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001910
Anders Carlsson75658592008-08-31 02:33:12 +00001911 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001912 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001913
John McCall9e2e22f2011-02-22 07:16:58 +00001914 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001915 // If the element was not a declaration, set it to be null.
1916
John McCall1c926b72011-01-07 01:49:06 +00001917 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1918 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001919 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001920 }
1921
Eric Christopher7cdf9482011-10-13 21:45:18 +00001922 if (DI)
1923 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001924
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001925 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001926 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001927}
1928
Mike Stump11289f42009-09-09 15:08:12 +00001929void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001930 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001931}
1932
Mike Stump11289f42009-09-09 15:08:12 +00001933void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001934 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1935}
1936
Chris Lattnere132e242008-11-15 21:26:17 +00001937void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001938 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001939 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001940}
1941
John McCall31168b02011-06-15 23:02:42 +00001942namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001943 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001944 CallObjCRelease(llvm::Value *object) : object(object) {}
1945 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001946
Craig Topper4f12f102014-03-12 06:41:41 +00001947 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001948 // Releases at the end of the full-expression are imprecise.
1949 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001950 }
1951 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001952}
John McCall31168b02011-06-15 23:02:42 +00001953
John McCall2d637d22011-09-10 06:18:15 +00001954/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001955/// release at the end of the full-expression.
1956llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1957 llvm::Value *object) {
1958 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001959 // conditional.
1960 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001961 return object;
1962}
1963
1964llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1965 llvm::Value *value) {
1966 return EmitARCRetainAutorelease(type, value);
1967}
1968
John McCalleff18842013-03-23 02:35:54 +00001969/// Given a number of pointers, inform the optimizer that they're
1970/// being intrinsically used up until this point in the program.
1971void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001972 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001973 if (!fn)
1974 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001975
1976 // This isn't really a "runtime" function, but as an intrinsic it
1977 // doesn't really matter as long as we align things up.
1978 EmitNounwindRuntimeCall(fn, values);
1979}
1980
James Y Knight9871db02019-02-05 16:42:33 +00001981static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001982 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001983 // If the target runtime doesn't naturally support ARC, emit weak
1984 // references to the runtime support library. We don't really
1985 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001986 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1987 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001988 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001989 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001990 }
John McCall31168b02011-06-15 23:02:42 +00001991}
1992
James Y Knight9871db02019-02-05 16:42:33 +00001993static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1994 llvm::FunctionCallee RTF) {
1995 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1996}
1997
John McCall31168b02011-06-15 23:02:42 +00001998/// Perform an operation having the signature
1999/// i8* (i8*)
2000/// where a null input causes a no-op and returns null.
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002001static llvm::Value *emitARCValueOperation(
2002 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2003 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2004 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002005 if (isa<llvm::ConstantPointerNull>(value))
2006 return value;
John McCall31168b02011-06-15 23:02:42 +00002007
2008 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002009 fn = CGF.CGM.getIntrinsic(IntID);
2010 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002011 }
2012
2013 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00002014 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00002015 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2016
2017 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00002018 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002019 call->setTailCallKind(tailKind);
John McCall31168b02011-06-15 23:02:42 +00002020
2021 // Cast the result back to the original type.
2022 return CGF.Builder.CreateBitCast(call, origType);
2023}
2024
2025/// Perform an operation having the following signature:
2026/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002027static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2028 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002029 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00002030 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002031 fn = CGF.CGM.getIntrinsic(IntID);
2032 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002033 }
2034
2035 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00002036 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00002037 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2038
2039 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002040 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002041
2042 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002043 if (origType != CGF.Int8PtrTy)
2044 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002045
2046 return result;
2047}
2048
2049/// Perform an operation having the following signature:
2050/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002051static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002052 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002053 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002054 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002055 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002056 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002057
2058 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002059 fn = CGF.CGM.getIntrinsic(IntID);
2060 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002061 }
2062
Chris Lattner2192fe52011-07-18 04:24:23 +00002063 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002064
John McCall882987f2013-02-28 19:01:20 +00002065 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002066 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002067 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2068 };
2069 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002070
Craig Topper8a13c412014-05-21 05:09:00 +00002071 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002072
2073 return CGF.Builder.CreateBitCast(result, origType);
2074}
2075
2076/// Perform an operation having the following signature:
2077/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002078static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2079 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002080 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002081 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002082
2083 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002084 fn = CGF.CGM.getIntrinsic(IntID);
2085 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002086 }
2087
John McCall882987f2013-02-28 19:01:20 +00002088 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002089 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2090 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002091 };
2092 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002093}
2094
Pete Cooper2cd35962018-12-18 20:33:00 +00002095/// Perform an operation having the signature
2096/// i8* (i8*)
2097/// where a null input causes a no-op and returns null.
2098static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2099 llvm::Value *value,
2100 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002101 llvm::FunctionCallee &fn,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002102 StringRef fnName) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002103 if (isa<llvm::ConstantPointerNull>(value))
2104 return value;
2105
2106 if (!fn) {
2107 llvm::FunctionType *fnType =
2108 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2109 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002110
2111 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002112 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002113 if (fnName == "objc_retain")
2114 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002115 }
2116
2117 // Cast the argument to 'id'.
2118 llvm::Type *origType = returnType ? returnType : value->getType();
2119 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2120
2121 // Call the function.
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002122 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002123
2124 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002125 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002126}
2127
John McCall31168b02011-06-15 23:02:42 +00002128/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002129/// call i8* \@objc_retain(i8* %value)
2130/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002131llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2132 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002133 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002134 else
2135 return EmitARCRetainNonBlock(value);
2136}
2137
2138/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002139/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002140llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002141 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002142 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002143 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002144}
2145
2146/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002147/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002148///
2149/// \param mandatory - If false, emit the call with metadata
2150/// indicating that it's okay for the optimizer to eliminate this call
2151/// if it can prove that the block never escapes except down the stack.
2152llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2153 bool mandatory) {
2154 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002155 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002156 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002157 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002158
2159 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2160 // tell the optimizer that it doesn't need to do this copy if the
2161 // block doesn't escape, where being passed as an argument doesn't
2162 // count as escaping.
2163 if (!mandatory && isa<llvm::Instruction>(result)) {
2164 llvm::CallInst *call
2165 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002166 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002167
John McCallff613032011-10-04 06:23:45 +00002168 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002169 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002170 }
2171
2172 return result;
John McCall31168b02011-06-15 23:02:42 +00002173}
2174
John McCalle399e5b2016-01-27 18:32:30 +00002175static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002176 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002177 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002178 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002179 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002180 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002181 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002182 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002183 .getARCRetainAutoreleasedReturnValueMarker();
2184
2185 // If we have an empty assembly string, there's nothing to do.
2186 if (assembly.empty()) {
2187
2188 // Otherwise, at -O0, build an inline asm that we're going to call
2189 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002190 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002191 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002192 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002193
John McCall31168b02011-06-15 23:02:42 +00002194 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2195
2196 // If we're at -O1 and above, we don't want to litter the code
2197 // with this marker yet, so leave a breadcrumb for the ARC
2198 // optimizer to pick up.
2199 } else {
Akira Hatanaka60c3a3b2019-04-10 06:20:23 +00002200 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2201 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2202 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2203 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
John McCall31168b02011-06-15 23:02:42 +00002204 }
2205 }
2206 }
2207
2208 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002209 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002210 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002211}
John McCall31168b02011-06-15 23:02:42 +00002212
John McCalle399e5b2016-01-27 18:32:30 +00002213/// Retain the given object which is the result of a function call.
2214/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2215///
2216/// Yes, this function name is one character away from a different
2217/// call with completely different semantics.
2218llvm::Value *
2219CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2220 emitAutoreleasedReturnValueMarker(*this);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002221 llvm::CallInst::TailCallKind tailKind =
2222 CGM.getTargetCodeGenInfo()
2223 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2224 ? llvm::CallInst::TCK_NoTail
2225 : llvm::CallInst::TCK_None;
2226 return emitARCValueOperation(
2227 *this, value, nullptr,
2228 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2229 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
John McCall31168b02011-06-15 23:02:42 +00002230}
2231
John McCalle399e5b2016-01-27 18:32:30 +00002232/// Claim a possibly-autoreleased return value at +0. This is only
2233/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002234/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002235/// the value is ignored, or when it is being assigned to an
2236/// __unsafe_unretained variable.
2237///
2238/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2239llvm::Value *
2240CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2241 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002242 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002243 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002244 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002245}
2246
John McCall31168b02011-06-15 23:02:42 +00002247/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002248/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002249void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2250 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002251 if (isa<llvm::ConstantPointerNull>(value)) return;
2252
James Y Knight9871db02019-02-05 16:42:33 +00002253 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002254 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002255 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2256 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002257 }
2258
2259 // Cast the argument to 'id'.
2260 value = Builder.CreateBitCast(value, Int8PtrTy);
2261
2262 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002263 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002264
John McCallcdda29c2013-03-13 03:10:54 +00002265 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002266 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002267 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002268 }
2269}
2270
John McCalle68b8f42012-10-17 02:28:37 +00002271/// Destroy a __strong variable.
2272///
2273/// At -O0, emit a call to store 'null' into the address;
2274/// instrumenting tools prefer this because the address is exposed,
2275/// but it's relatively cumbersome to optimize.
2276///
2277/// At -O1 and above, just load and call objc_release.
2278///
2279/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002280void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002281 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002282 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002283 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002284 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2285 return;
2286 }
2287
2288 llvm::Value *value = Builder.CreateLoad(addr);
2289 EmitARCRelease(value, precise);
2290}
2291
John McCall31168b02011-06-15 23:02:42 +00002292/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002293/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002294llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002295 llvm::Value *value,
2296 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002297 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002298
James Y Knight9871db02019-02-05 16:42:33 +00002299 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002300 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002301 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2302 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002303 }
2304
John McCall882987f2013-02-28 19:01:20 +00002305 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002306 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002307 Builder.CreateBitCast(value, Int8PtrTy)
2308 };
2309 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002310
Craig Topper8a13c412014-05-21 05:09:00 +00002311 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002312 return value;
2313}
2314
2315/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002316/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002317/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002318llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002319 llvm::Value *newValue,
2320 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002321 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002322 bool isBlock = type->isBlockPointerType();
2323
2324 // Use a store barrier at -O0 unless this is a block type or the
2325 // lvalue is inadequately aligned.
2326 if (shouldUseFusedARCCalls() &&
2327 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002328 (dst.getAlignment().isZero() ||
2329 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002330 return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
John McCall31168b02011-06-15 23:02:42 +00002331 }
2332
2333 // Otherwise, split it out.
2334
2335 // Retain the new value.
2336 newValue = EmitARCRetain(type, newValue);
2337
2338 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002339 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002340
2341 // Store. We do this before the release so that any deallocs won't
2342 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002343 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002344
2345 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002346 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002347
2348 return newValue;
2349}
2350
2351/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002352/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002353llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002354 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002355 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002356 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002357}
2358
2359/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002360/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002361llvm::Value *
2362CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002363 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002364 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002365 llvm::Intrinsic::objc_autoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002366 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002367}
2368
2369/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002370/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002371llvm::Value *
2372CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002373 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002374 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002375 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002376 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002377}
2378
2379/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002380/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002381/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002382/// %retain = call i8* \@objc_retainBlock(i8* %value)
2383/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002384llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2385 llvm::Value *value) {
2386 if (!type->isBlockPointerType())
2387 return EmitARCRetainAutoreleaseNonBlock(value);
2388
2389 if (isa<llvm::ConstantPointerNull>(value)) return value;
2390
Chris Lattner2192fe52011-07-18 04:24:23 +00002391 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002392 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002393 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002394 value = EmitARCAutorelease(value);
2395 return Builder.CreateBitCast(value, origType);
2396}
2397
2398/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002399/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002400llvm::Value *
2401CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002402 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002403 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002404 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002405}
2406
John McCallb04ecb72015-10-21 18:06:43 +00002407/// i8* \@objc_loadWeak(i8** %addr)
2408/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2409llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2410 return emitARCLoadOperation(*this, addr,
2411 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002412 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002413}
2414
James Dennett14c41ea2012-06-22 05:41:30 +00002415/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002416llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002417 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002418 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002419 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002420}
2421
James Dennett14c41ea2012-06-22 05:41:30 +00002422/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002423/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002424llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002425 llvm::Value *value,
2426 bool ignored) {
2427 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002428 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002429 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002430}
2431
James Dennett14c41ea2012-06-22 05:41:30 +00002432/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002433/// Returns %value. %addr is known to not have a current weak entry.
2434/// Essentially equivalent to:
2435/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002436void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002437 // If we're initializing to null, just write null to memory; no need
2438 // to get the runtime involved. But don't do this if optimization
2439 // is enabled, because accounting for this would make the optimizer
2440 // much more complicated.
2441 if (isa<llvm::ConstantPointerNull>(value) &&
2442 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2443 Builder.CreateStore(value, addr);
2444 return;
2445 }
2446
2447 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002448 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002449 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002450}
2451
James Dennett14c41ea2012-06-22 05:41:30 +00002452/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002453/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002454void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002455 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002456 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002457 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2458 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002459 }
2460
2461 // Cast the argument to 'id*'.
2462 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2463
John McCall7f416cc2015-09-08 08:05:57 +00002464 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002465}
2466
James Dennett14c41ea2012-06-22 05:41:30 +00002467/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002468/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2469/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002470void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002471 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002472 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002473 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002474}
2475
James Dennett14c41ea2012-06-22 05:41:30 +00002476/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002477/// Disregards the current value in %dest. Essentially
2478/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002479void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002480 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002481 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002482 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002483}
2484
Akira Hatanakad791e922018-03-19 17:38:40 +00002485void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2486 Address SrcAddr) {
2487 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2488 Object = EmitObjCConsumeObject(Ty, Object);
2489 EmitARCStoreWeak(DstAddr, Object, false);
2490}
2491
2492void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2493 Address SrcAddr) {
2494 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2495 Object = EmitObjCConsumeObject(Ty, Object);
2496 EmitARCStoreWeak(DstAddr, Object, false);
2497 EmitARCDestroyWeak(SrcAddr);
2498}
2499
John McCall31168b02011-06-15 23:02:42 +00002500/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002501/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002502llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002503 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002504 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002505 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2506 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002507 }
2508
John McCall882987f2013-02-28 19:01:20 +00002509 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002510}
2511
2512/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002513/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002514void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2515 assert(value->getType() == Int8PtrTy);
2516
Pete Cooper2cd35962018-12-18 20:33:00 +00002517 if (getInvokeDest()) {
2518 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002519 llvm::FunctionCallee &fn =
2520 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002521 if (!fn) {
2522 llvm::FunctionType *fnType =
2523 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2524 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2525 setARCRuntimeFunctionLinkage(CGM, fn);
2526 }
John McCall31168b02011-06-15 23:02:42 +00002527
Pete Cooper2cd35962018-12-18 20:33:00 +00002528 // objc_autoreleasePoolPop can throw.
2529 EmitRuntimeCallOrInvoke(fn, value);
2530 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002531 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002532 if (!fn) {
2533 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2534 setARCRuntimeFunctionLinkage(CGM, fn);
2535 }
2536
2537 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002538 }
John McCall31168b02011-06-15 23:02:42 +00002539}
2540
2541/// Produce the code to do an MRR version objc_autoreleasepool_push.
2542/// Which is: [[NSAutoreleasePool alloc] init];
2543/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2544/// init is declared as: - (id) init; in its NSObject super class.
2545///
2546llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2547 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002548 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002549 // [NSAutoreleasePool alloc]
2550 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2551 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2552 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002553 RValue AllocRV =
2554 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002555 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002556 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002557
2558 // [Receiver init]
2559 Receiver = AllocRV.getScalarVal();
2560 II = &CGM.getContext().Idents.get("init");
2561 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2562 RValue InitRV =
2563 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2564 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002565 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002566 return InitRV.getScalarVal();
2567}
2568
Pete Coopere3886802018-12-08 05:13:50 +00002569/// Allocate the given objc object.
2570/// call i8* \@objc_alloc(i8* %value)
2571llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2572 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002573 return emitObjCValueOperation(*this, value, resultType,
2574 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002575 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002576}
2577
2578/// Allocate the given objc object.
2579/// call i8* \@objc_allocWithZone(i8* %value)
2580llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2581 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002582 return emitObjCValueOperation(*this, value, resultType,
2583 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002584 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002585}
2586
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002587llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2588 llvm::Type *resultType) {
2589 return emitObjCValueOperation(*this, value, resultType,
2590 CGM.getObjCEntrypoints().objc_alloc_init,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002591 "objc_alloc_init");
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002592}
2593
John McCall31168b02011-06-15 23:02:42 +00002594/// Produce the code to do a primitive release.
2595/// [tmp drain];
2596void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2597 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2598 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2599 CallArgList Args;
2600 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002601 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002602}
2603
John McCall82fe67b2011-07-09 01:37:26 +00002604void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002605 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002606 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002607 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002608}
2609
2610void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002611 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002612 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002613 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002614}
2615
2616void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002617 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002618 QualType type) {
2619 CGF.EmitARCDestroyWeak(addr);
2620}
2621
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002622void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2623 QualType type) {
2624 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2625 CGF.EmitARCIntrinsicUse(value);
2626}
2627
Pete Coopere5b64ea2018-12-21 21:00:32 +00002628/// Autorelease the given object.
2629/// call i8* \@objc_autorelease(i8* %value)
2630llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2631 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002632 return emitObjCValueOperation(
2633 *this, value, returnType,
2634 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002635 "objc_autorelease");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002636}
2637
2638/// Retain the given object, with normal retain semantics.
2639/// call i8* \@objc_retain(i8* %value)
2640llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2641 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002642 return emitObjCValueOperation(
2643 *this, value, returnType,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002644 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002645}
2646
2647/// Release the given object.
2648/// call void \@objc_release(i8* %value)
2649void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2650 ARCPreciseLifetime_t precise) {
2651 if (isa<llvm::ConstantPointerNull>(value)) return;
2652
James Y Knight9871db02019-02-05 16:42:33 +00002653 llvm::FunctionCallee &fn =
2654 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002655 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002656 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002657 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002658 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2659 setARCRuntimeFunctionLinkage(CGM, fn);
2660 // We have Native ARC, so set nonlazybind attribute for performance
2661 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2662 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002663 }
2664
2665 // Cast the argument to 'id'.
2666 value = Builder.CreateBitCast(value, Int8PtrTy);
2667
2668 // Call objc_release.
Akira Hatanaka34d28cf2019-05-10 21:54:16 +00002669 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002670
2671 if (precise == ARCImpreciseLifetime) {
2672 call->setMetadata("clang.imprecise_release",
2673 llvm::MDNode::get(Builder.getContext(), None));
2674 }
2675}
2676
John McCall31168b02011-06-15 23:02:42 +00002677namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002678 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002679 llvm::Value *Token;
2680
2681 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2682
Craig Topper4f12f102014-03-12 06:41:41 +00002683 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002684 CGF.EmitObjCAutoreleasePoolPop(Token);
2685 }
2686 };
David Blaikie7e70d682015-08-18 22:40:54 +00002687 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002688 llvm::Value *Token;
2689
2690 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2691
Craig Topper4f12f102014-03-12 06:41:41 +00002692 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002693 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2694 }
2695 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002696}
John McCall31168b02011-06-15 23:02:42 +00002697
2698void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002699 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002700 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2701 else
2702 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2703}
2704
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002705static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2706 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002707 case Qualifiers::OCL_None:
2708 case Qualifiers::OCL_ExplicitNone:
2709 case Qualifiers::OCL_Strong:
2710 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002711 return true;
John McCall31168b02011-06-15 23:02:42 +00002712
2713 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002714 return false;
John McCall31168b02011-06-15 23:02:42 +00002715 }
2716
2717 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002718}
2719
2720static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002721 LValue lvalue,
2722 QualType type) {
2723 llvm::Value *result;
2724 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2725 if (shouldRetain) {
2726 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2727 } else {
2728 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002729 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002730 }
2731 return TryEmitResult(result, !shouldRetain);
2732}
2733
2734static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002735 const Expr *e) {
2736 e = e->IgnoreParens();
2737 QualType type = e->getType();
2738
Fangrui Song6907ce22018-07-30 19:24:48 +00002739 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002740 // an extra retain/release pair by zeroing out the source of this
2741 // "move" operation.
2742 if (e->isXValue() &&
2743 !type.isConstQualified() &&
2744 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2745 // Emit the lvalue.
2746 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002747
John McCall154a2fd2011-08-30 00:57:29 +00002748 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002749 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2750 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002751
John McCall154a2fd2011-08-30 00:57:29 +00002752 // Set the source pointer to NULL.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002753 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002754
John McCall154a2fd2011-08-30 00:57:29 +00002755 return TryEmitResult(result, true);
2756 }
2757
John McCall31168b02011-06-15 23:02:42 +00002758 // As a very special optimization, in ARC++, if the l-value is the
2759 // result of a non-volatile assignment, do a simple retain of the
2760 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002761 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002762 !type.isVolatileQualified() &&
2763 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2764 isa<BinaryOperator>(e) &&
2765 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2766 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2767
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002768 // Try to emit code for scalar constant instead of emitting LValue and
2769 // loading it because we are not guaranteed to have an l-value. One of such
2770 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2771 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2772 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2773 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2774 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2775 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2776 }
2777
John McCall31168b02011-06-15 23:02:42 +00002778 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2779}
2780
John McCalle399e5b2016-01-27 18:32:30 +00002781typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2782 llvm::Value *value)>
2783 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002784
John McCalle399e5b2016-01-27 18:32:30 +00002785/// Insert code immediately after a call.
2786static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2787 llvm::Value *value,
2788 ValueTransform doAfterCall,
2789 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002790 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2791 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2792
2793 // Place the retain immediately following the call.
2794 CGF.Builder.SetInsertPoint(call->getParent(),
2795 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002796 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002797
2798 CGF.Builder.restoreIP(ip);
2799 return value;
2800 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2801 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2802
2803 // Place the retain at the beginning of the normal destination block.
2804 llvm::BasicBlock *BB = invoke->getNormalDest();
2805 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002806 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002807
2808 CGF.Builder.restoreIP(ip);
2809 return value;
2810
2811 // Bitcasts can arise because of related-result returns. Rewrite
2812 // the operand.
2813 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2814 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002815 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002816 bitcast->setOperand(0, operand);
2817 return bitcast;
2818
2819 // Generic fall-back case.
2820 } else {
2821 // Retain using the non-block variant: we never need to do a copy
2822 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002823 return doFallback(CGF, value);
2824 }
2825}
2826
2827/// Given that the given expression is some sort of call (which does
2828/// not return retained), emit a retain following it.
2829static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2830 const Expr *e) {
2831 llvm::Value *value = CGF.EmitScalarExpr(e);
2832 return emitARCOperationAfterCall(CGF, value,
2833 [](CodeGenFunction &CGF, llvm::Value *value) {
2834 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2835 },
2836 [](CodeGenFunction &CGF, llvm::Value *value) {
2837 return CGF.EmitARCRetainNonBlock(value);
2838 });
2839}
2840
2841/// Given that the given expression is some sort of call (which does
2842/// not return retained), perform an unsafeClaim following it.
2843static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2844 const Expr *e) {
2845 llvm::Value *value = CGF.EmitScalarExpr(e);
2846 return emitARCOperationAfterCall(CGF, value,
2847 [](CodeGenFunction &CGF, llvm::Value *value) {
2848 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2849 },
2850 [](CodeGenFunction &CGF, llvm::Value *value) {
2851 return value;
2852 });
2853}
2854
2855llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2856 bool allowUnsafeClaim) {
2857 if (allowUnsafeClaim &&
2858 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2859 return emitARCUnsafeClaimCallResult(*this, E);
2860 } else {
2861 llvm::Value *value = emitARCRetainCallResult(*this, E);
2862 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002863 }
2864}
2865
John McCallcd78e802011-09-10 01:16:55 +00002866/// Determine whether it might be important to emit a separate
2867/// objc_retain_block on the result of the given expression, or
2868/// whether it's okay to just emit it in a +1 context.
2869static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2870 assert(e->getType()->isBlockPointerType());
2871 e = e->IgnoreParens();
2872
2873 // For future goodness, emit block expressions directly in +1
2874 // contexts if we can.
2875 if (isa<BlockExpr>(e))
2876 return false;
2877
2878 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2879 switch (cast->getCastKind()) {
2880 // Emitting these operations in +1 contexts is goodness.
2881 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002882 case CK_ARCReclaimReturnedObject:
2883 case CK_ARCConsumeObject:
2884 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002885 return false;
2886
2887 // These operations preserve a block type.
2888 case CK_NoOp:
2889 case CK_BitCast:
2890 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2891
2892 // These operations are known to be bad (or haven't been considered).
2893 case CK_AnyPointerToBlockPointerCast:
2894 default:
2895 return true;
2896 }
2897 }
2898
2899 return true;
2900}
2901
John McCalle399e5b2016-01-27 18:32:30 +00002902namespace {
2903/// A CRTP base class for emitting expressions of retainable object
2904/// pointer type in ARC.
2905template <typename Impl, typename Result> class ARCExprEmitter {
2906protected:
2907 CodeGenFunction &CGF;
2908 Impl &asImpl() { return *static_cast<Impl*>(this); }
2909
2910 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2911
2912public:
2913 Result visit(const Expr *e);
2914 Result visitCastExpr(const CastExpr *e);
2915 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002916 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002917 Result visitBinaryOperator(const BinaryOperator *e);
2918 Result visitBinAssign(const BinaryOperator *e);
2919 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2920 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2921 Result visitBinAssignWeak(const BinaryOperator *e);
2922 Result visitBinAssignStrong(const BinaryOperator *e);
2923
2924 // Minimal implementation:
2925 // Result visitLValueToRValue(const Expr *e)
2926 // Result visitConsumeObject(const Expr *e)
2927 // Result visitExtendBlockObject(const Expr *e)
2928 // Result visitReclaimReturnedObject(const Expr *e)
2929 // Result visitCall(const Expr *e)
2930 // Result visitExpr(const Expr *e)
2931 //
2932 // Result emitBitCast(Result result, llvm::Type *resultType)
2933 // llvm::Value *getValueOfResult(Result result)
2934};
2935}
2936
2937/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002938///
2939/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002940template <typename Impl, typename Result>
2941Result
2942ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002943 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002944
2945 // Find the result expression.
2946 const Expr *resultExpr = E->getResultExpr();
2947 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002948 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002949
2950 for (PseudoObjectExpr::const_semantics_iterator
2951 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2952 const Expr *semantic = *i;
2953
2954 // If this semantic expression is an opaque value, bind it
2955 // to the result of its source expression.
2956 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2957 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2958 OVMA opaqueData;
2959
2960 // If this semantic is the result of the pseudo-object
2961 // expression, try to evaluate the source as +1.
2962 if (ov == resultExpr) {
2963 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002964 result = asImpl().visit(ov->getSourceExpr());
2965 opaqueData = OVMA::bind(CGF, ov,
2966 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002967
2968 // Otherwise, just bind it.
2969 } else {
2970 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2971 }
2972 opaques.push_back(opaqueData);
2973
2974 // Otherwise, if the expression is the result, evaluate it
2975 // and remember the result.
2976 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002977 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002978
2979 // Otherwise, evaluate the expression in an ignored context.
2980 } else {
2981 CGF.EmitIgnoredExpr(semantic);
2982 }
2983 }
2984
2985 // Unbind all the opaques now.
2986 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2987 opaques[i].unbind(CGF);
2988
2989 return result;
2990}
2991
John McCalle399e5b2016-01-27 18:32:30 +00002992template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002993Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2994 // The default implementation just forwards the expression to visitExpr.
2995 return asImpl().visitExpr(e);
2996}
2997
2998template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00002999Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3000 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00003001
John McCalle399e5b2016-01-27 18:32:30 +00003002 // No-op casts don't change the type, so we just ignore them.
3003 case CK_NoOp:
3004 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00003005
John McCalle399e5b2016-01-27 18:32:30 +00003006 // These casts can change the type.
3007 case CK_CPointerToObjCPointerCast:
3008 case CK_BlockPointerToObjCPointerCast:
3009 case CK_AnyPointerToBlockPointerCast:
3010 case CK_BitCast: {
3011 llvm::Type *resultType = CGF.ConvertType(e->getType());
3012 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3013 Result result = asImpl().visit(e->getSubExpr());
3014 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00003015 }
3016
John McCalle399e5b2016-01-27 18:32:30 +00003017 // Handle some casts specially.
3018 case CK_LValueToRValue:
3019 return asImpl().visitLValueToRValue(e->getSubExpr());
3020 case CK_ARCConsumeObject:
3021 return asImpl().visitConsumeObject(e->getSubExpr());
3022 case CK_ARCExtendBlockObject:
3023 return asImpl().visitExtendBlockObject(e->getSubExpr());
3024 case CK_ARCReclaimReturnedObject:
3025 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3026
3027 // Otherwise, use the default logic.
3028 default:
3029 return asImpl().visitExpr(e);
3030 }
3031}
3032
3033template <typename Impl, typename Result>
3034Result
3035ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3036 switch (e->getOpcode()) {
3037 case BO_Comma:
3038 CGF.EmitIgnoredExpr(e->getLHS());
3039 CGF.EnsureInsertPoint();
3040 return asImpl().visit(e->getRHS());
3041
3042 case BO_Assign:
3043 return asImpl().visitBinAssign(e);
3044
3045 default:
3046 return asImpl().visitExpr(e);
3047 }
3048}
3049
3050template <typename Impl, typename Result>
3051Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3052 switch (e->getLHS()->getType().getObjCLifetime()) {
3053 case Qualifiers::OCL_ExplicitNone:
3054 return asImpl().visitBinAssignUnsafeUnretained(e);
3055
3056 case Qualifiers::OCL_Weak:
3057 return asImpl().visitBinAssignWeak(e);
3058
3059 case Qualifiers::OCL_Autoreleasing:
3060 return asImpl().visitBinAssignAutoreleasing(e);
3061
3062 case Qualifiers::OCL_Strong:
3063 return asImpl().visitBinAssignStrong(e);
3064
3065 case Qualifiers::OCL_None:
3066 return asImpl().visitExpr(e);
3067 }
3068 llvm_unreachable("bad ObjC ownership qualifier");
3069}
3070
3071/// The default rule for __unsafe_unretained emits the RHS recursively,
3072/// stores into the unsafe variable, and propagates the result outward.
3073template <typename Impl, typename Result>
3074Result ARCExprEmitter<Impl,Result>::
3075 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3076 // Recursively emit the RHS.
3077 // For __block safety, do this before emitting the LHS.
3078 Result result = asImpl().visit(e->getRHS());
3079
3080 // Perform the store.
3081 LValue lvalue =
3082 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3083 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3084 lvalue);
3085
3086 return result;
3087}
3088
3089template <typename Impl, typename Result>
3090Result
3091ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3092 return asImpl().visitExpr(e);
3093}
3094
3095template <typename Impl, typename Result>
3096Result
3097ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3098 return asImpl().visitExpr(e);
3099}
3100
3101template <typename Impl, typename Result>
3102Result
3103ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3104 return asImpl().visitExpr(e);
3105}
3106
3107/// The general expression-emission logic.
3108template <typename Impl, typename Result>
3109Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3110 // We should *never* see a nested full-expression here, because if
3111 // we fail to emit at +1, our caller must not retain after we close
3112 // out the full-expression. This isn't as important in the unsafe
3113 // emitter.
3114 assert(!isa<ExprWithCleanups>(e));
3115
3116 // Look through parens, __extension__, generic selection, etc.
3117 e = e->IgnoreParens();
3118
3119 // Handle certain kinds of casts.
3120 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3121 return asImpl().visitCastExpr(ce);
3122
3123 // Handle the comma operator.
3124 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3125 return asImpl().visitBinaryOperator(op);
3126
3127 // TODO: handle conditional operators here
3128
3129 // For calls and message sends, use the retained-call logic.
3130 // Delegate inits are a special case in that they're the only
3131 // returns-retained expression that *isn't* surrounded by
3132 // a consume.
3133 } else if (isa<CallExpr>(e) ||
3134 (isa<ObjCMessageExpr>(e) &&
3135 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3136 return asImpl().visitCall(e);
3137
3138 // Look through pseudo-object expressions.
3139 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3140 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003141 } else if (auto *be = dyn_cast<BlockExpr>(e))
3142 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003143
3144 return asImpl().visitExpr(e);
3145}
3146
3147namespace {
3148
3149/// An emitter for +1 results.
3150struct ARCRetainExprEmitter :
3151 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3152
3153 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3154
3155 llvm::Value *getValueOfResult(TryEmitResult result) {
3156 return result.getPointer();
3157 }
3158
3159 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3160 llvm::Value *value = result.getPointer();
3161 value = CGF.Builder.CreateBitCast(value, resultType);
3162 result.setPointer(value);
3163 return result;
3164 }
3165
3166 TryEmitResult visitLValueToRValue(const Expr *e) {
3167 return tryEmitARCRetainLoadOfScalar(CGF, e);
3168 }
3169
3170 /// For consumptions, just emit the subexpression and thus elide
3171 /// the retain/release pair.
3172 TryEmitResult visitConsumeObject(const Expr *e) {
3173 llvm::Value *result = CGF.EmitScalarExpr(e);
3174 return TryEmitResult(result, true);
3175 }
3176
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003177 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3178 TryEmitResult result = visitExpr(e);
3179 // Avoid the block-retain if this is a block literal that doesn't need to be
3180 // copied to the heap.
3181 if (e->getBlockDecl()->canAvoidCopyToHeap())
3182 result.setInt(true);
3183 return result;
3184 }
3185
John McCalle399e5b2016-01-27 18:32:30 +00003186 /// Block extends are net +0. Naively, we could just recurse on
3187 /// the subexpression, but actually we need to ensure that the
3188 /// value is copied as a block, so there's a little filter here.
3189 TryEmitResult visitExtendBlockObject(const Expr *e) {
3190 llvm::Value *result; // will be a +0 value
3191
3192 // If we can't safely assume the sub-expression will produce a
3193 // block-copied value, emit the sub-expression at +0.
3194 if (shouldEmitSeparateBlockRetain(e)) {
3195 result = CGF.EmitScalarExpr(e);
3196
3197 // Otherwise, try to emit the sub-expression at +1 recursively.
3198 } else {
3199 TryEmitResult subresult = asImpl().visit(e);
3200
3201 // If that produced a retained value, just use that.
3202 if (subresult.getInt()) {
3203 return subresult;
3204 }
3205
3206 // Otherwise it's +0.
3207 result = subresult.getPointer();
3208 }
3209
3210 // Retain the object as a block.
3211 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3212 return TryEmitResult(result, true);
3213 }
3214
3215 /// For reclaims, emit the subexpression as a retained call and
3216 /// skip the consumption.
3217 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3218 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3219 return TryEmitResult(result, true);
3220 }
3221
3222 /// When we have an undecorated call, retroactively do a claim.
3223 TryEmitResult visitCall(const Expr *e) {
3224 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3225 return TryEmitResult(result, true);
3226 }
3227
3228 // TODO: maybe special-case visitBinAssignWeak?
3229
3230 TryEmitResult visitExpr(const Expr *e) {
3231 // We didn't find an obvious production, so emit what we've got and
3232 // tell the caller that we didn't manage to retain.
3233 llvm::Value *result = CGF.EmitScalarExpr(e);
3234 return TryEmitResult(result, false);
3235 }
3236};
3237}
3238
3239static TryEmitResult
3240tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3241 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003242}
3243
3244static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3245 LValue lvalue,
3246 QualType type) {
3247 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3248 llvm::Value *value = result.getPointer();
3249 if (!result.getInt())
3250 value = CGF.EmitARCRetain(type, value);
3251 return value;
3252}
3253
3254/// EmitARCRetainScalarExpr - Semantically equivalent to
3255/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3256/// best-effort attempt to peephole expressions that naturally produce
3257/// retained objects.
3258llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003259 // The retain needs to happen within the full-expression.
3260 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3261 enterFullExpression(cleanups);
3262 RunCleanupsScope scope(*this);
3263 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3264 }
3265
John McCall31168b02011-06-15 23:02:42 +00003266 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3267 llvm::Value *value = result.getPointer();
3268 if (!result.getInt())
3269 value = EmitARCRetain(e->getType(), value);
3270 return value;
3271}
3272
3273llvm::Value *
3274CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003275 // The retain needs to happen within the full-expression.
3276 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3277 enterFullExpression(cleanups);
3278 RunCleanupsScope scope(*this);
3279 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3280 }
3281
John McCall31168b02011-06-15 23:02:42 +00003282 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3283 llvm::Value *value = result.getPointer();
3284 if (result.getInt())
3285 value = EmitARCAutorelease(value);
3286 else
3287 value = EmitARCRetainAutorelease(e->getType(), value);
3288 return value;
3289}
3290
John McCallff613032011-10-04 06:23:45 +00003291llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3292 llvm::Value *result;
3293 bool doRetain;
3294
3295 if (shouldEmitSeparateBlockRetain(e)) {
3296 result = EmitScalarExpr(e);
3297 doRetain = true;
3298 } else {
3299 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3300 result = subresult.getPointer();
3301 doRetain = !subresult.getInt();
3302 }
3303
3304 if (doRetain)
3305 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3306 return EmitObjCConsumeObject(e->getType(), result);
3307}
3308
John McCall248512a2011-10-01 10:32:24 +00003309llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3310 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003311 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003312 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003313 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003314 return EmitARCRetainAutoreleaseScalarExpr(expr);
3315 }
3316
3317 // Otherwise, use the normal scalar-expression emission. The
3318 // exception machinery doesn't do anything special with the
3319 // exception like retaining it, so there's no safety associated with
3320 // only running cleanups after the throw has started, and when it
3321 // matters it tends to be substantially inferior code.
3322 return EmitScalarExpr(expr);
3323}
3324
John McCalle399e5b2016-01-27 18:32:30 +00003325namespace {
3326
3327/// An emitter for assigning into an __unsafe_unretained context.
3328struct ARCUnsafeUnretainedExprEmitter :
3329 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3330
3331 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3332
3333 llvm::Value *getValueOfResult(llvm::Value *value) {
3334 return value;
3335 }
3336
3337 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3338 return CGF.Builder.CreateBitCast(value, resultType);
3339 }
3340
3341 llvm::Value *visitLValueToRValue(const Expr *e) {
3342 return CGF.EmitScalarExpr(e);
3343 }
3344
3345 /// For consumptions, just emit the subexpression and perform the
3346 /// consumption like normal.
3347 llvm::Value *visitConsumeObject(const Expr *e) {
3348 llvm::Value *value = CGF.EmitScalarExpr(e);
3349 return CGF.EmitObjCConsumeObject(e->getType(), value);
3350 }
3351
3352 /// No special logic for block extensions. (This probably can't
3353 /// actually happen in this emitter, though.)
3354 llvm::Value *visitExtendBlockObject(const Expr *e) {
3355 return CGF.EmitARCExtendBlockObject(e);
3356 }
3357
3358 /// For reclaims, perform an unsafeClaim if that's enabled.
3359 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3360 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3361 }
3362
3363 /// When we have an undecorated call, just emit it without adding
3364 /// the unsafeClaim.
3365 llvm::Value *visitCall(const Expr *e) {
3366 return CGF.EmitScalarExpr(e);
3367 }
3368
3369 /// Just do normal scalar emission in the default case.
3370 llvm::Value *visitExpr(const Expr *e) {
3371 return CGF.EmitScalarExpr(e);
3372 }
3373};
3374}
3375
3376static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3377 const Expr *e) {
3378 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3379}
3380
3381/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3382/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3383/// avoiding any spurious retains, including by performing reclaims
3384/// with objc_unsafeClaimAutoreleasedReturnValue.
3385llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3386 // Look through full-expressions.
3387 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3388 enterFullExpression(cleanups);
3389 RunCleanupsScope scope(*this);
3390 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3391 }
3392
3393 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3394}
3395
3396std::pair<LValue,llvm::Value*>
3397CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3398 bool ignored) {
3399 // Evaluate the RHS first. If we're ignoring the result, assume
3400 // that we can emit at an unsafe +0.
3401 llvm::Value *value;
3402 if (ignored) {
3403 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3404 } else {
3405 value = EmitScalarExpr(e->getRHS());
3406 }
3407
3408 // Emit the LHS and perform the store.
3409 LValue lvalue = EmitLValue(e->getLHS());
3410 EmitStoreOfScalar(value, lvalue);
3411
3412 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3413}
3414
John McCall31168b02011-06-15 23:02:42 +00003415std::pair<LValue,llvm::Value*>
3416CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3417 bool ignored) {
3418 // Evaluate the RHS first.
3419 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3420 llvm::Value *value = result.getPointer();
3421
John McCallb726a552011-07-28 07:23:35 +00003422 bool hasImmediateRetain = result.getInt();
3423
3424 // If we didn't emit a retained object, and the l-value is of block
3425 // type, then we need to emit the block-retain immediately in case
3426 // it invalidates the l-value.
3427 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003428 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003429 hasImmediateRetain = true;
3430 }
3431
John McCall31168b02011-06-15 23:02:42 +00003432 LValue lvalue = EmitLValue(e->getLHS());
3433
3434 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003435 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003436 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003437 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003438 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003439 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003440 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003441 }
3442
3443 return std::pair<LValue,llvm::Value*>(lvalue, value);
3444}
3445
3446std::pair<LValue,llvm::Value*>
3447CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3448 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3449 LValue lvalue = EmitLValue(e->getLHS());
3450
Eli Friedmana0544d62011-12-03 04:14:32 +00003451 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003452
3453 return std::pair<LValue,llvm::Value*>(lvalue, value);
3454}
3455
3456void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003457 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003458 const Stmt *subStmt = ARPS.getSubStmt();
3459 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3460
3461 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003462 if (DI)
3463 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003464
3465 // Keep track of the current cleanup stack depth.
3466 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003467 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003468 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3469 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3470 } else {
3471 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3472 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3473 }
3474
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003475 for (const auto *I : S.body())
3476 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003477
Eric Christopher7cdf9482011-10-13 21:45:18 +00003478 if (DI)
3479 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003480}
John McCall1bd25562011-06-24 23:21:27 +00003481
3482/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3483/// make sure it survives garbage collection until this point.
3484void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3485 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003486 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003487 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003488 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3489 /* assembly */ "",
3490 /* constraints */ "r",
3491 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003492
3493 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003494 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003495}
3496
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003497/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003498/// non-trivial copy assignment function, produce following helper function.
3499/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3500///
3501llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003502CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3503 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003504 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003505 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003506 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003507 QualType Ty = PID->getPropertyIvarDecl()->getType();
3508 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003509 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003510 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003511 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003512 return nullptr;
3513 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003514 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003515 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003516 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3517 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3518 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003519
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003520 ASTContext &C = getContext();
3521 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003522 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003523
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003524 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003525 QualType DestTy = C.getPointerType(Ty);
3526 QualType SrcTy = Ty;
3527 SrcTy.addConst();
3528 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003529
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003530 SmallVector<QualType, 2> ArgTys;
3531 ArgTys.push_back(DestTy);
3532 ArgTys.push_back(SrcTy);
3533 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3534
3535 FunctionDecl *FD = FunctionDecl::Create(
3536 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3537 FunctionTy, nullptr, SC_Static, false, false);
3538
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003539 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003540 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3541 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003542 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003543 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3544 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003545 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003546
John McCallc56a8b32016-03-11 04:30:31 +00003547 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003548 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003549
John McCalla729c622012-02-17 03:33:10 +00003550 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003551
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003552 llvm::Function *Fn =
3553 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003554 "__assign_helper_atomic_property_",
3555 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003556
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003557 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003558
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003559 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003560
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003561 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3562 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003563 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003564 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003565
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003566 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3567 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003568 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003569 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003570
John McCall113bee02012-03-10 09:33:50 +00003571 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003572 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003573 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3574 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3575 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003576
Bruno Riccic5885cf2018-12-21 15:20:32 +00003577 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003578
3579 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003580 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003581 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003582 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003583}
3584
3585llvm::Constant *
3586CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3587 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003588 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003589 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003590 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003591 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3592 QualType Ty = PD->getType();
3593 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003594 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003595 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003596 return nullptr;
3597 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003598 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003599 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003600 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3601 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3602 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003603
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003604 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003605 IdentifierInfo *II =
3606 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003607
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003608 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003609 QualType DestTy = C.getPointerType(Ty);
3610 QualType SrcTy = Ty;
3611 SrcTy.addConst();
3612 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003613
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003614 SmallVector<QualType, 2> ArgTys;
3615 ArgTys.push_back(DestTy);
3616 ArgTys.push_back(SrcTy);
3617 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3618
3619 FunctionDecl *FD = FunctionDecl::Create(
3620 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3621 FunctionTy, nullptr, SC_Static, false, false);
3622
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003623 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003624 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3625 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003626 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003627 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3628 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003629 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003630
John McCallc56a8b32016-03-11 04:30:31 +00003631 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003632 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003633
John McCalla729c622012-02-17 03:33:10 +00003634 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003635
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003636 llvm::Function *Fn = llvm::Function::Create(
3637 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3638 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003639
3640 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003641
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003642 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003643
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003644 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3645 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003646
John McCall113bee02012-03-10 09:33:50 +00003647 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003648 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003649
3650 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003651 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003652
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003653 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003654 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003655 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3656 CXXConstExpr->arg_end());
3657
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003658 CXXConstructExpr *TheCXXConstructExpr =
3659 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3660 CXXConstExpr->getConstructor(),
3661 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003662 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003663 CXXConstExpr->hadMultipleCandidates(),
3664 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003665 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003666 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003667 CXXConstExpr->getConstructionKind(),
3668 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003669
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003670 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3671 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003672
John McCall113bee02012-03-10 09:33:50 +00003673 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003674 CharUnits Alignment
3675 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003676 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003677 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3678 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003679 AggValueSlot::IsDestructed,
3680 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003681 AggValueSlot::IsNotAliased,
3682 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003683
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003684 FinishFunction();
3685 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3686 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3687 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003688}
3689
Eli Friedmanec75fec2012-02-28 01:08:45 +00003690llvm::Value *
3691CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3692 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003693 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3694 Selector CopySelector =
3695 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003696 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3697 Selector AutoreleaseSelector =
3698 getContext().Selectors.getNullarySelector(AutoreleaseID);
3699
3700 // Emit calls to retain/autorelease.
3701 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3702 llvm::Value *Val = Block;
3703 RValue Result;
3704 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003705 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003706 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003707 Val = Result.getScalarVal();
3708 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3709 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003710 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003711 Val = Result.getScalarVal();
3712 return Val;
3713}
3714
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003715llvm::Value *
3716CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3717 assert(Args.size() == 3 && "Expected 3 argument here!");
3718
3719 if (!CGM.IsOSVersionAtLeastFn) {
3720 llvm::FunctionType *FTy =
3721 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3722 CGM.IsOSVersionAtLeastFn =
3723 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3724 }
3725
3726 llvm::Value *CallRes =
3727 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3728
3729 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3730}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003731
Alex Lorenza8fbef42017-03-23 11:14:27 +00003732void CodeGenModule::emitAtAvailableLinkGuard() {
3733 if (!IsOSVersionAtLeastFn)
3734 return;
3735 // @available requires CoreFoundation only on Darwin.
3736 if (!Target.getTriple().isOSDarwin())
3737 return;
3738 // Add -framework CoreFoundation to the linker commands. We still want to
3739 // emit the core foundation reference down below because otherwise if
3740 // CoreFoundation is not used in the code, the linker won't link the
3741 // framework.
3742 auto &Context = getLLVMContext();
3743 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3744 llvm::MDString::get(Context, "CoreFoundation")};
3745 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3746 // Emit a reference to a symbol from CoreFoundation to ensure that
3747 // CoreFoundation is linked into the final binary.
3748 llvm::FunctionType *FTy =
3749 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003750 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003751 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3752
3753 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003754 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3755 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003756 llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00003757 llvm::Function *CFLinkCheckFunc =
3758 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3759 if (CFLinkCheckFunc->empty()) {
3760 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3761 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3762 CodeGenFunction CGF(*this);
3763 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3764 CGF.EmitNounwindRuntimeCall(CFFunc,
3765 llvm::Constant::getNullValue(VoidPtrTy));
3766 CGF.Builder.CreateUnreachable();
3767 addCompilerUsedGlobal(CFLinkCheckFunc);
3768 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003769}
3770
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003771CGObjCRuntime::~CGObjCRuntime() {}