blob: 3c11aa7f2f42aa7844a76c6c4ea7a33c3f5cd052 [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
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000464 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]' or
465 // we are in an ObjC class method and 'receiver' is '[self alloc]'.
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
472 // Check if we are in an ObjC class method and the receiver expression is
473 // 'self'.
474 const Expr *SelfInClassMethod = nullptr;
475 if (const auto *CurMD = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
476 if (CurMD->isClassMethod())
477 if ((SelfInClassMethod = SubOME->getInstanceReceiver()))
478 if (!SelfInClassMethod->isObjCSelfExpr())
479 SelfInClassMethod = nullptr;
480
481 if ((SubOME->getReceiverKind() != ObjCMessageExpr::Class &&
482 !SelfInClassMethod) || !SubOME->getType()->isObjCObjectPointerType() ||
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000483 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
484 return None;
485
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000486 llvm::Value *Receiver;
487 if (SelfInClassMethod) {
488 Receiver = CGF.EmitScalarExpr(SelfInClassMethod);
489 } else {
490 QualType ReceiverType = SubOME->getClassReceiver();
491 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
492 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
493 assert(ID && "null interface should be impossible here");
494 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
495 }
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000496 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
497}
498
John McCall78a15112010-05-22 01:48:05 +0000499RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
500 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000501 // Only the lookup mechanism and first two arguments of the method
502 // implementation vary between runtimes. We can get the receiver and
503 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000504
John McCall31168b02011-06-15 23:02:42 +0000505 bool isDelegateInit = E->isDelegateInitCall();
506
John McCallcf166702011-07-22 08:53:00 +0000507 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000508
John McCall460ce582015-10-22 18:38:17 +0000509 // If the method is -retain, and the receiver's being loaded from
510 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
511 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
512 method->getMethodFamily() == OMF_retain) {
513 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
514 LValue lvalue = EmitLValue(lvalueExpr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800515 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +0000516 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
517 }
518 }
519
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000520 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
521 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
522
John McCall31168b02011-06-15 23:02:42 +0000523 // We don't retain the receiver in delegate init calls, and this is
524 // safe because the receiver value is always loaded from 'self',
525 // which we zero out. We don't want to Block_copy block receivers,
526 // though.
527 bool retainSelf =
528 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000529 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000530 method &&
531 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000532
Daniel Dunbar8d480592008-08-11 18:12:00 +0000533 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000534 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000535 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000536 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000537 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000538 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000539 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000540 switch (E->getReceiverKind()) {
541 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000542 ReceiverType = E->getInstanceReceiver()->getType();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000543 if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl))
544 if (OMD->isClassMethod())
545 if (E->getInstanceReceiver()->isObjCSelfExpr())
546 isClassMessage = true;
John McCall31168b02011-06-15 23:02:42 +0000547 if (retainSelf) {
548 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
549 E->getInstanceReceiver());
550 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000551 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000552 } else
553 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000554 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000555
Douglas Gregor9a129192010-04-21 00:45:42 +0000556 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000557 ReceiverType = E->getClassReceiver();
558 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000559 assert(ObjTy && "Invalid Objective-C class message send");
560 OID = ObjTy->getInterface();
561 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000562 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000563 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000564 break;
565 }
566
567 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000568 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000569 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000570 isSuperMessage = true;
571 break;
572
573 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000574 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000575 Receiver = LoadObjCSelf();
576 isSuperMessage = true;
577 isClassMessage = true;
578 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000579 }
580
John McCallcf166702011-07-22 08:53:00 +0000581 if (retainSelf)
582 Receiver = EmitARCRetainNonBlock(Receiver);
583
584 // In ARC, we sometimes want to "extend the lifetime"
585 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
586 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000587 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000588 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
589 shouldExtendReceiverForInnerPointerMessage(E))
590 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
591
Alp Toker314cc812014-01-25 16:55:45 +0000592 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000593
Daniel Dunbarc722b852008-08-30 03:02:31 +0000594 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000595 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000596
John McCall31168b02011-06-15 23:02:42 +0000597 // For delegate init calls in ARC, do an unsafe store of null into
598 // self. This represents the call taking direct ownership of that
599 // value. We have to do this after emitting the other call
600 // arguments because they might also reference self, but we don't
601 // have to worry about any of them modifying self because that would
602 // be an undefined read and write of an object in unordered
603 // expressions.
604 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000605 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000606 "delegate init calls should only be marked in ARC");
607
608 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000609 Address selfAddr =
610 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000611 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
612 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000613
Douglas Gregor33823722011-06-11 01:09:30 +0000614 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000615 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000616 // super is only valid in an Objective-C method
617 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000618 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000619 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
620 E->getSelector(),
621 OMD->getClassInterface(),
622 isCategoryImpl,
623 Receiver,
624 isClassMessage,
625 Args,
John McCallcf166702011-07-22 08:53:00 +0000626 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000627 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000628 // Call runtime methods directly if we can.
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800629 result = Runtime.GeneratePossiblySpecializedMessageSend(
630 *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
631 method, isClassMessage);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000632 }
John McCall31168b02011-06-15 23:02:42 +0000633
634 // For delegate init calls in ARC, implicitly store the result of
635 // the call back into self. This takes ownership of the value.
636 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000637 Address selfAddr =
638 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000639 llvm::Value *newSelf = result.getScalarVal();
640
641 // The delegate return type isn't necessarily a matching type; in
642 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000643 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000644 newSelf = Builder.CreateBitCast(newSelf, selfTy);
645
646 Builder.CreateStore(newSelf, selfAddr);
647 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000648
Douglas Gregore83b9562015-07-07 03:57:53 +0000649 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000650}
651
John McCall31168b02011-06-15 23:02:42 +0000652namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000653struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000654 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000655 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000656
657 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000658 const ObjCInterfaceDecl *iface = impl->getClassInterface();
659 if (!iface->getSuperClass()) return;
660
John McCalldffafde2011-07-13 18:26:47 +0000661 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
662
John McCall31168b02011-06-15 23:02:42 +0000663 // Call [super dealloc] if we have a superclass.
664 llvm::Value *self = CGF.LoadObjCSelf();
665
666 CallArgList args;
667 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
668 CGF.getContext().VoidTy,
669 method->getSelector(),
670 iface,
John McCalldffafde2011-07-13 18:26:47 +0000671 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000672 self,
673 /*is class msg*/ false,
674 args,
675 method);
676 }
677};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000678}
John McCall31168b02011-06-15 23:02:42 +0000679
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000680/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
681/// the LLVM function and sets the other context used by
682/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000683void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000684 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000685 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000686 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000687 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000688 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000689 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000690
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000691 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000692
John McCalla729c622012-02-17 03:33:10 +0000693 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800694 if (OMD->isDirectMethod()) {
695 Fn->setVisibility(llvm::Function::HiddenVisibility);
696 CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
697 CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
698 } else {
699 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
700 }
Chris Lattner5696e7b2008-06-17 18:05:57 +0000701
John McCalla738c252011-03-09 04:27:21 +0000702 args.push_back(OMD->getSelfDecl());
703 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000704
Benjamin Kramerf9890422015-02-17 16:48:30 +0000705 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000706
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000707 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000708 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000709
Adrian Prantl42d71b92014-04-10 23:21:53 +0000710 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
711 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000712
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800713 if (OMD->isDirectMethod()) {
714 // This function is a direct call, it has to implement a nil check
715 // on entry.
716 //
717 // TODO: possibly have several entry points to elide the check
718 CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
719 }
720
John McCall31168b02011-06-15 23:02:42 +0000721 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000723 OMD->isInstanceMethod() &&
724 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000725 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000726 OMD->getSelector().getIdentifierInfoForSlot(0);
727 if (ident->isStr("dealloc"))
728 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
729 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000730}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000731
John McCall31168b02011-06-15 23:02:42 +0000732static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
733 LValue lvalue, QualType type);
734
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000735/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000736/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000737void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000738 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000739 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000740 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000741 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000742 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000743 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000744}
745
John McCallb923ece2011-09-12 23:06:44 +0000746/// emitStructGetterCall - Call the runtime function to load a property
747/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000748static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000749 bool isAtomic, bool hasStrong) {
750 ASTContext &Context = CGF.getContext();
751
John McCall7f416cc2015-09-08 08:05:57 +0000752 Address src =
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800753 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
754 .getAddress(CGF);
John McCallb923ece2011-09-12 23:06:44 +0000755
Fangrui Song6907ce22018-07-30 19:24:48 +0000756 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000757 // sizeof (Type of Ivar), isAtomic, false);
758 CallArgList args;
759
John McCall7f416cc2015-09-08 08:05:57 +0000760 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
761 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000762
763 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000764 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000765
766 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
767 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
768 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
769 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
770
James Y Knight9871db02019-02-05 16:42:33 +0000771 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000772 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000773 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000774 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000775}
776
John McCallf4528ae2011-09-13 03:34:09 +0000777/// Determine whether the given architecture supports unaligned atomic
778/// accesses. They don't have to be fast, just faster than a function
779/// call and a mutex.
780static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000781 // FIXME: Allow unaligned atomic load/store on x86. (It is not
782 // currently supported by the backend.)
783 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000784}
785
786/// Return the maximum size that permits atomic accesses for the given
787/// architecture.
788static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
789 llvm::Triple::ArchType arch) {
790 // ARM has 8-byte atomic accesses, but it's not clear whether we
791 // want to rely on them here.
792
793 // In the default case, just assume that any size up to a pointer is
794 // fine given adequate alignment.
795 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
796}
797
798namespace {
799 class PropertyImplStrategy {
800 public:
801 enum StrategyKind {
802 /// The 'native' strategy is to use the architecture's provided
803 /// reads and writes.
804 Native,
805
806 /// Use objc_setProperty and objc_getProperty.
807 GetSetProperty,
808
809 /// Use objc_setProperty for the setter, but use expression
810 /// evaluation for the getter.
811 SetPropertyAndExpressionGet,
812
813 /// Use objc_copyStruct.
814 CopyStruct,
815
816 /// The 'expression' strategy is to emit normal assignment or
817 /// lvalue-to-rvalue expressions.
818 Expression
819 };
820
821 StrategyKind getKind() const { return StrategyKind(Kind); }
822
823 bool hasStrongMember() const { return HasStrong; }
824 bool isAtomic() const { return IsAtomic; }
825 bool isCopy() const { return IsCopy; }
826
827 CharUnits getIvarSize() const { return IvarSize; }
828 CharUnits getIvarAlignment() const { return IvarAlignment; }
829
830 PropertyImplStrategy(CodeGenModule &CGM,
831 const ObjCPropertyImplDecl *propImpl);
832
833 private:
834 unsigned Kind : 8;
835 unsigned IsAtomic : 1;
836 unsigned IsCopy : 1;
837 unsigned HasStrong : 1;
838
839 CharUnits IvarSize;
840 CharUnits IvarAlignment;
841 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000842}
John McCallf4528ae2011-09-13 03:34:09 +0000843
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000844/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000845PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
846 const ObjCPropertyImplDecl *propImpl) {
847 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000848 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000849
John McCall43192862011-09-13 18:31:23 +0000850 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
851 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000852 HasStrong = false; // doesn't matter here.
853
854 // Evaluate the ivar's size and alignment.
855 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
856 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000857 std::tie(IvarSize, IvarAlignment) =
858 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000859
860 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000861 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000862 if (IsCopy) {
863 Kind = GetSetProperty;
864 return;
865 }
866
John McCall43192862011-09-13 18:31:23 +0000867 // Handle retain.
868 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000869 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000870 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000871 // fallthrough
872
873 // In ARC, if the property is non-atomic, use expression emission,
874 // which translates to objc_storeStrong. This isn't required, but
875 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000876 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000877 // Using standard expression emission for the setter is only
878 // acceptable if the ivar is __strong, which won't be true if
879 // the property is annotated with __attribute__((NSObject)).
880 // TODO: falling all the way back to objc_setProperty here is
881 // just laziness, though; we could still use objc_storeStrong
882 // if we hacked it right.
883 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
884 Kind = Expression;
885 else
886 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000887 return;
888
889 // Otherwise, we need to at least use setProperty. However, if
890 // the property isn't atomic, we can use normal expression
891 // emission for the getter.
892 } else if (!IsAtomic) {
893 Kind = SetPropertyAndExpressionGet;
894 return;
895
896 // Otherwise, we have to use both setProperty and getProperty.
897 } else {
898 Kind = GetSetProperty;
899 return;
900 }
901 }
902
903 // If we're not atomic, just use expression accesses.
904 if (!IsAtomic) {
905 Kind = Expression;
906 return;
907 }
908
John McCall0e5c0862011-09-13 05:36:29 +0000909 // Properties on bitfield ivars need to be emitted using expression
910 // accesses even if they're nominally atomic.
911 if (ivar->isBitField()) {
912 Kind = Expression;
913 return;
914 }
915
John McCallf4528ae2011-09-13 03:34:09 +0000916 // GC-qualified or ARC-qualified ivars need to be emitted as
917 // expressions. This actually works out to being atomic anyway,
918 // except for ARC __strong, but that should trigger the above code.
919 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000920 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000921 CGM.getContext().getObjCGCAttrKind(ivarType))) {
922 Kind = Expression;
923 return;
924 }
925
926 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000927 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000928 if (const RecordType *recordType = ivarType->getAs<RecordType>())
929 HasStrong = recordType->getDecl()->hasObjectMember();
930
931 // We can never access structs with object members with a native
932 // access, because we need to use write barriers. This is what
933 // objc_copyStruct is for.
934 if (HasStrong) {
935 Kind = CopyStruct;
936 return;
937 }
938
939 // Otherwise, this is target-dependent and based on the size and
940 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000941
942 // If the size of the ivar is not a power of two, give up. We don't
943 // want to get into the business of doing compare-and-swaps.
944 if (!IvarSize.isPowerOfTwo()) {
945 Kind = CopyStruct;
946 return;
947 }
948
John McCallf4528ae2011-09-13 03:34:09 +0000949 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000950 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000951
952 // Most architectures require memory to fit within a single cache
953 // line, so the alignment has to be at least the size of the access.
954 // Otherwise we have to grab a lock.
955 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
956 Kind = CopyStruct;
957 return;
958 }
959
960 // If the ivar's size exceeds the architecture's maximum atomic
961 // access size, we have to use CopyStruct.
962 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
963 Kind = CopyStruct;
964 return;
965 }
966
967 // Otherwise, we can use native loads and stores.
968 Kind = Native;
969}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000970
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000971/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000972///
973/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000974/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000975void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
976 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000977 llvm::Constant *AtomicHelperFn =
978 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -0800979 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000980 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000981 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000982
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000983 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000984
Adrian Prantlce7d3592019-12-05 12:26:16 -0800985 FinishFunction(OMD->getEndLoc());
John McCallf4528ae2011-09-13 03:34:09 +0000986}
987
John McCallbdd81852011-09-13 06:00:03 +0000988static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
989 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000990 if (!getter) return true;
991
992 // Sema only makes only of these when the ivar has a C++ class type,
993 // so the form is pretty constrained.
994
John McCallbdd81852011-09-13 06:00:03 +0000995 // If the property has a reference type, we might just be binding a
996 // reference, in which case the result will be a gl-value. We should
997 // treat this as a non-trivial operation.
998 if (getter->isGLValue())
999 return false;
1000
John McCallf4528ae2011-09-13 03:34:09 +00001001 // If we selected a trivial copy-constructor, we're okay.
1002 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1003 return (construct->getConstructor()->isTrivial());
1004
1005 // The constructor might require cleanups (in which case it's never
1006 // trivial).
1007 assert(isa<ExprWithCleanups>(getter));
1008 return false;
1009}
1010
Fangrui Song6907ce22018-07-30 19:24:48 +00001011/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001012/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +00001013static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001014 llvm::Value *returnAddr,
1015 ObjCIvarDecl *ivar,
1016 llvm::Constant *AtomicHelperFn) {
1017 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1018 // AtomicHelperFn);
1019 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001020
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001021 // The 1st argument is the return Slot.
1022 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001023
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001024 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001025 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001026 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1027 .getPointer(CGF);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001028 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1029 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001030
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001031 // Third argument is the helper function.
1032 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001033
James Y Knight9871db02019-02-05 16:42:33 +00001034 llvm::FunctionCallee copyCppAtomicObjectFn =
1035 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001036 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +00001037 CGF.EmitCall(
1038 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001039 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001040}
1041
John McCallf4528ae2011-09-13 03:34:09 +00001042void
1043CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001044 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001045 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001046 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +00001047 // If there's a non-trivial 'get' expression, we just have to emit that.
1048 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001049 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001050 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1051 propImpl->getGetterCXXConstructor(),
1052 /* NRVOCandidate=*/nullptr);
1053 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001054 }
1055 else {
1056 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001057 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001058 ivar, AtomicHelperFn);
1059 }
John McCallf4528ae2011-09-13 03:34:09 +00001060 return;
1061 }
1062
1063 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1064 QualType propType = prop->getType();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001065 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001066
Fangrui Song6907ce22018-07-30 19:24:48 +00001067 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001068
1069 // Pick an implementation strategy.
1070 PropertyImplStrategy strategy(CGM, propImpl);
1071 switch (strategy.getKind()) {
1072 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001073 // We don't need to do anything for a zero-size struct.
1074 if (strategy.getIvarSize().isZero())
1075 return;
1076
John McCallf4528ae2011-09-13 03:34:09 +00001077 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1078
1079 // Currently, all atomic accesses have to be through integer
1080 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001081 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1082 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001083 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1084
1085 // Perform an atomic load. This does not impose ordering constraints.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001086 Address ivarAddr = LV.getAddress(*this);
John McCallf4528ae2011-09-13 03:34:09 +00001087 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1088 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001089 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001090
1091 // Store that value into the return address. Doing this with a
1092 // bitcast is likely to produce some pretty ugly IR, but it's not
1093 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001094 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1095 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1096 llvm::Value *ivarVal = load;
1097 if (ivarSize > retTySize) {
1098 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1099 ivarVal = Builder.CreateTrunc(load, newTy);
1100 bitcastType = newTy->getPointerTo();
1101 }
1102 Builder.CreateStore(ivarVal,
1103 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001104
1105 // Make sure we don't do an autorelease.
1106 AutoreleaseResult = false;
1107 return;
1108 }
1109
1110 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001111 llvm::FunctionCallee getPropertyFn =
1112 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001113 if (!getPropertyFn) {
1114 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001115 return;
1116 }
John McCallb92ab1a2016-10-26 23:46:34 +00001117 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001118
1119 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1120 // FIXME: Can't this be simpler? This might even be worse than the
1121 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001122 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001123 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001124 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1125 llvm::Value *ivarOffset =
1126 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1127
1128 CallArgList args;
1129 args.add(RValue::get(self), getContext().getObjCIdType());
1130 args.add(RValue::get(cmd), getContext().getObjCSelType());
1131 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001132 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1133 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001134
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001135 // FIXME: We shouldn't need to get the function info here, the
1136 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001137 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001138 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1139 getContext().getObjCIdType(), args),
1140 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001141 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1142 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001143
Daniel Dunbara08dff12008-09-24 04:04:31 +00001144 // We need to fix the type here. Ivars with copy & retain are
1145 // always objects so we don't need to worry about complex or
1146 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001147 RV = RValue::get(Builder.CreateBitCast(
1148 RV.getScalarVal(),
1149 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001150
1151 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001152
1153 // objc_getProperty does an autorelease, so we should suppress ours.
1154 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001155
John McCallf4528ae2011-09-13 03:34:09 +00001156 return;
1157 }
1158
1159 case PropertyImplStrategy::CopyStruct:
1160 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1161 strategy.hasStrongMember());
1162 return;
1163
1164 case PropertyImplStrategy::Expression:
1165 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1166 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1167
1168 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001169 switch (getEvaluationKind(ivarType)) {
1170 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001171 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001172 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001173 /*init*/ true);
1174 return;
1175 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001176 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001177 // The return value slot is guaranteed to not be aliased, but
1178 // that's not necessarily the same as "on the stack", so
1179 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001180 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smith8cca3a52019-06-20 20:56:20 +00001181 /* Src= */ LV, ivarType, getOverlapForReturnValue());
Richard Smithe78fac52018-04-05 20:52:58 +00001182 return;
1183 }
John McCall47fb9502013-03-07 21:37:08 +00001184 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001185 llvm::Value *value;
1186 if (propType->isReferenceType()) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001187 value = LV.getAddress(*this).getPointer();
John McCall24fada12011-07-22 05:23:13 +00001188 } else {
1189 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1190 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001191 if (getLangOpts().ObjCAutoRefCount) {
1192 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1193 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001194 value = EmitARCLoadWeak(LV.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +00001195 }
John McCall24fada12011-07-22 05:23:13 +00001196
1197 // Otherwise we want to do a simple load, suppressing the
1198 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001199 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001200 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001201 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001202 }
John McCall31168b02011-06-15 23:02:42 +00001203
Alp Toker314cc812014-01-25 16:55:45 +00001204 value = Builder.CreateBitCast(
1205 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001206 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001207
John McCall24fada12011-07-22 05:23:13 +00001208 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001209 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001210 }
John McCall47fb9502013-03-07 21:37:08 +00001211 }
1212 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001213 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001214
John McCallf4528ae2011-09-13 03:34:09 +00001215 }
1216 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001217}
1218
John McCallb923ece2011-09-12 23:06:44 +00001219/// emitStructSetterCall - Call the runtime function to store the value
1220/// from the first formal parameter into the given ivar.
1221static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1222 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001223 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001224 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001225 CallArgList args;
1226
1227 // The first argument is the address of the ivar.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001228 llvm::Value *ivarAddr =
1229 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1230 .getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001231 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1232 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001233
1234 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001235 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001236 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1237 argVar->getType().getNonReferenceType(), VK_LValue,
1238 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001239 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001240 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1241 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001242
1243 // The third argument is the sizeof the type.
1244 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001245 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1246 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001247
John McCallb923ece2011-09-12 23:06:44 +00001248 // The fourth argument is the 'isAtomic' flag.
1249 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001250
John McCallb923ece2011-09-12 23:06:44 +00001251 // The fifth argument is the 'hasStrong' flag.
1252 // FIXME: should this really always be false?
1253 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1254
James Y Knight9871db02019-02-05 16:42:33 +00001255 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001256 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001257 CGF.EmitCall(
1258 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001259 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001260}
1261
Fangrui Song6907ce22018-07-30 19:24:48 +00001262/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1263/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001264/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001265static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001266 ObjCMethodDecl *OMD,
1267 ObjCIvarDecl *ivar,
1268 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001269 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001270 // AtomicHelperFn);
1271 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001272
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001273 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001274 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001275 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1276 .getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001277 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1278 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001279
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001280 // The second argument is the address of the parameter variable.
1281 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001282 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1283 argVar->getType().getNonReferenceType(), VK_LValue,
1284 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001285 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001286 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1287 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001288
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001289 // Third argument is the helper function.
1290 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001291
James Y Knight9871db02019-02-05 16:42:33 +00001292 llvm::FunctionCallee fn =
1293 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001294 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001295 CGF.EmitCall(
1296 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001297 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001298}
1299
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001300
John McCallf4528ae2011-09-13 03:34:09 +00001301static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1302 Expr *setter = PID->getSetterCXXAssignment();
1303 if (!setter) return true;
1304
1305 // Sema only makes only of these when the ivar has a C++ class type,
1306 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001307
1308 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001309 // This also implies that there's nothing non-trivial going on with
1310 // the arguments, because operator= can only be trivial if it's a
1311 // synthesized assignment operator and therefore both parameters are
1312 // references.
1313 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001314 if (const FunctionDecl *callee
1315 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1316 if (callee->isTrivial())
1317 return true;
1318 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001319 }
John McCall7f16c422011-09-10 09:17:20 +00001320
John McCallf4528ae2011-09-13 03:34:09 +00001321 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001322 return false;
1323}
1324
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001325static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001326 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001327 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001328 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001329}
1330
John McCall7f16c422011-09-10 09:17:20 +00001331void
1332CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001333 const ObjCPropertyImplDecl *propImpl,
1334 llvm::Constant *AtomicHelperFn) {
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001335 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001336 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001337
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001338 // Just use the setter expression if Sema gave us one and it's
1339 // non-trivial.
1340 if (!hasTrivialSetExpr(propImpl)) {
1341 if (!AtomicHelperFn)
1342 // If non-atomic, assignment is called directly.
1343 EmitStmt(propImpl->getSetterCXXAssignment());
1344 else
1345 // If atomic, assignment is called via a locking api.
1346 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1347 AtomicHelperFn);
1348 return;
1349 }
John McCall7f16c422011-09-10 09:17:20 +00001350
John McCallf4528ae2011-09-13 03:34:09 +00001351 PropertyImplStrategy strategy(CGM, propImpl);
1352 switch (strategy.getKind()) {
1353 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001354 // We don't need to do anything for a zero-size struct.
1355 if (strategy.getIvarSize().isZero())
1356 return;
1357
John McCall7f416cc2015-09-08 08:05:57 +00001358 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001359
John McCallf4528ae2011-09-13 03:34:09 +00001360 LValue ivarLValue =
1361 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001362 Address ivarAddr = ivarLValue.getAddress(*this);
John McCall7f16c422011-09-10 09:17:20 +00001363
John McCallf4528ae2011-09-13 03:34:09 +00001364 // Currently, all atomic accesses have to be through integer
1365 // types, so there's no point in trying to pick a prettier type.
1366 llvm::Type *bitcastType =
1367 llvm::Type::getIntNTy(getLLVMContext(),
1368 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001369
1370 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001371 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1372 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001373
1374 // This bitcast load is likely to cause some nasty IR.
1375 llvm::Value *load = Builder.CreateLoad(argAddr);
1376
1377 // Perform an atomic store. There are no memory ordering requirements.
1378 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001379 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001380 return;
1381 }
1382
1383 case PropertyImplStrategy::GetSetProperty:
1384 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001385
James Y Knight9871db02019-02-05 16:42:33 +00001386 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1387 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001388 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001389 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001390 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001391 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1392 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001393 if (!setOptimizedPropertyFn) {
1394 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1395 return;
1396 }
John McCall7f16c422011-09-10 09:17:20 +00001397 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001398 else {
1399 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1400 if (!setPropertyFn) {
1401 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1402 return;
1403 }
1404 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001405
John McCall7f16c422011-09-10 09:17:20 +00001406 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1407 // <is-atomic>, <is-copy>).
1408 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001409 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001410 llvm::Value *self =
1411 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1412 llvm::Value *ivarOffset =
1413 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001414 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1415 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1416 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001417
1418 CallArgList args;
1419 args.add(RValue::get(self), getContext().getObjCIdType());
1420 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001421 if (setOptimizedPropertyFn) {
1422 args.add(RValue::get(arg), getContext().getObjCIdType());
1423 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001424 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001425 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001426 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001427 } else {
1428 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1429 args.add(RValue::get(arg), getContext().getObjCIdType());
1430 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1431 getContext().BoolTy);
1432 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1433 getContext().BoolTy);
1434 // FIXME: We shouldn't need to get the function info here, the runtime
1435 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001436 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001437 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001438 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001439 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001440
John McCall7f16c422011-09-10 09:17:20 +00001441 return;
1442 }
1443
John McCallf4528ae2011-09-13 03:34:09 +00001444 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001445 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001446 return;
John McCallf4528ae2011-09-13 03:34:09 +00001447
1448 case PropertyImplStrategy::Expression:
1449 break;
John McCall7f16c422011-09-10 09:17:20 +00001450 }
1451
1452 // Otherwise, fake up some ASTs and emit a normal assignment.
1453 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001454 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001455 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001456 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1457 selfDecl->getType(), CK_LValueToRValue, &self,
1458 VK_RValue);
1459 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001460 SourceLocation(), SourceLocation(),
1461 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001462
1463 ParmVarDecl *argDecl = *setterMethod->param_begin();
1464 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001465 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1466 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001467 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1468 argType.getUnqualifiedType(), CK_LValueToRValue,
1469 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001470
John McCall7f16c422011-09-10 09:17:20 +00001471 // The property type can differ from the ivar type in some situations with
1472 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1473 // The following absurdity is just to ensure well-formed IR.
1474 CastKind argCK = CK_NoOp;
1475 if (ivarRef.getType()->isObjCObjectPointerType()) {
1476 if (argLoad.getType()->isObjCObjectPointerType())
1477 argCK = CK_BitCast;
1478 else if (argLoad.getType()->isBlockPointerType())
1479 argCK = CK_BlockPointerToObjCPointerCast;
1480 else
1481 argCK = CK_CPointerToObjCPointerCast;
1482 } else if (ivarRef.getType()->isBlockPointerType()) {
1483 if (argLoad.getType()->isBlockPointerType())
1484 argCK = CK_BitCast;
1485 else
1486 argCK = CK_AnyPointerToBlockPointerCast;
1487 } else if (ivarRef.getType()->isPointerType()) {
1488 argCK = CK_BitCast;
1489 }
1490 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1491 ivarRef.getType(), argCK, &argLoad,
1492 VK_RValue);
1493 Expr *finalArg = &argLoad;
1494 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1495 argLoad.getType()))
1496 finalArg = &argCast;
1497
1498
1499 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1500 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001501 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001502 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001503}
1504
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001505/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001506///
1507/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001508/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001509void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1510 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001511 llvm::Constant *AtomicHelperFn =
1512 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -08001513 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001514 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001515 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001516
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001517 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001518
Adrian Prantlce7d3592019-12-05 12:26:16 -08001519 FinishFunction(OMD->getEndLoc());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001520}
1521
John McCall6a4fa522011-03-22 07:05:39 +00001522namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001523 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001524 private:
1525 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001526 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001527 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001528 bool useEHCleanupForArray;
1529 public:
1530 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1531 CodeGenFunction::Destroyer *destroyer,
1532 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001533 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001534 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001535
Craig Topper4f12f102014-03-12 06:41:41 +00001536 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001537 LValue lvalue
1538 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001539 CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001540 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001541 }
1542 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001543}
John McCall6a4fa522011-03-22 07:05:39 +00001544
John McCall4bd0fb12011-07-12 16:41:08 +00001545/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1546static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001547 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001548 QualType type) {
1549 llvm::Value *null = getNullForVariable(addr);
1550 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1551}
John McCall31168b02011-06-15 23:02:42 +00001552
John McCall6a4fa522011-03-22 07:05:39 +00001553static void emitCXXDestructMethod(CodeGenFunction &CGF,
1554 ObjCImplementationDecl *impl) {
1555 CodeGenFunction::RunCleanupsScope scope(CGF);
1556
1557 llvm::Value *self = CGF.LoadObjCSelf();
1558
Jordy Rosea91768e2011-07-22 02:08:32 +00001559 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1560 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001561 ivar; ivar = ivar->getNextIvar()) {
1562 QualType type = ivar->getType();
1563
John McCall6a4fa522011-03-22 07:05:39 +00001564 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001565 QualType::DestructionKind dtorKind = type.isDestructedType();
1566 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001567
Craig Topper8a13c412014-05-21 05:09:00 +00001568 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001569
John McCall4bd0fb12011-07-12 16:41:08 +00001570 // Use a call to objc_storeStrong to destroy strong ivars, for the
1571 // general benefit of the tools.
1572 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001573 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001574
John McCall4bd0fb12011-07-12 16:41:08 +00001575 // Otherwise use the default for the destruction kind.
1576 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001577 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001578 }
John McCall4bd0fb12011-07-12 16:41:08 +00001579
1580 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1581
1582 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1583 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001584 }
1585
1586 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1587}
1588
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001589void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1590 ObjCMethodDecl *MD,
1591 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001592 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001593 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001594
1595 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001596 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001597 // Suppress the final autorelease in ARC.
1598 AutoreleaseResult = false;
1599
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001600 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001601 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001602 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001603 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001604 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001605 EmitAggExpr(IvarInit->getInit(),
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001606 AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001607 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001608 AggValueSlot::IsNotAliased,
1609 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001610 }
1611 // constructor returns 'self'.
1612 CodeGenTypes &Types = CGM.getTypes();
1613 QualType IdTy(CGM.getContext().getObjCIdType());
1614 llvm::Value *SelfAsId =
1615 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1616 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001617
1618 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001619 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001620 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001621 }
1622 FinishFunction();
1623}
1624
Daniel Dunbara08dff12008-09-24 04:04:31 +00001625llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001626 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001627 DeclRefExpr DRE(getContext(), Self,
1628 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001629 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001630 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001631}
1632
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001633QualType CodeGenFunction::TypeOfSelfObject() {
1634 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1635 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001636 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1637 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001638 return PTy->getPointeeType();
1639}
1640
Chris Lattnerd4808922009-03-22 21:03:39 +00001641void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001642 llvm::FunctionCallee EnumerationMutationFnPtr =
1643 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001644 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001645 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1646 return;
1647 }
John McCallb92ab1a2016-10-26 23:46:34 +00001648 CGCallee EnumerationMutationFn =
1649 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001650
Devang Pateld2d66652011-01-19 01:36:36 +00001651 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001652 if (DI)
1653 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001654
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001655 RunCleanupsScope ForScope(*this);
1656
Kuba Mracek82c21752017-04-14 01:00:03 +00001657 // The local variable comes into scope immediately.
1658 AutoVarEmission variable = AutoVarEmission::invalid();
1659 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1660 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1661
John McCall1c926b72011-01-07 01:49:06 +00001662 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001663
Anders Carlsson75658592008-08-31 02:33:12 +00001664 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001665 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001666 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001667 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001668
Anders Carlsson75658592008-08-31 02:33:12 +00001669 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001670 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001671
John McCall1c926b72011-01-07 01:49:06 +00001672 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001673 IdentifierInfo *II[] = {
1674 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1675 &CGM.getContext().Idents.get("objects"),
1676 &CGM.getContext().Idents.get("count")
1677 };
1678 Selector FastEnumSel =
1679 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001680
1681 QualType ItemsTy =
1682 getContext().getConstantArrayType(getContext().getObjCIdType(),
Richard Smith772e2662019-10-04 01:25:59 +00001683 llvm::APInt(32, NumItems), nullptr,
Anders Carlsson75658592008-08-31 02:33:12 +00001684 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001685 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001686
John McCall53848232011-07-27 01:07:15 +00001687 // Emit the collection pointer. In ARC, we do a retain.
1688 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001689 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001690 Collection = EmitARCRetainScalarExpr(S.getCollection());
1691
1692 // Enter a cleanup to do the release.
1693 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1694 } else {
1695 Collection = EmitScalarExpr(S.getCollection());
1696 }
Mike Stump11289f42009-09-09 15:08:12 +00001697
John McCall91e82dd2011-08-05 00:14:38 +00001698 // The 'continue' label needs to appear within the cleanup for the
1699 // collection object.
1700 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1701
John McCall1c926b72011-01-07 01:49:06 +00001702 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001703 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001704
1705 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001706 Args.add(RValue::get(StatePtr.getPointer()),
1707 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001708
John McCall1c926b72011-01-07 01:49:06 +00001709 // The second argument is a temporary array with space for NumItems
1710 // pointers. We'll actually be loading elements from the array
1711 // pointer written into the control state; this buffer is so that
1712 // collections that *aren't* backed by arrays can still queue up
1713 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001714 Args.add(RValue::get(ItemsPtr.getPointer()),
1715 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001716
John McCall1c926b72011-01-07 01:49:06 +00001717 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001718 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1719 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1720 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001721
John McCall1c926b72011-01-07 01:49:06 +00001722 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001723 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001724 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1725 getContext().getNSUIntegerType(),
1726 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001727
John McCall1c926b72011-01-07 01:49:06 +00001728 // The initial number of objects that were returned in the buffer.
1729 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001730
John McCall1c926b72011-01-07 01:49:06 +00001731 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1732 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001733
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001734 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001735
John McCall1c926b72011-01-07 01:49:06 +00001736 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001737 // empty; skip all this. Set the branch weight assuming this has the same
1738 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001739 uint64_t EntryCount = getCurrentProfileCount();
1740 Builder.CreateCondBr(
1741 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1742 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001743 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001744
John McCall1c926b72011-01-07 01:49:06 +00001745 // Otherwise, initialize the loop.
1746 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001747
John McCall1c926b72011-01-07 01:49:06 +00001748 // Save the initial mutations value. This is the value at an
1749 // address that was written into the state object by
1750 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001751 Address StateMutationsPtrPtr =
1752 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001753 llvm::Value *StateMutationsPtr
1754 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001755
John McCall1c926b72011-01-07 01:49:06 +00001756 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001757 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1758 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001759
John McCall1c926b72011-01-07 01:49:06 +00001760 // Start looping. This is the point we return to whenever we have a
1761 // fresh, non-empty batch of objects.
1762 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1763 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001764
John McCall1c926b72011-01-07 01:49:06 +00001765 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001766 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001767 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001768
John McCall1c926b72011-01-07 01:49:06 +00001769 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001770 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001771 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001772
Justin Bogner66242d62015-04-23 23:06:47 +00001773 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001774
John McCall1c926b72011-01-07 01:49:06 +00001775 // Check whether the mutations value has changed from where it was
1776 // at start. StateMutationsPtr should actually be invariant between
1777 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001778 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001779 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001780 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1781 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001782
John McCall1c926b72011-01-07 01:49:06 +00001783 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001784 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001785
John McCall1c926b72011-01-07 01:49:06 +00001786 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1787 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001788
John McCall1c926b72011-01-07 01:49:06 +00001789 // If so, call the enumeration-mutation function.
1790 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001791 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001792 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001793 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001794 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001795 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001796 // FIXME: We shouldn't need to get the function info here, the runtime already
1797 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001798 EmitCall(
1799 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001800 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall1c926b72011-01-07 01:49:06 +00001802 // Otherwise, or if the mutation function returns, just continue.
1803 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001804
John McCall1c926b72011-01-07 01:49:06 +00001805 // Initialize the element variable.
1806 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001807 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001808 LValue elementLValue;
1809 QualType elementType;
1810 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001811 // Initialize the variable, in case it's a __block variable or something.
1812 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001813
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001814 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1815 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1816 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001817 elementLValue = EmitLValue(&tempDRE);
1818 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001819 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001820
1821 if (D->isARCPseudoStrong())
1822 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001823 } else {
1824 elementLValue = LValue(); // suppress warning
1825 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001826 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001827 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001828 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001829
1830 // Fetch the buffer out of the enumeration state.
1831 // TODO: this pointer should actually be invariant between
1832 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001833 Address StateItemsPtr =
1834 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001835 llvm::Value *EnumStateItems =
1836 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001837
John McCall1c926b72011-01-07 01:49:06 +00001838 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001839 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001840 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001841 llvm::Value *CurrentItem =
1842 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001843
John McCall1c926b72011-01-07 01:49:06 +00001844 // Cast that value to the right type.
1845 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1846 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001847
John McCall1c926b72011-01-07 01:49:06 +00001848 // Make sure we have an l-value. Yes, this gets evaluated every
1849 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001850 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001851 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001852 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001853 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001854 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1855 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
John McCall9e2e22f2011-02-22 07:16:58 +00001858 // If we do have an element variable, this assignment is the end of
1859 // its initialization.
1860 if (elementIsVariable)
1861 EmitAutoVarCleanups(variable);
1862
John McCall1c926b72011-01-07 01:49:06 +00001863 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001864 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001865 {
1866 RunCleanupsScope Scope(*this);
1867 EmitStmt(S.getBody());
1868 }
Anders Carlsson75658592008-08-31 02:33:12 +00001869 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001870
John McCall1c926b72011-01-07 01:49:06 +00001871 // Destroy the element variable now.
1872 elementVariableScope.ForceCleanup();
1873
1874 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001875 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001876
John McCall1c926b72011-01-07 01:49:06 +00001877 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001878
John McCall1c926b72011-01-07 01:49:06 +00001879 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001880 llvm::Value *indexPlusOne =
1881 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001882
John McCall1c926b72011-01-07 01:49:06 +00001883 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001884 // Set the branch weights based on the simplifying assumption that this is
1885 // like a while-loop, i.e., ignoring that the false branch fetches more
1886 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001887 Builder.CreateCondBr(
1888 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001889 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001890
1891 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1892 count->addIncoming(count, AfterBody.getBlock());
1893
1894 // Otherwise, we have to fetch more elements.
1895 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001896
1897 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001898 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1899 getContext().getNSUIntegerType(),
1900 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001901
John McCall1c926b72011-01-07 01:49:06 +00001902 // If we got a zero count, we're done.
1903 llvm::Value *refetchCount = CountRV.getScalarVal();
1904
1905 // (note that the message send might split FetchMoreBB)
1906 index->addIncoming(zero, Builder.GetInsertBlock());
1907 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1908
1909 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1910 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Anders Carlsson75658592008-08-31 02:33:12 +00001912 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001913 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001914
John McCall9e2e22f2011-02-22 07:16:58 +00001915 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001916 // If the element was not a declaration, set it to be null.
1917
John McCall1c926b72011-01-07 01:49:06 +00001918 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1919 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001920 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001921 }
1922
Eric Christopher7cdf9482011-10-13 21:45:18 +00001923 if (DI)
1924 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001925
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001926 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001927 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001928}
1929
Mike Stump11289f42009-09-09 15:08:12 +00001930void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001931 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001932}
1933
Mike Stump11289f42009-09-09 15:08:12 +00001934void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001935 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1936}
1937
Chris Lattnere132e242008-11-15 21:26:17 +00001938void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001939 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001940 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001941}
1942
John McCall31168b02011-06-15 23:02:42 +00001943namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001944 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001945 CallObjCRelease(llvm::Value *object) : object(object) {}
1946 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001947
Craig Topper4f12f102014-03-12 06:41:41 +00001948 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001949 // Releases at the end of the full-expression are imprecise.
1950 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001951 }
1952 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001953}
John McCall31168b02011-06-15 23:02:42 +00001954
John McCall2d637d22011-09-10 06:18:15 +00001955/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001956/// release at the end of the full-expression.
1957llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1958 llvm::Value *object) {
1959 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001960 // conditional.
1961 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001962 return object;
1963}
1964
1965llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1966 llvm::Value *value) {
1967 return EmitARCRetainAutorelease(type, value);
1968}
1969
John McCalleff18842013-03-23 02:35:54 +00001970/// Given a number of pointers, inform the optimizer that they're
1971/// being intrinsically used up until this point in the program.
1972void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001973 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001974 if (!fn)
1975 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001976
1977 // This isn't really a "runtime" function, but as an intrinsic it
1978 // doesn't really matter as long as we align things up.
1979 EmitNounwindRuntimeCall(fn, values);
1980}
1981
James Y Knight9871db02019-02-05 16:42:33 +00001982static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001983 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001984 // If the target runtime doesn't naturally support ARC, emit weak
1985 // references to the runtime support library. We don't really
1986 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001987 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1988 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001989 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001990 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001991 }
John McCall31168b02011-06-15 23:02:42 +00001992}
1993
James Y Knight9871db02019-02-05 16:42:33 +00001994static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1995 llvm::FunctionCallee RTF) {
1996 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1997}
1998
John McCall31168b02011-06-15 23:02:42 +00001999/// Perform an operation having the signature
2000/// i8* (i8*)
2001/// where a null input causes a no-op and returns null.
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002002static llvm::Value *emitARCValueOperation(
2003 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2004 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2005 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002006 if (isa<llvm::ConstantPointerNull>(value))
2007 return value;
John McCall31168b02011-06-15 23:02:42 +00002008
2009 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002010 fn = CGF.CGM.getIntrinsic(IntID);
2011 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002012 }
2013
2014 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00002015 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00002016 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2017
2018 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00002019 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002020 call->setTailCallKind(tailKind);
John McCall31168b02011-06-15 23:02:42 +00002021
2022 // Cast the result back to the original type.
2023 return CGF.Builder.CreateBitCast(call, origType);
2024}
2025
2026/// Perform an operation having the following signature:
2027/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002028static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2029 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002030 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00002031 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002032 fn = CGF.CGM.getIntrinsic(IntID);
2033 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002034 }
2035
2036 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00002037 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00002038 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2039
2040 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002041 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002042
2043 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002044 if (origType != CGF.Int8PtrTy)
2045 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002046
2047 return result;
2048}
2049
2050/// Perform an operation having the following signature:
2051/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002052static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002053 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002054 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002055 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002056 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002057 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002058
2059 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002060 fn = CGF.CGM.getIntrinsic(IntID);
2061 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002062 }
2063
Chris Lattner2192fe52011-07-18 04:24:23 +00002064 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002065
John McCall882987f2013-02-28 19:01:20 +00002066 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002067 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002068 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2069 };
2070 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002071
Craig Topper8a13c412014-05-21 05:09:00 +00002072 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002073
2074 return CGF.Builder.CreateBitCast(result, origType);
2075}
2076
2077/// Perform an operation having the following signature:
2078/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002079static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2080 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002081 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002082 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002083
2084 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002085 fn = CGF.CGM.getIntrinsic(IntID);
2086 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002087 }
2088
John McCall882987f2013-02-28 19:01:20 +00002089 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002090 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2091 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002092 };
2093 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002094}
2095
Pete Cooper2cd35962018-12-18 20:33:00 +00002096/// Perform an operation having the signature
2097/// i8* (i8*)
2098/// where a null input causes a no-op and returns null.
2099static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2100 llvm::Value *value,
2101 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002102 llvm::FunctionCallee &fn,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002103 StringRef fnName) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002104 if (isa<llvm::ConstantPointerNull>(value))
2105 return value;
2106
2107 if (!fn) {
2108 llvm::FunctionType *fnType =
2109 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2110 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002111
2112 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002113 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002114 if (fnName == "objc_retain")
2115 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002116 }
2117
2118 // Cast the argument to 'id'.
2119 llvm::Type *origType = returnType ? returnType : value->getType();
2120 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2121
2122 // Call the function.
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002123 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002124
2125 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002126 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002127}
2128
John McCall31168b02011-06-15 23:02:42 +00002129/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002130/// call i8* \@objc_retain(i8* %value)
2131/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002132llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2133 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002134 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002135 else
2136 return EmitARCRetainNonBlock(value);
2137}
2138
2139/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002140/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002141llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002142 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002143 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002144 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002145}
2146
2147/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002148/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002149///
2150/// \param mandatory - If false, emit the call with metadata
2151/// indicating that it's okay for the optimizer to eliminate this call
2152/// if it can prove that the block never escapes except down the stack.
2153llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2154 bool mandatory) {
2155 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002156 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002157 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002158 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002159
2160 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2161 // tell the optimizer that it doesn't need to do this copy if the
2162 // block doesn't escape, where being passed as an argument doesn't
2163 // count as escaping.
2164 if (!mandatory && isa<llvm::Instruction>(result)) {
2165 llvm::CallInst *call
2166 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002167 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002168
John McCallff613032011-10-04 06:23:45 +00002169 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002170 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002171 }
2172
2173 return result;
John McCall31168b02011-06-15 23:02:42 +00002174}
2175
John McCalle399e5b2016-01-27 18:32:30 +00002176static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002177 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002178 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002179 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002180 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002181 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002182 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002183 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002184 .getARCRetainAutoreleasedReturnValueMarker();
2185
2186 // If we have an empty assembly string, there's nothing to do.
2187 if (assembly.empty()) {
2188
2189 // Otherwise, at -O0, build an inline asm that we're going to call
2190 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002191 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002192 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002193 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002194
John McCall31168b02011-06-15 23:02:42 +00002195 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2196
2197 // If we're at -O1 and above, we don't want to litter the code
2198 // with this marker yet, so leave a breadcrumb for the ARC
2199 // optimizer to pick up.
2200 } else {
Akira Hatanaka60c3a3b2019-04-10 06:20:23 +00002201 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2202 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2203 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2204 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
John McCall31168b02011-06-15 23:02:42 +00002205 }
2206 }
2207 }
2208
2209 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002210 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002211 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002212}
John McCall31168b02011-06-15 23:02:42 +00002213
John McCalle399e5b2016-01-27 18:32:30 +00002214/// Retain the given object which is the result of a function call.
2215/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2216///
2217/// Yes, this function name is one character away from a different
2218/// call with completely different semantics.
2219llvm::Value *
2220CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2221 emitAutoreleasedReturnValueMarker(*this);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002222 llvm::CallInst::TailCallKind tailKind =
2223 CGM.getTargetCodeGenInfo()
2224 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2225 ? llvm::CallInst::TCK_NoTail
2226 : llvm::CallInst::TCK_None;
2227 return emitARCValueOperation(
2228 *this, value, nullptr,
2229 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2230 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
John McCall31168b02011-06-15 23:02:42 +00002231}
2232
John McCalle399e5b2016-01-27 18:32:30 +00002233/// Claim a possibly-autoreleased return value at +0. This is only
2234/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002235/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002236/// the value is ignored, or when it is being assigned to an
2237/// __unsafe_unretained variable.
2238///
2239/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2240llvm::Value *
2241CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2242 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002243 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002244 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002245 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002246}
2247
John McCall31168b02011-06-15 23:02:42 +00002248/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002249/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002250void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2251 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002252 if (isa<llvm::ConstantPointerNull>(value)) return;
2253
James Y Knight9871db02019-02-05 16:42:33 +00002254 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002255 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002256 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2257 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002258 }
2259
2260 // Cast the argument to 'id'.
2261 value = Builder.CreateBitCast(value, Int8PtrTy);
2262
2263 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002264 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002265
John McCallcdda29c2013-03-13 03:10:54 +00002266 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002267 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002268 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002269 }
2270}
2271
John McCalle68b8f42012-10-17 02:28:37 +00002272/// Destroy a __strong variable.
2273///
2274/// At -O0, emit a call to store 'null' into the address;
2275/// instrumenting tools prefer this because the address is exposed,
2276/// but it's relatively cumbersome to optimize.
2277///
2278/// At -O1 and above, just load and call objc_release.
2279///
2280/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002281void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002282 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002283 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002284 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002285 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2286 return;
2287 }
2288
2289 llvm::Value *value = Builder.CreateLoad(addr);
2290 EmitARCRelease(value, precise);
2291}
2292
John McCall31168b02011-06-15 23:02:42 +00002293/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002294/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002295llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002296 llvm::Value *value,
2297 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002298 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002299
James Y Knight9871db02019-02-05 16:42:33 +00002300 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002301 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002302 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2303 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002304 }
2305
John McCall882987f2013-02-28 19:01:20 +00002306 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002307 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002308 Builder.CreateBitCast(value, Int8PtrTy)
2309 };
2310 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002311
Craig Topper8a13c412014-05-21 05:09:00 +00002312 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002313 return value;
2314}
2315
2316/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002317/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002318/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002319llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002320 llvm::Value *newValue,
2321 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002322 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002323 bool isBlock = type->isBlockPointerType();
2324
2325 // Use a store barrier at -O0 unless this is a block type or the
2326 // lvalue is inadequately aligned.
2327 if (shouldUseFusedARCCalls() &&
2328 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002329 (dst.getAlignment().isZero() ||
2330 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002331 return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
John McCall31168b02011-06-15 23:02:42 +00002332 }
2333
2334 // Otherwise, split it out.
2335
2336 // Retain the new value.
2337 newValue = EmitARCRetain(type, newValue);
2338
2339 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002340 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002341
2342 // Store. We do this before the release so that any deallocs won't
2343 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002344 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002345
2346 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002347 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002348
2349 return newValue;
2350}
2351
2352/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002353/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002354llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002355 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002356 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002357 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002358}
2359
2360/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002361/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002362llvm::Value *
2363CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002364 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002365 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002366 llvm::Intrinsic::objc_autoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002367 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002368}
2369
2370/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002371/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002372llvm::Value *
2373CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002374 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002375 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002376 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002377 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002378}
2379
2380/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002381/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002382/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002383/// %retain = call i8* \@objc_retainBlock(i8* %value)
2384/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002385llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2386 llvm::Value *value) {
2387 if (!type->isBlockPointerType())
2388 return EmitARCRetainAutoreleaseNonBlock(value);
2389
2390 if (isa<llvm::ConstantPointerNull>(value)) return value;
2391
Chris Lattner2192fe52011-07-18 04:24:23 +00002392 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002393 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002394 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002395 value = EmitARCAutorelease(value);
2396 return Builder.CreateBitCast(value, origType);
2397}
2398
2399/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002400/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002401llvm::Value *
2402CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002403 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002404 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002405 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002406}
2407
John McCallb04ecb72015-10-21 18:06:43 +00002408/// i8* \@objc_loadWeak(i8** %addr)
2409/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2410llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2411 return emitARCLoadOperation(*this, addr,
2412 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002413 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002414}
2415
James Dennett14c41ea2012-06-22 05:41:30 +00002416/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002417llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002418 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002419 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002420 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002421}
2422
James Dennett14c41ea2012-06-22 05:41:30 +00002423/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002424/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002425llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002426 llvm::Value *value,
2427 bool ignored) {
2428 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002429 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002430 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002431}
2432
James Dennett14c41ea2012-06-22 05:41:30 +00002433/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002434/// Returns %value. %addr is known to not have a current weak entry.
2435/// Essentially equivalent to:
2436/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002437void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002438 // If we're initializing to null, just write null to memory; no need
2439 // to get the runtime involved. But don't do this if optimization
2440 // is enabled, because accounting for this would make the optimizer
2441 // much more complicated.
2442 if (isa<llvm::ConstantPointerNull>(value) &&
2443 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2444 Builder.CreateStore(value, addr);
2445 return;
2446 }
2447
2448 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002449 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002450 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002451}
2452
James Dennett14c41ea2012-06-22 05:41:30 +00002453/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002454/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002455void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002456 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002457 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002458 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2459 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002460 }
2461
2462 // Cast the argument to 'id*'.
2463 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2464
John McCall7f416cc2015-09-08 08:05:57 +00002465 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002466}
2467
James Dennett14c41ea2012-06-22 05:41:30 +00002468/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002469/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2470/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002471void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002472 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002473 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002474 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002475}
2476
James Dennett14c41ea2012-06-22 05:41:30 +00002477/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002478/// Disregards the current value in %dest. Essentially
2479/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002480void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002481 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002482 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002483 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002484}
2485
Akira Hatanakad791e922018-03-19 17:38:40 +00002486void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2487 Address SrcAddr) {
2488 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2489 Object = EmitObjCConsumeObject(Ty, Object);
2490 EmitARCStoreWeak(DstAddr, Object, false);
2491}
2492
2493void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2494 Address SrcAddr) {
2495 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2496 Object = EmitObjCConsumeObject(Ty, Object);
2497 EmitARCStoreWeak(DstAddr, Object, false);
2498 EmitARCDestroyWeak(SrcAddr);
2499}
2500
John McCall31168b02011-06-15 23:02:42 +00002501/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002502/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002503llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002504 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002505 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002506 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2507 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002508 }
2509
John McCall882987f2013-02-28 19:01:20 +00002510 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002511}
2512
2513/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002514/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002515void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2516 assert(value->getType() == Int8PtrTy);
2517
Pete Cooper2cd35962018-12-18 20:33:00 +00002518 if (getInvokeDest()) {
2519 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002520 llvm::FunctionCallee &fn =
2521 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002522 if (!fn) {
2523 llvm::FunctionType *fnType =
2524 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2525 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2526 setARCRuntimeFunctionLinkage(CGM, fn);
2527 }
John McCall31168b02011-06-15 23:02:42 +00002528
Pete Cooper2cd35962018-12-18 20:33:00 +00002529 // objc_autoreleasePoolPop can throw.
2530 EmitRuntimeCallOrInvoke(fn, value);
2531 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002532 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002533 if (!fn) {
2534 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2535 setARCRuntimeFunctionLinkage(CGM, fn);
2536 }
2537
2538 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002539 }
John McCall31168b02011-06-15 23:02:42 +00002540}
2541
2542/// Produce the code to do an MRR version objc_autoreleasepool_push.
2543/// Which is: [[NSAutoreleasePool alloc] init];
2544/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2545/// init is declared as: - (id) init; in its NSObject super class.
2546///
2547llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2548 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002549 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002550 // [NSAutoreleasePool alloc]
2551 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2552 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2553 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002554 RValue AllocRV =
2555 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002556 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002557 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002558
2559 // [Receiver init]
2560 Receiver = AllocRV.getScalarVal();
2561 II = &CGM.getContext().Idents.get("init");
2562 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2563 RValue InitRV =
2564 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2565 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002566 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002567 return InitRV.getScalarVal();
2568}
2569
Pete Coopere3886802018-12-08 05:13:50 +00002570/// Allocate the given objc object.
2571/// call i8* \@objc_alloc(i8* %value)
2572llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2573 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002574 return emitObjCValueOperation(*this, value, resultType,
2575 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002576 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002577}
2578
2579/// Allocate the given objc object.
2580/// call i8* \@objc_allocWithZone(i8* %value)
2581llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2582 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002583 return emitObjCValueOperation(*this, value, resultType,
2584 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002585 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002586}
2587
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002588llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2589 llvm::Type *resultType) {
2590 return emitObjCValueOperation(*this, value, resultType,
2591 CGM.getObjCEntrypoints().objc_alloc_init,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002592 "objc_alloc_init");
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002593}
2594
John McCall31168b02011-06-15 23:02:42 +00002595/// Produce the code to do a primitive release.
2596/// [tmp drain];
2597void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2598 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2599 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2600 CallArgList Args;
2601 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002602 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002603}
2604
John McCall82fe67b2011-07-09 01:37:26 +00002605void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002606 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002607 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002608 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002609}
2610
2611void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002612 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002613 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002614 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002615}
2616
2617void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002618 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002619 QualType type) {
2620 CGF.EmitARCDestroyWeak(addr);
2621}
2622
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002623void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2624 QualType type) {
2625 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2626 CGF.EmitARCIntrinsicUse(value);
2627}
2628
Pete Coopere5b64ea2018-12-21 21:00:32 +00002629/// Autorelease the given object.
2630/// call i8* \@objc_autorelease(i8* %value)
2631llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2632 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002633 return emitObjCValueOperation(
2634 *this, value, returnType,
2635 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002636 "objc_autorelease");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002637}
2638
2639/// Retain the given object, with normal retain semantics.
2640/// call i8* \@objc_retain(i8* %value)
2641llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2642 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002643 return emitObjCValueOperation(
2644 *this, value, returnType,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002645 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002646}
2647
2648/// Release the given object.
2649/// call void \@objc_release(i8* %value)
2650void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2651 ARCPreciseLifetime_t precise) {
2652 if (isa<llvm::ConstantPointerNull>(value)) return;
2653
James Y Knight9871db02019-02-05 16:42:33 +00002654 llvm::FunctionCallee &fn =
2655 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002656 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002657 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002658 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002659 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2660 setARCRuntimeFunctionLinkage(CGM, fn);
2661 // We have Native ARC, so set nonlazybind attribute for performance
2662 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2663 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002664 }
2665
2666 // Cast the argument to 'id'.
2667 value = Builder.CreateBitCast(value, Int8PtrTy);
2668
2669 // Call objc_release.
Akira Hatanaka34d28cf2019-05-10 21:54:16 +00002670 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002671
2672 if (precise == ARCImpreciseLifetime) {
2673 call->setMetadata("clang.imprecise_release",
2674 llvm::MDNode::get(Builder.getContext(), None));
2675 }
2676}
2677
John McCall31168b02011-06-15 23:02:42 +00002678namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002679 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002680 llvm::Value *Token;
2681
2682 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2683
Craig Topper4f12f102014-03-12 06:41:41 +00002684 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002685 CGF.EmitObjCAutoreleasePoolPop(Token);
2686 }
2687 };
David Blaikie7e70d682015-08-18 22:40:54 +00002688 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002689 llvm::Value *Token;
2690
2691 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2692
Craig Topper4f12f102014-03-12 06:41:41 +00002693 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002694 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2695 }
2696 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002697}
John McCall31168b02011-06-15 23:02:42 +00002698
2699void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002700 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002701 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2702 else
2703 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2704}
2705
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002706static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2707 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002708 case Qualifiers::OCL_None:
2709 case Qualifiers::OCL_ExplicitNone:
2710 case Qualifiers::OCL_Strong:
2711 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002712 return true;
John McCall31168b02011-06-15 23:02:42 +00002713
2714 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002715 return false;
John McCall31168b02011-06-15 23:02:42 +00002716 }
2717
2718 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002719}
2720
2721static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002722 LValue lvalue,
2723 QualType type) {
2724 llvm::Value *result;
2725 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2726 if (shouldRetain) {
2727 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2728 } else {
2729 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002730 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002731 }
2732 return TryEmitResult(result, !shouldRetain);
2733}
2734
2735static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002736 const Expr *e) {
2737 e = e->IgnoreParens();
2738 QualType type = e->getType();
2739
Fangrui Song6907ce22018-07-30 19:24:48 +00002740 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002741 // an extra retain/release pair by zeroing out the source of this
2742 // "move" operation.
2743 if (e->isXValue() &&
2744 !type.isConstQualified() &&
2745 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2746 // Emit the lvalue.
2747 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002748
John McCall154a2fd2011-08-30 00:57:29 +00002749 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002750 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2751 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002752
John McCall154a2fd2011-08-30 00:57:29 +00002753 // Set the source pointer to NULL.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002754 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002755
John McCall154a2fd2011-08-30 00:57:29 +00002756 return TryEmitResult(result, true);
2757 }
2758
John McCall31168b02011-06-15 23:02:42 +00002759 // As a very special optimization, in ARC++, if the l-value is the
2760 // result of a non-volatile assignment, do a simple retain of the
2761 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002762 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002763 !type.isVolatileQualified() &&
2764 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2765 isa<BinaryOperator>(e) &&
2766 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2767 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2768
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002769 // Try to emit code for scalar constant instead of emitting LValue and
2770 // loading it because we are not guaranteed to have an l-value. One of such
2771 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2772 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2773 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2774 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2775 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2776 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2777 }
2778
John McCall31168b02011-06-15 23:02:42 +00002779 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2780}
2781
John McCalle399e5b2016-01-27 18:32:30 +00002782typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2783 llvm::Value *value)>
2784 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002785
John McCalle399e5b2016-01-27 18:32:30 +00002786/// Insert code immediately after a call.
2787static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2788 llvm::Value *value,
2789 ValueTransform doAfterCall,
2790 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002791 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2792 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2793
2794 // Place the retain immediately following the call.
2795 CGF.Builder.SetInsertPoint(call->getParent(),
2796 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002797 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002798
2799 CGF.Builder.restoreIP(ip);
2800 return value;
2801 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2802 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2803
2804 // Place the retain at the beginning of the normal destination block.
2805 llvm::BasicBlock *BB = invoke->getNormalDest();
2806 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002807 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002808
2809 CGF.Builder.restoreIP(ip);
2810 return value;
2811
2812 // Bitcasts can arise because of related-result returns. Rewrite
2813 // the operand.
2814 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2815 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002816 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002817 bitcast->setOperand(0, operand);
2818 return bitcast;
2819
2820 // Generic fall-back case.
2821 } else {
2822 // Retain using the non-block variant: we never need to do a copy
2823 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002824 return doFallback(CGF, value);
2825 }
2826}
2827
2828/// Given that the given expression is some sort of call (which does
2829/// not return retained), emit a retain following it.
2830static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2831 const Expr *e) {
2832 llvm::Value *value = CGF.EmitScalarExpr(e);
2833 return emitARCOperationAfterCall(CGF, value,
2834 [](CodeGenFunction &CGF, llvm::Value *value) {
2835 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2836 },
2837 [](CodeGenFunction &CGF, llvm::Value *value) {
2838 return CGF.EmitARCRetainNonBlock(value);
2839 });
2840}
2841
2842/// Given that the given expression is some sort of call (which does
2843/// not return retained), perform an unsafeClaim following it.
2844static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2845 const Expr *e) {
2846 llvm::Value *value = CGF.EmitScalarExpr(e);
2847 return emitARCOperationAfterCall(CGF, value,
2848 [](CodeGenFunction &CGF, llvm::Value *value) {
2849 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2850 },
2851 [](CodeGenFunction &CGF, llvm::Value *value) {
2852 return value;
2853 });
2854}
2855
2856llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2857 bool allowUnsafeClaim) {
2858 if (allowUnsafeClaim &&
2859 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2860 return emitARCUnsafeClaimCallResult(*this, E);
2861 } else {
2862 llvm::Value *value = emitARCRetainCallResult(*this, E);
2863 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002864 }
2865}
2866
John McCallcd78e802011-09-10 01:16:55 +00002867/// Determine whether it might be important to emit a separate
2868/// objc_retain_block on the result of the given expression, or
2869/// whether it's okay to just emit it in a +1 context.
2870static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2871 assert(e->getType()->isBlockPointerType());
2872 e = e->IgnoreParens();
2873
2874 // For future goodness, emit block expressions directly in +1
2875 // contexts if we can.
2876 if (isa<BlockExpr>(e))
2877 return false;
2878
2879 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2880 switch (cast->getCastKind()) {
2881 // Emitting these operations in +1 contexts is goodness.
2882 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002883 case CK_ARCReclaimReturnedObject:
2884 case CK_ARCConsumeObject:
2885 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002886 return false;
2887
2888 // These operations preserve a block type.
2889 case CK_NoOp:
2890 case CK_BitCast:
2891 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2892
2893 // These operations are known to be bad (or haven't been considered).
2894 case CK_AnyPointerToBlockPointerCast:
2895 default:
2896 return true;
2897 }
2898 }
2899
2900 return true;
2901}
2902
John McCalle399e5b2016-01-27 18:32:30 +00002903namespace {
2904/// A CRTP base class for emitting expressions of retainable object
2905/// pointer type in ARC.
2906template <typename Impl, typename Result> class ARCExprEmitter {
2907protected:
2908 CodeGenFunction &CGF;
2909 Impl &asImpl() { return *static_cast<Impl*>(this); }
2910
2911 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2912
2913public:
2914 Result visit(const Expr *e);
2915 Result visitCastExpr(const CastExpr *e);
2916 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002917 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002918 Result visitBinaryOperator(const BinaryOperator *e);
2919 Result visitBinAssign(const BinaryOperator *e);
2920 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2921 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2922 Result visitBinAssignWeak(const BinaryOperator *e);
2923 Result visitBinAssignStrong(const BinaryOperator *e);
2924
2925 // Minimal implementation:
2926 // Result visitLValueToRValue(const Expr *e)
2927 // Result visitConsumeObject(const Expr *e)
2928 // Result visitExtendBlockObject(const Expr *e)
2929 // Result visitReclaimReturnedObject(const Expr *e)
2930 // Result visitCall(const Expr *e)
2931 // Result visitExpr(const Expr *e)
2932 //
2933 // Result emitBitCast(Result result, llvm::Type *resultType)
2934 // llvm::Value *getValueOfResult(Result result)
2935};
2936}
2937
2938/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002939///
2940/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002941template <typename Impl, typename Result>
2942Result
2943ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002944 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002945
2946 // Find the result expression.
2947 const Expr *resultExpr = E->getResultExpr();
2948 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002949 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002950
2951 for (PseudoObjectExpr::const_semantics_iterator
2952 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2953 const Expr *semantic = *i;
2954
2955 // If this semantic expression is an opaque value, bind it
2956 // to the result of its source expression.
2957 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2958 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2959 OVMA opaqueData;
2960
2961 // If this semantic is the result of the pseudo-object
2962 // expression, try to evaluate the source as +1.
2963 if (ov == resultExpr) {
2964 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002965 result = asImpl().visit(ov->getSourceExpr());
2966 opaqueData = OVMA::bind(CGF, ov,
2967 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002968
2969 // Otherwise, just bind it.
2970 } else {
2971 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2972 }
2973 opaques.push_back(opaqueData);
2974
2975 // Otherwise, if the expression is the result, evaluate it
2976 // and remember the result.
2977 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002978 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002979
2980 // Otherwise, evaluate the expression in an ignored context.
2981 } else {
2982 CGF.EmitIgnoredExpr(semantic);
2983 }
2984 }
2985
2986 // Unbind all the opaques now.
2987 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2988 opaques[i].unbind(CGF);
2989
2990 return result;
2991}
2992
John McCalle399e5b2016-01-27 18:32:30 +00002993template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002994Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2995 // The default implementation just forwards the expression to visitExpr.
2996 return asImpl().visitExpr(e);
2997}
2998
2999template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00003000Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3001 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00003002
John McCalle399e5b2016-01-27 18:32:30 +00003003 // No-op casts don't change the type, so we just ignore them.
3004 case CK_NoOp:
3005 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00003006
John McCalle399e5b2016-01-27 18:32:30 +00003007 // These casts can change the type.
3008 case CK_CPointerToObjCPointerCast:
3009 case CK_BlockPointerToObjCPointerCast:
3010 case CK_AnyPointerToBlockPointerCast:
3011 case CK_BitCast: {
3012 llvm::Type *resultType = CGF.ConvertType(e->getType());
3013 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3014 Result result = asImpl().visit(e->getSubExpr());
3015 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00003016 }
3017
John McCalle399e5b2016-01-27 18:32:30 +00003018 // Handle some casts specially.
3019 case CK_LValueToRValue:
3020 return asImpl().visitLValueToRValue(e->getSubExpr());
3021 case CK_ARCConsumeObject:
3022 return asImpl().visitConsumeObject(e->getSubExpr());
3023 case CK_ARCExtendBlockObject:
3024 return asImpl().visitExtendBlockObject(e->getSubExpr());
3025 case CK_ARCReclaimReturnedObject:
3026 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3027
3028 // Otherwise, use the default logic.
3029 default:
3030 return asImpl().visitExpr(e);
3031 }
3032}
3033
3034template <typename Impl, typename Result>
3035Result
3036ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3037 switch (e->getOpcode()) {
3038 case BO_Comma:
3039 CGF.EmitIgnoredExpr(e->getLHS());
3040 CGF.EnsureInsertPoint();
3041 return asImpl().visit(e->getRHS());
3042
3043 case BO_Assign:
3044 return asImpl().visitBinAssign(e);
3045
3046 default:
3047 return asImpl().visitExpr(e);
3048 }
3049}
3050
3051template <typename Impl, typename Result>
3052Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3053 switch (e->getLHS()->getType().getObjCLifetime()) {
3054 case Qualifiers::OCL_ExplicitNone:
3055 return asImpl().visitBinAssignUnsafeUnretained(e);
3056
3057 case Qualifiers::OCL_Weak:
3058 return asImpl().visitBinAssignWeak(e);
3059
3060 case Qualifiers::OCL_Autoreleasing:
3061 return asImpl().visitBinAssignAutoreleasing(e);
3062
3063 case Qualifiers::OCL_Strong:
3064 return asImpl().visitBinAssignStrong(e);
3065
3066 case Qualifiers::OCL_None:
3067 return asImpl().visitExpr(e);
3068 }
3069 llvm_unreachable("bad ObjC ownership qualifier");
3070}
3071
3072/// The default rule for __unsafe_unretained emits the RHS recursively,
3073/// stores into the unsafe variable, and propagates the result outward.
3074template <typename Impl, typename Result>
3075Result ARCExprEmitter<Impl,Result>::
3076 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3077 // Recursively emit the RHS.
3078 // For __block safety, do this before emitting the LHS.
3079 Result result = asImpl().visit(e->getRHS());
3080
3081 // Perform the store.
3082 LValue lvalue =
3083 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3084 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3085 lvalue);
3086
3087 return result;
3088}
3089
3090template <typename Impl, typename Result>
3091Result
3092ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3093 return asImpl().visitExpr(e);
3094}
3095
3096template <typename Impl, typename Result>
3097Result
3098ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3099 return asImpl().visitExpr(e);
3100}
3101
3102template <typename Impl, typename Result>
3103Result
3104ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3105 return asImpl().visitExpr(e);
3106}
3107
3108/// The general expression-emission logic.
3109template <typename Impl, typename Result>
3110Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3111 // We should *never* see a nested full-expression here, because if
3112 // we fail to emit at +1, our caller must not retain after we close
3113 // out the full-expression. This isn't as important in the unsafe
3114 // emitter.
3115 assert(!isa<ExprWithCleanups>(e));
3116
3117 // Look through parens, __extension__, generic selection, etc.
3118 e = e->IgnoreParens();
3119
3120 // Handle certain kinds of casts.
3121 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3122 return asImpl().visitCastExpr(ce);
3123
3124 // Handle the comma operator.
3125 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3126 return asImpl().visitBinaryOperator(op);
3127
3128 // TODO: handle conditional operators here
3129
3130 // For calls and message sends, use the retained-call logic.
3131 // Delegate inits are a special case in that they're the only
3132 // returns-retained expression that *isn't* surrounded by
3133 // a consume.
3134 } else if (isa<CallExpr>(e) ||
3135 (isa<ObjCMessageExpr>(e) &&
3136 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3137 return asImpl().visitCall(e);
3138
3139 // Look through pseudo-object expressions.
3140 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3141 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003142 } else if (auto *be = dyn_cast<BlockExpr>(e))
3143 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003144
3145 return asImpl().visitExpr(e);
3146}
3147
3148namespace {
3149
3150/// An emitter for +1 results.
3151struct ARCRetainExprEmitter :
3152 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3153
3154 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3155
3156 llvm::Value *getValueOfResult(TryEmitResult result) {
3157 return result.getPointer();
3158 }
3159
3160 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3161 llvm::Value *value = result.getPointer();
3162 value = CGF.Builder.CreateBitCast(value, resultType);
3163 result.setPointer(value);
3164 return result;
3165 }
3166
3167 TryEmitResult visitLValueToRValue(const Expr *e) {
3168 return tryEmitARCRetainLoadOfScalar(CGF, e);
3169 }
3170
3171 /// For consumptions, just emit the subexpression and thus elide
3172 /// the retain/release pair.
3173 TryEmitResult visitConsumeObject(const Expr *e) {
3174 llvm::Value *result = CGF.EmitScalarExpr(e);
3175 return TryEmitResult(result, true);
3176 }
3177
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003178 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3179 TryEmitResult result = visitExpr(e);
3180 // Avoid the block-retain if this is a block literal that doesn't need to be
3181 // copied to the heap.
3182 if (e->getBlockDecl()->canAvoidCopyToHeap())
3183 result.setInt(true);
3184 return result;
3185 }
3186
John McCalle399e5b2016-01-27 18:32:30 +00003187 /// Block extends are net +0. Naively, we could just recurse on
3188 /// the subexpression, but actually we need to ensure that the
3189 /// value is copied as a block, so there's a little filter here.
3190 TryEmitResult visitExtendBlockObject(const Expr *e) {
3191 llvm::Value *result; // will be a +0 value
3192
3193 // If we can't safely assume the sub-expression will produce a
3194 // block-copied value, emit the sub-expression at +0.
3195 if (shouldEmitSeparateBlockRetain(e)) {
3196 result = CGF.EmitScalarExpr(e);
3197
3198 // Otherwise, try to emit the sub-expression at +1 recursively.
3199 } else {
3200 TryEmitResult subresult = asImpl().visit(e);
3201
3202 // If that produced a retained value, just use that.
3203 if (subresult.getInt()) {
3204 return subresult;
3205 }
3206
3207 // Otherwise it's +0.
3208 result = subresult.getPointer();
3209 }
3210
3211 // Retain the object as a block.
3212 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3213 return TryEmitResult(result, true);
3214 }
3215
3216 /// For reclaims, emit the subexpression as a retained call and
3217 /// skip the consumption.
3218 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3219 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3220 return TryEmitResult(result, true);
3221 }
3222
3223 /// When we have an undecorated call, retroactively do a claim.
3224 TryEmitResult visitCall(const Expr *e) {
3225 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3226 return TryEmitResult(result, true);
3227 }
3228
3229 // TODO: maybe special-case visitBinAssignWeak?
3230
3231 TryEmitResult visitExpr(const Expr *e) {
3232 // We didn't find an obvious production, so emit what we've got and
3233 // tell the caller that we didn't manage to retain.
3234 llvm::Value *result = CGF.EmitScalarExpr(e);
3235 return TryEmitResult(result, false);
3236 }
3237};
3238}
3239
3240static TryEmitResult
3241tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3242 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003243}
3244
3245static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3246 LValue lvalue,
3247 QualType type) {
3248 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3249 llvm::Value *value = result.getPointer();
3250 if (!result.getInt())
3251 value = CGF.EmitARCRetain(type, value);
3252 return value;
3253}
3254
3255/// EmitARCRetainScalarExpr - Semantically equivalent to
3256/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3257/// best-effort attempt to peephole expressions that naturally produce
3258/// retained objects.
3259llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003260 // The retain needs to happen within the full-expression.
3261 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3262 enterFullExpression(cleanups);
3263 RunCleanupsScope scope(*this);
3264 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3265 }
3266
John McCall31168b02011-06-15 23:02:42 +00003267 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3268 llvm::Value *value = result.getPointer();
3269 if (!result.getInt())
3270 value = EmitARCRetain(e->getType(), value);
3271 return value;
3272}
3273
3274llvm::Value *
3275CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003276 // The retain needs to happen within the full-expression.
3277 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3278 enterFullExpression(cleanups);
3279 RunCleanupsScope scope(*this);
3280 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3281 }
3282
John McCall31168b02011-06-15 23:02:42 +00003283 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3284 llvm::Value *value = result.getPointer();
3285 if (result.getInt())
3286 value = EmitARCAutorelease(value);
3287 else
3288 value = EmitARCRetainAutorelease(e->getType(), value);
3289 return value;
3290}
3291
John McCallff613032011-10-04 06:23:45 +00003292llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3293 llvm::Value *result;
3294 bool doRetain;
3295
3296 if (shouldEmitSeparateBlockRetain(e)) {
3297 result = EmitScalarExpr(e);
3298 doRetain = true;
3299 } else {
3300 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3301 result = subresult.getPointer();
3302 doRetain = !subresult.getInt();
3303 }
3304
3305 if (doRetain)
3306 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3307 return EmitObjCConsumeObject(e->getType(), result);
3308}
3309
John McCall248512a2011-10-01 10:32:24 +00003310llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3311 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003312 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003313 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003314 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003315 return EmitARCRetainAutoreleaseScalarExpr(expr);
3316 }
3317
3318 // Otherwise, use the normal scalar-expression emission. The
3319 // exception machinery doesn't do anything special with the
3320 // exception like retaining it, so there's no safety associated with
3321 // only running cleanups after the throw has started, and when it
3322 // matters it tends to be substantially inferior code.
3323 return EmitScalarExpr(expr);
3324}
3325
John McCalle399e5b2016-01-27 18:32:30 +00003326namespace {
3327
3328/// An emitter for assigning into an __unsafe_unretained context.
3329struct ARCUnsafeUnretainedExprEmitter :
3330 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3331
3332 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3333
3334 llvm::Value *getValueOfResult(llvm::Value *value) {
3335 return value;
3336 }
3337
3338 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3339 return CGF.Builder.CreateBitCast(value, resultType);
3340 }
3341
3342 llvm::Value *visitLValueToRValue(const Expr *e) {
3343 return CGF.EmitScalarExpr(e);
3344 }
3345
3346 /// For consumptions, just emit the subexpression and perform the
3347 /// consumption like normal.
3348 llvm::Value *visitConsumeObject(const Expr *e) {
3349 llvm::Value *value = CGF.EmitScalarExpr(e);
3350 return CGF.EmitObjCConsumeObject(e->getType(), value);
3351 }
3352
3353 /// No special logic for block extensions. (This probably can't
3354 /// actually happen in this emitter, though.)
3355 llvm::Value *visitExtendBlockObject(const Expr *e) {
3356 return CGF.EmitARCExtendBlockObject(e);
3357 }
3358
3359 /// For reclaims, perform an unsafeClaim if that's enabled.
3360 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3361 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3362 }
3363
3364 /// When we have an undecorated call, just emit it without adding
3365 /// the unsafeClaim.
3366 llvm::Value *visitCall(const Expr *e) {
3367 return CGF.EmitScalarExpr(e);
3368 }
3369
3370 /// Just do normal scalar emission in the default case.
3371 llvm::Value *visitExpr(const Expr *e) {
3372 return CGF.EmitScalarExpr(e);
3373 }
3374};
3375}
3376
3377static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3378 const Expr *e) {
3379 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3380}
3381
3382/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3383/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3384/// avoiding any spurious retains, including by performing reclaims
3385/// with objc_unsafeClaimAutoreleasedReturnValue.
3386llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3387 // Look through full-expressions.
3388 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3389 enterFullExpression(cleanups);
3390 RunCleanupsScope scope(*this);
3391 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3392 }
3393
3394 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3395}
3396
3397std::pair<LValue,llvm::Value*>
3398CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3399 bool ignored) {
3400 // Evaluate the RHS first. If we're ignoring the result, assume
3401 // that we can emit at an unsafe +0.
3402 llvm::Value *value;
3403 if (ignored) {
3404 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3405 } else {
3406 value = EmitScalarExpr(e->getRHS());
3407 }
3408
3409 // Emit the LHS and perform the store.
3410 LValue lvalue = EmitLValue(e->getLHS());
3411 EmitStoreOfScalar(value, lvalue);
3412
3413 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3414}
3415
John McCall31168b02011-06-15 23:02:42 +00003416std::pair<LValue,llvm::Value*>
3417CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3418 bool ignored) {
3419 // Evaluate the RHS first.
3420 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3421 llvm::Value *value = result.getPointer();
3422
John McCallb726a552011-07-28 07:23:35 +00003423 bool hasImmediateRetain = result.getInt();
3424
3425 // If we didn't emit a retained object, and the l-value is of block
3426 // type, then we need to emit the block-retain immediately in case
3427 // it invalidates the l-value.
3428 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003429 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003430 hasImmediateRetain = true;
3431 }
3432
John McCall31168b02011-06-15 23:02:42 +00003433 LValue lvalue = EmitLValue(e->getLHS());
3434
3435 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003436 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003437 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003438 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003439 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003440 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003441 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003442 }
3443
3444 return std::pair<LValue,llvm::Value*>(lvalue, value);
3445}
3446
3447std::pair<LValue,llvm::Value*>
3448CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3449 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3450 LValue lvalue = EmitLValue(e->getLHS());
3451
Eli Friedmana0544d62011-12-03 04:14:32 +00003452 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003453
3454 return std::pair<LValue,llvm::Value*>(lvalue, value);
3455}
3456
3457void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003458 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003459 const Stmt *subStmt = ARPS.getSubStmt();
3460 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3461
3462 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003463 if (DI)
3464 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003465
3466 // Keep track of the current cleanup stack depth.
3467 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003468 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003469 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3470 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3471 } else {
3472 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3473 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3474 }
3475
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003476 for (const auto *I : S.body())
3477 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003478
Eric Christopher7cdf9482011-10-13 21:45:18 +00003479 if (DI)
3480 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003481}
John McCall1bd25562011-06-24 23:21:27 +00003482
3483/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3484/// make sure it survives garbage collection until this point.
3485void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3486 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003487 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003488 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003489 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3490 /* assembly */ "",
3491 /* constraints */ "r",
3492 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003493
3494 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003495 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003496}
3497
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003498/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003499/// non-trivial copy assignment function, produce following helper function.
3500/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3501///
3502llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003503CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3504 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003505 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003506 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003507 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003508 QualType Ty = PID->getPropertyIvarDecl()->getType();
3509 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003510 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003511 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003512 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003513 return nullptr;
3514 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003515 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003516 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003517 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3518 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3519 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003520
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003521 ASTContext &C = getContext();
3522 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003523 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003524
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003525 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003526 QualType DestTy = C.getPointerType(Ty);
3527 QualType SrcTy = Ty;
3528 SrcTy.addConst();
3529 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003530
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003531 SmallVector<QualType, 2> ArgTys;
3532 ArgTys.push_back(DestTy);
3533 ArgTys.push_back(SrcTy);
3534 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3535
3536 FunctionDecl *FD = FunctionDecl::Create(
3537 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3538 FunctionTy, nullptr, SC_Static, false, false);
3539
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003540 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003541 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3542 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003543 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003544 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3545 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003546 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003547
John McCallc56a8b32016-03-11 04:30:31 +00003548 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003549 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003550
John McCalla729c622012-02-17 03:33:10 +00003551 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003552
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003553 llvm::Function *Fn =
3554 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003555 "__assign_helper_atomic_property_",
3556 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003557
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003558 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003559
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003560 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003561
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003562 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3563 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003564 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003565 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003566
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003567 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3568 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003569 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003570 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003571
John McCall113bee02012-03-10 09:33:50 +00003572 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003573 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003574 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3575 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3576 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003577
Bruno Riccic5885cf2018-12-21 15:20:32 +00003578 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003579
3580 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003581 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003582 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003583 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003584}
3585
3586llvm::Constant *
3587CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3588 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003589 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003590 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003591 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003592 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3593 QualType Ty = PD->getType();
3594 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003595 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003596 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003597 return nullptr;
3598 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003599 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003600 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003601 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3602 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3603 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003604
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003605 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003606 IdentifierInfo *II =
3607 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003608
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003609 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003610 QualType DestTy = C.getPointerType(Ty);
3611 QualType SrcTy = Ty;
3612 SrcTy.addConst();
3613 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003614
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003615 SmallVector<QualType, 2> ArgTys;
3616 ArgTys.push_back(DestTy);
3617 ArgTys.push_back(SrcTy);
3618 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3619
3620 FunctionDecl *FD = FunctionDecl::Create(
3621 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3622 FunctionTy, nullptr, SC_Static, false, false);
3623
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003624 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003625 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3626 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003627 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003628 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3629 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003630 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003631
John McCallc56a8b32016-03-11 04:30:31 +00003632 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003633 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003634
John McCalla729c622012-02-17 03:33:10 +00003635 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003636
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003637 llvm::Function *Fn = llvm::Function::Create(
3638 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3639 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003640
3641 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003642
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003643 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003644
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003645 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3646 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003647
John McCall113bee02012-03-10 09:33:50 +00003648 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003649 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003650
3651 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003652 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003653
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003654 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003655 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003656 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3657 CXXConstExpr->arg_end());
3658
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003659 CXXConstructExpr *TheCXXConstructExpr =
3660 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3661 CXXConstExpr->getConstructor(),
3662 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003663 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003664 CXXConstExpr->hadMultipleCandidates(),
3665 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003666 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003667 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003668 CXXConstExpr->getConstructionKind(),
3669 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003670
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003671 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3672 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003673
John McCall113bee02012-03-10 09:33:50 +00003674 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003675 CharUnits Alignment
3676 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003677 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003678 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3679 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003680 AggValueSlot::IsDestructed,
3681 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003682 AggValueSlot::IsNotAliased,
3683 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003684
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003685 FinishFunction();
3686 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3687 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3688 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003689}
3690
Eli Friedmanec75fec2012-02-28 01:08:45 +00003691llvm::Value *
3692CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3693 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003694 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3695 Selector CopySelector =
3696 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003697 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3698 Selector AutoreleaseSelector =
3699 getContext().Selectors.getNullarySelector(AutoreleaseID);
3700
3701 // Emit calls to retain/autorelease.
3702 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3703 llvm::Value *Val = Block;
3704 RValue Result;
3705 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003706 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003707 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003708 Val = Result.getScalarVal();
3709 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3710 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003711 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003712 Val = Result.getScalarVal();
3713 return Val;
3714}
3715
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003716llvm::Value *
3717CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3718 assert(Args.size() == 3 && "Expected 3 argument here!");
3719
3720 if (!CGM.IsOSVersionAtLeastFn) {
3721 llvm::FunctionType *FTy =
3722 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3723 CGM.IsOSVersionAtLeastFn =
3724 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3725 }
3726
3727 llvm::Value *CallRes =
3728 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3729
3730 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3731}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003732
Alex Lorenza8fbef42017-03-23 11:14:27 +00003733void CodeGenModule::emitAtAvailableLinkGuard() {
3734 if (!IsOSVersionAtLeastFn)
3735 return;
3736 // @available requires CoreFoundation only on Darwin.
3737 if (!Target.getTriple().isOSDarwin())
3738 return;
3739 // Add -framework CoreFoundation to the linker commands. We still want to
3740 // emit the core foundation reference down below because otherwise if
3741 // CoreFoundation is not used in the code, the linker won't link the
3742 // framework.
3743 auto &Context = getLLVMContext();
3744 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3745 llvm::MDString::get(Context, "CoreFoundation")};
3746 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3747 // Emit a reference to a symbol from CoreFoundation to ensure that
3748 // CoreFoundation is linked into the final binary.
3749 llvm::FunctionType *FTy =
3750 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003751 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003752 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3753
3754 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003755 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3756 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003757 llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00003758 llvm::Function *CFLinkCheckFunc =
3759 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3760 if (CFLinkCheckFunc->empty()) {
3761 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3762 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3763 CodeGenFunction CGF(*this);
3764 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3765 CGF.EmitNounwindRuntimeCall(CFFunc,
3766 llvm::Constant::getNullValue(VoidPtrTy));
3767 CGF.Builder.CreateUnreachable();
3768 addCompilerUsedGlobal(CFLinkCheckFunc);
3769 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003770}
3771
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003772CGObjCRuntime::~CGObjCRuntime() {}