blob: cd2b84f5dd20327366ae0d784444b572027d4f2b [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,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07001496 OK_Ordinary, SourceLocation(), FPOptionsOverride());
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07001497 EmitStmt(assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001498}
1499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001500/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001501///
1502/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001503/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001504void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1505 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001506 llvm::Constant *AtomicHelperFn =
1507 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -08001508 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001509 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001510 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001511
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001512 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001513
Adrian Prantlce7d3592019-12-05 12:26:16 -08001514 FinishFunction(OMD->getEndLoc());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001515}
1516
John McCall6a4fa522011-03-22 07:05:39 +00001517namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001518 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001519 private:
1520 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001521 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001522 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001523 bool useEHCleanupForArray;
1524 public:
1525 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1526 CodeGenFunction::Destroyer *destroyer,
1527 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001528 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001529 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001530
Craig Topper4f12f102014-03-12 06:41:41 +00001531 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001532 LValue lvalue
1533 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001534 CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001535 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001536 }
1537 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001538}
John McCall6a4fa522011-03-22 07:05:39 +00001539
John McCall4bd0fb12011-07-12 16:41:08 +00001540/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1541static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001542 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001543 QualType type) {
1544 llvm::Value *null = getNullForVariable(addr);
1545 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1546}
John McCall31168b02011-06-15 23:02:42 +00001547
John McCall6a4fa522011-03-22 07:05:39 +00001548static void emitCXXDestructMethod(CodeGenFunction &CGF,
1549 ObjCImplementationDecl *impl) {
1550 CodeGenFunction::RunCleanupsScope scope(CGF);
1551
1552 llvm::Value *self = CGF.LoadObjCSelf();
1553
Jordy Rosea91768e2011-07-22 02:08:32 +00001554 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1555 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001556 ivar; ivar = ivar->getNextIvar()) {
1557 QualType type = ivar->getType();
1558
John McCall6a4fa522011-03-22 07:05:39 +00001559 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001560 QualType::DestructionKind dtorKind = type.isDestructedType();
1561 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001562
Craig Topper8a13c412014-05-21 05:09:00 +00001563 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001564
John McCall4bd0fb12011-07-12 16:41:08 +00001565 // Use a call to objc_storeStrong to destroy strong ivars, for the
1566 // general benefit of the tools.
1567 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001568 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001569
John McCall4bd0fb12011-07-12 16:41:08 +00001570 // Otherwise use the default for the destruction kind.
1571 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001572 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001573 }
John McCall4bd0fb12011-07-12 16:41:08 +00001574
1575 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1576
1577 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1578 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001579 }
1580
1581 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1582}
1583
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001584void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1585 ObjCMethodDecl *MD,
1586 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001587 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001588 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001589
1590 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001591 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001592 // Suppress the final autorelease in ARC.
1593 AutoreleaseResult = false;
1594
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001595 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001596 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001597 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001598 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001599 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001600 EmitAggExpr(IvarInit->getInit(),
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001601 AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001602 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001603 AggValueSlot::IsNotAliased,
1604 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001605 }
1606 // constructor returns 'self'.
1607 CodeGenTypes &Types = CGM.getTypes();
1608 QualType IdTy(CGM.getContext().getObjCIdType());
1609 llvm::Value *SelfAsId =
1610 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1611 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001612
1613 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001614 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001615 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001616 }
1617 FinishFunction();
1618}
1619
Daniel Dunbara08dff12008-09-24 04:04:31 +00001620llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001621 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001622 DeclRefExpr DRE(getContext(), Self,
1623 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001624 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001625 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001626}
1627
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001628QualType CodeGenFunction::TypeOfSelfObject() {
1629 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1630 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001631 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1632 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001633 return PTy->getPointeeType();
1634}
1635
Chris Lattnerd4808922009-03-22 21:03:39 +00001636void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001637 llvm::FunctionCallee EnumerationMutationFnPtr =
1638 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001639 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001640 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1641 return;
1642 }
John McCallb92ab1a2016-10-26 23:46:34 +00001643 CGCallee EnumerationMutationFn =
1644 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001645
Devang Pateld2d66652011-01-19 01:36:36 +00001646 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001647 if (DI)
1648 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001649
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001650 RunCleanupsScope ForScope(*this);
1651
Kuba Mracek82c21752017-04-14 01:00:03 +00001652 // The local variable comes into scope immediately.
1653 AutoVarEmission variable = AutoVarEmission::invalid();
1654 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1655 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1656
John McCall1c926b72011-01-07 01:49:06 +00001657 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001658
Anders Carlsson75658592008-08-31 02:33:12 +00001659 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001660 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001661 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001662 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001663
Anders Carlsson75658592008-08-31 02:33:12 +00001664 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001665 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001666
John McCall1c926b72011-01-07 01:49:06 +00001667 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001668 IdentifierInfo *II[] = {
1669 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1670 &CGM.getContext().Idents.get("objects"),
1671 &CGM.getContext().Idents.get("count")
1672 };
1673 Selector FastEnumSel =
1674 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001675
1676 QualType ItemsTy =
1677 getContext().getConstantArrayType(getContext().getObjCIdType(),
Richard Smith772e2662019-10-04 01:25:59 +00001678 llvm::APInt(32, NumItems), nullptr,
Anders Carlsson75658592008-08-31 02:33:12 +00001679 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001680 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001681
John McCall53848232011-07-27 01:07:15 +00001682 // Emit the collection pointer. In ARC, we do a retain.
1683 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001684 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001685 Collection = EmitARCRetainScalarExpr(S.getCollection());
1686
1687 // Enter a cleanup to do the release.
1688 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1689 } else {
1690 Collection = EmitScalarExpr(S.getCollection());
1691 }
Mike Stump11289f42009-09-09 15:08:12 +00001692
John McCall91e82dd2011-08-05 00:14:38 +00001693 // The 'continue' label needs to appear within the cleanup for the
1694 // collection object.
1695 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1696
John McCall1c926b72011-01-07 01:49:06 +00001697 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001698 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001699
1700 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001701 Args.add(RValue::get(StatePtr.getPointer()),
1702 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001703
John McCall1c926b72011-01-07 01:49:06 +00001704 // The second argument is a temporary array with space for NumItems
1705 // pointers. We'll actually be loading elements from the array
1706 // pointer written into the control state; this buffer is so that
1707 // collections that *aren't* backed by arrays can still queue up
1708 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001709 Args.add(RValue::get(ItemsPtr.getPointer()),
1710 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001711
John McCall1c926b72011-01-07 01:49:06 +00001712 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001713 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1714 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1715 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001716
John McCall1c926b72011-01-07 01:49:06 +00001717 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001718 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001719 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1720 getContext().getNSUIntegerType(),
1721 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001722
John McCall1c926b72011-01-07 01:49:06 +00001723 // The initial number of objects that were returned in the buffer.
1724 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001725
John McCall1c926b72011-01-07 01:49:06 +00001726 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1727 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001728
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001729 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001730
John McCall1c926b72011-01-07 01:49:06 +00001731 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001732 // empty; skip all this. Set the branch weight assuming this has the same
1733 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001734 uint64_t EntryCount = getCurrentProfileCount();
1735 Builder.CreateCondBr(
1736 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1737 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001738 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001739
John McCall1c926b72011-01-07 01:49:06 +00001740 // Otherwise, initialize the loop.
1741 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001742
John McCall1c926b72011-01-07 01:49:06 +00001743 // Save the initial mutations value. This is the value at an
1744 // address that was written into the state object by
1745 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001746 Address StateMutationsPtrPtr =
1747 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001748 llvm::Value *StateMutationsPtr
1749 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001750
John McCall1c926b72011-01-07 01:49:06 +00001751 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001752 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1753 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001754
John McCall1c926b72011-01-07 01:49:06 +00001755 // Start looping. This is the point we return to whenever we have a
1756 // fresh, non-empty batch of objects.
1757 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1758 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001759
John McCall1c926b72011-01-07 01:49:06 +00001760 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001761 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001762 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001763
John McCall1c926b72011-01-07 01:49:06 +00001764 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001765 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001766 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Justin Bogner66242d62015-04-23 23:06:47 +00001768 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001769
John McCall1c926b72011-01-07 01:49:06 +00001770 // Check whether the mutations value has changed from where it was
1771 // at start. StateMutationsPtr should actually be invariant between
1772 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001773 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001774 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001775 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1776 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001777
John McCall1c926b72011-01-07 01:49:06 +00001778 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001779 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001780
John McCall1c926b72011-01-07 01:49:06 +00001781 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1782 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001783
John McCall1c926b72011-01-07 01:49:06 +00001784 // If so, call the enumeration-mutation function.
1785 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001786 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001787 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001788 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001789 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001790 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001791 // FIXME: We shouldn't need to get the function info here, the runtime already
1792 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001793 EmitCall(
1794 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001795 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001796
John McCall1c926b72011-01-07 01:49:06 +00001797 // Otherwise, or if the mutation function returns, just continue.
1798 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001799
John McCall1c926b72011-01-07 01:49:06 +00001800 // Initialize the element variable.
1801 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001802 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001803 LValue elementLValue;
1804 QualType elementType;
1805 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001806 // Initialize the variable, in case it's a __block variable or something.
1807 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001808
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001809 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1810 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1811 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001812 elementLValue = EmitLValue(&tempDRE);
1813 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001814 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001815
1816 if (D->isARCPseudoStrong())
1817 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001818 } else {
1819 elementLValue = LValue(); // suppress warning
1820 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001821 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001822 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001823 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001824
1825 // Fetch the buffer out of the enumeration state.
1826 // TODO: this pointer should actually be invariant between
1827 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001828 Address StateItemsPtr =
1829 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001830 llvm::Value *EnumStateItems =
1831 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001832
John McCall1c926b72011-01-07 01:49:06 +00001833 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001834 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001835 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001836 llvm::Value *CurrentItem =
1837 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001838
Vedant Kumar8c4a65b2019-12-13 12:59:40 -08001839 if (SanOpts.has(SanitizerKind::ObjCCast)) {
1840 // Before using an item from the collection, check that the implicit cast
1841 // from id to the element type is valid. This is done with instrumentation
1842 // roughly corresponding to:
1843 //
1844 // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
1845 const ObjCObjectPointerType *ObjPtrTy =
1846 elementType->getAsObjCInterfacePointerType();
1847 const ObjCInterfaceType *InterfaceTy =
1848 ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
1849 if (InterfaceTy) {
1850 SanitizerScope SanScope(this);
1851 auto &C = CGM.getContext();
1852 assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
1853 Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
1854 CallArgList IsKindOfClassArgs;
1855 llvm::Value *Cls =
1856 CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
1857 IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
1858 llvm::Value *IsClass =
1859 CGM.getObjCRuntime()
1860 .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
1861 IsKindOfClassSel, CurrentItem,
1862 IsKindOfClassArgs)
1863 .getScalarVal();
1864 llvm::Constant *StaticData[] = {
1865 EmitCheckSourceLocation(S.getBeginLoc()),
1866 EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
1867 EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
1868 SanitizerHandler::InvalidObjCCast,
1869 ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
1870 }
1871 }
1872
John McCall1c926b72011-01-07 01:49:06 +00001873 // Cast that value to the right type.
1874 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1875 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001876
John McCall1c926b72011-01-07 01:49:06 +00001877 // Make sure we have an l-value. Yes, this gets evaluated every
1878 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001879 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001880 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001881 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001882 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001883 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1884 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001885 }
Mike Stump11289f42009-09-09 15:08:12 +00001886
John McCall9e2e22f2011-02-22 07:16:58 +00001887 // If we do have an element variable, this assignment is the end of
1888 // its initialization.
1889 if (elementIsVariable)
1890 EmitAutoVarCleanups(variable);
1891
John McCall1c926b72011-01-07 01:49:06 +00001892 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001893 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001894 {
1895 RunCleanupsScope Scope(*this);
1896 EmitStmt(S.getBody());
1897 }
Anders Carlsson75658592008-08-31 02:33:12 +00001898 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCall1c926b72011-01-07 01:49:06 +00001900 // Destroy the element variable now.
1901 elementVariableScope.ForceCleanup();
1902
1903 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001904 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001905
John McCall1c926b72011-01-07 01:49:06 +00001906 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001907
John McCall1c926b72011-01-07 01:49:06 +00001908 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001909 llvm::Value *indexPlusOne =
1910 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001911
John McCall1c926b72011-01-07 01:49:06 +00001912 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001913 // Set the branch weights based on the simplifying assumption that this is
1914 // like a while-loop, i.e., ignoring that the false branch fetches more
1915 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001916 Builder.CreateCondBr(
1917 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001918 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001919
1920 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1921 count->addIncoming(count, AfterBody.getBlock());
1922
1923 // Otherwise, we have to fetch more elements.
1924 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001925
1926 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001927 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1928 getContext().getNSUIntegerType(),
1929 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001930
John McCall1c926b72011-01-07 01:49:06 +00001931 // If we got a zero count, we're done.
1932 llvm::Value *refetchCount = CountRV.getScalarVal();
1933
1934 // (note that the message send might split FetchMoreBB)
1935 index->addIncoming(zero, Builder.GetInsertBlock());
1936 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1937
1938 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1939 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001940
Anders Carlsson75658592008-08-31 02:33:12 +00001941 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001942 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001943
John McCall9e2e22f2011-02-22 07:16:58 +00001944 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001945 // If the element was not a declaration, set it to be null.
1946
John McCall1c926b72011-01-07 01:49:06 +00001947 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1948 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001949 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001950 }
1951
Eric Christopher7cdf9482011-10-13 21:45:18 +00001952 if (DI)
1953 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001954
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001955 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001956 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001957}
1958
Mike Stump11289f42009-09-09 15:08:12 +00001959void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001960 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001961}
1962
Mike Stump11289f42009-09-09 15:08:12 +00001963void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001964 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1965}
1966
Chris Lattnere132e242008-11-15 21:26:17 +00001967void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001968 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001969 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001970}
1971
John McCall31168b02011-06-15 23:02:42 +00001972namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001973 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001974 CallObjCRelease(llvm::Value *object) : object(object) {}
1975 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001976
Craig Topper4f12f102014-03-12 06:41:41 +00001977 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001978 // Releases at the end of the full-expression are imprecise.
1979 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001980 }
1981 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001982}
John McCall31168b02011-06-15 23:02:42 +00001983
John McCall2d637d22011-09-10 06:18:15 +00001984/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001985/// release at the end of the full-expression.
1986llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1987 llvm::Value *object) {
1988 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001989 // conditional.
1990 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001991 return object;
1992}
1993
1994llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1995 llvm::Value *value) {
1996 return EmitARCRetainAutorelease(type, value);
1997}
1998
John McCalleff18842013-03-23 02:35:54 +00001999/// Given a number of pointers, inform the optimizer that they're
2000/// being intrinsically used up until this point in the program.
2001void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00002002 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00002003 if (!fn)
2004 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00002005
2006 // This isn't really a "runtime" function, but as an intrinsic it
2007 // doesn't really matter as long as we align things up.
2008 EmitNounwindRuntimeCall(fn, values);
2009}
2010
James Y Knight9871db02019-02-05 16:42:33 +00002011static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002012 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00002013 // If the target runtime doesn't naturally support ARC, emit weak
2014 // references to the runtime support library. We don't really
2015 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002016 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
2017 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002018 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00002019 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00002020 }
John McCall31168b02011-06-15 23:02:42 +00002021}
2022
James Y Knight9871db02019-02-05 16:42:33 +00002023static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
2024 llvm::FunctionCallee RTF) {
2025 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
2026}
2027
John McCall31168b02011-06-15 23:02:42 +00002028/// Perform an operation having the signature
2029/// i8* (i8*)
2030/// where a null input causes a no-op and returns null.
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002031static llvm::Value *emitARCValueOperation(
2032 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2033 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2034 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002035 if (isa<llvm::ConstantPointerNull>(value))
2036 return value;
John McCall31168b02011-06-15 23:02:42 +00002037
2038 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002039 fn = CGF.CGM.getIntrinsic(IntID);
2040 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002041 }
2042
2043 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00002044 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00002045 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2046
2047 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00002048 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002049 call->setTailCallKind(tailKind);
John McCall31168b02011-06-15 23:02:42 +00002050
2051 // Cast the result back to the original type.
2052 return CGF.Builder.CreateBitCast(call, origType);
2053}
2054
2055/// Perform an operation having the following signature:
2056/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002057static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2058 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002059 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00002060 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002061 fn = CGF.CGM.getIntrinsic(IntID);
2062 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002063 }
2064
2065 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00002066 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00002067 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2068
2069 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002070 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002071
2072 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002073 if (origType != CGF.Int8PtrTy)
2074 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002075
2076 return result;
2077}
2078
2079/// Perform an operation having the following signature:
2080/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002081static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002082 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002083 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002084 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002085 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002086 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002087
2088 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002089 fn = CGF.CGM.getIntrinsic(IntID);
2090 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002091 }
2092
Chris Lattner2192fe52011-07-18 04:24:23 +00002093 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002094
John McCall882987f2013-02-28 19:01:20 +00002095 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002096 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002097 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2098 };
2099 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002100
Craig Topper8a13c412014-05-21 05:09:00 +00002101 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002102
2103 return CGF.Builder.CreateBitCast(result, origType);
2104}
2105
2106/// Perform an operation having the following signature:
2107/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002108static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2109 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002110 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002111 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002112
2113 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002114 fn = CGF.CGM.getIntrinsic(IntID);
2115 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002116 }
2117
John McCall882987f2013-02-28 19:01:20 +00002118 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002119 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2120 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002121 };
2122 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002123}
2124
Pete Cooper2cd35962018-12-18 20:33:00 +00002125/// Perform an operation having the signature
2126/// i8* (i8*)
2127/// where a null input causes a no-op and returns null.
2128static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2129 llvm::Value *value,
2130 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002131 llvm::FunctionCallee &fn,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002132 StringRef fnName) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002133 if (isa<llvm::ConstantPointerNull>(value))
2134 return value;
2135
2136 if (!fn) {
2137 llvm::FunctionType *fnType =
2138 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2139 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002140
2141 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002142 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002143 if (fnName == "objc_retain")
2144 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002145 }
2146
2147 // Cast the argument to 'id'.
2148 llvm::Type *origType = returnType ? returnType : value->getType();
2149 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2150
2151 // Call the function.
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002152 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002153
2154 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002155 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002156}
2157
John McCall31168b02011-06-15 23:02:42 +00002158/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002159/// call i8* \@objc_retain(i8* %value)
2160/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002161llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2162 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002163 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002164 else
2165 return EmitARCRetainNonBlock(value);
2166}
2167
2168/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002169/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002170llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002171 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002172 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002173 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002174}
2175
2176/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002177/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002178///
2179/// \param mandatory - If false, emit the call with metadata
2180/// indicating that it's okay for the optimizer to eliminate this call
2181/// if it can prove that the block never escapes except down the stack.
2182llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2183 bool mandatory) {
2184 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002185 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002186 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002187 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002188
2189 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2190 // tell the optimizer that it doesn't need to do this copy if the
2191 // block doesn't escape, where being passed as an argument doesn't
2192 // count as escaping.
2193 if (!mandatory && isa<llvm::Instruction>(result)) {
2194 llvm::CallInst *call
2195 = cast<llvm::CallInst>(result->stripPointerCasts());
Craig Toppera58b62b2020-04-27 20:15:59 -07002196 assert(call->getCalledOperand() ==
2197 CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002198
John McCallff613032011-10-04 06:23:45 +00002199 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002200 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002201 }
2202
2203 return result;
John McCall31168b02011-06-15 23:02:42 +00002204}
2205
John McCalle399e5b2016-01-27 18:32:30 +00002206static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002207 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002208 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002209 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002210 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002211 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002212 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002213 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002214 .getARCRetainAutoreleasedReturnValueMarker();
2215
2216 // If we have an empty assembly string, there's nothing to do.
2217 if (assembly.empty()) {
2218
2219 // Otherwise, at -O0, build an inline asm that we're going to call
2220 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002221 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002222 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002223 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002224
John McCall31168b02011-06-15 23:02:42 +00002225 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2226
2227 // If we're at -O1 and above, we don't want to litter the code
2228 // with this marker yet, so leave a breadcrumb for the ARC
2229 // optimizer to pick up.
2230 } else {
Akira Hatanaka60c3a3b2019-04-10 06:20:23 +00002231 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2232 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2233 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2234 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
John McCall31168b02011-06-15 23:02:42 +00002235 }
2236 }
2237 }
2238
2239 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002240 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002241 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002242}
John McCall31168b02011-06-15 23:02:42 +00002243
John McCalle399e5b2016-01-27 18:32:30 +00002244/// Retain the given object which is the result of a function call.
2245/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2246///
2247/// Yes, this function name is one character away from a different
2248/// call with completely different semantics.
2249llvm::Value *
2250CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2251 emitAutoreleasedReturnValueMarker(*this);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002252 llvm::CallInst::TailCallKind tailKind =
2253 CGM.getTargetCodeGenInfo()
2254 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2255 ? llvm::CallInst::TCK_NoTail
2256 : llvm::CallInst::TCK_None;
2257 return emitARCValueOperation(
2258 *this, value, nullptr,
2259 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2260 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
John McCall31168b02011-06-15 23:02:42 +00002261}
2262
John McCalle399e5b2016-01-27 18:32:30 +00002263/// Claim a possibly-autoreleased return value at +0. This is only
2264/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002265/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002266/// the value is ignored, or when it is being assigned to an
2267/// __unsafe_unretained variable.
2268///
2269/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2270llvm::Value *
2271CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2272 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002273 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002274 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002275 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002276}
2277
John McCall31168b02011-06-15 23:02:42 +00002278/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002279/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002280void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2281 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002282 if (isa<llvm::ConstantPointerNull>(value)) return;
2283
James Y Knight9871db02019-02-05 16:42:33 +00002284 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002285 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002286 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2287 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002288 }
2289
2290 // Cast the argument to 'id'.
2291 value = Builder.CreateBitCast(value, Int8PtrTy);
2292
2293 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002294 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002295
John McCallcdda29c2013-03-13 03:10:54 +00002296 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002297 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002298 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002299 }
2300}
2301
John McCalle68b8f42012-10-17 02:28:37 +00002302/// Destroy a __strong variable.
2303///
2304/// At -O0, emit a call to store 'null' into the address;
2305/// instrumenting tools prefer this because the address is exposed,
2306/// but it's relatively cumbersome to optimize.
2307///
2308/// At -O1 and above, just load and call objc_release.
2309///
2310/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002311void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002312 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002313 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002314 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002315 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2316 return;
2317 }
2318
2319 llvm::Value *value = Builder.CreateLoad(addr);
2320 EmitARCRelease(value, precise);
2321}
2322
John McCall31168b02011-06-15 23:02:42 +00002323/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002324/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002325llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002326 llvm::Value *value,
2327 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002328 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002329
James Y Knight9871db02019-02-05 16:42:33 +00002330 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002331 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002332 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2333 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002334 }
2335
John McCall882987f2013-02-28 19:01:20 +00002336 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002337 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002338 Builder.CreateBitCast(value, Int8PtrTy)
2339 };
2340 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002341
Craig Topper8a13c412014-05-21 05:09:00 +00002342 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002343 return value;
2344}
2345
2346/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002347/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002348/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002349llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002350 llvm::Value *newValue,
2351 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002352 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002353 bool isBlock = type->isBlockPointerType();
2354
2355 // Use a store barrier at -O0 unless this is a block type or the
2356 // lvalue is inadequately aligned.
2357 if (shouldUseFusedARCCalls() &&
2358 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002359 (dst.getAlignment().isZero() ||
2360 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002361 return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
John McCall31168b02011-06-15 23:02:42 +00002362 }
2363
2364 // Otherwise, split it out.
2365
2366 // Retain the new value.
2367 newValue = EmitARCRetain(type, newValue);
2368
2369 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002370 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002371
2372 // Store. We do this before the release so that any deallocs won't
2373 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002374 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002375
2376 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002377 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002378
2379 return newValue;
2380}
2381
2382/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002383/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002384llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002385 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002386 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002387 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002388}
2389
2390/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002391/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002392llvm::Value *
2393CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002394 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002395 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002396 llvm::Intrinsic::objc_autoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002397 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002398}
2399
2400/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002401/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002402llvm::Value *
2403CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002404 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002405 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002406 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002407 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002408}
2409
2410/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002411/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002412/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002413/// %retain = call i8* \@objc_retainBlock(i8* %value)
2414/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002415llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2416 llvm::Value *value) {
2417 if (!type->isBlockPointerType())
2418 return EmitARCRetainAutoreleaseNonBlock(value);
2419
2420 if (isa<llvm::ConstantPointerNull>(value)) return value;
2421
Chris Lattner2192fe52011-07-18 04:24:23 +00002422 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002423 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002424 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002425 value = EmitARCAutorelease(value);
2426 return Builder.CreateBitCast(value, origType);
2427}
2428
2429/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002430/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002431llvm::Value *
2432CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002433 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002434 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002435 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002436}
2437
John McCallb04ecb72015-10-21 18:06:43 +00002438/// i8* \@objc_loadWeak(i8** %addr)
2439/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2440llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2441 return emitARCLoadOperation(*this, addr,
2442 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002443 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002444}
2445
James Dennett14c41ea2012-06-22 05:41:30 +00002446/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002447llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002448 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002449 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002450 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002451}
2452
James Dennett14c41ea2012-06-22 05:41:30 +00002453/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002454/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002455llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002456 llvm::Value *value,
2457 bool ignored) {
2458 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002459 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002460 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002461}
2462
James Dennett14c41ea2012-06-22 05:41:30 +00002463/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002464/// Returns %value. %addr is known to not have a current weak entry.
2465/// Essentially equivalent to:
2466/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002467void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002468 // If we're initializing to null, just write null to memory; no need
2469 // to get the runtime involved. But don't do this if optimization
2470 // is enabled, because accounting for this would make the optimizer
2471 // much more complicated.
2472 if (isa<llvm::ConstantPointerNull>(value) &&
2473 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2474 Builder.CreateStore(value, addr);
2475 return;
2476 }
2477
2478 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002479 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002480 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002481}
2482
James Dennett14c41ea2012-06-22 05:41:30 +00002483/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002484/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002485void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002486 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002487 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002488 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2489 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002490 }
2491
2492 // Cast the argument to 'id*'.
2493 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2494
John McCall7f416cc2015-09-08 08:05:57 +00002495 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002496}
2497
James Dennett14c41ea2012-06-22 05:41:30 +00002498/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002499/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2500/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002501void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002502 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002503 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002504 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002505}
2506
James Dennett14c41ea2012-06-22 05:41:30 +00002507/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002508/// Disregards the current value in %dest. Essentially
2509/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002510void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002511 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002512 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002513 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002514}
2515
Akira Hatanakad791e922018-03-19 17:38:40 +00002516void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2517 Address SrcAddr) {
2518 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2519 Object = EmitObjCConsumeObject(Ty, Object);
2520 EmitARCStoreWeak(DstAddr, Object, false);
2521}
2522
2523void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2524 Address SrcAddr) {
2525 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2526 Object = EmitObjCConsumeObject(Ty, Object);
2527 EmitARCStoreWeak(DstAddr, Object, false);
2528 EmitARCDestroyWeak(SrcAddr);
2529}
2530
John McCall31168b02011-06-15 23:02:42 +00002531/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002532/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002533llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002534 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002535 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002536 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2537 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002538 }
2539
John McCall882987f2013-02-28 19:01:20 +00002540 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002541}
2542
2543/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002544/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002545void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2546 assert(value->getType() == Int8PtrTy);
2547
Pete Cooper2cd35962018-12-18 20:33:00 +00002548 if (getInvokeDest()) {
2549 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002550 llvm::FunctionCallee &fn =
2551 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002552 if (!fn) {
2553 llvm::FunctionType *fnType =
2554 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2555 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2556 setARCRuntimeFunctionLinkage(CGM, fn);
2557 }
John McCall31168b02011-06-15 23:02:42 +00002558
Pete Cooper2cd35962018-12-18 20:33:00 +00002559 // objc_autoreleasePoolPop can throw.
2560 EmitRuntimeCallOrInvoke(fn, value);
2561 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002562 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002563 if (!fn) {
2564 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2565 setARCRuntimeFunctionLinkage(CGM, fn);
2566 }
2567
2568 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002569 }
John McCall31168b02011-06-15 23:02:42 +00002570}
2571
2572/// Produce the code to do an MRR version objc_autoreleasepool_push.
2573/// Which is: [[NSAutoreleasePool alloc] init];
2574/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2575/// init is declared as: - (id) init; in its NSObject super class.
2576///
2577llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2578 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002579 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002580 // [NSAutoreleasePool alloc]
2581 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2582 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2583 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002584 RValue AllocRV =
2585 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002586 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002587 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002588
2589 // [Receiver init]
2590 Receiver = AllocRV.getScalarVal();
2591 II = &CGM.getContext().Idents.get("init");
2592 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2593 RValue InitRV =
2594 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2595 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002596 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002597 return InitRV.getScalarVal();
2598}
2599
Pete Coopere3886802018-12-08 05:13:50 +00002600/// Allocate the given objc object.
2601/// call i8* \@objc_alloc(i8* %value)
2602llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2603 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002604 return emitObjCValueOperation(*this, value, resultType,
2605 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002606 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002607}
2608
2609/// Allocate the given objc object.
2610/// call i8* \@objc_allocWithZone(i8* %value)
2611llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2612 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002613 return emitObjCValueOperation(*this, value, resultType,
2614 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002615 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002616}
2617
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002618llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2619 llvm::Type *resultType) {
2620 return emitObjCValueOperation(*this, value, resultType,
2621 CGM.getObjCEntrypoints().objc_alloc_init,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002622 "objc_alloc_init");
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002623}
2624
John McCall31168b02011-06-15 23:02:42 +00002625/// Produce the code to do a primitive release.
2626/// [tmp drain];
2627void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2628 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2629 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2630 CallArgList Args;
2631 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002632 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002633}
2634
John McCall82fe67b2011-07-09 01:37:26 +00002635void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002636 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002637 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002638 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002639}
2640
2641void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002642 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002643 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002644 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002645}
2646
2647void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002648 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002649 QualType type) {
2650 CGF.EmitARCDestroyWeak(addr);
2651}
2652
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002653void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2654 QualType type) {
2655 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2656 CGF.EmitARCIntrinsicUse(value);
2657}
2658
Pete Coopere5b64ea2018-12-21 21:00:32 +00002659/// Autorelease the given object.
2660/// call i8* \@objc_autorelease(i8* %value)
2661llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2662 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002663 return emitObjCValueOperation(
2664 *this, value, returnType,
2665 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002666 "objc_autorelease");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002667}
2668
2669/// Retain the given object, with normal retain semantics.
2670/// call i8* \@objc_retain(i8* %value)
2671llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2672 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002673 return emitObjCValueOperation(
2674 *this, value, returnType,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002675 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002676}
2677
2678/// Release the given object.
2679/// call void \@objc_release(i8* %value)
2680void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2681 ARCPreciseLifetime_t precise) {
2682 if (isa<llvm::ConstantPointerNull>(value)) return;
2683
James Y Knight9871db02019-02-05 16:42:33 +00002684 llvm::FunctionCallee &fn =
2685 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002686 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002687 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002688 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002689 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2690 setARCRuntimeFunctionLinkage(CGM, fn);
2691 // We have Native ARC, so set nonlazybind attribute for performance
2692 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2693 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002694 }
2695
2696 // Cast the argument to 'id'.
2697 value = Builder.CreateBitCast(value, Int8PtrTy);
2698
2699 // Call objc_release.
Akira Hatanaka34d28cf2019-05-10 21:54:16 +00002700 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002701
2702 if (precise == ARCImpreciseLifetime) {
2703 call->setMetadata("clang.imprecise_release",
2704 llvm::MDNode::get(Builder.getContext(), None));
2705 }
2706}
2707
John McCall31168b02011-06-15 23:02:42 +00002708namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002709 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002710 llvm::Value *Token;
2711
2712 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2713
Craig Topper4f12f102014-03-12 06:41:41 +00002714 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002715 CGF.EmitObjCAutoreleasePoolPop(Token);
2716 }
2717 };
David Blaikie7e70d682015-08-18 22:40:54 +00002718 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002719 llvm::Value *Token;
2720
2721 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2722
Craig Topper4f12f102014-03-12 06:41:41 +00002723 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002724 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2725 }
2726 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002727}
John McCall31168b02011-06-15 23:02:42 +00002728
2729void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002730 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002731 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2732 else
2733 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2734}
2735
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002736static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2737 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002738 case Qualifiers::OCL_None:
2739 case Qualifiers::OCL_ExplicitNone:
2740 case Qualifiers::OCL_Strong:
2741 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002742 return true;
John McCall31168b02011-06-15 23:02:42 +00002743
2744 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002745 return false;
John McCall31168b02011-06-15 23:02:42 +00002746 }
2747
2748 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002749}
2750
2751static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002752 LValue lvalue,
2753 QualType type) {
2754 llvm::Value *result;
2755 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2756 if (shouldRetain) {
2757 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2758 } else {
2759 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002760 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002761 }
2762 return TryEmitResult(result, !shouldRetain);
2763}
2764
2765static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002766 const Expr *e) {
2767 e = e->IgnoreParens();
2768 QualType type = e->getType();
2769
Fangrui Song6907ce22018-07-30 19:24:48 +00002770 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002771 // an extra retain/release pair by zeroing out the source of this
2772 // "move" operation.
2773 if (e->isXValue() &&
2774 !type.isConstQualified() &&
2775 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2776 // Emit the lvalue.
2777 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002778
John McCall154a2fd2011-08-30 00:57:29 +00002779 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002780 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2781 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002782
John McCall154a2fd2011-08-30 00:57:29 +00002783 // Set the source pointer to NULL.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002784 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002785
John McCall154a2fd2011-08-30 00:57:29 +00002786 return TryEmitResult(result, true);
2787 }
2788
John McCall31168b02011-06-15 23:02:42 +00002789 // As a very special optimization, in ARC++, if the l-value is the
2790 // result of a non-volatile assignment, do a simple retain of the
2791 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002792 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002793 !type.isVolatileQualified() &&
2794 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2795 isa<BinaryOperator>(e) &&
2796 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2797 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2798
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002799 // Try to emit code for scalar constant instead of emitting LValue and
2800 // loading it because we are not guaranteed to have an l-value. One of such
2801 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2802 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2803 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2804 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2805 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2806 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2807 }
2808
John McCall31168b02011-06-15 23:02:42 +00002809 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2810}
2811
John McCalle399e5b2016-01-27 18:32:30 +00002812typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2813 llvm::Value *value)>
2814 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002815
John McCalle399e5b2016-01-27 18:32:30 +00002816/// Insert code immediately after a call.
2817static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2818 llvm::Value *value,
2819 ValueTransform doAfterCall,
2820 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002821 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2822 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2823
2824 // Place the retain immediately following the call.
2825 CGF.Builder.SetInsertPoint(call->getParent(),
2826 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002827 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002828
2829 CGF.Builder.restoreIP(ip);
2830 return value;
2831 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2832 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2833
2834 // Place the retain at the beginning of the normal destination block.
2835 llvm::BasicBlock *BB = invoke->getNormalDest();
2836 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002837 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002838
2839 CGF.Builder.restoreIP(ip);
2840 return value;
2841
2842 // Bitcasts can arise because of related-result returns. Rewrite
2843 // the operand.
2844 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2845 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002846 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002847 bitcast->setOperand(0, operand);
2848 return bitcast;
2849
2850 // Generic fall-back case.
2851 } else {
2852 // Retain using the non-block variant: we never need to do a copy
2853 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002854 return doFallback(CGF, value);
2855 }
2856}
2857
2858/// Given that the given expression is some sort of call (which does
2859/// not return retained), emit a retain following it.
2860static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2861 const Expr *e) {
2862 llvm::Value *value = CGF.EmitScalarExpr(e);
2863 return emitARCOperationAfterCall(CGF, value,
2864 [](CodeGenFunction &CGF, llvm::Value *value) {
2865 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2866 },
2867 [](CodeGenFunction &CGF, llvm::Value *value) {
2868 return CGF.EmitARCRetainNonBlock(value);
2869 });
2870}
2871
2872/// Given that the given expression is some sort of call (which does
2873/// not return retained), perform an unsafeClaim following it.
2874static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2875 const Expr *e) {
2876 llvm::Value *value = CGF.EmitScalarExpr(e);
2877 return emitARCOperationAfterCall(CGF, value,
2878 [](CodeGenFunction &CGF, llvm::Value *value) {
2879 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2880 },
2881 [](CodeGenFunction &CGF, llvm::Value *value) {
2882 return value;
2883 });
2884}
2885
2886llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2887 bool allowUnsafeClaim) {
2888 if (allowUnsafeClaim &&
2889 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2890 return emitARCUnsafeClaimCallResult(*this, E);
2891 } else {
2892 llvm::Value *value = emitARCRetainCallResult(*this, E);
2893 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002894 }
2895}
2896
John McCallcd78e802011-09-10 01:16:55 +00002897/// Determine whether it might be important to emit a separate
2898/// objc_retain_block on the result of the given expression, or
2899/// whether it's okay to just emit it in a +1 context.
2900static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2901 assert(e->getType()->isBlockPointerType());
2902 e = e->IgnoreParens();
2903
2904 // For future goodness, emit block expressions directly in +1
2905 // contexts if we can.
2906 if (isa<BlockExpr>(e))
2907 return false;
2908
2909 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2910 switch (cast->getCastKind()) {
2911 // Emitting these operations in +1 contexts is goodness.
2912 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002913 case CK_ARCReclaimReturnedObject:
2914 case CK_ARCConsumeObject:
2915 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002916 return false;
2917
2918 // These operations preserve a block type.
2919 case CK_NoOp:
2920 case CK_BitCast:
2921 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2922
2923 // These operations are known to be bad (or haven't been considered).
2924 case CK_AnyPointerToBlockPointerCast:
2925 default:
2926 return true;
2927 }
2928 }
2929
2930 return true;
2931}
2932
John McCalle399e5b2016-01-27 18:32:30 +00002933namespace {
2934/// A CRTP base class for emitting expressions of retainable object
2935/// pointer type in ARC.
2936template <typename Impl, typename Result> class ARCExprEmitter {
2937protected:
2938 CodeGenFunction &CGF;
2939 Impl &asImpl() { return *static_cast<Impl*>(this); }
2940
2941 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2942
2943public:
2944 Result visit(const Expr *e);
2945 Result visitCastExpr(const CastExpr *e);
2946 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002947 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002948 Result visitBinaryOperator(const BinaryOperator *e);
2949 Result visitBinAssign(const BinaryOperator *e);
2950 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2951 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2952 Result visitBinAssignWeak(const BinaryOperator *e);
2953 Result visitBinAssignStrong(const BinaryOperator *e);
2954
2955 // Minimal implementation:
2956 // Result visitLValueToRValue(const Expr *e)
2957 // Result visitConsumeObject(const Expr *e)
2958 // Result visitExtendBlockObject(const Expr *e)
2959 // Result visitReclaimReturnedObject(const Expr *e)
2960 // Result visitCall(const Expr *e)
2961 // Result visitExpr(const Expr *e)
2962 //
2963 // Result emitBitCast(Result result, llvm::Type *resultType)
2964 // llvm::Value *getValueOfResult(Result result)
2965};
2966}
2967
2968/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002969///
2970/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002971template <typename Impl, typename Result>
2972Result
2973ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002974 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002975
2976 // Find the result expression.
2977 const Expr *resultExpr = E->getResultExpr();
2978 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002979 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002980
2981 for (PseudoObjectExpr::const_semantics_iterator
2982 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2983 const Expr *semantic = *i;
2984
2985 // If this semantic expression is an opaque value, bind it
2986 // to the result of its source expression.
2987 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2988 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2989 OVMA opaqueData;
2990
2991 // If this semantic is the result of the pseudo-object
2992 // expression, try to evaluate the source as +1.
2993 if (ov == resultExpr) {
2994 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002995 result = asImpl().visit(ov->getSourceExpr());
2996 opaqueData = OVMA::bind(CGF, ov,
2997 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002998
2999 // Otherwise, just bind it.
3000 } else {
3001 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3002 }
3003 opaques.push_back(opaqueData);
3004
3005 // Otherwise, if the expression is the result, evaluate it
3006 // and remember the result.
3007 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00003008 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00003009
3010 // Otherwise, evaluate the expression in an ignored context.
3011 } else {
3012 CGF.EmitIgnoredExpr(semantic);
3013 }
3014 }
3015
3016 // Unbind all the opaques now.
3017 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3018 opaques[i].unbind(CGF);
3019
3020 return result;
3021}
3022
John McCalle399e5b2016-01-27 18:32:30 +00003023template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003024Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
3025 // The default implementation just forwards the expression to visitExpr.
3026 return asImpl().visitExpr(e);
3027}
3028
3029template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00003030Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3031 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00003032
John McCalle399e5b2016-01-27 18:32:30 +00003033 // No-op casts don't change the type, so we just ignore them.
3034 case CK_NoOp:
3035 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00003036
John McCalle399e5b2016-01-27 18:32:30 +00003037 // These casts can change the type.
3038 case CK_CPointerToObjCPointerCast:
3039 case CK_BlockPointerToObjCPointerCast:
3040 case CK_AnyPointerToBlockPointerCast:
3041 case CK_BitCast: {
3042 llvm::Type *resultType = CGF.ConvertType(e->getType());
3043 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3044 Result result = asImpl().visit(e->getSubExpr());
3045 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00003046 }
3047
John McCalle399e5b2016-01-27 18:32:30 +00003048 // Handle some casts specially.
3049 case CK_LValueToRValue:
3050 return asImpl().visitLValueToRValue(e->getSubExpr());
3051 case CK_ARCConsumeObject:
3052 return asImpl().visitConsumeObject(e->getSubExpr());
3053 case CK_ARCExtendBlockObject:
3054 return asImpl().visitExtendBlockObject(e->getSubExpr());
3055 case CK_ARCReclaimReturnedObject:
3056 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3057
3058 // Otherwise, use the default logic.
3059 default:
3060 return asImpl().visitExpr(e);
3061 }
3062}
3063
3064template <typename Impl, typename Result>
3065Result
3066ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3067 switch (e->getOpcode()) {
3068 case BO_Comma:
3069 CGF.EmitIgnoredExpr(e->getLHS());
3070 CGF.EnsureInsertPoint();
3071 return asImpl().visit(e->getRHS());
3072
3073 case BO_Assign:
3074 return asImpl().visitBinAssign(e);
3075
3076 default:
3077 return asImpl().visitExpr(e);
3078 }
3079}
3080
3081template <typename Impl, typename Result>
3082Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3083 switch (e->getLHS()->getType().getObjCLifetime()) {
3084 case Qualifiers::OCL_ExplicitNone:
3085 return asImpl().visitBinAssignUnsafeUnretained(e);
3086
3087 case Qualifiers::OCL_Weak:
3088 return asImpl().visitBinAssignWeak(e);
3089
3090 case Qualifiers::OCL_Autoreleasing:
3091 return asImpl().visitBinAssignAutoreleasing(e);
3092
3093 case Qualifiers::OCL_Strong:
3094 return asImpl().visitBinAssignStrong(e);
3095
3096 case Qualifiers::OCL_None:
3097 return asImpl().visitExpr(e);
3098 }
3099 llvm_unreachable("bad ObjC ownership qualifier");
3100}
3101
3102/// The default rule for __unsafe_unretained emits the RHS recursively,
3103/// stores into the unsafe variable, and propagates the result outward.
3104template <typename Impl, typename Result>
3105Result ARCExprEmitter<Impl,Result>::
3106 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3107 // Recursively emit the RHS.
3108 // For __block safety, do this before emitting the LHS.
3109 Result result = asImpl().visit(e->getRHS());
3110
3111 // Perform the store.
3112 LValue lvalue =
3113 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3114 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3115 lvalue);
3116
3117 return result;
3118}
3119
3120template <typename Impl, typename Result>
3121Result
3122ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3123 return asImpl().visitExpr(e);
3124}
3125
3126template <typename Impl, typename Result>
3127Result
3128ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3129 return asImpl().visitExpr(e);
3130}
3131
3132template <typename Impl, typename Result>
3133Result
3134ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3135 return asImpl().visitExpr(e);
3136}
3137
3138/// The general expression-emission logic.
3139template <typename Impl, typename Result>
3140Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3141 // We should *never* see a nested full-expression here, because if
3142 // we fail to emit at +1, our caller must not retain after we close
3143 // out the full-expression. This isn't as important in the unsafe
3144 // emitter.
3145 assert(!isa<ExprWithCleanups>(e));
3146
3147 // Look through parens, __extension__, generic selection, etc.
3148 e = e->IgnoreParens();
3149
3150 // Handle certain kinds of casts.
3151 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3152 return asImpl().visitCastExpr(ce);
3153
3154 // Handle the comma operator.
3155 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3156 return asImpl().visitBinaryOperator(op);
3157
3158 // TODO: handle conditional operators here
3159
3160 // For calls and message sends, use the retained-call logic.
3161 // Delegate inits are a special case in that they're the only
3162 // returns-retained expression that *isn't* surrounded by
3163 // a consume.
3164 } else if (isa<CallExpr>(e) ||
3165 (isa<ObjCMessageExpr>(e) &&
3166 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3167 return asImpl().visitCall(e);
3168
3169 // Look through pseudo-object expressions.
3170 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3171 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003172 } else if (auto *be = dyn_cast<BlockExpr>(e))
3173 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003174
3175 return asImpl().visitExpr(e);
3176}
3177
3178namespace {
3179
3180/// An emitter for +1 results.
3181struct ARCRetainExprEmitter :
3182 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3183
3184 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3185
3186 llvm::Value *getValueOfResult(TryEmitResult result) {
3187 return result.getPointer();
3188 }
3189
3190 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3191 llvm::Value *value = result.getPointer();
3192 value = CGF.Builder.CreateBitCast(value, resultType);
3193 result.setPointer(value);
3194 return result;
3195 }
3196
3197 TryEmitResult visitLValueToRValue(const Expr *e) {
3198 return tryEmitARCRetainLoadOfScalar(CGF, e);
3199 }
3200
3201 /// For consumptions, just emit the subexpression and thus elide
3202 /// the retain/release pair.
3203 TryEmitResult visitConsumeObject(const Expr *e) {
3204 llvm::Value *result = CGF.EmitScalarExpr(e);
3205 return TryEmitResult(result, true);
3206 }
3207
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003208 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3209 TryEmitResult result = visitExpr(e);
3210 // Avoid the block-retain if this is a block literal that doesn't need to be
3211 // copied to the heap.
3212 if (e->getBlockDecl()->canAvoidCopyToHeap())
3213 result.setInt(true);
3214 return result;
3215 }
3216
John McCalle399e5b2016-01-27 18:32:30 +00003217 /// Block extends are net +0. Naively, we could just recurse on
3218 /// the subexpression, but actually we need to ensure that the
3219 /// value is copied as a block, so there's a little filter here.
3220 TryEmitResult visitExtendBlockObject(const Expr *e) {
3221 llvm::Value *result; // will be a +0 value
3222
3223 // If we can't safely assume the sub-expression will produce a
3224 // block-copied value, emit the sub-expression at +0.
3225 if (shouldEmitSeparateBlockRetain(e)) {
3226 result = CGF.EmitScalarExpr(e);
3227
3228 // Otherwise, try to emit the sub-expression at +1 recursively.
3229 } else {
3230 TryEmitResult subresult = asImpl().visit(e);
3231
3232 // If that produced a retained value, just use that.
3233 if (subresult.getInt()) {
3234 return subresult;
3235 }
3236
3237 // Otherwise it's +0.
3238 result = subresult.getPointer();
3239 }
3240
3241 // Retain the object as a block.
3242 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3243 return TryEmitResult(result, true);
3244 }
3245
3246 /// For reclaims, emit the subexpression as a retained call and
3247 /// skip the consumption.
3248 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3249 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3250 return TryEmitResult(result, true);
3251 }
3252
3253 /// When we have an undecorated call, retroactively do a claim.
3254 TryEmitResult visitCall(const Expr *e) {
3255 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3256 return TryEmitResult(result, true);
3257 }
3258
3259 // TODO: maybe special-case visitBinAssignWeak?
3260
3261 TryEmitResult visitExpr(const Expr *e) {
3262 // We didn't find an obvious production, so emit what we've got and
3263 // tell the caller that we didn't manage to retain.
3264 llvm::Value *result = CGF.EmitScalarExpr(e);
3265 return TryEmitResult(result, false);
3266 }
3267};
3268}
3269
3270static TryEmitResult
3271tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3272 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003273}
3274
3275static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3276 LValue lvalue,
3277 QualType type) {
3278 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3279 llvm::Value *value = result.getPointer();
3280 if (!result.getInt())
3281 value = CGF.EmitARCRetain(type, value);
3282 return value;
3283}
3284
3285/// EmitARCRetainScalarExpr - Semantically equivalent to
3286/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3287/// best-effort attempt to peephole expressions that naturally produce
3288/// retained objects.
3289llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003290 // The retain needs to happen within the full-expression.
3291 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCalld21cdd42013-02-12 00:25:08 +00003292 RunCleanupsScope scope(*this);
3293 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3294 }
3295
John McCall31168b02011-06-15 23:02:42 +00003296 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3297 llvm::Value *value = result.getPointer();
3298 if (!result.getInt())
3299 value = EmitARCRetain(e->getType(), value);
3300 return value;
3301}
3302
3303llvm::Value *
3304CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003305 // The retain needs to happen within the full-expression.
3306 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCalld21cdd42013-02-12 00:25:08 +00003307 RunCleanupsScope scope(*this);
3308 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3309 }
3310
John McCall31168b02011-06-15 23:02:42 +00003311 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3312 llvm::Value *value = result.getPointer();
3313 if (result.getInt())
3314 value = EmitARCAutorelease(value);
3315 else
3316 value = EmitARCRetainAutorelease(e->getType(), value);
3317 return value;
3318}
3319
John McCallff613032011-10-04 06:23:45 +00003320llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3321 llvm::Value *result;
3322 bool doRetain;
3323
3324 if (shouldEmitSeparateBlockRetain(e)) {
3325 result = EmitScalarExpr(e);
3326 doRetain = true;
3327 } else {
3328 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3329 result = subresult.getPointer();
3330 doRetain = !subresult.getInt();
3331 }
3332
3333 if (doRetain)
3334 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3335 return EmitObjCConsumeObject(e->getType(), result);
3336}
3337
John McCall248512a2011-10-01 10:32:24 +00003338llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3339 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003340 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003341 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003342 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003343 return EmitARCRetainAutoreleaseScalarExpr(expr);
3344 }
3345
3346 // Otherwise, use the normal scalar-expression emission. The
3347 // exception machinery doesn't do anything special with the
3348 // exception like retaining it, so there's no safety associated with
3349 // only running cleanups after the throw has started, and when it
3350 // matters it tends to be substantially inferior code.
3351 return EmitScalarExpr(expr);
3352}
3353
John McCalle399e5b2016-01-27 18:32:30 +00003354namespace {
3355
3356/// An emitter for assigning into an __unsafe_unretained context.
3357struct ARCUnsafeUnretainedExprEmitter :
3358 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3359
3360 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3361
3362 llvm::Value *getValueOfResult(llvm::Value *value) {
3363 return value;
3364 }
3365
3366 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3367 return CGF.Builder.CreateBitCast(value, resultType);
3368 }
3369
3370 llvm::Value *visitLValueToRValue(const Expr *e) {
3371 return CGF.EmitScalarExpr(e);
3372 }
3373
3374 /// For consumptions, just emit the subexpression and perform the
3375 /// consumption like normal.
3376 llvm::Value *visitConsumeObject(const Expr *e) {
3377 llvm::Value *value = CGF.EmitScalarExpr(e);
3378 return CGF.EmitObjCConsumeObject(e->getType(), value);
3379 }
3380
3381 /// No special logic for block extensions. (This probably can't
3382 /// actually happen in this emitter, though.)
3383 llvm::Value *visitExtendBlockObject(const Expr *e) {
3384 return CGF.EmitARCExtendBlockObject(e);
3385 }
3386
3387 /// For reclaims, perform an unsafeClaim if that's enabled.
3388 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3389 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3390 }
3391
3392 /// When we have an undecorated call, just emit it without adding
3393 /// the unsafeClaim.
3394 llvm::Value *visitCall(const Expr *e) {
3395 return CGF.EmitScalarExpr(e);
3396 }
3397
3398 /// Just do normal scalar emission in the default case.
3399 llvm::Value *visitExpr(const Expr *e) {
3400 return CGF.EmitScalarExpr(e);
3401 }
3402};
3403}
3404
3405static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3406 const Expr *e) {
3407 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3408}
3409
3410/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3411/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3412/// avoiding any spurious retains, including by performing reclaims
3413/// with objc_unsafeClaimAutoreleasedReturnValue.
3414llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3415 // Look through full-expressions.
3416 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCalle399e5b2016-01-27 18:32:30 +00003417 RunCleanupsScope scope(*this);
3418 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3419 }
3420
3421 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3422}
3423
3424std::pair<LValue,llvm::Value*>
3425CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3426 bool ignored) {
3427 // Evaluate the RHS first. If we're ignoring the result, assume
3428 // that we can emit at an unsafe +0.
3429 llvm::Value *value;
3430 if (ignored) {
3431 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3432 } else {
3433 value = EmitScalarExpr(e->getRHS());
3434 }
3435
3436 // Emit the LHS and perform the store.
3437 LValue lvalue = EmitLValue(e->getLHS());
3438 EmitStoreOfScalar(value, lvalue);
3439
3440 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3441}
3442
John McCall31168b02011-06-15 23:02:42 +00003443std::pair<LValue,llvm::Value*>
3444CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3445 bool ignored) {
3446 // Evaluate the RHS first.
3447 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3448 llvm::Value *value = result.getPointer();
3449
John McCallb726a552011-07-28 07:23:35 +00003450 bool hasImmediateRetain = result.getInt();
3451
3452 // If we didn't emit a retained object, and the l-value is of block
3453 // type, then we need to emit the block-retain immediately in case
3454 // it invalidates the l-value.
3455 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003456 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003457 hasImmediateRetain = true;
3458 }
3459
John McCall31168b02011-06-15 23:02:42 +00003460 LValue lvalue = EmitLValue(e->getLHS());
3461
3462 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003463 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003464 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003465 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003466 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003467 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003468 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003469 }
3470
3471 return std::pair<LValue,llvm::Value*>(lvalue, value);
3472}
3473
3474std::pair<LValue,llvm::Value*>
3475CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3476 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3477 LValue lvalue = EmitLValue(e->getLHS());
3478
Eli Friedmana0544d62011-12-03 04:14:32 +00003479 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003480
3481 return std::pair<LValue,llvm::Value*>(lvalue, value);
3482}
3483
3484void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003485 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003486 const Stmt *subStmt = ARPS.getSubStmt();
3487 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3488
3489 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003490 if (DI)
3491 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003492
3493 // Keep track of the current cleanup stack depth.
3494 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003495 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003496 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3497 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3498 } else {
3499 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3500 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3501 }
3502
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003503 for (const auto *I : S.body())
3504 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003505
Eric Christopher7cdf9482011-10-13 21:45:18 +00003506 if (DI)
3507 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003508}
John McCall1bd25562011-06-24 23:21:27 +00003509
3510/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3511/// make sure it survives garbage collection until this point.
3512void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3513 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003514 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003515 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003516 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3517 /* assembly */ "",
3518 /* constraints */ "r",
3519 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003520
3521 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003522 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003523}
3524
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003525/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003526/// non-trivial copy assignment function, produce following helper function.
3527/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3528///
3529llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003530CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3531 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003532 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003533 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003534 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003535 QualType Ty = PID->getPropertyIvarDecl()->getType();
3536 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003537 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003538 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04003539 if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003540 return nullptr;
3541 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003542 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003543 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003544 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3545 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3546 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003547
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003548 ASTContext &C = getContext();
3549 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003550 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003551
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003552 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003553 QualType DestTy = C.getPointerType(Ty);
3554 QualType SrcTy = Ty;
3555 SrcTy.addConst();
3556 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003557
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003558 SmallVector<QualType, 2> ArgTys;
3559 ArgTys.push_back(DestTy);
3560 ArgTys.push_back(SrcTy);
3561 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3562
3563 FunctionDecl *FD = FunctionDecl::Create(
3564 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3565 FunctionTy, nullptr, SC_Static, false, false);
3566
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003567 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003568 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3569 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003570 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003571 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3572 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003573 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003574
John McCallc56a8b32016-03-11 04:30:31 +00003575 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003576 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003577
John McCalla729c622012-02-17 03:33:10 +00003578 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003579
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003580 llvm::Function *Fn =
3581 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003582 "__assign_helper_atomic_property_",
3583 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003584
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003585 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003586
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003587 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003588
Melanie Blowerf5360d42020-05-01 10:32:06 -07003589 DeclRefExpr DstExpr(C, &DstDecl, false, DestTy, VK_RValue, SourceLocation());
3590 UnaryOperator *DST = UnaryOperator::Create(
3591 C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003592 SourceLocation(), false, FPOptionsOverride());
Fangrui Song6907ce22018-07-30 19:24:48 +00003593
Melanie Blowerf5360d42020-05-01 10:32:06 -07003594 DeclRefExpr SrcExpr(C, &SrcDecl, false, SrcTy, VK_RValue, SourceLocation());
3595 UnaryOperator *SRC = UnaryOperator::Create(
3596 C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003597 SourceLocation(), false, FPOptionsOverride());
Fangrui Song6907ce22018-07-30 19:24:48 +00003598
Melanie Blowerf5360d42020-05-01 10:32:06 -07003599 Expr *Args[2] = {DST, SRC};
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003600 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003601 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3602 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003603 VK_LValue, SourceLocation(), FPOptionsOverride());
Fangrui Song6907ce22018-07-30 19:24:48 +00003604
Bruno Riccic5885cf2018-12-21 15:20:32 +00003605 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003606
3607 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003608 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003609 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003610 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003611}
3612
3613llvm::Constant *
3614CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3615 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003616 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003617 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003618 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003619 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3620 QualType Ty = PD->getType();
3621 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003622 return nullptr;
Puyan Lotfi9721fbf2020-04-23 02:20:56 -04003623 if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003624 return nullptr;
3625 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003626 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003627 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003628 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3629 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3630 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003631
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003632 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003633 IdentifierInfo *II =
3634 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003635
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003636 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003637 QualType DestTy = C.getPointerType(Ty);
3638 QualType SrcTy = Ty;
3639 SrcTy.addConst();
3640 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003641
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003642 SmallVector<QualType, 2> ArgTys;
3643 ArgTys.push_back(DestTy);
3644 ArgTys.push_back(SrcTy);
3645 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3646
3647 FunctionDecl *FD = FunctionDecl::Create(
3648 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3649 FunctionTy, nullptr, SC_Static, false, false);
3650
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003651 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003652 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3653 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003654 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003655 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3656 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003657 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003658
John McCallc56a8b32016-03-11 04:30:31 +00003659 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003660 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003661
John McCalla729c622012-02-17 03:33:10 +00003662 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003663
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003664 llvm::Function *Fn = llvm::Function::Create(
3665 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3666 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003667
3668 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003669
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003670 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003671
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003672 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3673 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003674
Melanie Blowerf5360d42020-05-01 10:32:06 -07003675 UnaryOperator *SRC = UnaryOperator::Create(
3676 C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
Melanie Blowerf4aaed32020-06-26 09:23:45 -07003677 SourceLocation(), false, FPOptionsOverride());
Fangrui Song6907ce22018-07-30 19:24:48 +00003678
3679 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003680 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003681
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003682 SmallVector<Expr*, 4> ConstructorArgs;
Melanie Blowerf5360d42020-05-01 10:32:06 -07003683 ConstructorArgs.push_back(SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003684 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3685 CXXConstExpr->arg_end());
3686
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003687 CXXConstructExpr *TheCXXConstructExpr =
3688 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3689 CXXConstExpr->getConstructor(),
3690 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003691 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003692 CXXConstExpr->hadMultipleCandidates(),
3693 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003694 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003695 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003696 CXXConstExpr->getConstructionKind(),
3697 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003698
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003699 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3700 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003701
John McCall113bee02012-03-10 09:33:50 +00003702 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003703 CharUnits Alignment
3704 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003705 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003706 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3707 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003708 AggValueSlot::IsDestructed,
3709 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003710 AggValueSlot::IsNotAliased,
3711 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003712
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003713 FinishFunction();
3714 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3715 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3716 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003717}
3718
Eli Friedmanec75fec2012-02-28 01:08:45 +00003719llvm::Value *
3720CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3721 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003722 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3723 Selector CopySelector =
3724 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003725 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3726 Selector AutoreleaseSelector =
3727 getContext().Selectors.getNullarySelector(AutoreleaseID);
3728
3729 // Emit calls to retain/autorelease.
3730 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3731 llvm::Value *Val = Block;
3732 RValue Result;
3733 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003734 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003735 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003736 Val = Result.getScalarVal();
3737 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3738 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003739 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003740 Val = Result.getScalarVal();
3741 return Val;
3742}
3743
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003744llvm::Value *
3745CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3746 assert(Args.size() == 3 && "Expected 3 argument here!");
3747
3748 if (!CGM.IsOSVersionAtLeastFn) {
3749 llvm::FunctionType *FTy =
3750 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3751 CGM.IsOSVersionAtLeastFn =
3752 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3753 }
3754
3755 llvm::Value *CallRes =
3756 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3757
3758 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3759}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003760
Alex Lorenza8fbef42017-03-23 11:14:27 +00003761void CodeGenModule::emitAtAvailableLinkGuard() {
3762 if (!IsOSVersionAtLeastFn)
3763 return;
3764 // @available requires CoreFoundation only on Darwin.
3765 if (!Target.getTriple().isOSDarwin())
3766 return;
3767 // Add -framework CoreFoundation to the linker commands. We still want to
3768 // emit the core foundation reference down below because otherwise if
3769 // CoreFoundation is not used in the code, the linker won't link the
3770 // framework.
3771 auto &Context = getLLVMContext();
3772 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3773 llvm::MDString::get(Context, "CoreFoundation")};
3774 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3775 // Emit a reference to a symbol from CoreFoundation to ensure that
3776 // CoreFoundation is linked into the final binary.
3777 llvm::FunctionType *FTy =
3778 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003779 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003780 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3781
3782 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003783 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3784 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003785 llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00003786 llvm::Function *CFLinkCheckFunc =
3787 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3788 if (CFLinkCheckFunc->empty()) {
3789 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3790 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3791 CodeGenFunction CGF(*this);
3792 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3793 CGF.EmitNounwindRuntimeCall(CFFunc,
3794 llvm::Constant::getNullValue(VoidPtrTy));
3795 CGF.Builder.CreateUnreachable();
3796 addCompilerUsedGlobal(CFLinkCheckFunc);
3797 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003798}
3799
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003800CGObjCRuntime::~CGObjCRuntime() {}