blob: 561f21afdb13664f0b7f0fe35ceeb3c37f40dd67 [file] [log] [blame]
Erik Pilkington9227e102017-02-21 20:31:01 +00001//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
Anders Carlsson76f4a902007-08-21 17:43:55 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson76f4a902007-08-21 17:43:55 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Objective-C code as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
Devang Pateld2d66652011-01-19 01:36:36 +000013#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000014#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Akira Hatanaka1488ee42019-03-08 04:45:37 +000017#include "ConstantEmitter.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall31168b02011-06-15 23:02:42 +000030typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
31static TryEmitResult
32tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000033static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
34 QualType ET,
35 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000039static llvm::Constant *getNullForVariable(Address addr) {
40 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000041 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
42}
43
Chris Lattnerb1d329d2008-06-24 17:04:18 +000044/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000045llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000046{
Fangrui Song6907ce22018-07-30 19:24:48 +000047 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000048 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000049 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000050 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000051}
52
Patrick Beard0caa3942012-04-19 00:25:12 +000053/// EmitObjCBoxedExpr - This routine generates code to call
54/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000055/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
56/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000057///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000058llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000062 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000063 const Expr *SubExpr = E->getSubExpr();
Akira Hatanaka1488ee42019-03-08 04:45:37 +000064
65 if (E->isExpressibleAsConstantInitializer()) {
66 ConstantEmitter ConstEmitter(CGM);
67 return ConstEmitter.tryEmitAbstract(E, E->getType());
68 }
69
Patrick Beard0caa3942012-04-19 00:25:12 +000070 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
71 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000072
Ted Kremeneke65b0862012-03-06 20:05:56 +000073 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000074 // Assumes that the method was introduced in the class that should be
75 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000077 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000078 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000079
Ted Kremeneke65b0862012-03-06 20:05:56 +000080 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000081 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
82 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000083
84 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000085 // via [NSValue valueWithBytes:objCType:]
86 const QualType ValueType(SubExpr->getType().getCanonicalType());
87 if (ValueType->isObjCBoxableRecordType()) {
88 // Emit CodeGen for first parameter
89 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000090 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000091 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000092 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
93 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000094
95 // Create char array to store type encoding
96 std::string Str;
97 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000098 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +000099
Alex Denisovfde64952015-06-26 05:28:36 +0000100 // Cast type encoding to correct type
101 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
102 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
103 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
104
105 Args.add(RValue::get(Cast), EncodingQT);
106 } else {
107 Args.add(EmitAnyExpr(SubExpr), ArgQT);
108 }
Alp Toker314cc812014-01-25 16:55:45 +0000109
110 RValue result = Runtime.GenerateMessageSend(
111 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
112 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000113 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000114 ConvertType(E->getType()));
115}
116
117llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000118 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000120 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
122 if (!ALE)
123 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000124
125 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000126 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000127 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000128 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
129 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
130 QualType IdTy(CGM.getContext().getObjCIdType());
131 llvm::Constant *Constant =
132 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000133 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000134 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000135 cast<llvm::LoadInst>(Ptr)->setMetadata(
136 CGM.getModule().getMDKindID("invariant.load"),
137 llvm::MDNode::get(getLLVMContext(), None));
138 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000139 }
140
141 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000142 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
143 NumElements);
144 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000145 QualType ElementArrayType
146 = Context.getConstantArrayType(ElementType, APNumElements,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000147 ArrayType::Normal, /*IndexTypeQuals=*/0);
148
149 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000150 Address Objects = CreateMemTemp(ElementArrayType, "objects");
151 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000152 if (DLE)
153 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000154
John McCall770a4c12013-04-04 00:20:38 +0000155 // In ARC, we may need to do extra work to keep all the keys and
156 // values alive until after the call.
157 SmallVector<llvm::Value *, 16> NeededObjects;
158 bool TrackNeededObjects =
159 (getLangOpts().ObjCAutoRefCount &&
160 CGM.getCodeGenOpts().OptimizationLevel != 0);
161
Ted Kremeneke65b0862012-03-06 20:05:56 +0000162 // Perform the actual initialialization of the array(s).
163 for (uint64_t i = 0; i < NumElements; i++) {
164 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000165 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000166 const Expr *Rhs = ALE->getElement(i);
James Y Knight751fe282019-02-09 22:22:28 +0000167 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
168 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000169
170 llvm::Value *value = EmitScalarExpr(Rhs);
171 EmitStoreThroughLValue(RValue::get(value), LV, true);
172 if (TrackNeededObjects) {
173 NeededObjects.push_back(value);
174 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000175 } else {
John McCall770a4c12013-04-04 00:20:38 +0000176 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000177 const Expr *Key = DLE->getKeyValueElement(i).Key;
James Y Knight751fe282019-02-09 22:22:28 +0000178 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
179 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000180 llvm::Value *keyValue = EmitScalarExpr(Key);
181 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000182
John McCall770a4c12013-04-04 00:20:38 +0000183 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000184 const Expr *Value = DLE->getKeyValueElement(i).Value;
James Y Knight751fe282019-02-09 22:22:28 +0000185 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
186 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000187 llvm::Value *valueValue = EmitScalarExpr(Value);
188 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
189 if (TrackNeededObjects) {
190 NeededObjects.push_back(keyValue);
191 NeededObjects.push_back(valueValue);
192 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000193 }
194 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000195
Ted Kremeneke65b0862012-03-06 20:05:56 +0000196 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000197 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000198 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
199 const ParmVarDecl *argDecl = *PI++;
200 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000201 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000202 if (DLE) {
203 argDecl = *PI++;
204 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000205 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000206 }
207 argDecl = *PI;
208 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000209 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000210 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
211 Args.add(RValue::get(Count), ArgQT);
212
213 // Generate a reference to the class pointer, which will be the receiver.
214 Selector Sel = MethodWithObjects->getSelector();
215 QualType ResultType = E->getType();
216 const ObjCObjectPointerType *InterfacePointerType
217 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000218 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000219 = InterfacePointerType->getObjectType()->getInterface();
220 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000221 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000222
223 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000224 RValue result = Runtime.GenerateMessageSend(
225 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
226 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000227
228 // The above message send needs these objects, but in ARC they are
229 // passed in a buffer that is essentially __unsafe_unretained.
230 // Therefore we must prevent the optimizer from releasing them until
231 // after the call.
232 if (TrackNeededObjects) {
233 EmitARCIntrinsicUse(NeededObjects);
234 }
235
Fangrui Song6907ce22018-07-30 19:24:48 +0000236 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000237 ConvertType(E->getType()));
238}
239
240llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000241 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000242}
243
244llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
245 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000246 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000247}
248
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000249/// Emit a selector.
250llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
251 // Untyped selector.
252 // Note that this implementation allows for non-constant strings to be passed
253 // as arguments to @selector(). Currently, the only thing preventing this
254 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000255 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000256}
257
Daniel Dunbar66912a12008-08-20 00:28:19 +0000258llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
259 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000260 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000261}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000263/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000264/// to type erasure at various points, e.g., related result types or the use
265/// of parameterized classes.
266static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
267 RValue Result) {
268 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000269 return Result;
John McCall31168b02011-06-15 23:02:42 +0000270
Douglas Gregore83b9562015-07-07 03:57:53 +0000271 // If the converted types are the same, we're done.
272 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
273 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000274 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000275
276 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000277 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000278 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000279}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000280
John McCallcf166702011-07-22 08:53:00 +0000281/// Decide whether to extend the lifetime of the receiver of a
282/// returns-inner-pointer message.
283static bool
284shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
285 switch (message->getReceiverKind()) {
286
287 // For a normal instance message, we should extend unless the
288 // receiver is loaded from a variable with precise lifetime.
289 case ObjCMessageExpr::Instance: {
290 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000291
292 // Look through OVEs.
293 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
294 if (opaque->getSourceExpr())
295 receiver = opaque->getSourceExpr()->IgnoreParens();
296 }
297
John McCallcf166702011-07-22 08:53:00 +0000298 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
299 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
300 receiver = ice->getSubExpr()->IgnoreParens();
301
John McCall6380a282015-09-09 23:37:17 +0000302 // Look through OVEs.
303 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
304 if (opaque->getSourceExpr())
305 receiver = opaque->getSourceExpr()->IgnoreParens();
306 }
307
John McCallcf166702011-07-22 08:53:00 +0000308 // Only __strong variables.
309 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
310 return true;
311
312 // All ivars and fields have precise lifetime.
313 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
314 return false;
315
316 // Otherwise, check for variables.
317 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
318 if (!declRef) return true;
319 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
320 if (!var) return true;
321
322 // All variables have precise lifetime except local variables with
323 // automatic storage duration that aren't specially marked.
324 return (var->hasLocalStorage() &&
325 !var->hasAttr<ObjCPreciseLifetimeAttr>());
326 }
327
328 case ObjCMessageExpr::Class:
329 case ObjCMessageExpr::SuperClass:
330 // It's never necessary for class objects.
331 return false;
332
333 case ObjCMessageExpr::SuperInstance:
334 // We generally assume that 'self' lives throughout a method call.
335 return false;
336 }
337
338 llvm_unreachable("invalid receiver kind");
339}
340
John McCall460ce582015-10-22 18:38:17 +0000341/// Given an expression of ObjC pointer type, check whether it was
342/// immediately loaded from an ARC __weak l-value.
343static const Expr *findWeakLValue(const Expr *E) {
344 assert(E->getType()->isObjCRetainableType());
345 E = E->IgnoreParens();
346 if (auto CE = dyn_cast<CastExpr>(E)) {
347 if (CE->getCastKind() == CK_LValueToRValue) {
348 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
349 return CE->getSubExpr();
350 }
351 }
352
353 return nullptr;
354}
355
Pete Coopere3886802018-12-08 05:13:50 +0000356/// The ObjC runtime may provide entrypoints that are likely to be faster
357/// than an ordinary message send of the appropriate selector.
358///
359/// The entrypoints are guaranteed to be equivalent to just sending the
360/// corresponding message. If the entrypoint is implemented naively as just a
361/// message send, using it is a trade-off: it sacrifices a few cycles of
362/// overhead to save a small amount of code. However, it's possible for
363/// runtimes to detect and special-case classes that use "standard"
364/// behavior; if that's dynamically a large proportion of all objects, using
365/// the entrypoint will also be faster than using a message send.
366///
367/// If the runtime does support a required entrypoint, then this method will
368/// generate a call and return the resulting value. Otherwise it will return
369/// None and the caller can generate a msgSend instead.
370static Optional<llvm::Value *>
371tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
372 llvm::Value *Receiver,
373 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000374 const ObjCMethodDecl *method,
375 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000376 auto &CGM = CGF.CGM;
377 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
378 return None;
379
380 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
381 switch (Sel.getMethodFamily()) {
382 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000383 if (isClassMessage &&
384 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000385 ResultType->isObjCObjectPointerType()) {
386 // [Foo alloc] -> objc_alloc(Foo)
387 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
388 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
389 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
390 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
391 Args.size() == 1 && Args.front().getType()->isPointerType() &&
392 Sel.getNameForSlot(0) == "allocWithZone") {
393 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
394 if (isa<llvm::ConstantPointerNull>(arg))
395 return CGF.EmitObjCAllocWithZone(Receiver,
396 CGF.ConvertType(ResultType));
397 return None;
398 }
399 }
400 break;
401
Pete Coopere5b64ea2018-12-21 21:00:32 +0000402 case OMF_autorelease:
403 if (ResultType->isObjCObjectPointerType() &&
404 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
405 Runtime.shouldUseARCFunctionsForRetainRelease())
406 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
407 break;
408
409 case OMF_retain:
410 if (ResultType->isObjCObjectPointerType() &&
411 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
412 Runtime.shouldUseARCFunctionsForRetainRelease())
413 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
414 break;
415
416 case OMF_release:
417 if (ResultType->isVoidType() &&
418 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
419 Runtime.shouldUseARCFunctionsForRetainRelease()) {
420 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
421 return nullptr;
422 }
423 break;
424
Pete Coopere3886802018-12-08 05:13:50 +0000425 default:
426 break;
427 }
428 return None;
429}
430
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000431/// Instead of '[[MyClass alloc] init]', try to generate
432/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
433/// caller side, as well as the optimized objc_alloc.
434static Optional<llvm::Value *>
435tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
436 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
437 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
438 return None;
439
440 // Match the exact pattern '[[MyClass alloc] init]'.
441 Selector Sel = OME->getSelector();
Erik Pilkington55e703a2019-02-25 21:35:14 +0000442 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
443 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
444 Sel.getNameForSlot(0) != "init")
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000445 return None;
446
447 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'.
448 auto *SubOME =
449 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParens());
450 if (!SubOME)
451 return None;
452 Selector SubSel = SubOME->getSelector();
453 if (SubOME->getReceiverKind() != ObjCMessageExpr::Class ||
454 !SubOME->getType()->isObjCObjectPointerType() ||
455 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
456 return None;
457
458 QualType ReceiverType = SubOME->getClassReceiver();
459 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
460 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
461 assert(ID && "null interface should be impossible here");
462 llvm::Value *Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
463 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
464}
465
John McCall78a15112010-05-22 01:48:05 +0000466RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
467 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000468 // Only the lookup mechanism and first two arguments of the method
469 // implementation vary between runtimes. We can get the receiver and
470 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000471
John McCall31168b02011-06-15 23:02:42 +0000472 bool isDelegateInit = E->isDelegateInitCall();
473
John McCallcf166702011-07-22 08:53:00 +0000474 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000475
John McCall460ce582015-10-22 18:38:17 +0000476 // If the method is -retain, and the receiver's being loaded from
477 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
478 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
479 method->getMethodFamily() == OMF_retain) {
480 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
481 LValue lvalue = EmitLValue(lvalueExpr);
482 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
483 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
484 }
485 }
486
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000487 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
488 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
489
John McCall31168b02011-06-15 23:02:42 +0000490 // We don't retain the receiver in delegate init calls, and this is
491 // safe because the receiver value is always loaded from 'self',
492 // which we zero out. We don't want to Block_copy block receivers,
493 // though.
494 bool retainSelf =
495 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000496 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000497 method &&
498 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000499
Daniel Dunbar8d480592008-08-11 18:12:00 +0000500 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000501 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000502 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000503 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000504 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000505 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000506 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000507 switch (E->getReceiverKind()) {
508 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000509 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000510 if (retainSelf) {
511 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
512 E->getInstanceReceiver());
513 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000514 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000515 } else
516 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000517 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000518
Douglas Gregor9a129192010-04-21 00:45:42 +0000519 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000520 ReceiverType = E->getClassReceiver();
521 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000522 assert(ObjTy && "Invalid Objective-C class message send");
523 OID = ObjTy->getInterface();
524 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000525 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000526 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000527 break;
528 }
529
530 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000531 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000532 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000533 isSuperMessage = true;
534 break;
535
536 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000537 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000538 Receiver = LoadObjCSelf();
539 isSuperMessage = true;
540 isClassMessage = true;
541 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000542 }
543
John McCallcf166702011-07-22 08:53:00 +0000544 if (retainSelf)
545 Receiver = EmitARCRetainNonBlock(Receiver);
546
547 // In ARC, we sometimes want to "extend the lifetime"
548 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
549 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000550 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000551 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
552 shouldExtendReceiverForInnerPointerMessage(E))
553 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
554
Alp Toker314cc812014-01-25 16:55:45 +0000555 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000556
Daniel Dunbarc722b852008-08-30 03:02:31 +0000557 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000558 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000559
John McCall31168b02011-06-15 23:02:42 +0000560 // For delegate init calls in ARC, do an unsafe store of null into
561 // self. This represents the call taking direct ownership of that
562 // value. We have to do this after emitting the other call
563 // arguments because they might also reference self, but we don't
564 // have to worry about any of them modifying self because that would
565 // be an undefined read and write of an object in unordered
566 // expressions.
567 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000568 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000569 "delegate init calls should only be marked in ARC");
570
571 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000572 Address selfAddr =
573 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000574 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
575 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000576
Douglas Gregor33823722011-06-11 01:09:30 +0000577 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000578 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000579 // super is only valid in an Objective-C method
580 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000581 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000582 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
583 E->getSelector(),
584 OMD->getClassInterface(),
585 isCategoryImpl,
586 Receiver,
587 isClassMessage,
588 Args,
John McCallcf166702011-07-22 08:53:00 +0000589 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000590 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000591 // Call runtime methods directly if we can.
592 if (Optional<llvm::Value *> SpecializedResult =
593 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000594 E->getSelector(), method,
595 isClassMessage)) {
Pete Coopere3886802018-12-08 05:13:50 +0000596 result = RValue::get(SpecializedResult.getValue());
597 } else {
598 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
599 E->getSelector(), Receiver, Args,
600 OID, method);
601 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000602 }
John McCall31168b02011-06-15 23:02:42 +0000603
604 // For delegate init calls in ARC, implicitly store the result of
605 // the call back into self. This takes ownership of the value.
606 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000607 Address selfAddr =
608 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000609 llvm::Value *newSelf = result.getScalarVal();
610
611 // The delegate return type isn't necessarily a matching type; in
612 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000613 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000614 newSelf = Builder.CreateBitCast(newSelf, selfTy);
615
616 Builder.CreateStore(newSelf, selfAddr);
617 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000618
Douglas Gregore83b9562015-07-07 03:57:53 +0000619 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000620}
621
John McCall31168b02011-06-15 23:02:42 +0000622namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000623struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000624 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000625 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000626
627 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000628 const ObjCInterfaceDecl *iface = impl->getClassInterface();
629 if (!iface->getSuperClass()) return;
630
John McCalldffafde2011-07-13 18:26:47 +0000631 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
632
John McCall31168b02011-06-15 23:02:42 +0000633 // Call [super dealloc] if we have a superclass.
634 llvm::Value *self = CGF.LoadObjCSelf();
635
636 CallArgList args;
637 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
638 CGF.getContext().VoidTy,
639 method->getSelector(),
640 iface,
John McCalldffafde2011-07-13 18:26:47 +0000641 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000642 self,
643 /*is class msg*/ false,
644 args,
645 method);
646 }
647};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000648}
John McCall31168b02011-06-15 23:02:42 +0000649
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000650/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
651/// the LLVM function and sets the other context used by
652/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000653void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000654 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000655 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000656 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000657 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000658 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000659 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000660
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000661 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000662
John McCalla729c622012-02-17 03:33:10 +0000663 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000664 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000665
John McCalla738c252011-03-09 04:27:21 +0000666 args.push_back(OMD->getSelfDecl());
667 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000668
Benjamin Kramerf9890422015-02-17 16:48:30 +0000669 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000670
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000671 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000672 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000673
Adrian Prantl42d71b92014-04-10 23:21:53 +0000674 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
675 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000676
677 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000678 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000679 OMD->isInstanceMethod() &&
680 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000681 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000682 OMD->getSelector().getIdentifierInfoForSlot(0);
683 if (ident->isStr("dealloc"))
684 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
685 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000686}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000687
John McCall31168b02011-06-15 23:02:42 +0000688static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
689 LValue lvalue, QualType type);
690
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000691/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000692/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000693void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000694 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000695 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000696 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000697 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000698 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000699 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000700}
701
John McCallb923ece2011-09-12 23:06:44 +0000702/// emitStructGetterCall - Call the runtime function to load a property
703/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000704static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000705 bool isAtomic, bool hasStrong) {
706 ASTContext &Context = CGF.getContext();
707
John McCall7f416cc2015-09-08 08:05:57 +0000708 Address src =
709 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
710 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000711
Fangrui Song6907ce22018-07-30 19:24:48 +0000712 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000713 // sizeof (Type of Ivar), isAtomic, false);
714 CallArgList args;
715
John McCall7f416cc2015-09-08 08:05:57 +0000716 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
717 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000718
719 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000720 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000721
722 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
723 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
724 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
725 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
726
James Y Knight9871db02019-02-05 16:42:33 +0000727 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000728 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000729 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000730 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000731}
732
John McCallf4528ae2011-09-13 03:34:09 +0000733/// Determine whether the given architecture supports unaligned atomic
734/// accesses. They don't have to be fast, just faster than a function
735/// call and a mutex.
736static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000737 // FIXME: Allow unaligned atomic load/store on x86. (It is not
738 // currently supported by the backend.)
739 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000740}
741
742/// Return the maximum size that permits atomic accesses for the given
743/// architecture.
744static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
745 llvm::Triple::ArchType arch) {
746 // ARM has 8-byte atomic accesses, but it's not clear whether we
747 // want to rely on them here.
748
749 // In the default case, just assume that any size up to a pointer is
750 // fine given adequate alignment.
751 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
752}
753
754namespace {
755 class PropertyImplStrategy {
756 public:
757 enum StrategyKind {
758 /// The 'native' strategy is to use the architecture's provided
759 /// reads and writes.
760 Native,
761
762 /// Use objc_setProperty and objc_getProperty.
763 GetSetProperty,
764
765 /// Use objc_setProperty for the setter, but use expression
766 /// evaluation for the getter.
767 SetPropertyAndExpressionGet,
768
769 /// Use objc_copyStruct.
770 CopyStruct,
771
772 /// The 'expression' strategy is to emit normal assignment or
773 /// lvalue-to-rvalue expressions.
774 Expression
775 };
776
777 StrategyKind getKind() const { return StrategyKind(Kind); }
778
779 bool hasStrongMember() const { return HasStrong; }
780 bool isAtomic() const { return IsAtomic; }
781 bool isCopy() const { return IsCopy; }
782
783 CharUnits getIvarSize() const { return IvarSize; }
784 CharUnits getIvarAlignment() const { return IvarAlignment; }
785
786 PropertyImplStrategy(CodeGenModule &CGM,
787 const ObjCPropertyImplDecl *propImpl);
788
789 private:
790 unsigned Kind : 8;
791 unsigned IsAtomic : 1;
792 unsigned IsCopy : 1;
793 unsigned HasStrong : 1;
794
795 CharUnits IvarSize;
796 CharUnits IvarAlignment;
797 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000798}
John McCallf4528ae2011-09-13 03:34:09 +0000799
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000800/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000801PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
802 const ObjCPropertyImplDecl *propImpl) {
803 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000804 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000805
John McCall43192862011-09-13 18:31:23 +0000806 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
807 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000808 HasStrong = false; // doesn't matter here.
809
810 // Evaluate the ivar's size and alignment.
811 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
812 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000813 std::tie(IvarSize, IvarAlignment) =
814 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000815
816 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000817 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000818 if (IsCopy) {
819 Kind = GetSetProperty;
820 return;
821 }
822
John McCall43192862011-09-13 18:31:23 +0000823 // Handle retain.
824 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000825 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000826 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000827 // fallthrough
828
829 // In ARC, if the property is non-atomic, use expression emission,
830 // which translates to objc_storeStrong. This isn't required, but
831 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000833 // Using standard expression emission for the setter is only
834 // acceptable if the ivar is __strong, which won't be true if
835 // the property is annotated with __attribute__((NSObject)).
836 // TODO: falling all the way back to objc_setProperty here is
837 // just laziness, though; we could still use objc_storeStrong
838 // if we hacked it right.
839 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
840 Kind = Expression;
841 else
842 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000843 return;
844
845 // Otherwise, we need to at least use setProperty. However, if
846 // the property isn't atomic, we can use normal expression
847 // emission for the getter.
848 } else if (!IsAtomic) {
849 Kind = SetPropertyAndExpressionGet;
850 return;
851
852 // Otherwise, we have to use both setProperty and getProperty.
853 } else {
854 Kind = GetSetProperty;
855 return;
856 }
857 }
858
859 // If we're not atomic, just use expression accesses.
860 if (!IsAtomic) {
861 Kind = Expression;
862 return;
863 }
864
John McCall0e5c0862011-09-13 05:36:29 +0000865 // Properties on bitfield ivars need to be emitted using expression
866 // accesses even if they're nominally atomic.
867 if (ivar->isBitField()) {
868 Kind = Expression;
869 return;
870 }
871
John McCallf4528ae2011-09-13 03:34:09 +0000872 // GC-qualified or ARC-qualified ivars need to be emitted as
873 // expressions. This actually works out to being atomic anyway,
874 // except for ARC __strong, but that should trigger the above code.
875 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000876 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000877 CGM.getContext().getObjCGCAttrKind(ivarType))) {
878 Kind = Expression;
879 return;
880 }
881
882 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000883 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000884 if (const RecordType *recordType = ivarType->getAs<RecordType>())
885 HasStrong = recordType->getDecl()->hasObjectMember();
886
887 // We can never access structs with object members with a native
888 // access, because we need to use write barriers. This is what
889 // objc_copyStruct is for.
890 if (HasStrong) {
891 Kind = CopyStruct;
892 return;
893 }
894
895 // Otherwise, this is target-dependent and based on the size and
896 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000897
898 // If the size of the ivar is not a power of two, give up. We don't
899 // want to get into the business of doing compare-and-swaps.
900 if (!IvarSize.isPowerOfTwo()) {
901 Kind = CopyStruct;
902 return;
903 }
904
John McCallf4528ae2011-09-13 03:34:09 +0000905 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000906 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000907
908 // Most architectures require memory to fit within a single cache
909 // line, so the alignment has to be at least the size of the access.
910 // Otherwise we have to grab a lock.
911 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
912 Kind = CopyStruct;
913 return;
914 }
915
916 // If the ivar's size exceeds the architecture's maximum atomic
917 // access size, we have to use CopyStruct.
918 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
919 Kind = CopyStruct;
920 return;
921 }
922
923 // Otherwise, we can use native loads and stores.
924 Kind = Native;
925}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000927/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000928///
929/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000930/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000931void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
932 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000933 llvm::Constant *AtomicHelperFn =
934 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000935 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
936 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
937 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000938 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000939
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000940 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000941
942 FinishFunction();
943}
944
John McCallbdd81852011-09-13 06:00:03 +0000945static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
946 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000947 if (!getter) return true;
948
949 // Sema only makes only of these when the ivar has a C++ class type,
950 // so the form is pretty constrained.
951
John McCallbdd81852011-09-13 06:00:03 +0000952 // If the property has a reference type, we might just be binding a
953 // reference, in which case the result will be a gl-value. We should
954 // treat this as a non-trivial operation.
955 if (getter->isGLValue())
956 return false;
957
John McCallf4528ae2011-09-13 03:34:09 +0000958 // If we selected a trivial copy-constructor, we're okay.
959 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
960 return (construct->getConstructor()->isTrivial());
961
962 // The constructor might require cleanups (in which case it's never
963 // trivial).
964 assert(isa<ExprWithCleanups>(getter));
965 return false;
966}
967
Fangrui Song6907ce22018-07-30 19:24:48 +0000968/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000969/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000970static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000971 llvm::Value *returnAddr,
972 ObjCIvarDecl *ivar,
973 llvm::Constant *AtomicHelperFn) {
974 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
975 // AtomicHelperFn);
976 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000977
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000978 // The 1st argument is the return Slot.
979 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000980
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000981 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +0000982 llvm::Value *ivarAddr =
983 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +0000984 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000985 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
986 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000987
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000988 // Third argument is the helper function.
989 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000990
James Y Knight9871db02019-02-05 16:42:33 +0000991 llvm::FunctionCallee copyCppAtomicObjectFn =
992 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000993 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000994 CGF.EmitCall(
995 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000996 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000997}
998
John McCallf4528ae2011-09-13 03:34:09 +0000999void
1000CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001001 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001002 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001003 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +00001004 // If there's a non-trivial 'get' expression, we just have to emit that.
1005 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001006 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001007 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1008 propImpl->getGetterCXXConstructor(),
1009 /* NRVOCandidate=*/nullptr);
1010 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001011 }
1012 else {
1013 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001014 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001015 ivar, AtomicHelperFn);
1016 }
John McCallf4528ae2011-09-13 03:34:09 +00001017 return;
1018 }
1019
1020 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1021 QualType propType = prop->getType();
1022 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
1023
Fangrui Song6907ce22018-07-30 19:24:48 +00001024 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001025
1026 // Pick an implementation strategy.
1027 PropertyImplStrategy strategy(CGM, propImpl);
1028 switch (strategy.getKind()) {
1029 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001030 // We don't need to do anything for a zero-size struct.
1031 if (strategy.getIvarSize().isZero())
1032 return;
1033
John McCallf4528ae2011-09-13 03:34:09 +00001034 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1035
1036 // Currently, all atomic accesses have to be through integer
1037 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001038 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1039 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001040 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1041
1042 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +00001043 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +00001044 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1045 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001046 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001047
1048 // Store that value into the return address. Doing this with a
1049 // bitcast is likely to produce some pretty ugly IR, but it's not
1050 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001051 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1052 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1053 llvm::Value *ivarVal = load;
1054 if (ivarSize > retTySize) {
1055 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1056 ivarVal = Builder.CreateTrunc(load, newTy);
1057 bitcastType = newTy->getPointerTo();
1058 }
1059 Builder.CreateStore(ivarVal,
1060 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001061
1062 // Make sure we don't do an autorelease.
1063 AutoreleaseResult = false;
1064 return;
1065 }
1066
1067 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001068 llvm::FunctionCallee getPropertyFn =
1069 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001070 if (!getPropertyFn) {
1071 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001072 return;
1073 }
John McCallb92ab1a2016-10-26 23:46:34 +00001074 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001075
1076 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1077 // FIXME: Can't this be simpler? This might even be worse than the
1078 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001079 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001080 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001081 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1082 llvm::Value *ivarOffset =
1083 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1084
1085 CallArgList args;
1086 args.add(RValue::get(self), getContext().getObjCIdType());
1087 args.add(RValue::get(cmd), getContext().getObjCSelType());
1088 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001089 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1090 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001091
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001092 // FIXME: We shouldn't need to get the function info here, the
1093 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001094 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001095 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1096 getContext().getObjCIdType(), args),
1097 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001098 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1099 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001100
Daniel Dunbara08dff12008-09-24 04:04:31 +00001101 // We need to fix the type here. Ivars with copy & retain are
1102 // always objects so we don't need to worry about complex or
1103 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001104 RV = RValue::get(Builder.CreateBitCast(
1105 RV.getScalarVal(),
1106 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001107
1108 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001109
1110 // objc_getProperty does an autorelease, so we should suppress ours.
1111 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001112
John McCallf4528ae2011-09-13 03:34:09 +00001113 return;
1114 }
1115
1116 case PropertyImplStrategy::CopyStruct:
1117 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1118 strategy.hasStrongMember());
1119 return;
1120
1121 case PropertyImplStrategy::Expression:
1122 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1123 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1124
1125 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001126 switch (getEvaluationKind(ivarType)) {
1127 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001128 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001129 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001130 /*init*/ true);
1131 return;
1132 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001133 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001134 // The return value slot is guaranteed to not be aliased, but
1135 // that's not necessarily the same as "on the stack", so
1136 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001137 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smithe78fac52018-04-05 20:52:58 +00001138 /* Src= */ LV, ivarType, overlapForReturnValue());
1139 return;
1140 }
John McCall47fb9502013-03-07 21:37:08 +00001141 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001142 llvm::Value *value;
1143 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001144 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001145 } else {
1146 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1147 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001148 if (getLangOpts().ObjCAutoRefCount) {
1149 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1150 } else {
1151 value = EmitARCLoadWeak(LV.getAddress());
1152 }
John McCall24fada12011-07-22 05:23:13 +00001153
1154 // Otherwise we want to do a simple load, suppressing the
1155 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001156 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001157 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001158 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001159 }
John McCall31168b02011-06-15 23:02:42 +00001160
Alp Toker314cc812014-01-25 16:55:45 +00001161 value = Builder.CreateBitCast(
1162 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001163 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001164
John McCall24fada12011-07-22 05:23:13 +00001165 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001166 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001167 }
John McCall47fb9502013-03-07 21:37:08 +00001168 }
1169 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001170 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001171
John McCallf4528ae2011-09-13 03:34:09 +00001172 }
1173 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001174}
1175
John McCallb923ece2011-09-12 23:06:44 +00001176/// emitStructSetterCall - Call the runtime function to store the value
1177/// from the first formal parameter into the given ivar.
1178static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1179 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001180 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001181 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001182 CallArgList args;
1183
1184 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001185 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1186 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001187 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001188 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1189 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001190
1191 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001192 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001193 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1194 argVar->getType().getNonReferenceType(), VK_LValue,
1195 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001196 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001197 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1198 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001199
1200 // The third argument is the sizeof the type.
1201 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001202 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1203 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001204
John McCallb923ece2011-09-12 23:06:44 +00001205 // The fourth argument is the 'isAtomic' flag.
1206 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001207
John McCallb923ece2011-09-12 23:06:44 +00001208 // The fifth argument is the 'hasStrong' flag.
1209 // FIXME: should this really always be false?
1210 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1211
James Y Knight9871db02019-02-05 16:42:33 +00001212 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001213 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001214 CGF.EmitCall(
1215 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001216 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001217}
1218
Fangrui Song6907ce22018-07-30 19:24:48 +00001219/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1220/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001221/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001222static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001223 ObjCMethodDecl *OMD,
1224 ObjCIvarDecl *ivar,
1225 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001226 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001227 // AtomicHelperFn);
1228 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001229
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001230 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001231 llvm::Value *ivarAddr =
1232 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001233 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001234 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1235 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001236
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001237 // The second argument is the address of the parameter variable.
1238 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001239 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1240 argVar->getType().getNonReferenceType(), VK_LValue,
1241 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001242 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001243 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1244 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001245
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001246 // Third argument is the helper function.
1247 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001248
James Y Knight9871db02019-02-05 16:42:33 +00001249 llvm::FunctionCallee fn =
1250 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001251 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001252 CGF.EmitCall(
1253 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001254 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001255}
1256
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001257
John McCallf4528ae2011-09-13 03:34:09 +00001258static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1259 Expr *setter = PID->getSetterCXXAssignment();
1260 if (!setter) return true;
1261
1262 // Sema only makes only of these when the ivar has a C++ class type,
1263 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001264
1265 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001266 // This also implies that there's nothing non-trivial going on with
1267 // the arguments, because operator= can only be trivial if it's a
1268 // synthesized assignment operator and therefore both parameters are
1269 // references.
1270 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001271 if (const FunctionDecl *callee
1272 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1273 if (callee->isTrivial())
1274 return true;
1275 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001276 }
John McCall7f16c422011-09-10 09:17:20 +00001277
John McCallf4528ae2011-09-13 03:34:09 +00001278 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001279 return false;
1280}
1281
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001282static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001283 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001284 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001285 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001286}
1287
John McCall7f16c422011-09-10 09:17:20 +00001288void
1289CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001290 const ObjCPropertyImplDecl *propImpl,
1291 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001292 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001293 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001294 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001295
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001296 // Just use the setter expression if Sema gave us one and it's
1297 // non-trivial.
1298 if (!hasTrivialSetExpr(propImpl)) {
1299 if (!AtomicHelperFn)
1300 // If non-atomic, assignment is called directly.
1301 EmitStmt(propImpl->getSetterCXXAssignment());
1302 else
1303 // If atomic, assignment is called via a locking api.
1304 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1305 AtomicHelperFn);
1306 return;
1307 }
John McCall7f16c422011-09-10 09:17:20 +00001308
John McCallf4528ae2011-09-13 03:34:09 +00001309 PropertyImplStrategy strategy(CGM, propImpl);
1310 switch (strategy.getKind()) {
1311 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001312 // We don't need to do anything for a zero-size struct.
1313 if (strategy.getIvarSize().isZero())
1314 return;
1315
John McCall7f416cc2015-09-08 08:05:57 +00001316 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001317
John McCallf4528ae2011-09-13 03:34:09 +00001318 LValue ivarLValue =
1319 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001320 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001321
John McCallf4528ae2011-09-13 03:34:09 +00001322 // Currently, all atomic accesses have to be through integer
1323 // types, so there's no point in trying to pick a prettier type.
1324 llvm::Type *bitcastType =
1325 llvm::Type::getIntNTy(getLLVMContext(),
1326 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001327
1328 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001329 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1330 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001331
1332 // This bitcast load is likely to cause some nasty IR.
1333 llvm::Value *load = Builder.CreateLoad(argAddr);
1334
1335 // Perform an atomic store. There are no memory ordering requirements.
1336 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001337 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001338 return;
1339 }
1340
1341 case PropertyImplStrategy::GetSetProperty:
1342 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001343
James Y Knight9871db02019-02-05 16:42:33 +00001344 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1345 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001346 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001347 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001348 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001349 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1350 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001351 if (!setOptimizedPropertyFn) {
1352 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1353 return;
1354 }
John McCall7f16c422011-09-10 09:17:20 +00001355 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001356 else {
1357 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1358 if (!setPropertyFn) {
1359 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1360 return;
1361 }
1362 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001363
John McCall7f16c422011-09-10 09:17:20 +00001364 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1365 // <is-atomic>, <is-copy>).
1366 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001367 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001368 llvm::Value *self =
1369 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1370 llvm::Value *ivarOffset =
1371 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001372 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1373 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1374 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001375
1376 CallArgList args;
1377 args.add(RValue::get(self), getContext().getObjCIdType());
1378 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001379 if (setOptimizedPropertyFn) {
1380 args.add(RValue::get(arg), getContext().getObjCIdType());
1381 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001382 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001383 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001384 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001385 } else {
1386 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1387 args.add(RValue::get(arg), getContext().getObjCIdType());
1388 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1389 getContext().BoolTy);
1390 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1391 getContext().BoolTy);
1392 // FIXME: We shouldn't need to get the function info here, the runtime
1393 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001394 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001395 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001396 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001397 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001398
John McCall7f16c422011-09-10 09:17:20 +00001399 return;
1400 }
1401
John McCallf4528ae2011-09-13 03:34:09 +00001402 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001403 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001404 return;
John McCallf4528ae2011-09-13 03:34:09 +00001405
1406 case PropertyImplStrategy::Expression:
1407 break;
John McCall7f16c422011-09-10 09:17:20 +00001408 }
1409
1410 // Otherwise, fake up some ASTs and emit a normal assignment.
1411 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001412 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001413 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001414 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1415 selfDecl->getType(), CK_LValueToRValue, &self,
1416 VK_RValue);
1417 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001418 SourceLocation(), SourceLocation(),
1419 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001420
1421 ParmVarDecl *argDecl = *setterMethod->param_begin();
1422 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001423 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1424 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001425 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1426 argType.getUnqualifiedType(), CK_LValueToRValue,
1427 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001428
John McCall7f16c422011-09-10 09:17:20 +00001429 // The property type can differ from the ivar type in some situations with
1430 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1431 // The following absurdity is just to ensure well-formed IR.
1432 CastKind argCK = CK_NoOp;
1433 if (ivarRef.getType()->isObjCObjectPointerType()) {
1434 if (argLoad.getType()->isObjCObjectPointerType())
1435 argCK = CK_BitCast;
1436 else if (argLoad.getType()->isBlockPointerType())
1437 argCK = CK_BlockPointerToObjCPointerCast;
1438 else
1439 argCK = CK_CPointerToObjCPointerCast;
1440 } else if (ivarRef.getType()->isBlockPointerType()) {
1441 if (argLoad.getType()->isBlockPointerType())
1442 argCK = CK_BitCast;
1443 else
1444 argCK = CK_AnyPointerToBlockPointerCast;
1445 } else if (ivarRef.getType()->isPointerType()) {
1446 argCK = CK_BitCast;
1447 }
1448 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1449 ivarRef.getType(), argCK, &argLoad,
1450 VK_RValue);
1451 Expr *finalArg = &argLoad;
1452 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1453 argLoad.getType()))
1454 finalArg = &argCast;
1455
1456
1457 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1458 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001459 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001460 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001461}
1462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001463/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001464///
1465/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001466/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001467void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1468 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001469 llvm::Constant *AtomicHelperFn =
1470 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001471 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1472 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1473 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001474 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001475
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001476 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001477
1478 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001479}
1480
John McCall6a4fa522011-03-22 07:05:39 +00001481namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001482 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001483 private:
1484 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001485 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001486 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001487 bool useEHCleanupForArray;
1488 public:
1489 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1490 CodeGenFunction::Destroyer *destroyer,
1491 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001492 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001493 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001494
Craig Topper4f12f102014-03-12 06:41:41 +00001495 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001496 LValue lvalue
1497 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1498 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001499 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001500 }
1501 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001502}
John McCall6a4fa522011-03-22 07:05:39 +00001503
John McCall4bd0fb12011-07-12 16:41:08 +00001504/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1505static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001506 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001507 QualType type) {
1508 llvm::Value *null = getNullForVariable(addr);
1509 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1510}
John McCall31168b02011-06-15 23:02:42 +00001511
John McCall6a4fa522011-03-22 07:05:39 +00001512static void emitCXXDestructMethod(CodeGenFunction &CGF,
1513 ObjCImplementationDecl *impl) {
1514 CodeGenFunction::RunCleanupsScope scope(CGF);
1515
1516 llvm::Value *self = CGF.LoadObjCSelf();
1517
Jordy Rosea91768e2011-07-22 02:08:32 +00001518 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1519 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001520 ivar; ivar = ivar->getNextIvar()) {
1521 QualType type = ivar->getType();
1522
John McCall6a4fa522011-03-22 07:05:39 +00001523 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001524 QualType::DestructionKind dtorKind = type.isDestructedType();
1525 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001526
Craig Topper8a13c412014-05-21 05:09:00 +00001527 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001528
John McCall4bd0fb12011-07-12 16:41:08 +00001529 // Use a call to objc_storeStrong to destroy strong ivars, for the
1530 // general benefit of the tools.
1531 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001532 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001533
John McCall4bd0fb12011-07-12 16:41:08 +00001534 // Otherwise use the default for the destruction kind.
1535 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001536 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001537 }
John McCall4bd0fb12011-07-12 16:41:08 +00001538
1539 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1540
1541 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1542 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001543 }
1544
1545 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1546}
1547
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001548void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1549 ObjCMethodDecl *MD,
1550 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001551 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001552 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001553
1554 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001555 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001556 // Suppress the final autorelease in ARC.
1557 AutoreleaseResult = false;
1558
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001559 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001560 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001561 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001562 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001563 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001564 EmitAggExpr(IvarInit->getInit(),
1565 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001566 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001567 AggValueSlot::IsNotAliased,
1568 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001569 }
1570 // constructor returns 'self'.
1571 CodeGenTypes &Types = CGM.getTypes();
1572 QualType IdTy(CGM.getContext().getObjCIdType());
1573 llvm::Value *SelfAsId =
1574 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1575 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001576
1577 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001578 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001579 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001580 }
1581 FinishFunction();
1582}
1583
Daniel Dunbara08dff12008-09-24 04:04:31 +00001584llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001585 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001586 DeclRefExpr DRE(getContext(), Self,
1587 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001588 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001589 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001590}
1591
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001592QualType CodeGenFunction::TypeOfSelfObject() {
1593 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1594 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001595 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1596 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001597 return PTy->getPointeeType();
1598}
1599
Chris Lattnerd4808922009-03-22 21:03:39 +00001600void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001601 llvm::FunctionCallee EnumerationMutationFnPtr =
1602 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001603 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001604 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1605 return;
1606 }
John McCallb92ab1a2016-10-26 23:46:34 +00001607 CGCallee EnumerationMutationFn =
1608 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001609
Devang Pateld2d66652011-01-19 01:36:36 +00001610 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001611 if (DI)
1612 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001613
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001614 RunCleanupsScope ForScope(*this);
1615
Kuba Mracek82c21752017-04-14 01:00:03 +00001616 // The local variable comes into scope immediately.
1617 AutoVarEmission variable = AutoVarEmission::invalid();
1618 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1619 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1620
John McCall1c926b72011-01-07 01:49:06 +00001621 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001622
Anders Carlsson75658592008-08-31 02:33:12 +00001623 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001624 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001625 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001626 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001627
Anders Carlsson75658592008-08-31 02:33:12 +00001628 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001629 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001630
John McCall1c926b72011-01-07 01:49:06 +00001631 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001632 IdentifierInfo *II[] = {
1633 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1634 &CGM.getContext().Idents.get("objects"),
1635 &CGM.getContext().Idents.get("count")
1636 };
1637 Selector FastEnumSel =
1638 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001639
1640 QualType ItemsTy =
1641 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001642 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001643 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001644 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001645
John McCall53848232011-07-27 01:07:15 +00001646 // Emit the collection pointer. In ARC, we do a retain.
1647 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001648 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001649 Collection = EmitARCRetainScalarExpr(S.getCollection());
1650
1651 // Enter a cleanup to do the release.
1652 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1653 } else {
1654 Collection = EmitScalarExpr(S.getCollection());
1655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
John McCall91e82dd2011-08-05 00:14:38 +00001657 // The 'continue' label needs to appear within the cleanup for the
1658 // collection object.
1659 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1660
John McCall1c926b72011-01-07 01:49:06 +00001661 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001662 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001663
1664 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001665 Args.add(RValue::get(StatePtr.getPointer()),
1666 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001667
John McCall1c926b72011-01-07 01:49:06 +00001668 // The second argument is a temporary array with space for NumItems
1669 // pointers. We'll actually be loading elements from the array
1670 // pointer written into the control state; this buffer is so that
1671 // collections that *aren't* backed by arrays can still queue up
1672 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001673 Args.add(RValue::get(ItemsPtr.getPointer()),
1674 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001675
John McCall1c926b72011-01-07 01:49:06 +00001676 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001677 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1678 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1679 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001680
John McCall1c926b72011-01-07 01:49:06 +00001681 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001682 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001683 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1684 getContext().getNSUIntegerType(),
1685 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001686
John McCall1c926b72011-01-07 01:49:06 +00001687 // The initial number of objects that were returned in the buffer.
1688 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall1c926b72011-01-07 01:49:06 +00001690 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1691 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001692
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001693 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001694
John McCall1c926b72011-01-07 01:49:06 +00001695 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001696 // empty; skip all this. Set the branch weight assuming this has the same
1697 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001698 uint64_t EntryCount = getCurrentProfileCount();
1699 Builder.CreateCondBr(
1700 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1701 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001702 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001703
John McCall1c926b72011-01-07 01:49:06 +00001704 // Otherwise, initialize the loop.
1705 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall1c926b72011-01-07 01:49:06 +00001707 // Save the initial mutations value. This is the value at an
1708 // address that was written into the state object by
1709 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001710 Address StateMutationsPtrPtr =
1711 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001712 llvm::Value *StateMutationsPtr
1713 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001714
John McCall1c926b72011-01-07 01:49:06 +00001715 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001716 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1717 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001718
John McCall1c926b72011-01-07 01:49:06 +00001719 // Start looping. This is the point we return to whenever we have a
1720 // fresh, non-empty batch of objects.
1721 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1722 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001723
John McCall1c926b72011-01-07 01:49:06 +00001724 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001725 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001726 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001727
John McCall1c926b72011-01-07 01:49:06 +00001728 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001729 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001730 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Justin Bogner66242d62015-04-23 23:06:47 +00001732 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001733
John McCall1c926b72011-01-07 01:49:06 +00001734 // Check whether the mutations value has changed from where it was
1735 // at start. StateMutationsPtr should actually be invariant between
1736 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001737 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001738 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001739 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1740 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001741
John McCall1c926b72011-01-07 01:49:06 +00001742 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001743 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001744
John McCall1c926b72011-01-07 01:49:06 +00001745 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1746 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001747
John McCall1c926b72011-01-07 01:49:06 +00001748 // If so, call the enumeration-mutation function.
1749 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001750 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001751 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001752 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001753 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001754 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001755 // FIXME: We shouldn't need to get the function info here, the runtime already
1756 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001757 EmitCall(
1758 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001759 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001760
John McCall1c926b72011-01-07 01:49:06 +00001761 // Otherwise, or if the mutation function returns, just continue.
1762 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001763
John McCall1c926b72011-01-07 01:49:06 +00001764 // Initialize the element variable.
1765 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001766 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001767 LValue elementLValue;
1768 QualType elementType;
1769 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001770 // Initialize the variable, in case it's a __block variable or something.
1771 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001772
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001773 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1774 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1775 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001776 elementLValue = EmitLValue(&tempDRE);
1777 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001778 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001779
1780 if (D->isARCPseudoStrong())
1781 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001782 } else {
1783 elementLValue = LValue(); // suppress warning
1784 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001785 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001786 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001787 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001788
1789 // Fetch the buffer out of the enumeration state.
1790 // TODO: this pointer should actually be invariant between
1791 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001792 Address StateItemsPtr =
1793 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001794 llvm::Value *EnumStateItems =
1795 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001796
John McCall1c926b72011-01-07 01:49:06 +00001797 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001798 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001799 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001800 llvm::Value *CurrentItem =
1801 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001802
John McCall1c926b72011-01-07 01:49:06 +00001803 // Cast that value to the right type.
1804 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1805 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001806
John McCall1c926b72011-01-07 01:49:06 +00001807 // Make sure we have an l-value. Yes, this gets evaluated every
1808 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001809 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001810 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001811 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001812 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001813 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1814 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001815 }
Mike Stump11289f42009-09-09 15:08:12 +00001816
John McCall9e2e22f2011-02-22 07:16:58 +00001817 // If we do have an element variable, this assignment is the end of
1818 // its initialization.
1819 if (elementIsVariable)
1820 EmitAutoVarCleanups(variable);
1821
John McCall1c926b72011-01-07 01:49:06 +00001822 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001823 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001824 {
1825 RunCleanupsScope Scope(*this);
1826 EmitStmt(S.getBody());
1827 }
Anders Carlsson75658592008-08-31 02:33:12 +00001828 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001829
John McCall1c926b72011-01-07 01:49:06 +00001830 // Destroy the element variable now.
1831 elementVariableScope.ForceCleanup();
1832
1833 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001834 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001835
John McCall1c926b72011-01-07 01:49:06 +00001836 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001837
John McCall1c926b72011-01-07 01:49:06 +00001838 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001839 llvm::Value *indexPlusOne =
1840 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001841
John McCall1c926b72011-01-07 01:49:06 +00001842 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001843 // Set the branch weights based on the simplifying assumption that this is
1844 // like a while-loop, i.e., ignoring that the false branch fetches more
1845 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001846 Builder.CreateCondBr(
1847 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001848 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001849
1850 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1851 count->addIncoming(count, AfterBody.getBlock());
1852
1853 // Otherwise, we have to fetch more elements.
1854 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001855
1856 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001857 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1858 getContext().getNSUIntegerType(),
1859 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001860
John McCall1c926b72011-01-07 01:49:06 +00001861 // If we got a zero count, we're done.
1862 llvm::Value *refetchCount = CountRV.getScalarVal();
1863
1864 // (note that the message send might split FetchMoreBB)
1865 index->addIncoming(zero, Builder.GetInsertBlock());
1866 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1867
1868 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1869 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Anders Carlsson75658592008-08-31 02:33:12 +00001871 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001872 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001873
John McCall9e2e22f2011-02-22 07:16:58 +00001874 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001875 // If the element was not a declaration, set it to be null.
1876
John McCall1c926b72011-01-07 01:49:06 +00001877 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1878 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001879 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001880 }
1881
Eric Christopher7cdf9482011-10-13 21:45:18 +00001882 if (DI)
1883 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001884
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001885 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001886 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001887}
1888
Mike Stump11289f42009-09-09 15:08:12 +00001889void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001890 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001891}
1892
Mike Stump11289f42009-09-09 15:08:12 +00001893void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001894 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1895}
1896
Chris Lattnere132e242008-11-15 21:26:17 +00001897void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001898 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001899 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001900}
1901
John McCall31168b02011-06-15 23:02:42 +00001902namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001903 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001904 CallObjCRelease(llvm::Value *object) : object(object) {}
1905 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001906
Craig Topper4f12f102014-03-12 06:41:41 +00001907 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001908 // Releases at the end of the full-expression are imprecise.
1909 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001910 }
1911 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001912}
John McCall31168b02011-06-15 23:02:42 +00001913
John McCall2d637d22011-09-10 06:18:15 +00001914/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001915/// release at the end of the full-expression.
1916llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1917 llvm::Value *object) {
1918 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001919 // conditional.
1920 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001921 return object;
1922}
1923
1924llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1925 llvm::Value *value) {
1926 return EmitARCRetainAutorelease(type, value);
1927}
1928
John McCalleff18842013-03-23 02:35:54 +00001929/// Given a number of pointers, inform the optimizer that they're
1930/// being intrinsically used up until this point in the program.
1931void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001932 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001933 if (!fn)
1934 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001935
1936 // This isn't really a "runtime" function, but as an intrinsic it
1937 // doesn't really matter as long as we align things up.
1938 EmitNounwindRuntimeCall(fn, values);
1939}
1940
James Y Knight9871db02019-02-05 16:42:33 +00001941static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001942 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001943 // If the target runtime doesn't naturally support ARC, emit weak
1944 // references to the runtime support library. We don't really
1945 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001946 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1947 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001948 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001949 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001950 }
John McCall31168b02011-06-15 23:02:42 +00001951}
1952
James Y Knight9871db02019-02-05 16:42:33 +00001953static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1954 llvm::FunctionCallee RTF) {
1955 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1956}
1957
John McCall31168b02011-06-15 23:02:42 +00001958/// Perform an operation having the signature
1959/// i8* (i8*)
1960/// where a null input causes a no-op and returns null.
James Y Knight9871db02019-02-05 16:42:33 +00001961static llvm::Value *
1962emitARCValueOperation(CodeGenFunction &CGF, llvm::Value *value,
1963 llvm::Type *returnType, llvm::Function *&fn,
1964 llvm::Intrinsic::ID IntID, bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001965 if (isa<llvm::ConstantPointerNull>(value))
1966 return value;
John McCall31168b02011-06-15 23:02:42 +00001967
1968 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001969 fn = CGF.CGM.getIntrinsic(IntID);
1970 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001971 }
1972
1973 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001974 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001975 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1976
1977 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001978 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001979 if (isTailCall)
1980 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001981
1982 // Cast the result back to the original type.
1983 return CGF.Builder.CreateBitCast(call, origType);
1984}
1985
1986/// Perform an operation having the following signature:
1987/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00001988static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
1989 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001990 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00001991 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001992 fn = CGF.CGM.getIntrinsic(IntID);
1993 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001994 }
1995
1996 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001997 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001998 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1999
2000 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002001 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002002
2003 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002004 if (origType != CGF.Int8PtrTy)
2005 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002006
2007 return result;
2008}
2009
2010/// Perform an operation having the following signature:
2011/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002012static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002013 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002014 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002015 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002016 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002017 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002018
2019 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002020 fn = CGF.CGM.getIntrinsic(IntID);
2021 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002022 }
2023
Chris Lattner2192fe52011-07-18 04:24:23 +00002024 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002025
John McCall882987f2013-02-28 19:01:20 +00002026 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002027 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002028 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2029 };
2030 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002031
Craig Topper8a13c412014-05-21 05:09:00 +00002032 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002033
2034 return CGF.Builder.CreateBitCast(result, origType);
2035}
2036
2037/// Perform an operation having the following signature:
2038/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002039static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2040 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002041 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002042 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002043
2044 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002045 fn = CGF.CGM.getIntrinsic(IntID);
2046 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002047 }
2048
John McCall882987f2013-02-28 19:01:20 +00002049 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002050 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2051 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002052 };
2053 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002054}
2055
Pete Cooper2cd35962018-12-18 20:33:00 +00002056/// Perform an operation having the signature
2057/// i8* (i8*)
2058/// where a null input causes a no-op and returns null.
2059static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2060 llvm::Value *value,
2061 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002062 llvm::FunctionCallee &fn,
2063 StringRef fnName, bool MayThrow) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002064 if (isa<llvm::ConstantPointerNull>(value))
2065 return value;
2066
2067 if (!fn) {
2068 llvm::FunctionType *fnType =
2069 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2070 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002071
2072 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002073 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002074 if (fnName == "objc_retain")
2075 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002076 }
2077
2078 // Cast the argument to 'id'.
2079 llvm::Type *origType = returnType ? returnType : value->getType();
2080 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2081
2082 // Call the function.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002083 llvm::CallBase *Inst = nullptr;
2084 if (MayThrow)
2085 Inst = CGF.EmitCallOrInvoke(fn, value);
2086 else
2087 Inst = CGF.EmitNounwindRuntimeCall(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002088
2089 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002090 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002091}
2092
John McCall31168b02011-06-15 23:02:42 +00002093/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002094/// call i8* \@objc_retain(i8* %value)
2095/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002096llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2097 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002098 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002099 else
2100 return EmitARCRetainNonBlock(value);
2101}
2102
2103/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002104/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002105llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002106 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002107 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002108 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002109}
2110
2111/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002112/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002113///
2114/// \param mandatory - If false, emit the call with metadata
2115/// indicating that it's okay for the optimizer to eliminate this call
2116/// if it can prove that the block never escapes except down the stack.
2117llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2118 bool mandatory) {
2119 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002120 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002121 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002122 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002123
2124 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2125 // tell the optimizer that it doesn't need to do this copy if the
2126 // block doesn't escape, where being passed as an argument doesn't
2127 // count as escaping.
2128 if (!mandatory && isa<llvm::Instruction>(result)) {
2129 llvm::CallInst *call
2130 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002131 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002132
John McCallff613032011-10-04 06:23:45 +00002133 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002134 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002135 }
2136
2137 return result;
John McCall31168b02011-06-15 23:02:42 +00002138}
2139
John McCalle399e5b2016-01-27 18:32:30 +00002140static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002141 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002142 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002143 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002144 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002145 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002146 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002147 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002148 .getARCRetainAutoreleasedReturnValueMarker();
2149
2150 // If we have an empty assembly string, there's nothing to do.
2151 if (assembly.empty()) {
2152
2153 // Otherwise, at -O0, build an inline asm that we're going to call
2154 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002155 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002156 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002157 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002158
John McCall31168b02011-06-15 23:02:42 +00002159 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2160
2161 // If we're at -O1 and above, we don't want to litter the code
2162 // with this marker yet, so leave a breadcrumb for the ARC
2163 // optimizer to pick up.
2164 } else {
2165 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002166 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002167 "clang.arc.retainAutoreleasedReturnValueMarker");
2168 assert(metadata->getNumOperands() <= 1);
2169 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002170 auto &ctx = CGF.getLLVMContext();
2171 metadata->addOperand(llvm::MDNode::get(ctx,
2172 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002173 }
2174 }
2175 }
2176
2177 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002178 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002179 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002180}
John McCall31168b02011-06-15 23:02:42 +00002181
John McCalle399e5b2016-01-27 18:32:30 +00002182/// Retain the given object which is the result of a function call.
2183/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2184///
2185/// Yes, this function name is one character away from a different
2186/// call with completely different semantics.
2187llvm::Value *
2188CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2189 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002190 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002191 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002192 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
John McCall31168b02011-06-15 23:02:42 +00002193}
2194
John McCalle399e5b2016-01-27 18:32:30 +00002195/// Claim a possibly-autoreleased return value at +0. This is only
2196/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002197/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002198/// the value is ignored, or when it is being assigned to an
2199/// __unsafe_unretained variable.
2200///
2201/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2202llvm::Value *
2203CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2204 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002205 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002206 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002207 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002208}
2209
John McCall31168b02011-06-15 23:02:42 +00002210/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002211/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002212void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2213 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002214 if (isa<llvm::ConstantPointerNull>(value)) return;
2215
James Y Knight9871db02019-02-05 16:42:33 +00002216 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002217 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002218 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2219 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002220 }
2221
2222 // Cast the argument to 'id'.
2223 value = Builder.CreateBitCast(value, Int8PtrTy);
2224
2225 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002226 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002227
John McCallcdda29c2013-03-13 03:10:54 +00002228 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002229 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002230 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002231 }
2232}
2233
John McCalle68b8f42012-10-17 02:28:37 +00002234/// Destroy a __strong variable.
2235///
2236/// At -O0, emit a call to store 'null' into the address;
2237/// instrumenting tools prefer this because the address is exposed,
2238/// but it's relatively cumbersome to optimize.
2239///
2240/// At -O1 and above, just load and call objc_release.
2241///
2242/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002243void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002244 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002245 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002246 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002247 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2248 return;
2249 }
2250
2251 llvm::Value *value = Builder.CreateLoad(addr);
2252 EmitARCRelease(value, precise);
2253}
2254
John McCall31168b02011-06-15 23:02:42 +00002255/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002256/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002257llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002258 llvm::Value *value,
2259 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002260 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002261
James Y Knight9871db02019-02-05 16:42:33 +00002262 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002263 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002264 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2265 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002266 }
2267
John McCall882987f2013-02-28 19:01:20 +00002268 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002269 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002270 Builder.CreateBitCast(value, Int8PtrTy)
2271 };
2272 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002273
Craig Topper8a13c412014-05-21 05:09:00 +00002274 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002275 return value;
2276}
2277
2278/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002279/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002280/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002281llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002282 llvm::Value *newValue,
2283 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002284 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002285 bool isBlock = type->isBlockPointerType();
2286
2287 // Use a store barrier at -O0 unless this is a block type or the
2288 // lvalue is inadequately aligned.
2289 if (shouldUseFusedARCCalls() &&
2290 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002291 (dst.getAlignment().isZero() ||
2292 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002293 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2294 }
2295
2296 // Otherwise, split it out.
2297
2298 // Retain the new value.
2299 newValue = EmitARCRetain(type, newValue);
2300
2301 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002302 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002303
2304 // Store. We do this before the release so that any deallocs won't
2305 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002306 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002307
2308 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002309 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002310
2311 return newValue;
2312}
2313
2314/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002315/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002316llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002317 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002318 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002319 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002320}
2321
2322/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002323/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002324llvm::Value *
2325CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002326 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002327 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002328 llvm::Intrinsic::objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002329 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002330}
2331
2332/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002333/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002334llvm::Value *
2335CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002336 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002337 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002338 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002339 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002340}
2341
2342/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002343/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002344/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002345/// %retain = call i8* \@objc_retainBlock(i8* %value)
2346/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002347llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2348 llvm::Value *value) {
2349 if (!type->isBlockPointerType())
2350 return EmitARCRetainAutoreleaseNonBlock(value);
2351
2352 if (isa<llvm::ConstantPointerNull>(value)) return value;
2353
Chris Lattner2192fe52011-07-18 04:24:23 +00002354 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002355 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002356 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002357 value = EmitARCAutorelease(value);
2358 return Builder.CreateBitCast(value, origType);
2359}
2360
2361/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002362/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002363llvm::Value *
2364CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002365 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002366 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002367 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002368}
2369
John McCallb04ecb72015-10-21 18:06:43 +00002370/// i8* \@objc_loadWeak(i8** %addr)
2371/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2372llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2373 return emitARCLoadOperation(*this, addr,
2374 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002375 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002376}
2377
James Dennett14c41ea2012-06-22 05:41:30 +00002378/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002379llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002380 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002381 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002382 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002383}
2384
James Dennett14c41ea2012-06-22 05:41:30 +00002385/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002386/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002387llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002388 llvm::Value *value,
2389 bool ignored) {
2390 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002391 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002392 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002393}
2394
James Dennett14c41ea2012-06-22 05:41:30 +00002395/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002396/// Returns %value. %addr is known to not have a current weak entry.
2397/// Essentially equivalent to:
2398/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002399void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002400 // If we're initializing to null, just write null to memory; no need
2401 // to get the runtime involved. But don't do this if optimization
2402 // is enabled, because accounting for this would make the optimizer
2403 // much more complicated.
2404 if (isa<llvm::ConstantPointerNull>(value) &&
2405 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2406 Builder.CreateStore(value, addr);
2407 return;
2408 }
2409
2410 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002411 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002412 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002413}
2414
James Dennett14c41ea2012-06-22 05:41:30 +00002415/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002416/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002417void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002418 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002419 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002420 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2421 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002422 }
2423
2424 // Cast the argument to 'id*'.
2425 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2426
John McCall7f416cc2015-09-08 08:05:57 +00002427 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002428}
2429
James Dennett14c41ea2012-06-22 05:41:30 +00002430/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002431/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2432/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002433void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002434 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002435 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002436 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002437}
2438
James Dennett14c41ea2012-06-22 05:41:30 +00002439/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002440/// Disregards the current value in %dest. Essentially
2441/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002442void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002443 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002444 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002445 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002446}
2447
Akira Hatanakad791e922018-03-19 17:38:40 +00002448void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2449 Address SrcAddr) {
2450 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2451 Object = EmitObjCConsumeObject(Ty, Object);
2452 EmitARCStoreWeak(DstAddr, Object, false);
2453}
2454
2455void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2456 Address SrcAddr) {
2457 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2458 Object = EmitObjCConsumeObject(Ty, Object);
2459 EmitARCStoreWeak(DstAddr, Object, false);
2460 EmitARCDestroyWeak(SrcAddr);
2461}
2462
John McCall31168b02011-06-15 23:02:42 +00002463/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002464/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002465llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002466 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002467 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002468 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2469 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002470 }
2471
John McCall882987f2013-02-28 19:01:20 +00002472 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002473}
2474
2475/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002476/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002477void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2478 assert(value->getType() == Int8PtrTy);
2479
Pete Cooper2cd35962018-12-18 20:33:00 +00002480 if (getInvokeDest()) {
2481 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002482 llvm::FunctionCallee &fn =
2483 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002484 if (!fn) {
2485 llvm::FunctionType *fnType =
2486 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2487 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2488 setARCRuntimeFunctionLinkage(CGM, fn);
2489 }
John McCall31168b02011-06-15 23:02:42 +00002490
Pete Cooper2cd35962018-12-18 20:33:00 +00002491 // objc_autoreleasePoolPop can throw.
2492 EmitRuntimeCallOrInvoke(fn, value);
2493 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002494 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002495 if (!fn) {
2496 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2497 setARCRuntimeFunctionLinkage(CGM, fn);
2498 }
2499
2500 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002501 }
John McCall31168b02011-06-15 23:02:42 +00002502}
2503
2504/// Produce the code to do an MRR version objc_autoreleasepool_push.
2505/// Which is: [[NSAutoreleasePool alloc] init];
2506/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2507/// init is declared as: - (id) init; in its NSObject super class.
2508///
2509llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2510 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002511 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002512 // [NSAutoreleasePool alloc]
2513 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2514 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2515 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002516 RValue AllocRV =
2517 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002518 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002519 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002520
2521 // [Receiver init]
2522 Receiver = AllocRV.getScalarVal();
2523 II = &CGM.getContext().Idents.get("init");
2524 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2525 RValue InitRV =
2526 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2527 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002528 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002529 return InitRV.getScalarVal();
2530}
2531
Pete Coopere3886802018-12-08 05:13:50 +00002532/// Allocate the given objc object.
2533/// call i8* \@objc_alloc(i8* %value)
2534llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2535 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002536 return emitObjCValueOperation(*this, value, resultType,
2537 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002538 "objc_alloc", /*MayThrow=*/true);
Pete Coopere3886802018-12-08 05:13:50 +00002539}
2540
2541/// Allocate the given objc object.
2542/// call i8* \@objc_allocWithZone(i8* %value)
2543llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2544 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002545 return emitObjCValueOperation(*this, value, resultType,
2546 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002547 "objc_allocWithZone", /*MayThrow=*/true);
Pete Coopere3886802018-12-08 05:13:50 +00002548}
2549
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002550llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2551 llvm::Type *resultType) {
2552 return emitObjCValueOperation(*this, value, resultType,
2553 CGM.getObjCEntrypoints().objc_alloc_init,
2554 "objc_alloc_init", /*MayThrow=*/true);
2555}
2556
John McCall31168b02011-06-15 23:02:42 +00002557/// Produce the code to do a primitive release.
2558/// [tmp drain];
2559void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2560 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2561 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2562 CallArgList Args;
2563 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002564 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002565}
2566
John McCall82fe67b2011-07-09 01:37:26 +00002567void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002568 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002569 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002570 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002571}
2572
2573void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002574 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002575 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002576 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002577}
2578
2579void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002580 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002581 QualType type) {
2582 CGF.EmitARCDestroyWeak(addr);
2583}
2584
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002585void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2586 QualType type) {
2587 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2588 CGF.EmitARCIntrinsicUse(value);
2589}
2590
Pete Coopere5b64ea2018-12-21 21:00:32 +00002591/// Autorelease the given object.
2592/// call i8* \@objc_autorelease(i8* %value)
2593llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2594 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002595 return emitObjCValueOperation(
2596 *this, value, returnType,
2597 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2598 "objc_autorelease", /*MayThrow=*/false);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002599}
2600
2601/// Retain the given object, with normal retain semantics.
2602/// call i8* \@objc_retain(i8* %value)
2603llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2604 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002605 return emitObjCValueOperation(
2606 *this, value, returnType,
2607 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain",
2608 /*MayThrow=*/false);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002609}
2610
2611/// Release the given object.
2612/// call void \@objc_release(i8* %value)
2613void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2614 ARCPreciseLifetime_t precise) {
2615 if (isa<llvm::ConstantPointerNull>(value)) return;
2616
James Y Knight9871db02019-02-05 16:42:33 +00002617 llvm::FunctionCallee &fn =
2618 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002619 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002620 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002621 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002622 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2623 setARCRuntimeFunctionLinkage(CGM, fn);
2624 // We have Native ARC, so set nonlazybind attribute for performance
2625 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2626 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002627 }
2628
2629 // Cast the argument to 'id'.
2630 value = Builder.CreateBitCast(value, Int8PtrTy);
2631
2632 // Call objc_release.
2633 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2634
2635 if (precise == ARCImpreciseLifetime) {
2636 call->setMetadata("clang.imprecise_release",
2637 llvm::MDNode::get(Builder.getContext(), None));
2638 }
2639}
2640
John McCall31168b02011-06-15 23:02:42 +00002641namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002642 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002643 llvm::Value *Token;
2644
2645 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2646
Craig Topper4f12f102014-03-12 06:41:41 +00002647 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002648 CGF.EmitObjCAutoreleasePoolPop(Token);
2649 }
2650 };
David Blaikie7e70d682015-08-18 22:40:54 +00002651 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002652 llvm::Value *Token;
2653
2654 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2655
Craig Topper4f12f102014-03-12 06:41:41 +00002656 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002657 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2658 }
2659 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002660}
John McCall31168b02011-06-15 23:02:42 +00002661
2662void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002663 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002664 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2665 else
2666 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2667}
2668
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002669static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2670 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002671 case Qualifiers::OCL_None:
2672 case Qualifiers::OCL_ExplicitNone:
2673 case Qualifiers::OCL_Strong:
2674 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002675 return true;
John McCall31168b02011-06-15 23:02:42 +00002676
2677 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002678 return false;
John McCall31168b02011-06-15 23:02:42 +00002679 }
2680
2681 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002682}
2683
2684static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002685 LValue lvalue,
2686 QualType type) {
2687 llvm::Value *result;
2688 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2689 if (shouldRetain) {
2690 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2691 } else {
2692 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2693 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2694 }
2695 return TryEmitResult(result, !shouldRetain);
2696}
2697
2698static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002699 const Expr *e) {
2700 e = e->IgnoreParens();
2701 QualType type = e->getType();
2702
Fangrui Song6907ce22018-07-30 19:24:48 +00002703 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002704 // an extra retain/release pair by zeroing out the source of this
2705 // "move" operation.
2706 if (e->isXValue() &&
2707 !type.isConstQualified() &&
2708 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2709 // Emit the lvalue.
2710 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002711
John McCall154a2fd2011-08-30 00:57:29 +00002712 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002713 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2714 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002715
John McCall154a2fd2011-08-30 00:57:29 +00002716 // Set the source pointer to NULL.
2717 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002718
John McCall154a2fd2011-08-30 00:57:29 +00002719 return TryEmitResult(result, true);
2720 }
2721
John McCall31168b02011-06-15 23:02:42 +00002722 // As a very special optimization, in ARC++, if the l-value is the
2723 // result of a non-volatile assignment, do a simple retain of the
2724 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002725 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002726 !type.isVolatileQualified() &&
2727 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2728 isa<BinaryOperator>(e) &&
2729 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2730 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2731
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002732 // Try to emit code for scalar constant instead of emitting LValue and
2733 // loading it because we are not guaranteed to have an l-value. One of such
2734 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2735 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2736 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2737 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2738 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2739 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2740 }
2741
John McCall31168b02011-06-15 23:02:42 +00002742 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2743}
2744
John McCalle399e5b2016-01-27 18:32:30 +00002745typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2746 llvm::Value *value)>
2747 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002748
John McCalle399e5b2016-01-27 18:32:30 +00002749/// Insert code immediately after a call.
2750static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2751 llvm::Value *value,
2752 ValueTransform doAfterCall,
2753 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002754 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2755 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2756
2757 // Place the retain immediately following the call.
2758 CGF.Builder.SetInsertPoint(call->getParent(),
2759 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002760 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002761
2762 CGF.Builder.restoreIP(ip);
2763 return value;
2764 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2765 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2766
2767 // Place the retain at the beginning of the normal destination block.
2768 llvm::BasicBlock *BB = invoke->getNormalDest();
2769 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002770 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002771
2772 CGF.Builder.restoreIP(ip);
2773 return value;
2774
2775 // Bitcasts can arise because of related-result returns. Rewrite
2776 // the operand.
2777 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2778 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002779 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002780 bitcast->setOperand(0, operand);
2781 return bitcast;
2782
2783 // Generic fall-back case.
2784 } else {
2785 // Retain using the non-block variant: we never need to do a copy
2786 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002787 return doFallback(CGF, value);
2788 }
2789}
2790
2791/// Given that the given expression is some sort of call (which does
2792/// not return retained), emit a retain following it.
2793static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2794 const Expr *e) {
2795 llvm::Value *value = CGF.EmitScalarExpr(e);
2796 return emitARCOperationAfterCall(CGF, value,
2797 [](CodeGenFunction &CGF, llvm::Value *value) {
2798 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2799 },
2800 [](CodeGenFunction &CGF, llvm::Value *value) {
2801 return CGF.EmitARCRetainNonBlock(value);
2802 });
2803}
2804
2805/// Given that the given expression is some sort of call (which does
2806/// not return retained), perform an unsafeClaim following it.
2807static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2808 const Expr *e) {
2809 llvm::Value *value = CGF.EmitScalarExpr(e);
2810 return emitARCOperationAfterCall(CGF, value,
2811 [](CodeGenFunction &CGF, llvm::Value *value) {
2812 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2813 },
2814 [](CodeGenFunction &CGF, llvm::Value *value) {
2815 return value;
2816 });
2817}
2818
2819llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2820 bool allowUnsafeClaim) {
2821 if (allowUnsafeClaim &&
2822 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2823 return emitARCUnsafeClaimCallResult(*this, E);
2824 } else {
2825 llvm::Value *value = emitARCRetainCallResult(*this, E);
2826 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002827 }
2828}
2829
John McCallcd78e802011-09-10 01:16:55 +00002830/// Determine whether it might be important to emit a separate
2831/// objc_retain_block on the result of the given expression, or
2832/// whether it's okay to just emit it in a +1 context.
2833static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2834 assert(e->getType()->isBlockPointerType());
2835 e = e->IgnoreParens();
2836
2837 // For future goodness, emit block expressions directly in +1
2838 // contexts if we can.
2839 if (isa<BlockExpr>(e))
2840 return false;
2841
2842 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2843 switch (cast->getCastKind()) {
2844 // Emitting these operations in +1 contexts is goodness.
2845 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002846 case CK_ARCReclaimReturnedObject:
2847 case CK_ARCConsumeObject:
2848 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002849 return false;
2850
2851 // These operations preserve a block type.
2852 case CK_NoOp:
2853 case CK_BitCast:
2854 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2855
2856 // These operations are known to be bad (or haven't been considered).
2857 case CK_AnyPointerToBlockPointerCast:
2858 default:
2859 return true;
2860 }
2861 }
2862
2863 return true;
2864}
2865
John McCalle399e5b2016-01-27 18:32:30 +00002866namespace {
2867/// A CRTP base class for emitting expressions of retainable object
2868/// pointer type in ARC.
2869template <typename Impl, typename Result> class ARCExprEmitter {
2870protected:
2871 CodeGenFunction &CGF;
2872 Impl &asImpl() { return *static_cast<Impl*>(this); }
2873
2874 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2875
2876public:
2877 Result visit(const Expr *e);
2878 Result visitCastExpr(const CastExpr *e);
2879 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002880 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002881 Result visitBinaryOperator(const BinaryOperator *e);
2882 Result visitBinAssign(const BinaryOperator *e);
2883 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2884 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2885 Result visitBinAssignWeak(const BinaryOperator *e);
2886 Result visitBinAssignStrong(const BinaryOperator *e);
2887
2888 // Minimal implementation:
2889 // Result visitLValueToRValue(const Expr *e)
2890 // Result visitConsumeObject(const Expr *e)
2891 // Result visitExtendBlockObject(const Expr *e)
2892 // Result visitReclaimReturnedObject(const Expr *e)
2893 // Result visitCall(const Expr *e)
2894 // Result visitExpr(const Expr *e)
2895 //
2896 // Result emitBitCast(Result result, llvm::Type *resultType)
2897 // llvm::Value *getValueOfResult(Result result)
2898};
2899}
2900
2901/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002902///
2903/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002904template <typename Impl, typename Result>
2905Result
2906ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002907 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002908
2909 // Find the result expression.
2910 const Expr *resultExpr = E->getResultExpr();
2911 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002912 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002913
2914 for (PseudoObjectExpr::const_semantics_iterator
2915 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2916 const Expr *semantic = *i;
2917
2918 // If this semantic expression is an opaque value, bind it
2919 // to the result of its source expression.
2920 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2921 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2922 OVMA opaqueData;
2923
2924 // If this semantic is the result of the pseudo-object
2925 // expression, try to evaluate the source as +1.
2926 if (ov == resultExpr) {
2927 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002928 result = asImpl().visit(ov->getSourceExpr());
2929 opaqueData = OVMA::bind(CGF, ov,
2930 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002931
2932 // Otherwise, just bind it.
2933 } else {
2934 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2935 }
2936 opaques.push_back(opaqueData);
2937
2938 // Otherwise, if the expression is the result, evaluate it
2939 // and remember the result.
2940 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002941 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002942
2943 // Otherwise, evaluate the expression in an ignored context.
2944 } else {
2945 CGF.EmitIgnoredExpr(semantic);
2946 }
2947 }
2948
2949 // Unbind all the opaques now.
2950 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2951 opaques[i].unbind(CGF);
2952
2953 return result;
2954}
2955
John McCalle399e5b2016-01-27 18:32:30 +00002956template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002957Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2958 // The default implementation just forwards the expression to visitExpr.
2959 return asImpl().visitExpr(e);
2960}
2961
2962template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00002963Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2964 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002965
John McCalle399e5b2016-01-27 18:32:30 +00002966 // No-op casts don't change the type, so we just ignore them.
2967 case CK_NoOp:
2968 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002969
John McCalle399e5b2016-01-27 18:32:30 +00002970 // These casts can change the type.
2971 case CK_CPointerToObjCPointerCast:
2972 case CK_BlockPointerToObjCPointerCast:
2973 case CK_AnyPointerToBlockPointerCast:
2974 case CK_BitCast: {
2975 llvm::Type *resultType = CGF.ConvertType(e->getType());
2976 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2977 Result result = asImpl().visit(e->getSubExpr());
2978 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002979 }
2980
John McCalle399e5b2016-01-27 18:32:30 +00002981 // Handle some casts specially.
2982 case CK_LValueToRValue:
2983 return asImpl().visitLValueToRValue(e->getSubExpr());
2984 case CK_ARCConsumeObject:
2985 return asImpl().visitConsumeObject(e->getSubExpr());
2986 case CK_ARCExtendBlockObject:
2987 return asImpl().visitExtendBlockObject(e->getSubExpr());
2988 case CK_ARCReclaimReturnedObject:
2989 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2990
2991 // Otherwise, use the default logic.
2992 default:
2993 return asImpl().visitExpr(e);
2994 }
2995}
2996
2997template <typename Impl, typename Result>
2998Result
2999ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3000 switch (e->getOpcode()) {
3001 case BO_Comma:
3002 CGF.EmitIgnoredExpr(e->getLHS());
3003 CGF.EnsureInsertPoint();
3004 return asImpl().visit(e->getRHS());
3005
3006 case BO_Assign:
3007 return asImpl().visitBinAssign(e);
3008
3009 default:
3010 return asImpl().visitExpr(e);
3011 }
3012}
3013
3014template <typename Impl, typename Result>
3015Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3016 switch (e->getLHS()->getType().getObjCLifetime()) {
3017 case Qualifiers::OCL_ExplicitNone:
3018 return asImpl().visitBinAssignUnsafeUnretained(e);
3019
3020 case Qualifiers::OCL_Weak:
3021 return asImpl().visitBinAssignWeak(e);
3022
3023 case Qualifiers::OCL_Autoreleasing:
3024 return asImpl().visitBinAssignAutoreleasing(e);
3025
3026 case Qualifiers::OCL_Strong:
3027 return asImpl().visitBinAssignStrong(e);
3028
3029 case Qualifiers::OCL_None:
3030 return asImpl().visitExpr(e);
3031 }
3032 llvm_unreachable("bad ObjC ownership qualifier");
3033}
3034
3035/// The default rule for __unsafe_unretained emits the RHS recursively,
3036/// stores into the unsafe variable, and propagates the result outward.
3037template <typename Impl, typename Result>
3038Result ARCExprEmitter<Impl,Result>::
3039 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3040 // Recursively emit the RHS.
3041 // For __block safety, do this before emitting the LHS.
3042 Result result = asImpl().visit(e->getRHS());
3043
3044 // Perform the store.
3045 LValue lvalue =
3046 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3047 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3048 lvalue);
3049
3050 return result;
3051}
3052
3053template <typename Impl, typename Result>
3054Result
3055ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3056 return asImpl().visitExpr(e);
3057}
3058
3059template <typename Impl, typename Result>
3060Result
3061ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3062 return asImpl().visitExpr(e);
3063}
3064
3065template <typename Impl, typename Result>
3066Result
3067ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3068 return asImpl().visitExpr(e);
3069}
3070
3071/// The general expression-emission logic.
3072template <typename Impl, typename Result>
3073Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3074 // We should *never* see a nested full-expression here, because if
3075 // we fail to emit at +1, our caller must not retain after we close
3076 // out the full-expression. This isn't as important in the unsafe
3077 // emitter.
3078 assert(!isa<ExprWithCleanups>(e));
3079
3080 // Look through parens, __extension__, generic selection, etc.
3081 e = e->IgnoreParens();
3082
3083 // Handle certain kinds of casts.
3084 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3085 return asImpl().visitCastExpr(ce);
3086
3087 // Handle the comma operator.
3088 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3089 return asImpl().visitBinaryOperator(op);
3090
3091 // TODO: handle conditional operators here
3092
3093 // For calls and message sends, use the retained-call logic.
3094 // Delegate inits are a special case in that they're the only
3095 // returns-retained expression that *isn't* surrounded by
3096 // a consume.
3097 } else if (isa<CallExpr>(e) ||
3098 (isa<ObjCMessageExpr>(e) &&
3099 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3100 return asImpl().visitCall(e);
3101
3102 // Look through pseudo-object expressions.
3103 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3104 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003105 } else if (auto *be = dyn_cast<BlockExpr>(e))
3106 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003107
3108 return asImpl().visitExpr(e);
3109}
3110
3111namespace {
3112
3113/// An emitter for +1 results.
3114struct ARCRetainExprEmitter :
3115 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3116
3117 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3118
3119 llvm::Value *getValueOfResult(TryEmitResult result) {
3120 return result.getPointer();
3121 }
3122
3123 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3124 llvm::Value *value = result.getPointer();
3125 value = CGF.Builder.CreateBitCast(value, resultType);
3126 result.setPointer(value);
3127 return result;
3128 }
3129
3130 TryEmitResult visitLValueToRValue(const Expr *e) {
3131 return tryEmitARCRetainLoadOfScalar(CGF, e);
3132 }
3133
3134 /// For consumptions, just emit the subexpression and thus elide
3135 /// the retain/release pair.
3136 TryEmitResult visitConsumeObject(const Expr *e) {
3137 llvm::Value *result = CGF.EmitScalarExpr(e);
3138 return TryEmitResult(result, true);
3139 }
3140
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003141 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3142 TryEmitResult result = visitExpr(e);
3143 // Avoid the block-retain if this is a block literal that doesn't need to be
3144 // copied to the heap.
3145 if (e->getBlockDecl()->canAvoidCopyToHeap())
3146 result.setInt(true);
3147 return result;
3148 }
3149
John McCalle399e5b2016-01-27 18:32:30 +00003150 /// Block extends are net +0. Naively, we could just recurse on
3151 /// the subexpression, but actually we need to ensure that the
3152 /// value is copied as a block, so there's a little filter here.
3153 TryEmitResult visitExtendBlockObject(const Expr *e) {
3154 llvm::Value *result; // will be a +0 value
3155
3156 // If we can't safely assume the sub-expression will produce a
3157 // block-copied value, emit the sub-expression at +0.
3158 if (shouldEmitSeparateBlockRetain(e)) {
3159 result = CGF.EmitScalarExpr(e);
3160
3161 // Otherwise, try to emit the sub-expression at +1 recursively.
3162 } else {
3163 TryEmitResult subresult = asImpl().visit(e);
3164
3165 // If that produced a retained value, just use that.
3166 if (subresult.getInt()) {
3167 return subresult;
3168 }
3169
3170 // Otherwise it's +0.
3171 result = subresult.getPointer();
3172 }
3173
3174 // Retain the object as a block.
3175 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3176 return TryEmitResult(result, true);
3177 }
3178
3179 /// For reclaims, emit the subexpression as a retained call and
3180 /// skip the consumption.
3181 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3182 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3183 return TryEmitResult(result, true);
3184 }
3185
3186 /// When we have an undecorated call, retroactively do a claim.
3187 TryEmitResult visitCall(const Expr *e) {
3188 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3189 return TryEmitResult(result, true);
3190 }
3191
3192 // TODO: maybe special-case visitBinAssignWeak?
3193
3194 TryEmitResult visitExpr(const Expr *e) {
3195 // We didn't find an obvious production, so emit what we've got and
3196 // tell the caller that we didn't manage to retain.
3197 llvm::Value *result = CGF.EmitScalarExpr(e);
3198 return TryEmitResult(result, false);
3199 }
3200};
3201}
3202
3203static TryEmitResult
3204tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3205 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003206}
3207
3208static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3209 LValue lvalue,
3210 QualType type) {
3211 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3212 llvm::Value *value = result.getPointer();
3213 if (!result.getInt())
3214 value = CGF.EmitARCRetain(type, value);
3215 return value;
3216}
3217
3218/// EmitARCRetainScalarExpr - Semantically equivalent to
3219/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3220/// best-effort attempt to peephole expressions that naturally produce
3221/// retained objects.
3222llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003223 // The retain needs to happen within the full-expression.
3224 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3225 enterFullExpression(cleanups);
3226 RunCleanupsScope scope(*this);
3227 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3228 }
3229
John McCall31168b02011-06-15 23:02:42 +00003230 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3231 llvm::Value *value = result.getPointer();
3232 if (!result.getInt())
3233 value = EmitARCRetain(e->getType(), value);
3234 return value;
3235}
3236
3237llvm::Value *
3238CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003239 // The retain needs to happen within the full-expression.
3240 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3241 enterFullExpression(cleanups);
3242 RunCleanupsScope scope(*this);
3243 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3244 }
3245
John McCall31168b02011-06-15 23:02:42 +00003246 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3247 llvm::Value *value = result.getPointer();
3248 if (result.getInt())
3249 value = EmitARCAutorelease(value);
3250 else
3251 value = EmitARCRetainAutorelease(e->getType(), value);
3252 return value;
3253}
3254
John McCallff613032011-10-04 06:23:45 +00003255llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3256 llvm::Value *result;
3257 bool doRetain;
3258
3259 if (shouldEmitSeparateBlockRetain(e)) {
3260 result = EmitScalarExpr(e);
3261 doRetain = true;
3262 } else {
3263 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3264 result = subresult.getPointer();
3265 doRetain = !subresult.getInt();
3266 }
3267
3268 if (doRetain)
3269 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3270 return EmitObjCConsumeObject(e->getType(), result);
3271}
3272
John McCall248512a2011-10-01 10:32:24 +00003273llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3274 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003275 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003276 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003277 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003278 return EmitARCRetainAutoreleaseScalarExpr(expr);
3279 }
3280
3281 // Otherwise, use the normal scalar-expression emission. The
3282 // exception machinery doesn't do anything special with the
3283 // exception like retaining it, so there's no safety associated with
3284 // only running cleanups after the throw has started, and when it
3285 // matters it tends to be substantially inferior code.
3286 return EmitScalarExpr(expr);
3287}
3288
John McCalle399e5b2016-01-27 18:32:30 +00003289namespace {
3290
3291/// An emitter for assigning into an __unsafe_unretained context.
3292struct ARCUnsafeUnretainedExprEmitter :
3293 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3294
3295 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3296
3297 llvm::Value *getValueOfResult(llvm::Value *value) {
3298 return value;
3299 }
3300
3301 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3302 return CGF.Builder.CreateBitCast(value, resultType);
3303 }
3304
3305 llvm::Value *visitLValueToRValue(const Expr *e) {
3306 return CGF.EmitScalarExpr(e);
3307 }
3308
3309 /// For consumptions, just emit the subexpression and perform the
3310 /// consumption like normal.
3311 llvm::Value *visitConsumeObject(const Expr *e) {
3312 llvm::Value *value = CGF.EmitScalarExpr(e);
3313 return CGF.EmitObjCConsumeObject(e->getType(), value);
3314 }
3315
3316 /// No special logic for block extensions. (This probably can't
3317 /// actually happen in this emitter, though.)
3318 llvm::Value *visitExtendBlockObject(const Expr *e) {
3319 return CGF.EmitARCExtendBlockObject(e);
3320 }
3321
3322 /// For reclaims, perform an unsafeClaim if that's enabled.
3323 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3324 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3325 }
3326
3327 /// When we have an undecorated call, just emit it without adding
3328 /// the unsafeClaim.
3329 llvm::Value *visitCall(const Expr *e) {
3330 return CGF.EmitScalarExpr(e);
3331 }
3332
3333 /// Just do normal scalar emission in the default case.
3334 llvm::Value *visitExpr(const Expr *e) {
3335 return CGF.EmitScalarExpr(e);
3336 }
3337};
3338}
3339
3340static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3341 const Expr *e) {
3342 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3343}
3344
3345/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3346/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3347/// avoiding any spurious retains, including by performing reclaims
3348/// with objc_unsafeClaimAutoreleasedReturnValue.
3349llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3350 // Look through full-expressions.
3351 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3352 enterFullExpression(cleanups);
3353 RunCleanupsScope scope(*this);
3354 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3355 }
3356
3357 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3358}
3359
3360std::pair<LValue,llvm::Value*>
3361CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3362 bool ignored) {
3363 // Evaluate the RHS first. If we're ignoring the result, assume
3364 // that we can emit at an unsafe +0.
3365 llvm::Value *value;
3366 if (ignored) {
3367 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3368 } else {
3369 value = EmitScalarExpr(e->getRHS());
3370 }
3371
3372 // Emit the LHS and perform the store.
3373 LValue lvalue = EmitLValue(e->getLHS());
3374 EmitStoreOfScalar(value, lvalue);
3375
3376 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3377}
3378
John McCall31168b02011-06-15 23:02:42 +00003379std::pair<LValue,llvm::Value*>
3380CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3381 bool ignored) {
3382 // Evaluate the RHS first.
3383 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3384 llvm::Value *value = result.getPointer();
3385
John McCallb726a552011-07-28 07:23:35 +00003386 bool hasImmediateRetain = result.getInt();
3387
3388 // If we didn't emit a retained object, and the l-value is of block
3389 // type, then we need to emit the block-retain immediately in case
3390 // it invalidates the l-value.
3391 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003392 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003393 hasImmediateRetain = true;
3394 }
3395
John McCall31168b02011-06-15 23:02:42 +00003396 LValue lvalue = EmitLValue(e->getLHS());
3397
3398 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003399 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003400 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003401 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003402 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003403 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003404 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003405 }
3406
3407 return std::pair<LValue,llvm::Value*>(lvalue, value);
3408}
3409
3410std::pair<LValue,llvm::Value*>
3411CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3412 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3413 LValue lvalue = EmitLValue(e->getLHS());
3414
Eli Friedmana0544d62011-12-03 04:14:32 +00003415 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003416
3417 return std::pair<LValue,llvm::Value*>(lvalue, value);
3418}
3419
3420void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003421 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003422 const Stmt *subStmt = ARPS.getSubStmt();
3423 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3424
3425 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003426 if (DI)
3427 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003428
3429 // Keep track of the current cleanup stack depth.
3430 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003431 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003432 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3433 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3434 } else {
3435 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3436 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3437 }
3438
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003439 for (const auto *I : S.body())
3440 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003441
Eric Christopher7cdf9482011-10-13 21:45:18 +00003442 if (DI)
3443 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003444}
John McCall1bd25562011-06-24 23:21:27 +00003445
3446/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3447/// make sure it survives garbage collection until this point.
3448void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3449 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003450 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003451 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003452 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3453 /* assembly */ "",
3454 /* constraints */ "r",
3455 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003456
3457 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003458 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003459}
3460
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003461/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003462/// non-trivial copy assignment function, produce following helper function.
3463/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3464///
3465llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003466CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3467 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003468 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003469 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003470 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003471 QualType Ty = PID->getPropertyIvarDecl()->getType();
3472 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003473 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003474 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003475 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003476 return nullptr;
3477 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003478 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003479 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003480 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3481 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3482 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003483
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003484 ASTContext &C = getContext();
3485 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003486 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003487
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003488 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003489 QualType DestTy = C.getPointerType(Ty);
3490 QualType SrcTy = Ty;
3491 SrcTy.addConst();
3492 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003493
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003494 SmallVector<QualType, 2> ArgTys;
3495 ArgTys.push_back(DestTy);
3496 ArgTys.push_back(SrcTy);
3497 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3498
3499 FunctionDecl *FD = FunctionDecl::Create(
3500 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3501 FunctionTy, nullptr, SC_Static, false, false);
3502
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003503 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003504 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3505 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003506 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003507 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3508 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003509 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003510
John McCallc56a8b32016-03-11 04:30:31 +00003511 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003512 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003513
John McCalla729c622012-02-17 03:33:10 +00003514 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003515
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003516 llvm::Function *Fn =
3517 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003518 "__assign_helper_atomic_property_",
3519 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003520
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003521 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003522
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003523 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003524
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003525 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3526 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003527 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003528 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003529
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003530 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3531 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003532 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003533 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003534
John McCall113bee02012-03-10 09:33:50 +00003535 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003536 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003537 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3538 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3539 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003540
Bruno Riccic5885cf2018-12-21 15:20:32 +00003541 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003542
3543 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003544 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003545 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003546 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003547}
3548
3549llvm::Constant *
3550CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3551 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003552 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003553 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003554 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003555 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3556 QualType Ty = PD->getType();
3557 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003558 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003559 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003560 return nullptr;
3561 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003562 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003563 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003564 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3565 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3566 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003567
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003568 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003569 IdentifierInfo *II =
3570 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003571
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003572 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003573 QualType DestTy = C.getPointerType(Ty);
3574 QualType SrcTy = Ty;
3575 SrcTy.addConst();
3576 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003577
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003578 SmallVector<QualType, 2> ArgTys;
3579 ArgTys.push_back(DestTy);
3580 ArgTys.push_back(SrcTy);
3581 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3582
3583 FunctionDecl *FD = FunctionDecl::Create(
3584 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3585 FunctionTy, nullptr, SC_Static, false, false);
3586
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003587 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003588 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3589 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003590 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003591 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3592 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003593 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003594
John McCallc56a8b32016-03-11 04:30:31 +00003595 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003596 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003597
John McCalla729c622012-02-17 03:33:10 +00003598 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003599
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003600 llvm::Function *Fn = llvm::Function::Create(
3601 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3602 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003603
3604 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003605
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003606 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003607
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003608 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3609 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003610
John McCall113bee02012-03-10 09:33:50 +00003611 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003612 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003613
3614 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003615 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003616
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003617 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003618 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003619 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3620 CXXConstExpr->arg_end());
3621
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003622 CXXConstructExpr *TheCXXConstructExpr =
3623 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3624 CXXConstExpr->getConstructor(),
3625 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003626 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003627 CXXConstExpr->hadMultipleCandidates(),
3628 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003629 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003630 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003631 CXXConstExpr->getConstructionKind(),
3632 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003633
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003634 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3635 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003636
John McCall113bee02012-03-10 09:33:50 +00003637 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003638 CharUnits Alignment
3639 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003640 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003641 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3642 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003643 AggValueSlot::IsDestructed,
3644 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003645 AggValueSlot::IsNotAliased,
3646 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003647
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003648 FinishFunction();
3649 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3650 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3651 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003652}
3653
Eli Friedmanec75fec2012-02-28 01:08:45 +00003654llvm::Value *
3655CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3656 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003657 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3658 Selector CopySelector =
3659 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003660 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3661 Selector AutoreleaseSelector =
3662 getContext().Selectors.getNullarySelector(AutoreleaseID);
3663
3664 // Emit calls to retain/autorelease.
3665 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3666 llvm::Value *Val = Block;
3667 RValue Result;
3668 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003669 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003670 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003671 Val = Result.getScalarVal();
3672 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3673 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003674 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003675 Val = Result.getScalarVal();
3676 return Val;
3677}
3678
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003679llvm::Value *
3680CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3681 assert(Args.size() == 3 && "Expected 3 argument here!");
3682
3683 if (!CGM.IsOSVersionAtLeastFn) {
3684 llvm::FunctionType *FTy =
3685 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3686 CGM.IsOSVersionAtLeastFn =
3687 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3688 }
3689
3690 llvm::Value *CallRes =
3691 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3692
3693 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3694}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003695
Alex Lorenza8fbef42017-03-23 11:14:27 +00003696void CodeGenModule::emitAtAvailableLinkGuard() {
3697 if (!IsOSVersionAtLeastFn)
3698 return;
3699 // @available requires CoreFoundation only on Darwin.
3700 if (!Target.getTriple().isOSDarwin())
3701 return;
3702 // Add -framework CoreFoundation to the linker commands. We still want to
3703 // emit the core foundation reference down below because otherwise if
3704 // CoreFoundation is not used in the code, the linker won't link the
3705 // framework.
3706 auto &Context = getLLVMContext();
3707 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3708 llvm::MDString::get(Context, "CoreFoundation")};
3709 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3710 // Emit a reference to a symbol from CoreFoundation to ensure that
3711 // CoreFoundation is linked into the final binary.
3712 llvm::FunctionType *FTy =
3713 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003714 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003715 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3716
3717 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003718 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3719 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
3720 llvm::AttributeList(), /*IsLocal=*/true);
3721 llvm::Function *CFLinkCheckFunc =
3722 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3723 if (CFLinkCheckFunc->empty()) {
3724 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3725 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3726 CodeGenFunction CGF(*this);
3727 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3728 CGF.EmitNounwindRuntimeCall(CFFunc,
3729 llvm::Constant::getNullValue(VoidPtrTy));
3730 CGF.Builder.CreateUnreachable();
3731 addCompilerUsedGlobal(CFLinkCheckFunc);
3732 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003733}
3734
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003735CGObjCRuntime::~CGObjCRuntime() {}