blob: 4c5311cf001ddede60a8b21fe7f15dc2fa9616c7 [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"
Reid Kleckner98031782019-12-09 16:11:56 -080020#include "clang/AST/Attr.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000022#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000023#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000024#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000025#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
Fangrui Song6907ce22018-07-30 19:24:48 +000048 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000049 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Patrick Beard0caa3942012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000056/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000058///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000059llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000064 const Expr *SubExpr = E->getSubExpr();
Akira Hatanaka1488ee42019-03-08 04:45:37 +000065
66 if (E->isExpressibleAsConstantInitializer()) {
67 ConstantEmitter ConstEmitter(CGM);
68 return ConstEmitter.tryEmitAbstract(E, E->getType());
69 }
70
Patrick Beard0caa3942012-04-19 00:25:12 +000071 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
72 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000073
Ted Kremeneke65b0862012-03-06 20:05:56 +000074 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000075 // Assumes that the method was introduced in the class that should be
76 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000077 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000078 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000079 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000080
Ted Kremeneke65b0862012-03-06 20:05:56 +000081 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000082 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
83 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000084
85 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000086 // via [NSValue valueWithBytes:objCType:]
87 const QualType ValueType(SubExpr->getType().getCanonicalType());
88 if (ValueType->isObjCBoxableRecordType()) {
89 // Emit CodeGen for first parameter
90 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000091 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000092 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000093 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
94 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000095
96 // Create char array to store type encoding
97 std::string Str;
98 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000099 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +0000100
Alex Denisovfde64952015-06-26 05:28:36 +0000101 // Cast type encoding to correct type
102 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
103 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
104 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
105
106 Args.add(RValue::get(Cast), EncodingQT);
107 } else {
108 Args.add(EmitAnyExpr(SubExpr), ArgQT);
109 }
Alp Toker314cc812014-01-25 16:55:45 +0000110
111 RValue result = Runtime.GenerateMessageSend(
112 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
113 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000114 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 ConvertType(E->getType()));
116}
117
118llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000119 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000120 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000121 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000122 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
123 if (!ALE)
124 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000125
126 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000127 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000128 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000129 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
130 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
131 QualType IdTy(CGM.getContext().getObjCIdType());
132 llvm::Constant *Constant =
133 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000134 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000135 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000136 cast<llvm::LoadInst>(Ptr)->setMetadata(
137 CGM.getModule().getMDKindID("invariant.load"),
138 llvm::MDNode::get(getLLVMContext(), None));
139 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000140 }
141
142 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000143 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
144 NumElements);
145 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000146 QualType ElementArrayType
Richard Smith772e2662019-10-04 01:25:59 +0000147 = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 ArrayType::Normal, /*IndexTypeQuals=*/0);
149
150 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000151 Address Objects = CreateMemTemp(ElementArrayType, "objects");
152 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000153 if (DLE)
154 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000155
John McCall770a4c12013-04-04 00:20:38 +0000156 // In ARC, we may need to do extra work to keep all the keys and
157 // values alive until after the call.
158 SmallVector<llvm::Value *, 16> NeededObjects;
159 bool TrackNeededObjects =
160 (getLangOpts().ObjCAutoRefCount &&
161 CGM.getCodeGenOpts().OptimizationLevel != 0);
162
Ted Kremeneke65b0862012-03-06 20:05:56 +0000163 // Perform the actual initialialization of the array(s).
164 for (uint64_t i = 0; i < NumElements; i++) {
165 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000166 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000167 const Expr *Rhs = ALE->getElement(i);
James Y Knight751fe282019-02-09 22:22:28 +0000168 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
169 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000170
171 llvm::Value *value = EmitScalarExpr(Rhs);
172 EmitStoreThroughLValue(RValue::get(value), LV, true);
173 if (TrackNeededObjects) {
174 NeededObjects.push_back(value);
175 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000176 } else {
John McCall770a4c12013-04-04 00:20:38 +0000177 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000178 const Expr *Key = DLE->getKeyValueElement(i).Key;
James Y Knight751fe282019-02-09 22:22:28 +0000179 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
180 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000181 llvm::Value *keyValue = EmitScalarExpr(Key);
182 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000183
John McCall770a4c12013-04-04 00:20:38 +0000184 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000185 const Expr *Value = DLE->getKeyValueElement(i).Value;
James Y Knight751fe282019-02-09 22:22:28 +0000186 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
187 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000188 llvm::Value *valueValue = EmitScalarExpr(Value);
189 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
190 if (TrackNeededObjects) {
191 NeededObjects.push_back(keyValue);
192 NeededObjects.push_back(valueValue);
193 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000194 }
195 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000196
Ted Kremeneke65b0862012-03-06 20:05:56 +0000197 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000198 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000199 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
200 const ParmVarDecl *argDecl = *PI++;
201 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000202 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000203 if (DLE) {
204 argDecl = *PI++;
205 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000206 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000207 }
208 argDecl = *PI;
209 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000210 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000211 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
212 Args.add(RValue::get(Count), ArgQT);
213
214 // Generate a reference to the class pointer, which will be the receiver.
215 Selector Sel = MethodWithObjects->getSelector();
216 QualType ResultType = E->getType();
217 const ObjCObjectPointerType *InterfacePointerType
218 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000219 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000220 = InterfacePointerType->getObjectType()->getInterface();
221 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000222 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000223
224 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000225 RValue result = Runtime.GenerateMessageSend(
226 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
227 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000228
229 // The above message send needs these objects, but in ARC they are
230 // passed in a buffer that is essentially __unsafe_unretained.
231 // Therefore we must prevent the optimizer from releasing them until
232 // after the call.
233 if (TrackNeededObjects) {
234 EmitARCIntrinsicUse(NeededObjects);
235 }
236
Fangrui Song6907ce22018-07-30 19:24:48 +0000237 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000238 ConvertType(E->getType()));
239}
240
241llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000242 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000243}
244
245llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
246 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000247 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248}
249
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000250/// Emit a selector.
251llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
252 // Untyped selector.
253 // Note that this implementation allows for non-constant strings to be passed
254 // as arguments to @selector(). Currently, the only thing preventing this
255 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000256 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000257}
258
Daniel Dunbar66912a12008-08-20 00:28:19 +0000259llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
260 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000261 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000262}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000264/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000265/// to type erasure at various points, e.g., related result types or the use
266/// of parameterized classes.
267static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
268 RValue Result) {
269 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000270 return Result;
John McCall31168b02011-06-15 23:02:42 +0000271
Douglas Gregore83b9562015-07-07 03:57:53 +0000272 // If the converted types are the same, we're done.
273 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
274 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000275 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000276
277 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000278 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000279 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000280}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000281
John McCallcf166702011-07-22 08:53:00 +0000282/// Decide whether to extend the lifetime of the receiver of a
283/// returns-inner-pointer message.
284static bool
285shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
286 switch (message->getReceiverKind()) {
287
288 // For a normal instance message, we should extend unless the
289 // receiver is loaded from a variable with precise lifetime.
290 case ObjCMessageExpr::Instance: {
291 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000292
293 // Look through OVEs.
294 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
295 if (opaque->getSourceExpr())
296 receiver = opaque->getSourceExpr()->IgnoreParens();
297 }
298
John McCallcf166702011-07-22 08:53:00 +0000299 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
300 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
301 receiver = ice->getSubExpr()->IgnoreParens();
302
John McCall6380a282015-09-09 23:37:17 +0000303 // Look through OVEs.
304 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
305 if (opaque->getSourceExpr())
306 receiver = opaque->getSourceExpr()->IgnoreParens();
307 }
308
John McCallcf166702011-07-22 08:53:00 +0000309 // Only __strong variables.
310 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
311 return true;
312
313 // All ivars and fields have precise lifetime.
314 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
315 return false;
316
317 // Otherwise, check for variables.
318 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
319 if (!declRef) return true;
320 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
321 if (!var) return true;
322
323 // All variables have precise lifetime except local variables with
324 // automatic storage duration that aren't specially marked.
325 return (var->hasLocalStorage() &&
326 !var->hasAttr<ObjCPreciseLifetimeAttr>());
327 }
328
329 case ObjCMessageExpr::Class:
330 case ObjCMessageExpr::SuperClass:
331 // It's never necessary for class objects.
332 return false;
333
334 case ObjCMessageExpr::SuperInstance:
335 // We generally assume that 'self' lives throughout a method call.
336 return false;
337 }
338
339 llvm_unreachable("invalid receiver kind");
340}
341
John McCall460ce582015-10-22 18:38:17 +0000342/// Given an expression of ObjC pointer type, check whether it was
343/// immediately loaded from an ARC __weak l-value.
344static const Expr *findWeakLValue(const Expr *E) {
345 assert(E->getType()->isObjCRetainableType());
346 E = E->IgnoreParens();
347 if (auto CE = dyn_cast<CastExpr>(E)) {
348 if (CE->getCastKind() == CK_LValueToRValue) {
349 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
350 return CE->getSubExpr();
351 }
352 }
353
354 return nullptr;
355}
356
Pete Coopere3886802018-12-08 05:13:50 +0000357/// The ObjC runtime may provide entrypoints that are likely to be faster
358/// than an ordinary message send of the appropriate selector.
359///
360/// The entrypoints are guaranteed to be equivalent to just sending the
361/// corresponding message. If the entrypoint is implemented naively as just a
362/// message send, using it is a trade-off: it sacrifices a few cycles of
363/// overhead to save a small amount of code. However, it's possible for
364/// runtimes to detect and special-case classes that use "standard"
365/// behavior; if that's dynamically a large proportion of all objects, using
366/// the entrypoint will also be faster than using a message send.
367///
368/// If the runtime does support a required entrypoint, then this method will
369/// generate a call and return the resulting value. Otherwise it will return
370/// None and the caller can generate a msgSend instead.
371static Optional<llvm::Value *>
372tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
373 llvm::Value *Receiver,
374 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000375 const ObjCMethodDecl *method,
376 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000377 auto &CGM = CGF.CGM;
378 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
379 return None;
380
381 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
382 switch (Sel.getMethodFamily()) {
383 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000384 if (isClassMessage &&
385 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000386 ResultType->isObjCObjectPointerType()) {
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000387 // [Foo alloc] -> objc_alloc(Foo) or
388 // [self alloc] -> objc_alloc(self)
Pete Coopere3886802018-12-08 05:13:50 +0000389 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
390 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000391 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
392 // [self allocWithZone:nil] -> objc_allocWithZone(self)
Pete Coopere3886802018-12-08 05:13:50 +0000393 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
394 Args.size() == 1 && Args.front().getType()->isPointerType() &&
395 Sel.getNameForSlot(0) == "allocWithZone") {
396 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
397 if (isa<llvm::ConstantPointerNull>(arg))
398 return CGF.EmitObjCAllocWithZone(Receiver,
399 CGF.ConvertType(ResultType));
400 return None;
401 }
402 }
403 break;
404
Pete Coopere5b64ea2018-12-21 21:00:32 +0000405 case OMF_autorelease:
406 if (ResultType->isObjCObjectPointerType() &&
407 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
408 Runtime.shouldUseARCFunctionsForRetainRelease())
409 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
410 break;
411
412 case OMF_retain:
413 if (ResultType->isObjCObjectPointerType() &&
414 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
415 Runtime.shouldUseARCFunctionsForRetainRelease())
416 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
417 break;
418
419 case OMF_release:
420 if (ResultType->isVoidType() &&
421 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
422 Runtime.shouldUseARCFunctionsForRetainRelease()) {
423 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
424 return nullptr;
425 }
426 break;
427
Pete Coopere3886802018-12-08 05:13:50 +0000428 default:
429 break;
430 }
431 return None;
432}
433
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800434CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
435 CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
436 Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
437 const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
438 bool isClassMessage) {
439 if (Optional<llvm::Value *> SpecializedResult =
440 tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
441 Sel, Method, isClassMessage)) {
442 return RValue::get(SpecializedResult.getValue());
443 }
444 return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
445 Method);
446}
447
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000448/// Instead of '[[MyClass alloc] init]', try to generate
449/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
450/// caller side, as well as the optimized objc_alloc.
451static Optional<llvm::Value *>
452tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
453 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
454 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
455 return None;
456
457 // Match the exact pattern '[[MyClass alloc] init]'.
458 Selector Sel = OME->getSelector();
Erik Pilkington55e703a2019-02-25 21:35:14 +0000459 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
460 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
461 Sel.getNameForSlot(0) != "init")
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000462 return None;
463
Pierre Habouzitd18fbfc2020-01-14 18:56:26 -0800464 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
465 // with 'cls' a Class.
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000466 auto *SubOME =
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000467 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000468 if (!SubOME)
469 return None;
470 Selector SubSel = SubOME->getSelector();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000471
Pierre Habouzitd18fbfc2020-01-14 18:56:26 -0800472 if (!SubOME->getType()->isObjCObjectPointerType() ||
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000473 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
474 return None;
475
Pierre Habouzitd18fbfc2020-01-14 18:56:26 -0800476 llvm::Value *Receiver = nullptr;
477 switch (SubOME->getReceiverKind()) {
478 case ObjCMessageExpr::Instance:
479 if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
480 return None;
481 Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
482 break;
483
484 case ObjCMessageExpr::Class: {
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000485 QualType ReceiverType = SubOME->getClassReceiver();
Simon Pilgrim25dc5c72020-01-14 13:28:46 +0000486 const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000487 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
488 assert(ID && "null interface should be impossible here");
489 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
Pierre Habouzitd18fbfc2020-01-14 18:56:26 -0800490 break;
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000491 }
Pierre Habouzitd18fbfc2020-01-14 18:56:26 -0800492 case ObjCMessageExpr::SuperInstance:
493 case ObjCMessageExpr::SuperClass:
494 return None;
495 }
496
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000497 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
498}
499
John McCall78a15112010-05-22 01:48:05 +0000500RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
501 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000502 // Only the lookup mechanism and first two arguments of the method
503 // implementation vary between runtimes. We can get the receiver and
504 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000505
John McCall31168b02011-06-15 23:02:42 +0000506 bool isDelegateInit = E->isDelegateInitCall();
507
John McCallcf166702011-07-22 08:53:00 +0000508 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000509
John McCall460ce582015-10-22 18:38:17 +0000510 // If the method is -retain, and the receiver's being loaded from
511 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
512 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
513 method->getMethodFamily() == OMF_retain) {
514 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
515 LValue lvalue = EmitLValue(lvalueExpr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800516 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +0000517 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
518 }
519 }
520
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000521 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
522 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
523
John McCall31168b02011-06-15 23:02:42 +0000524 // We don't retain the receiver in delegate init calls, and this is
525 // safe because the receiver value is always loaded from 'self',
526 // which we zero out. We don't want to Block_copy block receivers,
527 // though.
528 bool retainSelf =
529 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000530 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000531 method &&
532 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000533
Daniel Dunbar8d480592008-08-11 18:12:00 +0000534 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000535 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000536 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000537 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000538 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000539 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000540 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000541 switch (E->getReceiverKind()) {
542 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000543 ReceiverType = E->getInstanceReceiver()->getType();
Pierre Habouzitd18fbfc2020-01-14 18:56:26 -0800544 isClassMessage = ReceiverType->isObjCClassType();
John McCall31168b02011-06-15 23:02:42 +0000545 if (retainSelf) {
546 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
547 E->getInstanceReceiver());
548 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000549 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000550 } else
551 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000552 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000553
Douglas Gregor9a129192010-04-21 00:45:42 +0000554 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000555 ReceiverType = E->getClassReceiver();
Simon Pilgrim25dc5c72020-01-14 13:28:46 +0000556 OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
John McCall3e294922010-05-17 20:12:43 +0000557 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000558 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000559 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000560 break;
561 }
562
563 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000564 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000565 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000566 isSuperMessage = true;
567 break;
568
569 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000570 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000571 Receiver = LoadObjCSelf();
572 isSuperMessage = true;
573 isClassMessage = true;
574 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000575 }
576
John McCallcf166702011-07-22 08:53:00 +0000577 if (retainSelf)
578 Receiver = EmitARCRetainNonBlock(Receiver);
579
580 // In ARC, we sometimes want to "extend the lifetime"
581 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
582 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000583 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000584 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
585 shouldExtendReceiverForInnerPointerMessage(E))
586 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
587
Alp Toker314cc812014-01-25 16:55:45 +0000588 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000589
Daniel Dunbarc722b852008-08-30 03:02:31 +0000590 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000591 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000592
John McCall31168b02011-06-15 23:02:42 +0000593 // For delegate init calls in ARC, do an unsafe store of null into
594 // self. This represents the call taking direct ownership of that
595 // value. We have to do this after emitting the other call
596 // arguments because they might also reference self, but we don't
597 // have to worry about any of them modifying self because that would
598 // be an undefined read and write of an object in unordered
599 // expressions.
600 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000601 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000602 "delegate init calls should only be marked in ARC");
603
604 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000605 Address selfAddr =
606 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000607 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
608 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000609
Douglas Gregor33823722011-06-11 01:09:30 +0000610 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000611 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000612 // super is only valid in an Objective-C method
613 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000614 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000615 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
616 E->getSelector(),
617 OMD->getClassInterface(),
618 isCategoryImpl,
619 Receiver,
620 isClassMessage,
621 Args,
John McCallcf166702011-07-22 08:53:00 +0000622 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000623 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000624 // Call runtime methods directly if we can.
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800625 result = Runtime.GeneratePossiblySpecializedMessageSend(
626 *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
627 method, isClassMessage);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000628 }
John McCall31168b02011-06-15 23:02:42 +0000629
630 // For delegate init calls in ARC, implicitly store the result of
631 // the call back into self. This takes ownership of the value.
632 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000633 Address selfAddr =
634 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000635 llvm::Value *newSelf = result.getScalarVal();
636
637 // The delegate return type isn't necessarily a matching type; in
638 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000640 newSelf = Builder.CreateBitCast(newSelf, selfTy);
641
642 Builder.CreateStore(newSelf, selfAddr);
643 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000644
Douglas Gregore83b9562015-07-07 03:57:53 +0000645 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000646}
647
John McCall31168b02011-06-15 23:02:42 +0000648namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000649struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000650 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000651 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000652
653 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000654 const ObjCInterfaceDecl *iface = impl->getClassInterface();
655 if (!iface->getSuperClass()) return;
656
John McCalldffafde2011-07-13 18:26:47 +0000657 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
658
John McCall31168b02011-06-15 23:02:42 +0000659 // Call [super dealloc] if we have a superclass.
660 llvm::Value *self = CGF.LoadObjCSelf();
661
662 CallArgList args;
663 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
664 CGF.getContext().VoidTy,
665 method->getSelector(),
666 iface,
John McCalldffafde2011-07-13 18:26:47 +0000667 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000668 self,
669 /*is class msg*/ false,
670 args,
671 method);
672 }
673};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000674}
John McCall31168b02011-06-15 23:02:42 +0000675
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000676/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
677/// the LLVM function and sets the other context used by
678/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000679void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000680 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000681 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000682 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000683 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000684 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000685 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000686
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000687 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000688
John McCalla729c622012-02-17 03:33:10 +0000689 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800690 if (OMD->isDirectMethod()) {
691 Fn->setVisibility(llvm::Function::HiddenVisibility);
692 CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
693 CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
694 } else {
695 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
696 }
Chris Lattner5696e7b2008-06-17 18:05:57 +0000697
John McCalla738c252011-03-09 04:27:21 +0000698 args.push_back(OMD->getSelfDecl());
699 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000700
Benjamin Kramerf9890422015-02-17 16:48:30 +0000701 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000702
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000703 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000704 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000705
Adrian Prantl42d71b92014-04-10 23:21:53 +0000706 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
707 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000708
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800709 if (OMD->isDirectMethod()) {
710 // This function is a direct call, it has to implement a nil check
711 // on entry.
712 //
713 // TODO: possibly have several entry points to elide the check
714 CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
715 }
716
John McCall31168b02011-06-15 23:02:42 +0000717 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000718 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000719 OMD->isInstanceMethod() &&
720 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000721 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000722 OMD->getSelector().getIdentifierInfoForSlot(0);
723 if (ident->isStr("dealloc"))
724 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
725 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000726}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000727
John McCall31168b02011-06-15 23:02:42 +0000728static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
729 LValue lvalue, QualType type);
730
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000731/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000732/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000733void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000734 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000735 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000736 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000737 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000738 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000739 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000740}
741
John McCallb923ece2011-09-12 23:06:44 +0000742/// emitStructGetterCall - Call the runtime function to load a property
743/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000744static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000745 bool isAtomic, bool hasStrong) {
746 ASTContext &Context = CGF.getContext();
747
John McCall7f416cc2015-09-08 08:05:57 +0000748 Address src =
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800749 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
750 .getAddress(CGF);
John McCallb923ece2011-09-12 23:06:44 +0000751
Fangrui Song6907ce22018-07-30 19:24:48 +0000752 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000753 // sizeof (Type of Ivar), isAtomic, false);
754 CallArgList args;
755
John McCall7f416cc2015-09-08 08:05:57 +0000756 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
757 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000758
759 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000760 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000761
762 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
763 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
764 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
765 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
766
James Y Knight9871db02019-02-05 16:42:33 +0000767 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000768 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000769 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000770 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000771}
772
John McCallf4528ae2011-09-13 03:34:09 +0000773/// Determine whether the given architecture supports unaligned atomic
774/// accesses. They don't have to be fast, just faster than a function
775/// call and a mutex.
776static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000777 // FIXME: Allow unaligned atomic load/store on x86. (It is not
778 // currently supported by the backend.)
779 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000780}
781
782/// Return the maximum size that permits atomic accesses for the given
783/// architecture.
784static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
785 llvm::Triple::ArchType arch) {
786 // ARM has 8-byte atomic accesses, but it's not clear whether we
787 // want to rely on them here.
788
789 // In the default case, just assume that any size up to a pointer is
790 // fine given adequate alignment.
791 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
792}
793
794namespace {
795 class PropertyImplStrategy {
796 public:
797 enum StrategyKind {
798 /// The 'native' strategy is to use the architecture's provided
799 /// reads and writes.
800 Native,
801
802 /// Use objc_setProperty and objc_getProperty.
803 GetSetProperty,
804
805 /// Use objc_setProperty for the setter, but use expression
806 /// evaluation for the getter.
807 SetPropertyAndExpressionGet,
808
809 /// Use objc_copyStruct.
810 CopyStruct,
811
812 /// The 'expression' strategy is to emit normal assignment or
813 /// lvalue-to-rvalue expressions.
814 Expression
815 };
816
817 StrategyKind getKind() const { return StrategyKind(Kind); }
818
819 bool hasStrongMember() const { return HasStrong; }
820 bool isAtomic() const { return IsAtomic; }
821 bool isCopy() const { return IsCopy; }
822
823 CharUnits getIvarSize() const { return IvarSize; }
824 CharUnits getIvarAlignment() const { return IvarAlignment; }
825
826 PropertyImplStrategy(CodeGenModule &CGM,
827 const ObjCPropertyImplDecl *propImpl);
828
829 private:
830 unsigned Kind : 8;
831 unsigned IsAtomic : 1;
832 unsigned IsCopy : 1;
833 unsigned HasStrong : 1;
834
835 CharUnits IvarSize;
836 CharUnits IvarAlignment;
837 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000838}
John McCallf4528ae2011-09-13 03:34:09 +0000839
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000840/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000841PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
842 const ObjCPropertyImplDecl *propImpl) {
843 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000844 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000845
John McCall43192862011-09-13 18:31:23 +0000846 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
847 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000848 HasStrong = false; // doesn't matter here.
849
850 // Evaluate the ivar's size and alignment.
851 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
852 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000853 std::tie(IvarSize, IvarAlignment) =
854 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000855
856 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000857 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000858 if (IsCopy) {
859 Kind = GetSetProperty;
860 return;
861 }
862
John McCall43192862011-09-13 18:31:23 +0000863 // Handle retain.
864 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000865 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000866 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000867 // fallthrough
868
869 // In ARC, if the property is non-atomic, use expression emission,
870 // which translates to objc_storeStrong. This isn't required, but
871 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000873 // Using standard expression emission for the setter is only
874 // acceptable if the ivar is __strong, which won't be true if
875 // the property is annotated with __attribute__((NSObject)).
876 // TODO: falling all the way back to objc_setProperty here is
877 // just laziness, though; we could still use objc_storeStrong
878 // if we hacked it right.
879 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
880 Kind = Expression;
881 else
882 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000883 return;
884
885 // Otherwise, we need to at least use setProperty. However, if
886 // the property isn't atomic, we can use normal expression
887 // emission for the getter.
888 } else if (!IsAtomic) {
889 Kind = SetPropertyAndExpressionGet;
890 return;
891
892 // Otherwise, we have to use both setProperty and getProperty.
893 } else {
894 Kind = GetSetProperty;
895 return;
896 }
897 }
898
899 // If we're not atomic, just use expression accesses.
900 if (!IsAtomic) {
901 Kind = Expression;
902 return;
903 }
904
John McCall0e5c0862011-09-13 05:36:29 +0000905 // Properties on bitfield ivars need to be emitted using expression
906 // accesses even if they're nominally atomic.
907 if (ivar->isBitField()) {
908 Kind = Expression;
909 return;
910 }
911
John McCallf4528ae2011-09-13 03:34:09 +0000912 // GC-qualified or ARC-qualified ivars need to be emitted as
913 // expressions. This actually works out to being atomic anyway,
914 // except for ARC __strong, but that should trigger the above code.
915 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000916 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000917 CGM.getContext().getObjCGCAttrKind(ivarType))) {
918 Kind = Expression;
919 return;
920 }
921
922 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000923 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000924 if (const RecordType *recordType = ivarType->getAs<RecordType>())
925 HasStrong = recordType->getDecl()->hasObjectMember();
926
927 // We can never access structs with object members with a native
928 // access, because we need to use write barriers. This is what
929 // objc_copyStruct is for.
930 if (HasStrong) {
931 Kind = CopyStruct;
932 return;
933 }
934
935 // Otherwise, this is target-dependent and based on the size and
936 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000937
938 // If the size of the ivar is not a power of two, give up. We don't
939 // want to get into the business of doing compare-and-swaps.
940 if (!IvarSize.isPowerOfTwo()) {
941 Kind = CopyStruct;
942 return;
943 }
944
John McCallf4528ae2011-09-13 03:34:09 +0000945 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000946 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000947
948 // Most architectures require memory to fit within a single cache
949 // line, so the alignment has to be at least the size of the access.
950 // Otherwise we have to grab a lock.
951 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
952 Kind = CopyStruct;
953 return;
954 }
955
956 // If the ivar's size exceeds the architecture's maximum atomic
957 // access size, we have to use CopyStruct.
958 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
959 Kind = CopyStruct;
960 return;
961 }
962
963 // Otherwise, we can use native loads and stores.
964 Kind = Native;
965}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000966
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000967/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000968///
969/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000970/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000971void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
972 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000973 llvm::Constant *AtomicHelperFn =
974 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -0800975 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000976 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000977 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000978
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000979 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000980
Adrian Prantlce7d3592019-12-05 12:26:16 -0800981 FinishFunction(OMD->getEndLoc());
John McCallf4528ae2011-09-13 03:34:09 +0000982}
983
John McCallbdd81852011-09-13 06:00:03 +0000984static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
985 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000986 if (!getter) return true;
987
988 // Sema only makes only of these when the ivar has a C++ class type,
989 // so the form is pretty constrained.
990
John McCallbdd81852011-09-13 06:00:03 +0000991 // If the property has a reference type, we might just be binding a
992 // reference, in which case the result will be a gl-value. We should
993 // treat this as a non-trivial operation.
994 if (getter->isGLValue())
995 return false;
996
John McCallf4528ae2011-09-13 03:34:09 +0000997 // If we selected a trivial copy-constructor, we're okay.
998 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
999 return (construct->getConstructor()->isTrivial());
1000
1001 // The constructor might require cleanups (in which case it's never
1002 // trivial).
1003 assert(isa<ExprWithCleanups>(getter));
1004 return false;
1005}
1006
Fangrui Song6907ce22018-07-30 19:24:48 +00001007/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001008/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +00001009static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001010 llvm::Value *returnAddr,
1011 ObjCIvarDecl *ivar,
1012 llvm::Constant *AtomicHelperFn) {
1013 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1014 // AtomicHelperFn);
1015 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001016
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001017 // The 1st argument is the return Slot.
1018 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001019
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001020 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001021 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001022 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1023 .getPointer(CGF);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001024 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1025 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001026
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001027 // Third argument is the helper function.
1028 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001029
James Y Knight9871db02019-02-05 16:42:33 +00001030 llvm::FunctionCallee copyCppAtomicObjectFn =
1031 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001032 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +00001033 CGF.EmitCall(
1034 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001035 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001036}
1037
John McCallf4528ae2011-09-13 03:34:09 +00001038void
1039CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001040 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001041 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001042 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +00001043 // If there's a non-trivial 'get' expression, we just have to emit that.
1044 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001045 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001046 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1047 propImpl->getGetterCXXConstructor(),
1048 /* NRVOCandidate=*/nullptr);
1049 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001050 }
1051 else {
1052 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001053 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001054 ivar, AtomicHelperFn);
1055 }
John McCallf4528ae2011-09-13 03:34:09 +00001056 return;
1057 }
1058
1059 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1060 QualType propType = prop->getType();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001061 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001062
Fangrui Song6907ce22018-07-30 19:24:48 +00001063 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001064
1065 // Pick an implementation strategy.
1066 PropertyImplStrategy strategy(CGM, propImpl);
1067 switch (strategy.getKind()) {
1068 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001069 // We don't need to do anything for a zero-size struct.
1070 if (strategy.getIvarSize().isZero())
1071 return;
1072
John McCallf4528ae2011-09-13 03:34:09 +00001073 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1074
1075 // Currently, all atomic accesses have to be through integer
1076 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001077 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1078 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001079 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1080
1081 // Perform an atomic load. This does not impose ordering constraints.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001082 Address ivarAddr = LV.getAddress(*this);
John McCallf4528ae2011-09-13 03:34:09 +00001083 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1084 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001085 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001086
1087 // Store that value into the return address. Doing this with a
1088 // bitcast is likely to produce some pretty ugly IR, but it's not
1089 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001090 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1091 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1092 llvm::Value *ivarVal = load;
1093 if (ivarSize > retTySize) {
1094 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1095 ivarVal = Builder.CreateTrunc(load, newTy);
1096 bitcastType = newTy->getPointerTo();
1097 }
1098 Builder.CreateStore(ivarVal,
1099 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001100
1101 // Make sure we don't do an autorelease.
1102 AutoreleaseResult = false;
1103 return;
1104 }
1105
1106 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001107 llvm::FunctionCallee getPropertyFn =
1108 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001109 if (!getPropertyFn) {
1110 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001111 return;
1112 }
John McCallb92ab1a2016-10-26 23:46:34 +00001113 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001114
1115 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1116 // FIXME: Can't this be simpler? This might even be worse than the
1117 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001118 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001119 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001120 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1121 llvm::Value *ivarOffset =
1122 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1123
1124 CallArgList args;
1125 args.add(RValue::get(self), getContext().getObjCIdType());
1126 args.add(RValue::get(cmd), getContext().getObjCSelType());
1127 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001128 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1129 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001130
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001131 // FIXME: We shouldn't need to get the function info here, the
1132 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001133 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001134 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1135 getContext().getObjCIdType(), args),
1136 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001137 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1138 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001139
Daniel Dunbara08dff12008-09-24 04:04:31 +00001140 // We need to fix the type here. Ivars with copy & retain are
1141 // always objects so we don't need to worry about complex or
1142 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001143 RV = RValue::get(Builder.CreateBitCast(
1144 RV.getScalarVal(),
1145 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001146
1147 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001148
1149 // objc_getProperty does an autorelease, so we should suppress ours.
1150 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001151
John McCallf4528ae2011-09-13 03:34:09 +00001152 return;
1153 }
1154
1155 case PropertyImplStrategy::CopyStruct:
1156 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1157 strategy.hasStrongMember());
1158 return;
1159
1160 case PropertyImplStrategy::Expression:
1161 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1162 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1163
1164 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001165 switch (getEvaluationKind(ivarType)) {
1166 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001167 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001168 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001169 /*init*/ true);
1170 return;
1171 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001172 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001173 // The return value slot is guaranteed to not be aliased, but
1174 // that's not necessarily the same as "on the stack", so
1175 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001176 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smith8cca3a52019-06-20 20:56:20 +00001177 /* Src= */ LV, ivarType, getOverlapForReturnValue());
Richard Smithe78fac52018-04-05 20:52:58 +00001178 return;
1179 }
John McCall47fb9502013-03-07 21:37:08 +00001180 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001181 llvm::Value *value;
1182 if (propType->isReferenceType()) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001183 value = LV.getAddress(*this).getPointer();
John McCall24fada12011-07-22 05:23:13 +00001184 } else {
1185 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1186 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001187 if (getLangOpts().ObjCAutoRefCount) {
1188 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1189 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001190 value = EmitARCLoadWeak(LV.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +00001191 }
John McCall24fada12011-07-22 05:23:13 +00001192
1193 // Otherwise we want to do a simple load, suppressing the
1194 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001195 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001196 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001197 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001198 }
John McCall31168b02011-06-15 23:02:42 +00001199
Alp Toker314cc812014-01-25 16:55:45 +00001200 value = Builder.CreateBitCast(
1201 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001202 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001203
John McCall24fada12011-07-22 05:23:13 +00001204 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001205 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001206 }
John McCall47fb9502013-03-07 21:37:08 +00001207 }
1208 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001209 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001210
John McCallf4528ae2011-09-13 03:34:09 +00001211 }
1212 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001213}
1214
John McCallb923ece2011-09-12 23:06:44 +00001215/// emitStructSetterCall - Call the runtime function to store the value
1216/// from the first formal parameter into the given ivar.
1217static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1218 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001219 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001220 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001221 CallArgList args;
1222
1223 // The first argument is the address of the ivar.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001224 llvm::Value *ivarAddr =
1225 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1226 .getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001227 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1228 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001229
1230 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001231 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001232 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1233 argVar->getType().getNonReferenceType(), VK_LValue,
1234 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001235 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001236 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1237 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001238
1239 // The third argument is the sizeof the type.
1240 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001241 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1242 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001243
John McCallb923ece2011-09-12 23:06:44 +00001244 // The fourth argument is the 'isAtomic' flag.
1245 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001246
John McCallb923ece2011-09-12 23:06:44 +00001247 // The fifth argument is the 'hasStrong' flag.
1248 // FIXME: should this really always be false?
1249 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1250
James Y Knight9871db02019-02-05 16:42:33 +00001251 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001252 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001253 CGF.EmitCall(
1254 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001255 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001256}
1257
Fangrui Song6907ce22018-07-30 19:24:48 +00001258/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1259/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001260/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001261static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001262 ObjCMethodDecl *OMD,
1263 ObjCIvarDecl *ivar,
1264 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001265 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001266 // AtomicHelperFn);
1267 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001268
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001269 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001270 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001271 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1272 .getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001273 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1274 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001275
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001276 // The second argument is the address of the parameter variable.
1277 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001278 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1279 argVar->getType().getNonReferenceType(), VK_LValue,
1280 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001281 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001282 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1283 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001284
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001285 // Third argument is the helper function.
1286 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001287
James Y Knight9871db02019-02-05 16:42:33 +00001288 llvm::FunctionCallee fn =
1289 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001290 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001291 CGF.EmitCall(
1292 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001293 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001294}
1295
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001296
John McCallf4528ae2011-09-13 03:34:09 +00001297static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1298 Expr *setter = PID->getSetterCXXAssignment();
1299 if (!setter) return true;
1300
1301 // Sema only makes only of these when the ivar has a C++ class type,
1302 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001303
1304 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001305 // This also implies that there's nothing non-trivial going on with
1306 // the arguments, because operator= can only be trivial if it's a
1307 // synthesized assignment operator and therefore both parameters are
1308 // references.
1309 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001310 if (const FunctionDecl *callee
1311 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1312 if (callee->isTrivial())
1313 return true;
1314 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001315 }
John McCall7f16c422011-09-10 09:17:20 +00001316
John McCallf4528ae2011-09-13 03:34:09 +00001317 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001318 return false;
1319}
1320
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001321static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001322 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001323 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001324 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001325}
1326
John McCall7f16c422011-09-10 09:17:20 +00001327void
1328CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001329 const ObjCPropertyImplDecl *propImpl,
1330 llvm::Constant *AtomicHelperFn) {
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001331 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001332 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001333
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001334 // Just use the setter expression if Sema gave us one and it's
1335 // non-trivial.
1336 if (!hasTrivialSetExpr(propImpl)) {
1337 if (!AtomicHelperFn)
1338 // If non-atomic, assignment is called directly.
1339 EmitStmt(propImpl->getSetterCXXAssignment());
1340 else
1341 // If atomic, assignment is called via a locking api.
1342 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1343 AtomicHelperFn);
1344 return;
1345 }
John McCall7f16c422011-09-10 09:17:20 +00001346
John McCallf4528ae2011-09-13 03:34:09 +00001347 PropertyImplStrategy strategy(CGM, propImpl);
1348 switch (strategy.getKind()) {
1349 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001350 // We don't need to do anything for a zero-size struct.
1351 if (strategy.getIvarSize().isZero())
1352 return;
1353
John McCall7f416cc2015-09-08 08:05:57 +00001354 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001355
John McCallf4528ae2011-09-13 03:34:09 +00001356 LValue ivarLValue =
1357 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001358 Address ivarAddr = ivarLValue.getAddress(*this);
John McCall7f16c422011-09-10 09:17:20 +00001359
John McCallf4528ae2011-09-13 03:34:09 +00001360 // Currently, all atomic accesses have to be through integer
1361 // types, so there's no point in trying to pick a prettier type.
1362 llvm::Type *bitcastType =
1363 llvm::Type::getIntNTy(getLLVMContext(),
1364 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001365
1366 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001367 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1368 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001369
1370 // This bitcast load is likely to cause some nasty IR.
1371 llvm::Value *load = Builder.CreateLoad(argAddr);
1372
1373 // Perform an atomic store. There are no memory ordering requirements.
1374 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001375 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001376 return;
1377 }
1378
1379 case PropertyImplStrategy::GetSetProperty:
1380 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001381
James Y Knight9871db02019-02-05 16:42:33 +00001382 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1383 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001384 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001385 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001386 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001387 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1388 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001389 if (!setOptimizedPropertyFn) {
1390 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1391 return;
1392 }
John McCall7f16c422011-09-10 09:17:20 +00001393 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001394 else {
1395 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1396 if (!setPropertyFn) {
1397 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1398 return;
1399 }
1400 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001401
John McCall7f16c422011-09-10 09:17:20 +00001402 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1403 // <is-atomic>, <is-copy>).
1404 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001405 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001406 llvm::Value *self =
1407 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1408 llvm::Value *ivarOffset =
1409 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001410 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1411 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1412 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001413
1414 CallArgList args;
1415 args.add(RValue::get(self), getContext().getObjCIdType());
1416 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001417 if (setOptimizedPropertyFn) {
1418 args.add(RValue::get(arg), getContext().getObjCIdType());
1419 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001420 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001421 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001422 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001423 } else {
1424 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1425 args.add(RValue::get(arg), getContext().getObjCIdType());
1426 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1427 getContext().BoolTy);
1428 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1429 getContext().BoolTy);
1430 // FIXME: We shouldn't need to get the function info here, the runtime
1431 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001432 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001433 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001434 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001435 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001436
John McCall7f16c422011-09-10 09:17:20 +00001437 return;
1438 }
1439
John McCallf4528ae2011-09-13 03:34:09 +00001440 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001441 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001442 return;
John McCallf4528ae2011-09-13 03:34:09 +00001443
1444 case PropertyImplStrategy::Expression:
1445 break;
John McCall7f16c422011-09-10 09:17:20 +00001446 }
1447
1448 // Otherwise, fake up some ASTs and emit a normal assignment.
1449 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001450 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001451 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001452 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1453 selfDecl->getType(), CK_LValueToRValue, &self,
1454 VK_RValue);
1455 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001456 SourceLocation(), SourceLocation(),
1457 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001458
1459 ParmVarDecl *argDecl = *setterMethod->param_begin();
1460 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001461 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1462 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001463 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1464 argType.getUnqualifiedType(), CK_LValueToRValue,
1465 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001466
John McCall7f16c422011-09-10 09:17:20 +00001467 // The property type can differ from the ivar type in some situations with
1468 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1469 // The following absurdity is just to ensure well-formed IR.
1470 CastKind argCK = CK_NoOp;
1471 if (ivarRef.getType()->isObjCObjectPointerType()) {
1472 if (argLoad.getType()->isObjCObjectPointerType())
1473 argCK = CK_BitCast;
1474 else if (argLoad.getType()->isBlockPointerType())
1475 argCK = CK_BlockPointerToObjCPointerCast;
1476 else
1477 argCK = CK_CPointerToObjCPointerCast;
1478 } else if (ivarRef.getType()->isBlockPointerType()) {
1479 if (argLoad.getType()->isBlockPointerType())
1480 argCK = CK_BitCast;
1481 else
1482 argCK = CK_AnyPointerToBlockPointerCast;
1483 } else if (ivarRef.getType()->isPointerType()) {
1484 argCK = CK_BitCast;
1485 }
1486 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1487 ivarRef.getType(), argCK, &argLoad,
1488 VK_RValue);
1489 Expr *finalArg = &argLoad;
1490 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1491 argLoad.getType()))
1492 finalArg = &argCast;
1493
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07001494 BinaryOperator *assign = BinaryOperator::Create(
1495 getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(), VK_RValue,
1496 OK_Ordinary, SourceLocation(),
1497 FPOptions(getContext().getLangOpts()));
1498 EmitStmt(assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001499}
1500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001501/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001502///
1503/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001504/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001505void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1506 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001507 llvm::Constant *AtomicHelperFn =
1508 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -08001509 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001510 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001511 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001512
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001513 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001514
Adrian Prantlce7d3592019-12-05 12:26:16 -08001515 FinishFunction(OMD->getEndLoc());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001516}
1517
John McCall6a4fa522011-03-22 07:05:39 +00001518namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001519 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001520 private:
1521 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001522 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001523 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001524 bool useEHCleanupForArray;
1525 public:
1526 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1527 CodeGenFunction::Destroyer *destroyer,
1528 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001529 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001530 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001531
Craig Topper4f12f102014-03-12 06:41:41 +00001532 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001533 LValue lvalue
1534 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001535 CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001536 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001537 }
1538 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001539}
John McCall6a4fa522011-03-22 07:05:39 +00001540
John McCall4bd0fb12011-07-12 16:41:08 +00001541/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1542static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001543 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001544 QualType type) {
1545 llvm::Value *null = getNullForVariable(addr);
1546 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1547}
John McCall31168b02011-06-15 23:02:42 +00001548
John McCall6a4fa522011-03-22 07:05:39 +00001549static void emitCXXDestructMethod(CodeGenFunction &CGF,
1550 ObjCImplementationDecl *impl) {
1551 CodeGenFunction::RunCleanupsScope scope(CGF);
1552
1553 llvm::Value *self = CGF.LoadObjCSelf();
1554
Jordy Rosea91768e2011-07-22 02:08:32 +00001555 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1556 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001557 ivar; ivar = ivar->getNextIvar()) {
1558 QualType type = ivar->getType();
1559
John McCall6a4fa522011-03-22 07:05:39 +00001560 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001561 QualType::DestructionKind dtorKind = type.isDestructedType();
1562 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001563
Craig Topper8a13c412014-05-21 05:09:00 +00001564 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001565
John McCall4bd0fb12011-07-12 16:41:08 +00001566 // Use a call to objc_storeStrong to destroy strong ivars, for the
1567 // general benefit of the tools.
1568 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001569 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001570
John McCall4bd0fb12011-07-12 16:41:08 +00001571 // Otherwise use the default for the destruction kind.
1572 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001573 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001574 }
John McCall4bd0fb12011-07-12 16:41:08 +00001575
1576 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1577
1578 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1579 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001580 }
1581
1582 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1583}
1584
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001585void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1586 ObjCMethodDecl *MD,
1587 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001588 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001589 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001590
1591 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001592 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001593 // Suppress the final autorelease in ARC.
1594 AutoreleaseResult = false;
1595
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001596 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001597 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001598 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001599 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001600 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001601 EmitAggExpr(IvarInit->getInit(),
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001602 AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001603 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001604 AggValueSlot::IsNotAliased,
1605 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001606 }
1607 // constructor returns 'self'.
1608 CodeGenTypes &Types = CGM.getTypes();
1609 QualType IdTy(CGM.getContext().getObjCIdType());
1610 llvm::Value *SelfAsId =
1611 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1612 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001613
1614 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001615 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001616 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001617 }
1618 FinishFunction();
1619}
1620
Daniel Dunbara08dff12008-09-24 04:04:31 +00001621llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001622 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001623 DeclRefExpr DRE(getContext(), Self,
1624 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001625 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001626 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001627}
1628
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001629QualType CodeGenFunction::TypeOfSelfObject() {
1630 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1631 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001632 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1633 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001634 return PTy->getPointeeType();
1635}
1636
Chris Lattnerd4808922009-03-22 21:03:39 +00001637void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001638 llvm::FunctionCallee EnumerationMutationFnPtr =
1639 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001640 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001641 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1642 return;
1643 }
John McCallb92ab1a2016-10-26 23:46:34 +00001644 CGCallee EnumerationMutationFn =
1645 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001646
Devang Pateld2d66652011-01-19 01:36:36 +00001647 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001648 if (DI)
1649 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001650
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001651 RunCleanupsScope ForScope(*this);
1652
Kuba Mracek82c21752017-04-14 01:00:03 +00001653 // The local variable comes into scope immediately.
1654 AutoVarEmission variable = AutoVarEmission::invalid();
1655 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1656 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1657
John McCall1c926b72011-01-07 01:49:06 +00001658 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001659
Anders Carlsson75658592008-08-31 02:33:12 +00001660 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001661 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001662 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001663 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001664
Anders Carlsson75658592008-08-31 02:33:12 +00001665 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001666 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001667
John McCall1c926b72011-01-07 01:49:06 +00001668 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001669 IdentifierInfo *II[] = {
1670 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1671 &CGM.getContext().Idents.get("objects"),
1672 &CGM.getContext().Idents.get("count")
1673 };
1674 Selector FastEnumSel =
1675 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001676
1677 QualType ItemsTy =
1678 getContext().getConstantArrayType(getContext().getObjCIdType(),
Richard Smith772e2662019-10-04 01:25:59 +00001679 llvm::APInt(32, NumItems), nullptr,
Anders Carlsson75658592008-08-31 02:33:12 +00001680 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001681 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001682
John McCall53848232011-07-27 01:07:15 +00001683 // Emit the collection pointer. In ARC, we do a retain.
1684 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001685 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001686 Collection = EmitARCRetainScalarExpr(S.getCollection());
1687
1688 // Enter a cleanup to do the release.
1689 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1690 } else {
1691 Collection = EmitScalarExpr(S.getCollection());
1692 }
Mike Stump11289f42009-09-09 15:08:12 +00001693
John McCall91e82dd2011-08-05 00:14:38 +00001694 // The 'continue' label needs to appear within the cleanup for the
1695 // collection object.
1696 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1697
John McCall1c926b72011-01-07 01:49:06 +00001698 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001699 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001700
1701 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001702 Args.add(RValue::get(StatePtr.getPointer()),
1703 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001704
John McCall1c926b72011-01-07 01:49:06 +00001705 // The second argument is a temporary array with space for NumItems
1706 // pointers. We'll actually be loading elements from the array
1707 // pointer written into the control state; this buffer is so that
1708 // collections that *aren't* backed by arrays can still queue up
1709 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001710 Args.add(RValue::get(ItemsPtr.getPointer()),
1711 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001712
John McCall1c926b72011-01-07 01:49:06 +00001713 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001714 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1715 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1716 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001717
John McCall1c926b72011-01-07 01:49:06 +00001718 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001719 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001720 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1721 getContext().getNSUIntegerType(),
1722 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001723
John McCall1c926b72011-01-07 01:49:06 +00001724 // The initial number of objects that were returned in the buffer.
1725 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001726
John McCall1c926b72011-01-07 01:49:06 +00001727 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1728 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001729
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001730 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001731
John McCall1c926b72011-01-07 01:49:06 +00001732 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001733 // empty; skip all this. Set the branch weight assuming this has the same
1734 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001735 uint64_t EntryCount = getCurrentProfileCount();
1736 Builder.CreateCondBr(
1737 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1738 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001739 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001740
John McCall1c926b72011-01-07 01:49:06 +00001741 // Otherwise, initialize the loop.
1742 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001743
John McCall1c926b72011-01-07 01:49:06 +00001744 // Save the initial mutations value. This is the value at an
1745 // address that was written into the state object by
1746 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001747 Address StateMutationsPtrPtr =
1748 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001749 llvm::Value *StateMutationsPtr
1750 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001751
John McCall1c926b72011-01-07 01:49:06 +00001752 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001753 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1754 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001755
John McCall1c926b72011-01-07 01:49:06 +00001756 // Start looping. This is the point we return to whenever we have a
1757 // fresh, non-empty batch of objects.
1758 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1759 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001760
John McCall1c926b72011-01-07 01:49:06 +00001761 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001762 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001763 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001764
John McCall1c926b72011-01-07 01:49:06 +00001765 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001766 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001767 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001768
Justin Bogner66242d62015-04-23 23:06:47 +00001769 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001770
John McCall1c926b72011-01-07 01:49:06 +00001771 // Check whether the mutations value has changed from where it was
1772 // at start. StateMutationsPtr should actually be invariant between
1773 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001774 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001775 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001776 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1777 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001778
John McCall1c926b72011-01-07 01:49:06 +00001779 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001780 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001781
John McCall1c926b72011-01-07 01:49:06 +00001782 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1783 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001784
John McCall1c926b72011-01-07 01:49:06 +00001785 // If so, call the enumeration-mutation function.
1786 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001787 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001788 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001789 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001790 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001791 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001792 // FIXME: We shouldn't need to get the function info here, the runtime already
1793 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001794 EmitCall(
1795 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001796 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001797
John McCall1c926b72011-01-07 01:49:06 +00001798 // Otherwise, or if the mutation function returns, just continue.
1799 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001800
John McCall1c926b72011-01-07 01:49:06 +00001801 // Initialize the element variable.
1802 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001803 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001804 LValue elementLValue;
1805 QualType elementType;
1806 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001807 // Initialize the variable, in case it's a __block variable or something.
1808 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001809
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001810 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1811 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1812 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001813 elementLValue = EmitLValue(&tempDRE);
1814 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001815 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001816
1817 if (D->isARCPseudoStrong())
1818 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001819 } else {
1820 elementLValue = LValue(); // suppress warning
1821 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001822 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001823 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001824 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001825
1826 // Fetch the buffer out of the enumeration state.
1827 // TODO: this pointer should actually be invariant between
1828 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001829 Address StateItemsPtr =
1830 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001831 llvm::Value *EnumStateItems =
1832 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001833
John McCall1c926b72011-01-07 01:49:06 +00001834 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001835 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001836 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001837 llvm::Value *CurrentItem =
1838 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001839
John McCall1c926b72011-01-07 01:49:06 +00001840 // Cast that value to the right type.
1841 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1842 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001843
John McCall1c926b72011-01-07 01:49:06 +00001844 // Make sure we have an l-value. Yes, this gets evaluated every
1845 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001846 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001847 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001848 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001849 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001850 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1851 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
John McCall9e2e22f2011-02-22 07:16:58 +00001854 // If we do have an element variable, this assignment is the end of
1855 // its initialization.
1856 if (elementIsVariable)
1857 EmitAutoVarCleanups(variable);
1858
John McCall1c926b72011-01-07 01:49:06 +00001859 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001860 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001861 {
1862 RunCleanupsScope Scope(*this);
1863 EmitStmt(S.getBody());
1864 }
Anders Carlsson75658592008-08-31 02:33:12 +00001865 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001866
John McCall1c926b72011-01-07 01:49:06 +00001867 // Destroy the element variable now.
1868 elementVariableScope.ForceCleanup();
1869
1870 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001871 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001872
John McCall1c926b72011-01-07 01:49:06 +00001873 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001874
John McCall1c926b72011-01-07 01:49:06 +00001875 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001876 llvm::Value *indexPlusOne =
1877 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001878
John McCall1c926b72011-01-07 01:49:06 +00001879 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001880 // Set the branch weights based on the simplifying assumption that this is
1881 // like a while-loop, i.e., ignoring that the false branch fetches more
1882 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001883 Builder.CreateCondBr(
1884 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001885 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001886
1887 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1888 count->addIncoming(count, AfterBody.getBlock());
1889
1890 // Otherwise, we have to fetch more elements.
1891 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001892
1893 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001894 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1895 getContext().getNSUIntegerType(),
1896 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001897
John McCall1c926b72011-01-07 01:49:06 +00001898 // If we got a zero count, we're done.
1899 llvm::Value *refetchCount = CountRV.getScalarVal();
1900
1901 // (note that the message send might split FetchMoreBB)
1902 index->addIncoming(zero, Builder.GetInsertBlock());
1903 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1904
1905 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1906 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlsson75658592008-08-31 02:33:12 +00001908 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001909 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001910
John McCall9e2e22f2011-02-22 07:16:58 +00001911 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001912 // If the element was not a declaration, set it to be null.
1913
John McCall1c926b72011-01-07 01:49:06 +00001914 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1915 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001916 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001917 }
1918
Eric Christopher7cdf9482011-10-13 21:45:18 +00001919 if (DI)
1920 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001921
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001922 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001923 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001924}
1925
Mike Stump11289f42009-09-09 15:08:12 +00001926void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001927 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001928}
1929
Mike Stump11289f42009-09-09 15:08:12 +00001930void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001931 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1932}
1933
Chris Lattnere132e242008-11-15 21:26:17 +00001934void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001935 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001936 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001937}
1938
John McCall31168b02011-06-15 23:02:42 +00001939namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001940 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001941 CallObjCRelease(llvm::Value *object) : object(object) {}
1942 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001943
Craig Topper4f12f102014-03-12 06:41:41 +00001944 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001945 // Releases at the end of the full-expression are imprecise.
1946 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001947 }
1948 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001949}
John McCall31168b02011-06-15 23:02:42 +00001950
John McCall2d637d22011-09-10 06:18:15 +00001951/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001952/// release at the end of the full-expression.
1953llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1954 llvm::Value *object) {
1955 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001956 // conditional.
1957 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001958 return object;
1959}
1960
1961llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1962 llvm::Value *value) {
1963 return EmitARCRetainAutorelease(type, value);
1964}
1965
John McCalleff18842013-03-23 02:35:54 +00001966/// Given a number of pointers, inform the optimizer that they're
1967/// being intrinsically used up until this point in the program.
1968void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001969 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001970 if (!fn)
1971 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001972
1973 // This isn't really a "runtime" function, but as an intrinsic it
1974 // doesn't really matter as long as we align things up.
1975 EmitNounwindRuntimeCall(fn, values);
1976}
1977
James Y Knight9871db02019-02-05 16:42:33 +00001978static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001979 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001980 // If the target runtime doesn't naturally support ARC, emit weak
1981 // references to the runtime support library. We don't really
1982 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001983 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1984 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001985 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001986 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001987 }
John McCall31168b02011-06-15 23:02:42 +00001988}
1989
James Y Knight9871db02019-02-05 16:42:33 +00001990static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1991 llvm::FunctionCallee RTF) {
1992 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1993}
1994
John McCall31168b02011-06-15 23:02:42 +00001995/// Perform an operation having the signature
1996/// i8* (i8*)
1997/// where a null input causes a no-op and returns null.
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00001998static llvm::Value *emitARCValueOperation(
1999 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2000 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2001 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002002 if (isa<llvm::ConstantPointerNull>(value))
2003 return value;
John McCall31168b02011-06-15 23:02:42 +00002004
2005 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002006 fn = CGF.CGM.getIntrinsic(IntID);
2007 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002008 }
2009
2010 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00002011 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00002012 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2013
2014 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00002015 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002016 call->setTailCallKind(tailKind);
John McCall31168b02011-06-15 23:02:42 +00002017
2018 // Cast the result back to the original type.
2019 return CGF.Builder.CreateBitCast(call, origType);
2020}
2021
2022/// Perform an operation having the following signature:
2023/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002024static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2025 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002026 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00002027 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002028 fn = CGF.CGM.getIntrinsic(IntID);
2029 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002030 }
2031
2032 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00002033 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00002034 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2035
2036 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002037 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002038
2039 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002040 if (origType != CGF.Int8PtrTy)
2041 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002042
2043 return result;
2044}
2045
2046/// Perform an operation having the following signature:
2047/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002048static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002049 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002050 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002051 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002052 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002053 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002054
2055 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002056 fn = CGF.CGM.getIntrinsic(IntID);
2057 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002058 }
2059
Chris Lattner2192fe52011-07-18 04:24:23 +00002060 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002061
John McCall882987f2013-02-28 19:01:20 +00002062 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002063 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002064 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2065 };
2066 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002067
Craig Topper8a13c412014-05-21 05:09:00 +00002068 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002069
2070 return CGF.Builder.CreateBitCast(result, origType);
2071}
2072
2073/// Perform an operation having the following signature:
2074/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002075static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2076 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002077 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002078 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002079
2080 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002081 fn = CGF.CGM.getIntrinsic(IntID);
2082 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002083 }
2084
John McCall882987f2013-02-28 19:01:20 +00002085 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002086 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2087 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002088 };
2089 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002090}
2091
Pete Cooper2cd35962018-12-18 20:33:00 +00002092/// Perform an operation having the signature
2093/// i8* (i8*)
2094/// where a null input causes a no-op and returns null.
2095static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2096 llvm::Value *value,
2097 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002098 llvm::FunctionCallee &fn,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002099 StringRef fnName) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002100 if (isa<llvm::ConstantPointerNull>(value))
2101 return value;
2102
2103 if (!fn) {
2104 llvm::FunctionType *fnType =
2105 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2106 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002107
2108 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002109 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002110 if (fnName == "objc_retain")
2111 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002112 }
2113
2114 // Cast the argument to 'id'.
2115 llvm::Type *origType = returnType ? returnType : value->getType();
2116 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2117
2118 // Call the function.
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002119 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002120
2121 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002122 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002123}
2124
John McCall31168b02011-06-15 23:02:42 +00002125/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002126/// call i8* \@objc_retain(i8* %value)
2127/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002128llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2129 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002130 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002131 else
2132 return EmitARCRetainNonBlock(value);
2133}
2134
2135/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002136/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002137llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002138 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002139 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002140 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002141}
2142
2143/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002144/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002145///
2146/// \param mandatory - If false, emit the call with metadata
2147/// indicating that it's okay for the optimizer to eliminate this call
2148/// if it can prove that the block never escapes except down the stack.
2149llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2150 bool mandatory) {
2151 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002152 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002153 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002154 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002155
2156 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2157 // tell the optimizer that it doesn't need to do this copy if the
2158 // block doesn't escape, where being passed as an argument doesn't
2159 // count as escaping.
2160 if (!mandatory && isa<llvm::Instruction>(result)) {
2161 llvm::CallInst *call
2162 = cast<llvm::CallInst>(result->stripPointerCasts());
Craig Toppera58b62b2020-04-27 20:15:59 -07002163 assert(call->getCalledOperand() ==
2164 CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002165
John McCallff613032011-10-04 06:23:45 +00002166 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002167 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002168 }
2169
2170 return result;
John McCall31168b02011-06-15 23:02:42 +00002171}
2172
John McCalle399e5b2016-01-27 18:32:30 +00002173static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002174 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002175 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002176 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002177 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002178 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002179 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002180 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002181 .getARCRetainAutoreleasedReturnValueMarker();
2182
2183 // If we have an empty assembly string, there's nothing to do.
2184 if (assembly.empty()) {
2185
2186 // Otherwise, at -O0, build an inline asm that we're going to call
2187 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002188 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002189 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002190 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002191
John McCall31168b02011-06-15 23:02:42 +00002192 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2193
2194 // If we're at -O1 and above, we don't want to litter the code
2195 // with this marker yet, so leave a breadcrumb for the ARC
2196 // optimizer to pick up.
2197 } else {
Akira Hatanaka60c3a3b2019-04-10 06:20:23 +00002198 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2199 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2200 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2201 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
John McCall31168b02011-06-15 23:02:42 +00002202 }
2203 }
2204 }
2205
2206 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002207 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002208 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002209}
John McCall31168b02011-06-15 23:02:42 +00002210
John McCalle399e5b2016-01-27 18:32:30 +00002211/// Retain the given object which is the result of a function call.
2212/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2213///
2214/// Yes, this function name is one character away from a different
2215/// call with completely different semantics.
2216llvm::Value *
2217CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2218 emitAutoreleasedReturnValueMarker(*this);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002219 llvm::CallInst::TailCallKind tailKind =
2220 CGM.getTargetCodeGenInfo()
2221 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2222 ? llvm::CallInst::TCK_NoTail
2223 : llvm::CallInst::TCK_None;
2224 return emitARCValueOperation(
2225 *this, value, nullptr,
2226 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2227 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
John McCall31168b02011-06-15 23:02:42 +00002228}
2229
John McCalle399e5b2016-01-27 18:32:30 +00002230/// Claim a possibly-autoreleased return value at +0. This is only
2231/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002232/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002233/// the value is ignored, or when it is being assigned to an
2234/// __unsafe_unretained variable.
2235///
2236/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2237llvm::Value *
2238CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2239 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002240 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002241 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002242 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002243}
2244
John McCall31168b02011-06-15 23:02:42 +00002245/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002246/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002247void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2248 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002249 if (isa<llvm::ConstantPointerNull>(value)) return;
2250
James Y Knight9871db02019-02-05 16:42:33 +00002251 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002252 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002253 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2254 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002255 }
2256
2257 // Cast the argument to 'id'.
2258 value = Builder.CreateBitCast(value, Int8PtrTy);
2259
2260 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002261 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002262
John McCallcdda29c2013-03-13 03:10:54 +00002263 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002264 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002265 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002266 }
2267}
2268
John McCalle68b8f42012-10-17 02:28:37 +00002269/// Destroy a __strong variable.
2270///
2271/// At -O0, emit a call to store 'null' into the address;
2272/// instrumenting tools prefer this because the address is exposed,
2273/// but it's relatively cumbersome to optimize.
2274///
2275/// At -O1 and above, just load and call objc_release.
2276///
2277/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002278void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002279 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002280 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002281 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002282 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2283 return;
2284 }
2285
2286 llvm::Value *value = Builder.CreateLoad(addr);
2287 EmitARCRelease(value, precise);
2288}
2289
John McCall31168b02011-06-15 23:02:42 +00002290/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002291/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002292llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002293 llvm::Value *value,
2294 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002295 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002296
James Y Knight9871db02019-02-05 16:42:33 +00002297 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002298 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002299 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2300 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002301 }
2302
John McCall882987f2013-02-28 19:01:20 +00002303 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002304 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002305 Builder.CreateBitCast(value, Int8PtrTy)
2306 };
2307 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002308
Craig Topper8a13c412014-05-21 05:09:00 +00002309 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002310 return value;
2311}
2312
2313/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002314/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002315/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002316llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002317 llvm::Value *newValue,
2318 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002319 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002320 bool isBlock = type->isBlockPointerType();
2321
2322 // Use a store barrier at -O0 unless this is a block type or the
2323 // lvalue is inadequately aligned.
2324 if (shouldUseFusedARCCalls() &&
2325 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002326 (dst.getAlignment().isZero() ||
2327 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002328 return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
John McCall31168b02011-06-15 23:02:42 +00002329 }
2330
2331 // Otherwise, split it out.
2332
2333 // Retain the new value.
2334 newValue = EmitARCRetain(type, newValue);
2335
2336 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002337 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002338
2339 // Store. We do this before the release so that any deallocs won't
2340 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002341 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002342
2343 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002344 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002345
2346 return newValue;
2347}
2348
2349/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002350/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002351llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002352 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002353 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002354 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002355}
2356
2357/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002358/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002359llvm::Value *
2360CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002361 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002362 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002363 llvm::Intrinsic::objc_autoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002364 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002365}
2366
2367/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002368/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002369llvm::Value *
2370CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002371 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002372 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002373 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002374 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002375}
2376
2377/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002378/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002379/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002380/// %retain = call i8* \@objc_retainBlock(i8* %value)
2381/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002382llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2383 llvm::Value *value) {
2384 if (!type->isBlockPointerType())
2385 return EmitARCRetainAutoreleaseNonBlock(value);
2386
2387 if (isa<llvm::ConstantPointerNull>(value)) return value;
2388
Chris Lattner2192fe52011-07-18 04:24:23 +00002389 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002390 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002391 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002392 value = EmitARCAutorelease(value);
2393 return Builder.CreateBitCast(value, origType);
2394}
2395
2396/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002397/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002398llvm::Value *
2399CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002400 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002401 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002402 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002403}
2404
John McCallb04ecb72015-10-21 18:06:43 +00002405/// i8* \@objc_loadWeak(i8** %addr)
2406/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2407llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2408 return emitARCLoadOperation(*this, addr,
2409 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002410 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002411}
2412
James Dennett14c41ea2012-06-22 05:41:30 +00002413/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002414llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002415 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002416 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002417 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002418}
2419
James Dennett14c41ea2012-06-22 05:41:30 +00002420/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002421/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002422llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002423 llvm::Value *value,
2424 bool ignored) {
2425 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002426 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002427 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002428}
2429
James Dennett14c41ea2012-06-22 05:41:30 +00002430/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002431/// Returns %value. %addr is known to not have a current weak entry.
2432/// Essentially equivalent to:
2433/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002434void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002435 // If we're initializing to null, just write null to memory; no need
2436 // to get the runtime involved. But don't do this if optimization
2437 // is enabled, because accounting for this would make the optimizer
2438 // much more complicated.
2439 if (isa<llvm::ConstantPointerNull>(value) &&
2440 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2441 Builder.CreateStore(value, addr);
2442 return;
2443 }
2444
2445 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002446 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002447 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002448}
2449
James Dennett14c41ea2012-06-22 05:41:30 +00002450/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002451/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002452void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002453 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002454 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002455 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2456 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002457 }
2458
2459 // Cast the argument to 'id*'.
2460 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2461
John McCall7f416cc2015-09-08 08:05:57 +00002462 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002463}
2464
James Dennett14c41ea2012-06-22 05:41:30 +00002465/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002466/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2467/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002468void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002469 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002470 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002471 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002472}
2473
James Dennett14c41ea2012-06-22 05:41:30 +00002474/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002475/// Disregards the current value in %dest. Essentially
2476/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002477void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002478 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002479 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002480 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002481}
2482
Akira Hatanakad791e922018-03-19 17:38:40 +00002483void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2484 Address SrcAddr) {
2485 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2486 Object = EmitObjCConsumeObject(Ty, Object);
2487 EmitARCStoreWeak(DstAddr, Object, false);
2488}
2489
2490void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2491 Address SrcAddr) {
2492 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2493 Object = EmitObjCConsumeObject(Ty, Object);
2494 EmitARCStoreWeak(DstAddr, Object, false);
2495 EmitARCDestroyWeak(SrcAddr);
2496}
2497
John McCall31168b02011-06-15 23:02:42 +00002498/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002499/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002500llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002501 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002502 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002503 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2504 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002505 }
2506
John McCall882987f2013-02-28 19:01:20 +00002507 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002508}
2509
2510/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002511/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002512void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2513 assert(value->getType() == Int8PtrTy);
2514
Pete Cooper2cd35962018-12-18 20:33:00 +00002515 if (getInvokeDest()) {
2516 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002517 llvm::FunctionCallee &fn =
2518 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002519 if (!fn) {
2520 llvm::FunctionType *fnType =
2521 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2522 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2523 setARCRuntimeFunctionLinkage(CGM, fn);
2524 }
John McCall31168b02011-06-15 23:02:42 +00002525
Pete Cooper2cd35962018-12-18 20:33:00 +00002526 // objc_autoreleasePoolPop can throw.
2527 EmitRuntimeCallOrInvoke(fn, value);
2528 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002529 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002530 if (!fn) {
2531 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2532 setARCRuntimeFunctionLinkage(CGM, fn);
2533 }
2534
2535 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002536 }
John McCall31168b02011-06-15 23:02:42 +00002537}
2538
2539/// Produce the code to do an MRR version objc_autoreleasepool_push.
2540/// Which is: [[NSAutoreleasePool alloc] init];
2541/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2542/// init is declared as: - (id) init; in its NSObject super class.
2543///
2544llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2545 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002546 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002547 // [NSAutoreleasePool alloc]
2548 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2549 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2550 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002551 RValue AllocRV =
2552 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002553 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002554 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002555
2556 // [Receiver init]
2557 Receiver = AllocRV.getScalarVal();
2558 II = &CGM.getContext().Idents.get("init");
2559 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2560 RValue InitRV =
2561 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2562 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002563 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002564 return InitRV.getScalarVal();
2565}
2566
Pete Coopere3886802018-12-08 05:13:50 +00002567/// Allocate the given objc object.
2568/// call i8* \@objc_alloc(i8* %value)
2569llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2570 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002571 return emitObjCValueOperation(*this, value, resultType,
2572 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002573 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002574}
2575
2576/// Allocate the given objc object.
2577/// call i8* \@objc_allocWithZone(i8* %value)
2578llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2579 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002580 return emitObjCValueOperation(*this, value, resultType,
2581 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002582 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002583}
2584
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002585llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2586 llvm::Type *resultType) {
2587 return emitObjCValueOperation(*this, value, resultType,
2588 CGM.getObjCEntrypoints().objc_alloc_init,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002589 "objc_alloc_init");
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002590}
2591
John McCall31168b02011-06-15 23:02:42 +00002592/// Produce the code to do a primitive release.
2593/// [tmp drain];
2594void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2595 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2596 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2597 CallArgList Args;
2598 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002599 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002600}
2601
John McCall82fe67b2011-07-09 01:37:26 +00002602void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002603 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002604 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002605 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002606}
2607
2608void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002609 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002610 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002611 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002612}
2613
2614void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002615 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002616 QualType type) {
2617 CGF.EmitARCDestroyWeak(addr);
2618}
2619
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002620void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2621 QualType type) {
2622 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2623 CGF.EmitARCIntrinsicUse(value);
2624}
2625
Pete Coopere5b64ea2018-12-21 21:00:32 +00002626/// Autorelease the given object.
2627/// call i8* \@objc_autorelease(i8* %value)
2628llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2629 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002630 return emitObjCValueOperation(
2631 *this, value, returnType,
2632 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002633 "objc_autorelease");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002634}
2635
2636/// Retain the given object, with normal retain semantics.
2637/// call i8* \@objc_retain(i8* %value)
2638llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2639 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002640 return emitObjCValueOperation(
2641 *this, value, returnType,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002642 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002643}
2644
2645/// Release the given object.
2646/// call void \@objc_release(i8* %value)
2647void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2648 ARCPreciseLifetime_t precise) {
2649 if (isa<llvm::ConstantPointerNull>(value)) return;
2650
James Y Knight9871db02019-02-05 16:42:33 +00002651 llvm::FunctionCallee &fn =
2652 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002653 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002654 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002655 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002656 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2657 setARCRuntimeFunctionLinkage(CGM, fn);
2658 // We have Native ARC, so set nonlazybind attribute for performance
2659 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2660 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002661 }
2662
2663 // Cast the argument to 'id'.
2664 value = Builder.CreateBitCast(value, Int8PtrTy);
2665
2666 // Call objc_release.
Akira Hatanaka34d28cf2019-05-10 21:54:16 +00002667 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002668
2669 if (precise == ARCImpreciseLifetime) {
2670 call->setMetadata("clang.imprecise_release",
2671 llvm::MDNode::get(Builder.getContext(), None));
2672 }
2673}
2674
John McCall31168b02011-06-15 23:02:42 +00002675namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002676 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002677 llvm::Value *Token;
2678
2679 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2680
Craig Topper4f12f102014-03-12 06:41:41 +00002681 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002682 CGF.EmitObjCAutoreleasePoolPop(Token);
2683 }
2684 };
David Blaikie7e70d682015-08-18 22:40:54 +00002685 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002686 llvm::Value *Token;
2687
2688 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2689
Craig Topper4f12f102014-03-12 06:41:41 +00002690 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002691 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2692 }
2693 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002694}
John McCall31168b02011-06-15 23:02:42 +00002695
2696void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002697 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002698 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2699 else
2700 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2701}
2702
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002703static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2704 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002705 case Qualifiers::OCL_None:
2706 case Qualifiers::OCL_ExplicitNone:
2707 case Qualifiers::OCL_Strong:
2708 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002709 return true;
John McCall31168b02011-06-15 23:02:42 +00002710
2711 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002712 return false;
John McCall31168b02011-06-15 23:02:42 +00002713 }
2714
2715 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002716}
2717
2718static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002719 LValue lvalue,
2720 QualType type) {
2721 llvm::Value *result;
2722 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2723 if (shouldRetain) {
2724 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2725 } else {
2726 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002727 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002728 }
2729 return TryEmitResult(result, !shouldRetain);
2730}
2731
2732static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002733 const Expr *e) {
2734 e = e->IgnoreParens();
2735 QualType type = e->getType();
2736
Fangrui Song6907ce22018-07-30 19:24:48 +00002737 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002738 // an extra retain/release pair by zeroing out the source of this
2739 // "move" operation.
2740 if (e->isXValue() &&
2741 !type.isConstQualified() &&
2742 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2743 // Emit the lvalue.
2744 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002745
John McCall154a2fd2011-08-30 00:57:29 +00002746 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002747 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2748 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002749
John McCall154a2fd2011-08-30 00:57:29 +00002750 // Set the source pointer to NULL.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002751 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002752
John McCall154a2fd2011-08-30 00:57:29 +00002753 return TryEmitResult(result, true);
2754 }
2755
John McCall31168b02011-06-15 23:02:42 +00002756 // As a very special optimization, in ARC++, if the l-value is the
2757 // result of a non-volatile assignment, do a simple retain of the
2758 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002759 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002760 !type.isVolatileQualified() &&
2761 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2762 isa<BinaryOperator>(e) &&
2763 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2764 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2765
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002766 // Try to emit code for scalar constant instead of emitting LValue and
2767 // loading it because we are not guaranteed to have an l-value. One of such
2768 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2769 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2770 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2771 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2772 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2773 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2774 }
2775
John McCall31168b02011-06-15 23:02:42 +00002776 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2777}
2778
John McCalle399e5b2016-01-27 18:32:30 +00002779typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2780 llvm::Value *value)>
2781 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002782
John McCalle399e5b2016-01-27 18:32:30 +00002783/// Insert code immediately after a call.
2784static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2785 llvm::Value *value,
2786 ValueTransform doAfterCall,
2787 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002788 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2789 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2790
2791 // Place the retain immediately following the call.
2792 CGF.Builder.SetInsertPoint(call->getParent(),
2793 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002794 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002795
2796 CGF.Builder.restoreIP(ip);
2797 return value;
2798 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2799 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2800
2801 // Place the retain at the beginning of the normal destination block.
2802 llvm::BasicBlock *BB = invoke->getNormalDest();
2803 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002804 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002805
2806 CGF.Builder.restoreIP(ip);
2807 return value;
2808
2809 // Bitcasts can arise because of related-result returns. Rewrite
2810 // the operand.
2811 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2812 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002813 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002814 bitcast->setOperand(0, operand);
2815 return bitcast;
2816
2817 // Generic fall-back case.
2818 } else {
2819 // Retain using the non-block variant: we never need to do a copy
2820 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002821 return doFallback(CGF, value);
2822 }
2823}
2824
2825/// Given that the given expression is some sort of call (which does
2826/// not return retained), emit a retain following it.
2827static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2828 const Expr *e) {
2829 llvm::Value *value = CGF.EmitScalarExpr(e);
2830 return emitARCOperationAfterCall(CGF, value,
2831 [](CodeGenFunction &CGF, llvm::Value *value) {
2832 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2833 },
2834 [](CodeGenFunction &CGF, llvm::Value *value) {
2835 return CGF.EmitARCRetainNonBlock(value);
2836 });
2837}
2838
2839/// Given that the given expression is some sort of call (which does
2840/// not return retained), perform an unsafeClaim following it.
2841static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2842 const Expr *e) {
2843 llvm::Value *value = CGF.EmitScalarExpr(e);
2844 return emitARCOperationAfterCall(CGF, value,
2845 [](CodeGenFunction &CGF, llvm::Value *value) {
2846 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2847 },
2848 [](CodeGenFunction &CGF, llvm::Value *value) {
2849 return value;
2850 });
2851}
2852
2853llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2854 bool allowUnsafeClaim) {
2855 if (allowUnsafeClaim &&
2856 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2857 return emitARCUnsafeClaimCallResult(*this, E);
2858 } else {
2859 llvm::Value *value = emitARCRetainCallResult(*this, E);
2860 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002861 }
2862}
2863
John McCallcd78e802011-09-10 01:16:55 +00002864/// Determine whether it might be important to emit a separate
2865/// objc_retain_block on the result of the given expression, or
2866/// whether it's okay to just emit it in a +1 context.
2867static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2868 assert(e->getType()->isBlockPointerType());
2869 e = e->IgnoreParens();
2870
2871 // For future goodness, emit block expressions directly in +1
2872 // contexts if we can.
2873 if (isa<BlockExpr>(e))
2874 return false;
2875
2876 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2877 switch (cast->getCastKind()) {
2878 // Emitting these operations in +1 contexts is goodness.
2879 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002880 case CK_ARCReclaimReturnedObject:
2881 case CK_ARCConsumeObject:
2882 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002883 return false;
2884
2885 // These operations preserve a block type.
2886 case CK_NoOp:
2887 case CK_BitCast:
2888 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2889
2890 // These operations are known to be bad (or haven't been considered).
2891 case CK_AnyPointerToBlockPointerCast:
2892 default:
2893 return true;
2894 }
2895 }
2896
2897 return true;
2898}
2899
John McCalle399e5b2016-01-27 18:32:30 +00002900namespace {
2901/// A CRTP base class for emitting expressions of retainable object
2902/// pointer type in ARC.
2903template <typename Impl, typename Result> class ARCExprEmitter {
2904protected:
2905 CodeGenFunction &CGF;
2906 Impl &asImpl() { return *static_cast<Impl*>(this); }
2907
2908 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2909
2910public:
2911 Result visit(const Expr *e);
2912 Result visitCastExpr(const CastExpr *e);
2913 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002914 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002915 Result visitBinaryOperator(const BinaryOperator *e);
2916 Result visitBinAssign(const BinaryOperator *e);
2917 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2918 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2919 Result visitBinAssignWeak(const BinaryOperator *e);
2920 Result visitBinAssignStrong(const BinaryOperator *e);
2921
2922 // Minimal implementation:
2923 // Result visitLValueToRValue(const Expr *e)
2924 // Result visitConsumeObject(const Expr *e)
2925 // Result visitExtendBlockObject(const Expr *e)
2926 // Result visitReclaimReturnedObject(const Expr *e)
2927 // Result visitCall(const Expr *e)
2928 // Result visitExpr(const Expr *e)
2929 //
2930 // Result emitBitCast(Result result, llvm::Type *resultType)
2931 // llvm::Value *getValueOfResult(Result result)
2932};
2933}
2934
2935/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002936///
2937/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002938template <typename Impl, typename Result>
2939Result
2940ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002941 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002942
2943 // Find the result expression.
2944 const Expr *resultExpr = E->getResultExpr();
2945 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002946 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002947
2948 for (PseudoObjectExpr::const_semantics_iterator
2949 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2950 const Expr *semantic = *i;
2951
2952 // If this semantic expression is an opaque value, bind it
2953 // to the result of its source expression.
2954 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2955 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2956 OVMA opaqueData;
2957
2958 // If this semantic is the result of the pseudo-object
2959 // expression, try to evaluate the source as +1.
2960 if (ov == resultExpr) {
2961 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002962 result = asImpl().visit(ov->getSourceExpr());
2963 opaqueData = OVMA::bind(CGF, ov,
2964 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002965
2966 // Otherwise, just bind it.
2967 } else {
2968 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2969 }
2970 opaques.push_back(opaqueData);
2971
2972 // Otherwise, if the expression is the result, evaluate it
2973 // and remember the result.
2974 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002975 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002976
2977 // Otherwise, evaluate the expression in an ignored context.
2978 } else {
2979 CGF.EmitIgnoredExpr(semantic);
2980 }
2981 }
2982
2983 // Unbind all the opaques now.
2984 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2985 opaques[i].unbind(CGF);
2986
2987 return result;
2988}
2989
John McCalle399e5b2016-01-27 18:32:30 +00002990template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002991Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2992 // The default implementation just forwards the expression to visitExpr.
2993 return asImpl().visitExpr(e);
2994}
2995
2996template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00002997Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2998 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002999
John McCalle399e5b2016-01-27 18:32:30 +00003000 // No-op casts don't change the type, so we just ignore them.
3001 case CK_NoOp:
3002 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00003003
John McCalle399e5b2016-01-27 18:32:30 +00003004 // These casts can change the type.
3005 case CK_CPointerToObjCPointerCast:
3006 case CK_BlockPointerToObjCPointerCast:
3007 case CK_AnyPointerToBlockPointerCast:
3008 case CK_BitCast: {
3009 llvm::Type *resultType = CGF.ConvertType(e->getType());
3010 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3011 Result result = asImpl().visit(e->getSubExpr());
3012 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00003013 }
3014
John McCalle399e5b2016-01-27 18:32:30 +00003015 // Handle some casts specially.
3016 case CK_LValueToRValue:
3017 return asImpl().visitLValueToRValue(e->getSubExpr());
3018 case CK_ARCConsumeObject:
3019 return asImpl().visitConsumeObject(e->getSubExpr());
3020 case CK_ARCExtendBlockObject:
3021 return asImpl().visitExtendBlockObject(e->getSubExpr());
3022 case CK_ARCReclaimReturnedObject:
3023 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3024
3025 // Otherwise, use the default logic.
3026 default:
3027 return asImpl().visitExpr(e);
3028 }
3029}
3030
3031template <typename Impl, typename Result>
3032Result
3033ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3034 switch (e->getOpcode()) {
3035 case BO_Comma:
3036 CGF.EmitIgnoredExpr(e->getLHS());
3037 CGF.EnsureInsertPoint();
3038 return asImpl().visit(e->getRHS());
3039
3040 case BO_Assign:
3041 return asImpl().visitBinAssign(e);
3042
3043 default:
3044 return asImpl().visitExpr(e);
3045 }
3046}
3047
3048template <typename Impl, typename Result>
3049Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3050 switch (e->getLHS()->getType().getObjCLifetime()) {
3051 case Qualifiers::OCL_ExplicitNone:
3052 return asImpl().visitBinAssignUnsafeUnretained(e);
3053
3054 case Qualifiers::OCL_Weak:
3055 return asImpl().visitBinAssignWeak(e);
3056
3057 case Qualifiers::OCL_Autoreleasing:
3058 return asImpl().visitBinAssignAutoreleasing(e);
3059
3060 case Qualifiers::OCL_Strong:
3061 return asImpl().visitBinAssignStrong(e);
3062
3063 case Qualifiers::OCL_None:
3064 return asImpl().visitExpr(e);
3065 }
3066 llvm_unreachable("bad ObjC ownership qualifier");
3067}
3068
3069/// The default rule for __unsafe_unretained emits the RHS recursively,
3070/// stores into the unsafe variable, and propagates the result outward.
3071template <typename Impl, typename Result>
3072Result ARCExprEmitter<Impl,Result>::
3073 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3074 // Recursively emit the RHS.
3075 // For __block safety, do this before emitting the LHS.
3076 Result result = asImpl().visit(e->getRHS());
3077
3078 // Perform the store.
3079 LValue lvalue =
3080 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3081 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3082 lvalue);
3083
3084 return result;
3085}
3086
3087template <typename Impl, typename Result>
3088Result
3089ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3090 return asImpl().visitExpr(e);
3091}
3092
3093template <typename Impl, typename Result>
3094Result
3095ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3096 return asImpl().visitExpr(e);
3097}
3098
3099template <typename Impl, typename Result>
3100Result
3101ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3102 return asImpl().visitExpr(e);
3103}
3104
3105/// The general expression-emission logic.
3106template <typename Impl, typename Result>
3107Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3108 // We should *never* see a nested full-expression here, because if
3109 // we fail to emit at +1, our caller must not retain after we close
3110 // out the full-expression. This isn't as important in the unsafe
3111 // emitter.
3112 assert(!isa<ExprWithCleanups>(e));
3113
3114 // Look through parens, __extension__, generic selection, etc.
3115 e = e->IgnoreParens();
3116
3117 // Handle certain kinds of casts.
3118 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3119 return asImpl().visitCastExpr(ce);
3120
3121 // Handle the comma operator.
3122 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3123 return asImpl().visitBinaryOperator(op);
3124
3125 // TODO: handle conditional operators here
3126
3127 // For calls and message sends, use the retained-call logic.
3128 // Delegate inits are a special case in that they're the only
3129 // returns-retained expression that *isn't* surrounded by
3130 // a consume.
3131 } else if (isa<CallExpr>(e) ||
3132 (isa<ObjCMessageExpr>(e) &&
3133 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3134 return asImpl().visitCall(e);
3135
3136 // Look through pseudo-object expressions.
3137 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3138 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003139 } else if (auto *be = dyn_cast<BlockExpr>(e))
3140 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003141
3142 return asImpl().visitExpr(e);
3143}
3144
3145namespace {
3146
3147/// An emitter for +1 results.
3148struct ARCRetainExprEmitter :
3149 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3150
3151 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3152
3153 llvm::Value *getValueOfResult(TryEmitResult result) {
3154 return result.getPointer();
3155 }
3156
3157 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3158 llvm::Value *value = result.getPointer();
3159 value = CGF.Builder.CreateBitCast(value, resultType);
3160 result.setPointer(value);
3161 return result;
3162 }
3163
3164 TryEmitResult visitLValueToRValue(const Expr *e) {
3165 return tryEmitARCRetainLoadOfScalar(CGF, e);
3166 }
3167
3168 /// For consumptions, just emit the subexpression and thus elide
3169 /// the retain/release pair.
3170 TryEmitResult visitConsumeObject(const Expr *e) {
3171 llvm::Value *result = CGF.EmitScalarExpr(e);
3172 return TryEmitResult(result, true);
3173 }
3174
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003175 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3176 TryEmitResult result = visitExpr(e);
3177 // Avoid the block-retain if this is a block literal that doesn't need to be
3178 // copied to the heap.
3179 if (e->getBlockDecl()->canAvoidCopyToHeap())
3180 result.setInt(true);
3181 return result;
3182 }
3183
John McCalle399e5b2016-01-27 18:32:30 +00003184 /// Block extends are net +0. Naively, we could just recurse on
3185 /// the subexpression, but actually we need to ensure that the
3186 /// value is copied as a block, so there's a little filter here.
3187 TryEmitResult visitExtendBlockObject(const Expr *e) {
3188 llvm::Value *result; // will be a +0 value
3189
3190 // If we can't safely assume the sub-expression will produce a
3191 // block-copied value, emit the sub-expression at +0.
3192 if (shouldEmitSeparateBlockRetain(e)) {
3193 result = CGF.EmitScalarExpr(e);
3194
3195 // Otherwise, try to emit the sub-expression at +1 recursively.
3196 } else {
3197 TryEmitResult subresult = asImpl().visit(e);
3198
3199 // If that produced a retained value, just use that.
3200 if (subresult.getInt()) {
3201 return subresult;
3202 }
3203
3204 // Otherwise it's +0.
3205 result = subresult.getPointer();
3206 }
3207
3208 // Retain the object as a block.
3209 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3210 return TryEmitResult(result, true);
3211 }
3212
3213 /// For reclaims, emit the subexpression as a retained call and
3214 /// skip the consumption.
3215 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3216 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3217 return TryEmitResult(result, true);
3218 }
3219
3220 /// When we have an undecorated call, retroactively do a claim.
3221 TryEmitResult visitCall(const Expr *e) {
3222 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3223 return TryEmitResult(result, true);
3224 }
3225
3226 // TODO: maybe special-case visitBinAssignWeak?
3227
3228 TryEmitResult visitExpr(const Expr *e) {
3229 // We didn't find an obvious production, so emit what we've got and
3230 // tell the caller that we didn't manage to retain.
3231 llvm::Value *result = CGF.EmitScalarExpr(e);
3232 return TryEmitResult(result, false);
3233 }
3234};
3235}
3236
3237static TryEmitResult
3238tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3239 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003240}
3241
3242static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3243 LValue lvalue,
3244 QualType type) {
3245 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3246 llvm::Value *value = result.getPointer();
3247 if (!result.getInt())
3248 value = CGF.EmitARCRetain(type, value);
3249 return value;
3250}
3251
3252/// EmitARCRetainScalarExpr - Semantically equivalent to
3253/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3254/// best-effort attempt to peephole expressions that naturally produce
3255/// retained objects.
3256llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003257 // The retain needs to happen within the full-expression.
3258 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCalld21cdd42013-02-12 00:25:08 +00003259 RunCleanupsScope scope(*this);
3260 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3261 }
3262
John McCall31168b02011-06-15 23:02:42 +00003263 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3264 llvm::Value *value = result.getPointer();
3265 if (!result.getInt())
3266 value = EmitARCRetain(e->getType(), value);
3267 return value;
3268}
3269
3270llvm::Value *
3271CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003272 // The retain needs to happen within the full-expression.
3273 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCalld21cdd42013-02-12 00:25:08 +00003274 RunCleanupsScope scope(*this);
3275 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3276 }
3277
John McCall31168b02011-06-15 23:02:42 +00003278 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3279 llvm::Value *value = result.getPointer();
3280 if (result.getInt())
3281 value = EmitARCAutorelease(value);
3282 else
3283 value = EmitARCRetainAutorelease(e->getType(), value);
3284 return value;
3285}
3286
John McCallff613032011-10-04 06:23:45 +00003287llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3288 llvm::Value *result;
3289 bool doRetain;
3290
3291 if (shouldEmitSeparateBlockRetain(e)) {
3292 result = EmitScalarExpr(e);
3293 doRetain = true;
3294 } else {
3295 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3296 result = subresult.getPointer();
3297 doRetain = !subresult.getInt();
3298 }
3299
3300 if (doRetain)
3301 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3302 return EmitObjCConsumeObject(e->getType(), result);
3303}
3304
John McCall248512a2011-10-01 10:32:24 +00003305llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3306 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003307 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003308 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003309 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003310 return EmitARCRetainAutoreleaseScalarExpr(expr);
3311 }
3312
3313 // Otherwise, use the normal scalar-expression emission. The
3314 // exception machinery doesn't do anything special with the
3315 // exception like retaining it, so there's no safety associated with
3316 // only running cleanups after the throw has started, and when it
3317 // matters it tends to be substantially inferior code.
3318 return EmitScalarExpr(expr);
3319}
3320
John McCalle399e5b2016-01-27 18:32:30 +00003321namespace {
3322
3323/// An emitter for assigning into an __unsafe_unretained context.
3324struct ARCUnsafeUnretainedExprEmitter :
3325 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3326
3327 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3328
3329 llvm::Value *getValueOfResult(llvm::Value *value) {
3330 return value;
3331 }
3332
3333 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3334 return CGF.Builder.CreateBitCast(value, resultType);
3335 }
3336
3337 llvm::Value *visitLValueToRValue(const Expr *e) {
3338 return CGF.EmitScalarExpr(e);
3339 }
3340
3341 /// For consumptions, just emit the subexpression and perform the
3342 /// consumption like normal.
3343 llvm::Value *visitConsumeObject(const Expr *e) {
3344 llvm::Value *value = CGF.EmitScalarExpr(e);
3345 return CGF.EmitObjCConsumeObject(e->getType(), value);
3346 }
3347
3348 /// No special logic for block extensions. (This probably can't
3349 /// actually happen in this emitter, though.)
3350 llvm::Value *visitExtendBlockObject(const Expr *e) {
3351 return CGF.EmitARCExtendBlockObject(e);
3352 }
3353
3354 /// For reclaims, perform an unsafeClaim if that's enabled.
3355 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3356 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3357 }
3358
3359 /// When we have an undecorated call, just emit it without adding
3360 /// the unsafeClaim.
3361 llvm::Value *visitCall(const Expr *e) {
3362 return CGF.EmitScalarExpr(e);
3363 }
3364
3365 /// Just do normal scalar emission in the default case.
3366 llvm::Value *visitExpr(const Expr *e) {
3367 return CGF.EmitScalarExpr(e);
3368 }
3369};
3370}
3371
3372static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3373 const Expr *e) {
3374 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3375}
3376
3377/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3378/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3379/// avoiding any spurious retains, including by performing reclaims
3380/// with objc_unsafeClaimAutoreleasedReturnValue.
3381llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3382 // Look through full-expressions.
3383 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCalle399e5b2016-01-27 18:32:30 +00003384 RunCleanupsScope scope(*this);
3385 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3386 }
3387
3388 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3389}
3390
3391std::pair<LValue,llvm::Value*>
3392CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3393 bool ignored) {
3394 // Evaluate the RHS first. If we're ignoring the result, assume
3395 // that we can emit at an unsafe +0.
3396 llvm::Value *value;
3397 if (ignored) {
3398 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3399 } else {
3400 value = EmitScalarExpr(e->getRHS());
3401 }
3402
3403 // Emit the LHS and perform the store.
3404 LValue lvalue = EmitLValue(e->getLHS());
3405 EmitStoreOfScalar(value, lvalue);
3406
3407 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3408}
3409
John McCall31168b02011-06-15 23:02:42 +00003410std::pair<LValue,llvm::Value*>
3411CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3412 bool ignored) {
3413 // Evaluate the RHS first.
3414 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3415 llvm::Value *value = result.getPointer();
3416
John McCallb726a552011-07-28 07:23:35 +00003417 bool hasImmediateRetain = result.getInt();
3418
3419 // If we didn't emit a retained object, and the l-value is of block
3420 // type, then we need to emit the block-retain immediately in case
3421 // it invalidates the l-value.
3422 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003423 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003424 hasImmediateRetain = true;
3425 }
3426
John McCall31168b02011-06-15 23:02:42 +00003427 LValue lvalue = EmitLValue(e->getLHS());
3428
3429 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003430 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003431 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003432 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003433 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003434 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003435 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003436 }
3437
3438 return std::pair<LValue,llvm::Value*>(lvalue, value);
3439}
3440
3441std::pair<LValue,llvm::Value*>
3442CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3443 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3444 LValue lvalue = EmitLValue(e->getLHS());
3445
Eli Friedmana0544d62011-12-03 04:14:32 +00003446 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003447
3448 return std::pair<LValue,llvm::Value*>(lvalue, value);
3449}
3450
3451void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003452 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003453 const Stmt *subStmt = ARPS.getSubStmt();
3454 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3455
3456 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003457 if (DI)
3458 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003459
3460 // Keep track of the current cleanup stack depth.
3461 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003462 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003463 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3464 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3465 } else {
3466 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3467 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3468 }
3469
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003470 for (const auto *I : S.body())
3471 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003472
Eric Christopher7cdf9482011-10-13 21:45:18 +00003473 if (DI)
3474 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003475}
John McCall1bd25562011-06-24 23:21:27 +00003476
3477/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3478/// make sure it survives garbage collection until this point.
3479void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3480 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003481 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003482 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003483 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3484 /* assembly */ "",
3485 /* constraints */ "r",
3486 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003487
3488 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003489 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003490}
3491
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003492/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003493/// non-trivial copy assignment function, produce following helper function.
3494/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3495///
3496llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003497CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3498 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003499 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003500 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003501 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003502 QualType Ty = PID->getPropertyIvarDecl()->getType();
3503 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003504 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003505 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04003506 if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003507 return nullptr;
3508 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003509 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003510 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003511 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3512 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3513 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003514
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003515 ASTContext &C = getContext();
3516 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003517 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003518
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003519 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003520 QualType DestTy = C.getPointerType(Ty);
3521 QualType SrcTy = Ty;
3522 SrcTy.addConst();
3523 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003524
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003525 SmallVector<QualType, 2> ArgTys;
3526 ArgTys.push_back(DestTy);
3527 ArgTys.push_back(SrcTy);
3528 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3529
3530 FunctionDecl *FD = FunctionDecl::Create(
3531 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3532 FunctionTy, nullptr, SC_Static, false, false);
3533
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003534 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003535 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3536 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003537 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003538 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3539 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003540 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003541
John McCallc56a8b32016-03-11 04:30:31 +00003542 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003543 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003544
John McCalla729c622012-02-17 03:33:10 +00003545 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003546
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003547 llvm::Function *Fn =
3548 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003549 "__assign_helper_atomic_property_",
3550 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003551
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003552 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003553
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003554 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003555
Melanie Blowerf5360d42020-05-01 10:32:06 -07003556 DeclRefExpr DstExpr(C, &DstDecl, false, DestTy, VK_RValue, SourceLocation());
3557 UnaryOperator *DST = UnaryOperator::Create(
3558 C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
3559 SourceLocation(), false, FPOptions(C.getLangOpts()));
Fangrui Song6907ce22018-07-30 19:24:48 +00003560
Melanie Blowerf5360d42020-05-01 10:32:06 -07003561 DeclRefExpr SrcExpr(C, &SrcDecl, false, SrcTy, VK_RValue, SourceLocation());
3562 UnaryOperator *SRC = UnaryOperator::Create(
3563 C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3564 SourceLocation(), false, FPOptions(C.getLangOpts()));
Fangrui Song6907ce22018-07-30 19:24:48 +00003565
Melanie Blowerf5360d42020-05-01 10:32:06 -07003566 Expr *Args[2] = {DST, SRC};
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003567 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003568 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3569 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07003570 VK_LValue, SourceLocation(), FPOptions(C.getLangOpts()));
Fangrui Song6907ce22018-07-30 19:24:48 +00003571
Bruno Riccic5885cf2018-12-21 15:20:32 +00003572 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003573
3574 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003575 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003576 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003577 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003578}
3579
3580llvm::Constant *
3581CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3582 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003583 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003584 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003585 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003586 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3587 QualType Ty = PD->getType();
3588 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003589 return nullptr;
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04003590 if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003591 return nullptr;
3592 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003593 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003594 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003595 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3596 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3597 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003598
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003599 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003600 IdentifierInfo *II =
3601 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003602
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003603 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003604 QualType DestTy = C.getPointerType(Ty);
3605 QualType SrcTy = Ty;
3606 SrcTy.addConst();
3607 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003608
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003609 SmallVector<QualType, 2> ArgTys;
3610 ArgTys.push_back(DestTy);
3611 ArgTys.push_back(SrcTy);
3612 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3613
3614 FunctionDecl *FD = FunctionDecl::Create(
3615 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3616 FunctionTy, nullptr, SC_Static, false, false);
3617
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003618 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003619 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3620 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003621 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003622 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3623 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003624 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003625
John McCallc56a8b32016-03-11 04:30:31 +00003626 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003627 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003628
John McCalla729c622012-02-17 03:33:10 +00003629 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003630
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003631 llvm::Function *Fn = llvm::Function::Create(
3632 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3633 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003634
3635 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003636
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003637 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003638
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003639 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3640 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003641
Melanie Blowerf5360d42020-05-01 10:32:06 -07003642 UnaryOperator *SRC = UnaryOperator::Create(
3643 C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3644 SourceLocation(), false, FPOptions(C.getLangOpts()));
Fangrui Song6907ce22018-07-30 19:24:48 +00003645
3646 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003647 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003648
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003649 SmallVector<Expr*, 4> ConstructorArgs;
Melanie Blowerf5360d42020-05-01 10:32:06 -07003650 ConstructorArgs.push_back(SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003651 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3652 CXXConstExpr->arg_end());
3653
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003654 CXXConstructExpr *TheCXXConstructExpr =
3655 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3656 CXXConstExpr->getConstructor(),
3657 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003658 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003659 CXXConstExpr->hadMultipleCandidates(),
3660 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003661 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003662 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003663 CXXConstExpr->getConstructionKind(),
3664 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003665
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003666 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3667 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003668
John McCall113bee02012-03-10 09:33:50 +00003669 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003670 CharUnits Alignment
3671 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003672 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003673 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3674 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003675 AggValueSlot::IsDestructed,
3676 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003677 AggValueSlot::IsNotAliased,
3678 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003679
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003680 FinishFunction();
3681 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3682 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3683 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003684}
3685
Eli Friedmanec75fec2012-02-28 01:08:45 +00003686llvm::Value *
3687CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3688 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003689 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3690 Selector CopySelector =
3691 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003692 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3693 Selector AutoreleaseSelector =
3694 getContext().Selectors.getNullarySelector(AutoreleaseID);
3695
3696 // Emit calls to retain/autorelease.
3697 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3698 llvm::Value *Val = Block;
3699 RValue Result;
3700 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003701 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003702 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003703 Val = Result.getScalarVal();
3704 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3705 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003706 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003707 Val = Result.getScalarVal();
3708 return Val;
3709}
3710
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003711llvm::Value *
3712CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3713 assert(Args.size() == 3 && "Expected 3 argument here!");
3714
3715 if (!CGM.IsOSVersionAtLeastFn) {
3716 llvm::FunctionType *FTy =
3717 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3718 CGM.IsOSVersionAtLeastFn =
3719 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3720 }
3721
3722 llvm::Value *CallRes =
3723 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3724
3725 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3726}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003727
Alex Lorenza8fbef42017-03-23 11:14:27 +00003728void CodeGenModule::emitAtAvailableLinkGuard() {
3729 if (!IsOSVersionAtLeastFn)
3730 return;
3731 // @available requires CoreFoundation only on Darwin.
3732 if (!Target.getTriple().isOSDarwin())
3733 return;
3734 // Add -framework CoreFoundation to the linker commands. We still want to
3735 // emit the core foundation reference down below because otherwise if
3736 // CoreFoundation is not used in the code, the linker won't link the
3737 // framework.
3738 auto &Context = getLLVMContext();
3739 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3740 llvm::MDString::get(Context, "CoreFoundation")};
3741 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3742 // Emit a reference to a symbol from CoreFoundation to ensure that
3743 // CoreFoundation is linked into the final binary.
3744 llvm::FunctionType *FTy =
3745 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003746 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003747 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3748
3749 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003750 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3751 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003752 llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00003753 llvm::Function *CFLinkCheckFunc =
3754 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3755 if (CFLinkCheckFunc->empty()) {
3756 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3757 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3758 CodeGenFunction CGF(*this);
3759 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3760 CGF.EmitNounwindRuntimeCall(CFFunc,
3761 llvm::Constant::getNullValue(VoidPtrTy));
3762 CGF.Builder.CreateUnreachable();
3763 addCompilerUsedGlobal(CFLinkCheckFunc);
3764 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003765}
3766
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003767CGObjCRuntime::~CGObjCRuntime() {}