blob: 3e64080e7b45e6705d50eeb5685c6c9ae5793d6a [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"
John McCall31168b02011-06-15 23:02:42 +000017#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000021#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000022#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000032static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
33 QualType ET,
34 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000035
36/// Given the address of a variable of pointer type, find the correct
37/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000038static llvm::Constant *getNullForVariable(Address addr) {
39 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000040 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
41}
42
Chris Lattnerb1d329d2008-06-24 17:04:18 +000043/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000044llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000045{
Fangrui Song6907ce22018-07-30 19:24:48 +000046 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000047 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000048 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000049 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000050}
51
Patrick Beard0caa3942012-04-19 00:25:12 +000052/// EmitObjCBoxedExpr - This routine generates code to call
53/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000054/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
55/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000056///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000057llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000058CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000059 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000060 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000061 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000062 const Expr *SubExpr = E->getSubExpr();
Patrick Beard0caa3942012-04-19 00:25:12 +000063 assert(BoxingMethod && "BoxingMethod is null");
64 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
65 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000066
Ted Kremeneke65b0862012-03-06 20:05:56 +000067 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000068 // Assumes that the method was introduced in the class that should be
69 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000070 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000071 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000072 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000073
Ted Kremeneke65b0862012-03-06 20:05:56 +000074 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000075 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
76 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000077
78 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000079 // via [NSValue valueWithBytes:objCType:]
80 const QualType ValueType(SubExpr->getType().getCanonicalType());
81 if (ValueType->isObjCBoxableRecordType()) {
82 // Emit CodeGen for first parameter
83 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000084 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000085 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000086 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
87 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000088
89 // Create char array to store type encoding
90 std::string Str;
91 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000092 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +000093
Alex Denisovfde64952015-06-26 05:28:36 +000094 // Cast type encoding to correct type
95 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
96 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
97 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
98
99 Args.add(RValue::get(Cast), EncodingQT);
100 } else {
101 Args.add(EmitAnyExpr(SubExpr), ArgQT);
102 }
Alp Toker314cc812014-01-25 16:55:45 +0000103
104 RValue result = Runtime.GenerateMessageSend(
105 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
106 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000107 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000108 ConvertType(E->getType()));
109}
110
111llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000112 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000113 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000114 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
116 if (!ALE)
117 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000118
119 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000120 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000122 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
123 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
124 QualType IdTy(CGM.getContext().getObjCIdType());
125 llvm::Constant *Constant =
126 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000127 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000128 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000129 cast<llvm::LoadInst>(Ptr)->setMetadata(
130 CGM.getModule().getMDKindID("invariant.load"),
131 llvm::MDNode::get(getLLVMContext(), None));
132 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000133 }
134
135 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000136 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
137 NumElements);
138 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 QualType ElementArrayType
140 = Context.getConstantArrayType(ElementType, APNumElements,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141 ArrayType::Normal, /*IndexTypeQuals=*/0);
142
143 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000144 Address Objects = CreateMemTemp(ElementArrayType, "objects");
145 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000146 if (DLE)
147 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
John McCall770a4c12013-04-04 00:20:38 +0000149 // In ARC, we may need to do extra work to keep all the keys and
150 // values alive until after the call.
151 SmallVector<llvm::Value *, 16> NeededObjects;
152 bool TrackNeededObjects =
153 (getLangOpts().ObjCAutoRefCount &&
154 CGM.getCodeGenOpts().OptimizationLevel != 0);
155
Ted Kremeneke65b0862012-03-06 20:05:56 +0000156 // Perform the actual initialialization of the array(s).
157 for (uint64_t i = 0; i < NumElements; i++) {
158 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000159 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000160 const Expr *Rhs = ALE->getElement(i);
John McCall7f416cc2015-09-08 08:05:57 +0000161 LValue LV = MakeAddrLValue(
162 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000163 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000164
165 llvm::Value *value = EmitScalarExpr(Rhs);
166 EmitStoreThroughLValue(RValue::get(value), LV, true);
167 if (TrackNeededObjects) {
168 NeededObjects.push_back(value);
169 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000170 } else {
John McCall770a4c12013-04-04 00:20:38 +0000171 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000172 const Expr *Key = DLE->getKeyValueElement(i).Key;
John McCall7f416cc2015-09-08 08:05:57 +0000173 LValue KeyLV = MakeAddrLValue(
174 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000175 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000176 llvm::Value *keyValue = EmitScalarExpr(Key);
177 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000178
John McCall770a4c12013-04-04 00:20:38 +0000179 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000180 const Expr *Value = DLE->getKeyValueElement(i).Value;
John McCall7f416cc2015-09-08 08:05:57 +0000181 LValue ValueLV = MakeAddrLValue(
182 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000183 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000184 llvm::Value *valueValue = EmitScalarExpr(Value);
185 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
186 if (TrackNeededObjects) {
187 NeededObjects.push_back(keyValue);
188 NeededObjects.push_back(valueValue);
189 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000190 }
191 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000192
Ted Kremeneke65b0862012-03-06 20:05:56 +0000193 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000194 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000195 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
196 const ParmVarDecl *argDecl = *PI++;
197 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000198 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000199 if (DLE) {
200 argDecl = *PI++;
201 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000202 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000203 }
204 argDecl = *PI;
205 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000206 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000207 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
208 Args.add(RValue::get(Count), ArgQT);
209
210 // Generate a reference to the class pointer, which will be the receiver.
211 Selector Sel = MethodWithObjects->getSelector();
212 QualType ResultType = E->getType();
213 const ObjCObjectPointerType *InterfacePointerType
214 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000215 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000216 = InterfacePointerType->getObjectType()->getInterface();
217 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000218 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000219
220 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000221 RValue result = Runtime.GenerateMessageSend(
222 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
223 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000224
225 // The above message send needs these objects, but in ARC they are
226 // passed in a buffer that is essentially __unsafe_unretained.
227 // Therefore we must prevent the optimizer from releasing them until
228 // after the call.
229 if (TrackNeededObjects) {
230 EmitARCIntrinsicUse(NeededObjects);
231 }
232
Fangrui Song6907ce22018-07-30 19:24:48 +0000233 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000234 ConvertType(E->getType()));
235}
236
237llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000238 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000239}
240
241llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
242 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000243 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000244}
245
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000246/// Emit a selector.
247llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
248 // Untyped selector.
249 // Note that this implementation allows for non-constant strings to be passed
250 // as arguments to @selector(). Currently, the only thing preventing this
251 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000252 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000253}
254
Daniel Dunbar66912a12008-08-20 00:28:19 +0000255llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
256 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000257 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000258}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000259
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000260/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000261/// to type erasure at various points, e.g., related result types or the use
262/// of parameterized classes.
263static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
264 RValue Result) {
265 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000266 return Result;
John McCall31168b02011-06-15 23:02:42 +0000267
Douglas Gregore83b9562015-07-07 03:57:53 +0000268 // If the converted types are the same, we're done.
269 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
270 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000271 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000272
273 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000274 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000275 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000276}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000277
John McCallcf166702011-07-22 08:53:00 +0000278/// Decide whether to extend the lifetime of the receiver of a
279/// returns-inner-pointer message.
280static bool
281shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
282 switch (message->getReceiverKind()) {
283
284 // For a normal instance message, we should extend unless the
285 // receiver is loaded from a variable with precise lifetime.
286 case ObjCMessageExpr::Instance: {
287 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000288
289 // Look through OVEs.
290 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
291 if (opaque->getSourceExpr())
292 receiver = opaque->getSourceExpr()->IgnoreParens();
293 }
294
John McCallcf166702011-07-22 08:53:00 +0000295 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
296 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
297 receiver = ice->getSubExpr()->IgnoreParens();
298
John McCall6380a282015-09-09 23:37:17 +0000299 // Look through OVEs.
300 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
301 if (opaque->getSourceExpr())
302 receiver = opaque->getSourceExpr()->IgnoreParens();
303 }
304
John McCallcf166702011-07-22 08:53:00 +0000305 // Only __strong variables.
306 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
307 return true;
308
309 // All ivars and fields have precise lifetime.
310 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
311 return false;
312
313 // Otherwise, check for variables.
314 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
315 if (!declRef) return true;
316 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
317 if (!var) return true;
318
319 // All variables have precise lifetime except local variables with
320 // automatic storage duration that aren't specially marked.
321 return (var->hasLocalStorage() &&
322 !var->hasAttr<ObjCPreciseLifetimeAttr>());
323 }
324
325 case ObjCMessageExpr::Class:
326 case ObjCMessageExpr::SuperClass:
327 // It's never necessary for class objects.
328 return false;
329
330 case ObjCMessageExpr::SuperInstance:
331 // We generally assume that 'self' lives throughout a method call.
332 return false;
333 }
334
335 llvm_unreachable("invalid receiver kind");
336}
337
John McCall460ce582015-10-22 18:38:17 +0000338/// Given an expression of ObjC pointer type, check whether it was
339/// immediately loaded from an ARC __weak l-value.
340static const Expr *findWeakLValue(const Expr *E) {
341 assert(E->getType()->isObjCRetainableType());
342 E = E->IgnoreParens();
343 if (auto CE = dyn_cast<CastExpr>(E)) {
344 if (CE->getCastKind() == CK_LValueToRValue) {
345 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
346 return CE->getSubExpr();
347 }
348 }
349
350 return nullptr;
351}
352
Pete Coopere3886802018-12-08 05:13:50 +0000353/// The ObjC runtime may provide entrypoints that are likely to be faster
354/// than an ordinary message send of the appropriate selector.
355///
356/// The entrypoints are guaranteed to be equivalent to just sending the
357/// corresponding message. If the entrypoint is implemented naively as just a
358/// message send, using it is a trade-off: it sacrifices a few cycles of
359/// overhead to save a small amount of code. However, it's possible for
360/// runtimes to detect and special-case classes that use "standard"
361/// behavior; if that's dynamically a large proportion of all objects, using
362/// the entrypoint will also be faster than using a message send.
363///
364/// If the runtime does support a required entrypoint, then this method will
365/// generate a call and return the resulting value. Otherwise it will return
366/// None and the caller can generate a msgSend instead.
367static Optional<llvm::Value *>
368tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
369 llvm::Value *Receiver,
370 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000371 const ObjCMethodDecl *method,
372 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000373 auto &CGM = CGF.CGM;
374 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
375 return None;
376
377 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
378 switch (Sel.getMethodFamily()) {
379 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000380 if (isClassMessage &&
381 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000382 ResultType->isObjCObjectPointerType()) {
383 // [Foo alloc] -> objc_alloc(Foo)
384 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
385 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
386 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
387 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
388 Args.size() == 1 && Args.front().getType()->isPointerType() &&
389 Sel.getNameForSlot(0) == "allocWithZone") {
390 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
391 if (isa<llvm::ConstantPointerNull>(arg))
392 return CGF.EmitObjCAllocWithZone(Receiver,
393 CGF.ConvertType(ResultType));
394 return None;
395 }
396 }
397 break;
398
Pete Coopere5b64ea2018-12-21 21:00:32 +0000399 case OMF_autorelease:
400 if (ResultType->isObjCObjectPointerType() &&
401 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
402 Runtime.shouldUseARCFunctionsForRetainRelease())
403 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
404 break;
405
406 case OMF_retain:
407 if (ResultType->isObjCObjectPointerType() &&
408 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
409 Runtime.shouldUseARCFunctionsForRetainRelease())
410 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
411 break;
412
413 case OMF_release:
414 if (ResultType->isVoidType() &&
415 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
416 Runtime.shouldUseARCFunctionsForRetainRelease()) {
417 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
418 return nullptr;
419 }
420 break;
421
Pete Coopere3886802018-12-08 05:13:50 +0000422 default:
423 break;
424 }
425 return None;
426}
427
John McCall78a15112010-05-22 01:48:05 +0000428RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
429 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000430 // Only the lookup mechanism and first two arguments of the method
431 // implementation vary between runtimes. We can get the receiver and
432 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000433
John McCall31168b02011-06-15 23:02:42 +0000434 bool isDelegateInit = E->isDelegateInitCall();
435
John McCallcf166702011-07-22 08:53:00 +0000436 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000437
John McCall460ce582015-10-22 18:38:17 +0000438 // If the method is -retain, and the receiver's being loaded from
439 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
440 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
441 method->getMethodFamily() == OMF_retain) {
442 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
443 LValue lvalue = EmitLValue(lvalueExpr);
444 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
445 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
446 }
447 }
448
John McCall31168b02011-06-15 23:02:42 +0000449 // We don't retain the receiver in delegate init calls, and this is
450 // safe because the receiver value is always loaded from 'self',
451 // which we zero out. We don't want to Block_copy block receivers,
452 // though.
453 bool retainSelf =
454 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000455 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000456 method &&
457 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000458
Daniel Dunbar8d480592008-08-11 18:12:00 +0000459 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000460 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000461 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000462 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000463 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000464 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000465 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000466 switch (E->getReceiverKind()) {
467 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000468 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000469 if (retainSelf) {
470 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
471 E->getInstanceReceiver());
472 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000473 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000474 } else
475 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000476 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000477
Douglas Gregor9a129192010-04-21 00:45:42 +0000478 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000479 ReceiverType = E->getClassReceiver();
480 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000481 assert(ObjTy && "Invalid Objective-C class message send");
482 OID = ObjTy->getInterface();
483 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000484 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000485 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000486 break;
487 }
488
489 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000490 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000491 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000492 isSuperMessage = true;
493 break;
494
495 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000496 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000497 Receiver = LoadObjCSelf();
498 isSuperMessage = true;
499 isClassMessage = true;
500 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000501 }
502
John McCallcf166702011-07-22 08:53:00 +0000503 if (retainSelf)
504 Receiver = EmitARCRetainNonBlock(Receiver);
505
506 // In ARC, we sometimes want to "extend the lifetime"
507 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
508 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000509 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000510 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
511 shouldExtendReceiverForInnerPointerMessage(E))
512 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
513
Alp Toker314cc812014-01-25 16:55:45 +0000514 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000515
Daniel Dunbarc722b852008-08-30 03:02:31 +0000516 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000517 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000518
John McCall31168b02011-06-15 23:02:42 +0000519 // For delegate init calls in ARC, do an unsafe store of null into
520 // self. This represents the call taking direct ownership of that
521 // value. We have to do this after emitting the other call
522 // arguments because they might also reference self, but we don't
523 // have to worry about any of them modifying self because that would
524 // be an undefined read and write of an object in unordered
525 // expressions.
526 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000527 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000528 "delegate init calls should only be marked in ARC");
529
530 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address selfAddr =
532 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000533 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
534 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000535
Douglas Gregor33823722011-06-11 01:09:30 +0000536 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000537 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000538 // super is only valid in an Objective-C method
539 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000540 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000541 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
542 E->getSelector(),
543 OMD->getClassInterface(),
544 isCategoryImpl,
545 Receiver,
546 isClassMessage,
547 Args,
John McCallcf166702011-07-22 08:53:00 +0000548 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000549 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000550 // Call runtime methods directly if we can.
551 if (Optional<llvm::Value *> SpecializedResult =
552 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000553 E->getSelector(), method,
554 isClassMessage)) {
Pete Coopere3886802018-12-08 05:13:50 +0000555 result = RValue::get(SpecializedResult.getValue());
556 } else {
557 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
558 E->getSelector(), Receiver, Args,
559 OID, method);
560 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000561 }
John McCall31168b02011-06-15 23:02:42 +0000562
563 // For delegate init calls in ARC, implicitly store the result of
564 // the call back into self. This takes ownership of the value.
565 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000566 Address selfAddr =
567 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000568 llvm::Value *newSelf = result.getScalarVal();
569
570 // The delegate return type isn't necessarily a matching type; in
571 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000572 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000573 newSelf = Builder.CreateBitCast(newSelf, selfTy);
574
575 Builder.CreateStore(newSelf, selfAddr);
576 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000577
Douglas Gregore83b9562015-07-07 03:57:53 +0000578 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000579}
580
John McCall31168b02011-06-15 23:02:42 +0000581namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000582struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000583 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000584 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000585
586 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000587 const ObjCInterfaceDecl *iface = impl->getClassInterface();
588 if (!iface->getSuperClass()) return;
589
John McCalldffafde2011-07-13 18:26:47 +0000590 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
591
John McCall31168b02011-06-15 23:02:42 +0000592 // Call [super dealloc] if we have a superclass.
593 llvm::Value *self = CGF.LoadObjCSelf();
594
595 CallArgList args;
596 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
597 CGF.getContext().VoidTy,
598 method->getSelector(),
599 iface,
John McCalldffafde2011-07-13 18:26:47 +0000600 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000601 self,
602 /*is class msg*/ false,
603 args,
604 method);
605 }
606};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000607}
John McCall31168b02011-06-15 23:02:42 +0000608
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000609/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
610/// the LLVM function and sets the other context used by
611/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000612void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000613 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000614 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000615 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000616 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000617 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000618 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000619
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000620 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000621
John McCalla729c622012-02-17 03:33:10 +0000622 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000623 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000624
John McCalla738c252011-03-09 04:27:21 +0000625 args.push_back(OMD->getSelfDecl());
626 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000627
Benjamin Kramerf9890422015-02-17 16:48:30 +0000628 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000629
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000630 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000631 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000632
Adrian Prantl42d71b92014-04-10 23:21:53 +0000633 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
634 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000635
636 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000638 OMD->isInstanceMethod() &&
639 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000640 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000641 OMD->getSelector().getIdentifierInfoForSlot(0);
642 if (ident->isStr("dealloc"))
643 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
644 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000645}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000646
John McCall31168b02011-06-15 23:02:42 +0000647static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
648 LValue lvalue, QualType type);
649
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000650/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000651/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000652void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000653 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000654 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000655 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000656 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000657 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000658 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000659}
660
John McCallb923ece2011-09-12 23:06:44 +0000661/// emitStructGetterCall - Call the runtime function to load a property
662/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000663static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000664 bool isAtomic, bool hasStrong) {
665 ASTContext &Context = CGF.getContext();
666
John McCall7f416cc2015-09-08 08:05:57 +0000667 Address src =
668 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
669 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000670
Fangrui Song6907ce22018-07-30 19:24:48 +0000671 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000672 // sizeof (Type of Ivar), isAtomic, false);
673 CallArgList args;
674
John McCall7f416cc2015-09-08 08:05:57 +0000675 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
676 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000677
678 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000679 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000680
681 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
682 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
683 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
684 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
685
John McCallb92ab1a2016-10-26 23:46:34 +0000686 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
687 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000688 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000689 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000690}
691
John McCallf4528ae2011-09-13 03:34:09 +0000692/// Determine whether the given architecture supports unaligned atomic
693/// accesses. They don't have to be fast, just faster than a function
694/// call and a mutex.
695static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000696 // FIXME: Allow unaligned atomic load/store on x86. (It is not
697 // currently supported by the backend.)
698 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000699}
700
701/// Return the maximum size that permits atomic accesses for the given
702/// architecture.
703static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
704 llvm::Triple::ArchType arch) {
705 // ARM has 8-byte atomic accesses, but it's not clear whether we
706 // want to rely on them here.
707
708 // In the default case, just assume that any size up to a pointer is
709 // fine given adequate alignment.
710 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
711}
712
713namespace {
714 class PropertyImplStrategy {
715 public:
716 enum StrategyKind {
717 /// The 'native' strategy is to use the architecture's provided
718 /// reads and writes.
719 Native,
720
721 /// Use objc_setProperty and objc_getProperty.
722 GetSetProperty,
723
724 /// Use objc_setProperty for the setter, but use expression
725 /// evaluation for the getter.
726 SetPropertyAndExpressionGet,
727
728 /// Use objc_copyStruct.
729 CopyStruct,
730
731 /// The 'expression' strategy is to emit normal assignment or
732 /// lvalue-to-rvalue expressions.
733 Expression
734 };
735
736 StrategyKind getKind() const { return StrategyKind(Kind); }
737
738 bool hasStrongMember() const { return HasStrong; }
739 bool isAtomic() const { return IsAtomic; }
740 bool isCopy() const { return IsCopy; }
741
742 CharUnits getIvarSize() const { return IvarSize; }
743 CharUnits getIvarAlignment() const { return IvarAlignment; }
744
745 PropertyImplStrategy(CodeGenModule &CGM,
746 const ObjCPropertyImplDecl *propImpl);
747
748 private:
749 unsigned Kind : 8;
750 unsigned IsAtomic : 1;
751 unsigned IsCopy : 1;
752 unsigned HasStrong : 1;
753
754 CharUnits IvarSize;
755 CharUnits IvarAlignment;
756 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000757}
John McCallf4528ae2011-09-13 03:34:09 +0000758
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000759/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000760PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
761 const ObjCPropertyImplDecl *propImpl) {
762 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000763 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000764
John McCall43192862011-09-13 18:31:23 +0000765 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
766 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000767 HasStrong = false; // doesn't matter here.
768
769 // Evaluate the ivar's size and alignment.
770 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
771 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000772 std::tie(IvarSize, IvarAlignment) =
773 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000774
775 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000776 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000777 if (IsCopy) {
778 Kind = GetSetProperty;
779 return;
780 }
781
John McCall43192862011-09-13 18:31:23 +0000782 // Handle retain.
783 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000784 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000786 // fallthrough
787
788 // In ARC, if the property is non-atomic, use expression emission,
789 // which translates to objc_storeStrong. This isn't required, but
790 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000791 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000792 // Using standard expression emission for the setter is only
793 // acceptable if the ivar is __strong, which won't be true if
794 // the property is annotated with __attribute__((NSObject)).
795 // TODO: falling all the way back to objc_setProperty here is
796 // just laziness, though; we could still use objc_storeStrong
797 // if we hacked it right.
798 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
799 Kind = Expression;
800 else
801 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000802 return;
803
804 // Otherwise, we need to at least use setProperty. However, if
805 // the property isn't atomic, we can use normal expression
806 // emission for the getter.
807 } else if (!IsAtomic) {
808 Kind = SetPropertyAndExpressionGet;
809 return;
810
811 // Otherwise, we have to use both setProperty and getProperty.
812 } else {
813 Kind = GetSetProperty;
814 return;
815 }
816 }
817
818 // If we're not atomic, just use expression accesses.
819 if (!IsAtomic) {
820 Kind = Expression;
821 return;
822 }
823
John McCall0e5c0862011-09-13 05:36:29 +0000824 // Properties on bitfield ivars need to be emitted using expression
825 // accesses even if they're nominally atomic.
826 if (ivar->isBitField()) {
827 Kind = Expression;
828 return;
829 }
830
John McCallf4528ae2011-09-13 03:34:09 +0000831 // GC-qualified or ARC-qualified ivars need to be emitted as
832 // expressions. This actually works out to being atomic anyway,
833 // except for ARC __strong, but that should trigger the above code.
834 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000835 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000836 CGM.getContext().getObjCGCAttrKind(ivarType))) {
837 Kind = Expression;
838 return;
839 }
840
841 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000842 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000843 if (const RecordType *recordType = ivarType->getAs<RecordType>())
844 HasStrong = recordType->getDecl()->hasObjectMember();
845
846 // We can never access structs with object members with a native
847 // access, because we need to use write barriers. This is what
848 // objc_copyStruct is for.
849 if (HasStrong) {
850 Kind = CopyStruct;
851 return;
852 }
853
854 // Otherwise, this is target-dependent and based on the size and
855 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000856
857 // If the size of the ivar is not a power of two, give up. We don't
858 // want to get into the business of doing compare-and-swaps.
859 if (!IvarSize.isPowerOfTwo()) {
860 Kind = CopyStruct;
861 return;
862 }
863
John McCallf4528ae2011-09-13 03:34:09 +0000864 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000865 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000866
867 // Most architectures require memory to fit within a single cache
868 // line, so the alignment has to be at least the size of the access.
869 // Otherwise we have to grab a lock.
870 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
871 Kind = CopyStruct;
872 return;
873 }
874
875 // If the ivar's size exceeds the architecture's maximum atomic
876 // access size, we have to use CopyStruct.
877 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
878 Kind = CopyStruct;
879 return;
880 }
881
882 // Otherwise, we can use native loads and stores.
883 Kind = Native;
884}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000885
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000886/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000887///
888/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000889/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000890void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
891 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000892 llvm::Constant *AtomicHelperFn =
893 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000894 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
895 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
896 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000897 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000898
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000899 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000900
901 FinishFunction();
902}
903
John McCallbdd81852011-09-13 06:00:03 +0000904static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
905 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000906 if (!getter) return true;
907
908 // Sema only makes only of these when the ivar has a C++ class type,
909 // so the form is pretty constrained.
910
John McCallbdd81852011-09-13 06:00:03 +0000911 // If the property has a reference type, we might just be binding a
912 // reference, in which case the result will be a gl-value. We should
913 // treat this as a non-trivial operation.
914 if (getter->isGLValue())
915 return false;
916
John McCallf4528ae2011-09-13 03:34:09 +0000917 // If we selected a trivial copy-constructor, we're okay.
918 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
919 return (construct->getConstructor()->isTrivial());
920
921 // The constructor might require cleanups (in which case it's never
922 // trivial).
923 assert(isa<ExprWithCleanups>(getter));
924 return false;
925}
926
Fangrui Song6907ce22018-07-30 19:24:48 +0000927/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000928/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000929static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000930 llvm::Value *returnAddr,
931 ObjCIvarDecl *ivar,
932 llvm::Constant *AtomicHelperFn) {
933 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
934 // AtomicHelperFn);
935 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000936
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000937 // The 1st argument is the return Slot.
938 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000939
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000940 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +0000941 llvm::Value *ivarAddr =
942 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +0000943 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000944 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
945 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000946
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000947 // Third argument is the helper function.
948 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000949
950 llvm::Constant *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000951 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000952 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000953 CGF.EmitCall(
954 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000955 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000956}
957
John McCallf4528ae2011-09-13 03:34:09 +0000958void
959CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000960 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000961 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000962 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000963 // If there's a non-trivial 'get' expression, we just have to emit that.
964 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000965 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +0000966 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
967 propImpl->getGetterCXXConstructor(),
968 /* NRVOCandidate=*/nullptr);
969 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000970 }
971 else {
972 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000973 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000974 ivar, AtomicHelperFn);
975 }
John McCallf4528ae2011-09-13 03:34:09 +0000976 return;
977 }
978
979 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
980 QualType propType = prop->getType();
981 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
982
Fangrui Song6907ce22018-07-30 19:24:48 +0000983 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +0000984
985 // Pick an implementation strategy.
986 PropertyImplStrategy strategy(CGM, propImpl);
987 switch (strategy.getKind()) {
988 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000989 // We don't need to do anything for a zero-size struct.
990 if (strategy.getIvarSize().isZero())
991 return;
992
John McCallf4528ae2011-09-13 03:34:09 +0000993 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
994
995 // Currently, all atomic accesses have to be through integer
996 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000997 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
998 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +0000999 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1000
1001 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +00001002 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +00001003 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1004 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001005 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001006
1007 // Store that value into the return address. Doing this with a
1008 // bitcast is likely to produce some pretty ugly IR, but it's not
1009 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001010 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1011 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1012 llvm::Value *ivarVal = load;
1013 if (ivarSize > retTySize) {
1014 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1015 ivarVal = Builder.CreateTrunc(load, newTy);
1016 bitcastType = newTy->getPointerTo();
1017 }
1018 Builder.CreateStore(ivarVal,
1019 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001020
1021 // Make sure we don't do an autorelease.
1022 AutoreleaseResult = false;
1023 return;
1024 }
1025
1026 case PropertyImplStrategy::GetSetProperty: {
John McCallb92ab1a2016-10-26 23:46:34 +00001027 llvm::Constant *getPropertyFn =
John McCallf4528ae2011-09-13 03:34:09 +00001028 CGM.getObjCRuntime().GetPropertyGetFunction();
1029 if (!getPropertyFn) {
1030 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001031 return;
1032 }
John McCallb92ab1a2016-10-26 23:46:34 +00001033 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001034
1035 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1036 // FIXME: Can't this be simpler? This might even be worse than the
1037 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001038 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001039 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001040 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1041 llvm::Value *ivarOffset =
1042 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1043
1044 CallArgList args;
1045 args.add(RValue::get(self), getContext().getObjCIdType());
1046 args.add(RValue::get(cmd), getContext().getObjCSelType());
1047 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001048 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1049 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001050
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001051 // FIXME: We shouldn't need to get the function info here, the
1052 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001053 llvm::CallBase *CallInstruction;
Samuel Antao798f11c2015-11-23 22:04:44 +00001054 RValue RV = EmitCall(
John McCallc56a8b32016-03-11 04:30:31 +00001055 getTypes().arrangeBuiltinFunctionCall(propType, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001056 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001057 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1058 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001059
Daniel Dunbara08dff12008-09-24 04:04:31 +00001060 // We need to fix the type here. Ivars with copy & retain are
1061 // always objects so we don't need to worry about complex or
1062 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001063 RV = RValue::get(Builder.CreateBitCast(
1064 RV.getScalarVal(),
1065 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001066
1067 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001068
1069 // objc_getProperty does an autorelease, so we should suppress ours.
1070 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001071
John McCallf4528ae2011-09-13 03:34:09 +00001072 return;
1073 }
1074
1075 case PropertyImplStrategy::CopyStruct:
1076 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1077 strategy.hasStrongMember());
1078 return;
1079
1080 case PropertyImplStrategy::Expression:
1081 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1082 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1083
1084 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001085 switch (getEvaluationKind(ivarType)) {
1086 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001087 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001088 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001089 /*init*/ true);
1090 return;
1091 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001092 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001093 // The return value slot is guaranteed to not be aliased, but
1094 // that's not necessarily the same as "on the stack", so
1095 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001096 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smithe78fac52018-04-05 20:52:58 +00001097 /* Src= */ LV, ivarType, overlapForReturnValue());
1098 return;
1099 }
John McCall47fb9502013-03-07 21:37:08 +00001100 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001101 llvm::Value *value;
1102 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001103 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001104 } else {
1105 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1106 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001107 if (getLangOpts().ObjCAutoRefCount) {
1108 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1109 } else {
1110 value = EmitARCLoadWeak(LV.getAddress());
1111 }
John McCall24fada12011-07-22 05:23:13 +00001112
1113 // Otherwise we want to do a simple load, suppressing the
1114 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001115 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001116 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001117 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001118 }
John McCall31168b02011-06-15 23:02:42 +00001119
Alp Toker314cc812014-01-25 16:55:45 +00001120 value = Builder.CreateBitCast(
1121 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001122 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001123
John McCall24fada12011-07-22 05:23:13 +00001124 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001125 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001126 }
John McCall47fb9502013-03-07 21:37:08 +00001127 }
1128 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001129 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001130
John McCallf4528ae2011-09-13 03:34:09 +00001131 }
1132 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001133}
1134
John McCallb923ece2011-09-12 23:06:44 +00001135/// emitStructSetterCall - Call the runtime function to store the value
1136/// from the first formal parameter into the given ivar.
1137static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1138 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001139 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001140 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001141 CallArgList args;
1142
1143 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001144 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1145 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001146 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001147 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1148 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001149
1150 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001151 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001152 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1153 argVar->getType().getNonReferenceType(), VK_LValue,
1154 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001155 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001156 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1157 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001158
1159 // The third argument is the sizeof the type.
1160 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001161 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1162 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001163
John McCallb923ece2011-09-12 23:06:44 +00001164 // The fourth argument is the 'isAtomic' flag.
1165 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001166
John McCallb923ece2011-09-12 23:06:44 +00001167 // The fifth argument is the 'hasStrong' flag.
1168 // FIXME: should this really always be false?
1169 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1170
John McCallb92ab1a2016-10-26 23:46:34 +00001171 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1172 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001173 CGF.EmitCall(
1174 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001175 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001176}
1177
Fangrui Song6907ce22018-07-30 19:24:48 +00001178/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1179/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001180/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001181static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001182 ObjCMethodDecl *OMD,
1183 ObjCIvarDecl *ivar,
1184 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001185 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001186 // AtomicHelperFn);
1187 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001188
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001189 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001190 llvm::Value *ivarAddr =
1191 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001192 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001193 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1194 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001195
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001196 // The second argument is the address of the parameter variable.
1197 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001198 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1199 argVar->getType().getNonReferenceType(), VK_LValue,
1200 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001201 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001202 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1203 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001204
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001205 // Third argument is the helper function.
1206 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001207
1208 llvm::Constant *fn =
David Chisnall0d75e062012-12-17 18:54:24 +00001209 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001210 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001211 CGF.EmitCall(
1212 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001213 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001214}
1215
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001216
John McCallf4528ae2011-09-13 03:34:09 +00001217static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1218 Expr *setter = PID->getSetterCXXAssignment();
1219 if (!setter) return true;
1220
1221 // Sema only makes only of these when the ivar has a C++ class type,
1222 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001223
1224 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001225 // This also implies that there's nothing non-trivial going on with
1226 // the arguments, because operator= can only be trivial if it's a
1227 // synthesized assignment operator and therefore both parameters are
1228 // references.
1229 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001230 if (const FunctionDecl *callee
1231 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1232 if (callee->isTrivial())
1233 return true;
1234 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001235 }
John McCall7f16c422011-09-10 09:17:20 +00001236
John McCallf4528ae2011-09-13 03:34:09 +00001237 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001238 return false;
1239}
1240
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001241static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001242 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001243 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001244 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001245}
1246
John McCall7f16c422011-09-10 09:17:20 +00001247void
1248CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001249 const ObjCPropertyImplDecl *propImpl,
1250 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001251 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001252 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001253 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001254
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001255 // Just use the setter expression if Sema gave us one and it's
1256 // non-trivial.
1257 if (!hasTrivialSetExpr(propImpl)) {
1258 if (!AtomicHelperFn)
1259 // If non-atomic, assignment is called directly.
1260 EmitStmt(propImpl->getSetterCXXAssignment());
1261 else
1262 // If atomic, assignment is called via a locking api.
1263 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1264 AtomicHelperFn);
1265 return;
1266 }
John McCall7f16c422011-09-10 09:17:20 +00001267
John McCallf4528ae2011-09-13 03:34:09 +00001268 PropertyImplStrategy strategy(CGM, propImpl);
1269 switch (strategy.getKind()) {
1270 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001271 // We don't need to do anything for a zero-size struct.
1272 if (strategy.getIvarSize().isZero())
1273 return;
1274
John McCall7f416cc2015-09-08 08:05:57 +00001275 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001276
John McCallf4528ae2011-09-13 03:34:09 +00001277 LValue ivarLValue =
1278 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001279 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001280
John McCallf4528ae2011-09-13 03:34:09 +00001281 // Currently, all atomic accesses have to be through integer
1282 // types, so there's no point in trying to pick a prettier type.
1283 llvm::Type *bitcastType =
1284 llvm::Type::getIntNTy(getLLVMContext(),
1285 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001286
1287 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001288 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1289 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001290
1291 // This bitcast load is likely to cause some nasty IR.
1292 llvm::Value *load = Builder.CreateLoad(argAddr);
1293
1294 // Perform an atomic store. There are no memory ordering requirements.
1295 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001296 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001297 return;
1298 }
1299
1300 case PropertyImplStrategy::GetSetProperty:
1301 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001302
John McCallb92ab1a2016-10-26 23:46:34 +00001303 llvm::Constant *setOptimizedPropertyFn = nullptr;
1304 llvm::Constant *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001305 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001306 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001307 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001308 CGM.getObjCRuntime()
1309 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1310 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001311 if (!setOptimizedPropertyFn) {
1312 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1313 return;
1314 }
John McCall7f16c422011-09-10 09:17:20 +00001315 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001316 else {
1317 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1318 if (!setPropertyFn) {
1319 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1320 return;
1321 }
1322 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001323
John McCall7f16c422011-09-10 09:17:20 +00001324 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1325 // <is-atomic>, <is-copy>).
1326 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001327 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001328 llvm::Value *self =
1329 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1330 llvm::Value *ivarOffset =
1331 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001332 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1333 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1334 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001335
1336 CallArgList args;
1337 args.add(RValue::get(self), getContext().getObjCIdType());
1338 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001339 if (setOptimizedPropertyFn) {
1340 args.add(RValue::get(arg), getContext().getObjCIdType());
1341 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001342 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001343 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001344 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001345 } else {
1346 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1347 args.add(RValue::get(arg), getContext().getObjCIdType());
1348 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1349 getContext().BoolTy);
1350 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1351 getContext().BoolTy);
1352 // FIXME: We shouldn't need to get the function info here, the runtime
1353 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001354 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001355 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001356 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001357 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001358
John McCall7f16c422011-09-10 09:17:20 +00001359 return;
1360 }
1361
John McCallf4528ae2011-09-13 03:34:09 +00001362 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001363 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001364 return;
John McCallf4528ae2011-09-13 03:34:09 +00001365
1366 case PropertyImplStrategy::Expression:
1367 break;
John McCall7f16c422011-09-10 09:17:20 +00001368 }
1369
1370 // Otherwise, fake up some ASTs and emit a normal assignment.
1371 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001372 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001373 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001374 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1375 selfDecl->getType(), CK_LValueToRValue, &self,
1376 VK_RValue);
1377 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001378 SourceLocation(), SourceLocation(),
1379 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001380
1381 ParmVarDecl *argDecl = *setterMethod->param_begin();
1382 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001383 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1384 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001385 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1386 argType.getUnqualifiedType(), CK_LValueToRValue,
1387 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001388
John McCall7f16c422011-09-10 09:17:20 +00001389 // The property type can differ from the ivar type in some situations with
1390 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1391 // The following absurdity is just to ensure well-formed IR.
1392 CastKind argCK = CK_NoOp;
1393 if (ivarRef.getType()->isObjCObjectPointerType()) {
1394 if (argLoad.getType()->isObjCObjectPointerType())
1395 argCK = CK_BitCast;
1396 else if (argLoad.getType()->isBlockPointerType())
1397 argCK = CK_BlockPointerToObjCPointerCast;
1398 else
1399 argCK = CK_CPointerToObjCPointerCast;
1400 } else if (ivarRef.getType()->isBlockPointerType()) {
1401 if (argLoad.getType()->isBlockPointerType())
1402 argCK = CK_BitCast;
1403 else
1404 argCK = CK_AnyPointerToBlockPointerCast;
1405 } else if (ivarRef.getType()->isPointerType()) {
1406 argCK = CK_BitCast;
1407 }
1408 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1409 ivarRef.getType(), argCK, &argLoad,
1410 VK_RValue);
1411 Expr *finalArg = &argLoad;
1412 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1413 argLoad.getType()))
1414 finalArg = &argCast;
1415
1416
1417 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1418 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001419 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001420 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001421}
1422
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001423/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001424///
1425/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001426/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001427void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1428 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001429 llvm::Constant *AtomicHelperFn =
1430 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001431 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1432 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1433 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001434 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001435
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001436 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001437
1438 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001439}
1440
John McCall6a4fa522011-03-22 07:05:39 +00001441namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001442 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001443 private:
1444 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001445 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001446 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001447 bool useEHCleanupForArray;
1448 public:
1449 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1450 CodeGenFunction::Destroyer *destroyer,
1451 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001452 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001453 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001454
Craig Topper4f12f102014-03-12 06:41:41 +00001455 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001456 LValue lvalue
1457 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1458 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001459 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001460 }
1461 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001462}
John McCall6a4fa522011-03-22 07:05:39 +00001463
John McCall4bd0fb12011-07-12 16:41:08 +00001464/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1465static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001466 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001467 QualType type) {
1468 llvm::Value *null = getNullForVariable(addr);
1469 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1470}
John McCall31168b02011-06-15 23:02:42 +00001471
John McCall6a4fa522011-03-22 07:05:39 +00001472static void emitCXXDestructMethod(CodeGenFunction &CGF,
1473 ObjCImplementationDecl *impl) {
1474 CodeGenFunction::RunCleanupsScope scope(CGF);
1475
1476 llvm::Value *self = CGF.LoadObjCSelf();
1477
Jordy Rosea91768e2011-07-22 02:08:32 +00001478 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1479 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001480 ivar; ivar = ivar->getNextIvar()) {
1481 QualType type = ivar->getType();
1482
John McCall6a4fa522011-03-22 07:05:39 +00001483 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001484 QualType::DestructionKind dtorKind = type.isDestructedType();
1485 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001486
Craig Topper8a13c412014-05-21 05:09:00 +00001487 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001488
John McCall4bd0fb12011-07-12 16:41:08 +00001489 // Use a call to objc_storeStrong to destroy strong ivars, for the
1490 // general benefit of the tools.
1491 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001492 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001493
John McCall4bd0fb12011-07-12 16:41:08 +00001494 // Otherwise use the default for the destruction kind.
1495 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001496 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001497 }
John McCall4bd0fb12011-07-12 16:41:08 +00001498
1499 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1500
1501 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1502 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001503 }
1504
1505 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1506}
1507
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001508void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1509 ObjCMethodDecl *MD,
1510 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001511 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001512 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001513
1514 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001515 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001516 // Suppress the final autorelease in ARC.
1517 AutoreleaseResult = false;
1518
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001519 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001520 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001521 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001522 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001523 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001524 EmitAggExpr(IvarInit->getInit(),
1525 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001526 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001527 AggValueSlot::IsNotAliased,
1528 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001529 }
1530 // constructor returns 'self'.
1531 CodeGenTypes &Types = CGM.getTypes();
1532 QualType IdTy(CGM.getContext().getObjCIdType());
1533 llvm::Value *SelfAsId =
1534 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1535 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001536
1537 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001538 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001539 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001540 }
1541 FinishFunction();
1542}
1543
Daniel Dunbara08dff12008-09-24 04:04:31 +00001544llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001545 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001546 DeclRefExpr DRE(getContext(), Self,
1547 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001548 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001549 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001550}
1551
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001552QualType CodeGenFunction::TypeOfSelfObject() {
1553 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1554 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001555 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1556 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001557 return PTy->getPointeeType();
1558}
1559
Chris Lattnerd4808922009-03-22 21:03:39 +00001560void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
John McCallb92ab1a2016-10-26 23:46:34 +00001561 llvm::Constant *EnumerationMutationFnPtr =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001562 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001563 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001564 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1565 return;
1566 }
John McCallb92ab1a2016-10-26 23:46:34 +00001567 CGCallee EnumerationMutationFn =
1568 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001569
Devang Pateld2d66652011-01-19 01:36:36 +00001570 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001571 if (DI)
1572 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001573
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001574 RunCleanupsScope ForScope(*this);
1575
Kuba Mracek82c21752017-04-14 01:00:03 +00001576 // The local variable comes into scope immediately.
1577 AutoVarEmission variable = AutoVarEmission::invalid();
1578 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1579 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1580
John McCall1c926b72011-01-07 01:49:06 +00001581 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001582
Anders Carlsson75658592008-08-31 02:33:12 +00001583 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001584 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001585 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001586 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Anders Carlsson75658592008-08-31 02:33:12 +00001588 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001589 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001590
John McCall1c926b72011-01-07 01:49:06 +00001591 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001592 IdentifierInfo *II[] = {
1593 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1594 &CGM.getContext().Idents.get("objects"),
1595 &CGM.getContext().Idents.get("count")
1596 };
1597 Selector FastEnumSel =
1598 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001599
1600 QualType ItemsTy =
1601 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001602 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001603 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001604 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001605
John McCall53848232011-07-27 01:07:15 +00001606 // Emit the collection pointer. In ARC, we do a retain.
1607 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001608 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001609 Collection = EmitARCRetainScalarExpr(S.getCollection());
1610
1611 // Enter a cleanup to do the release.
1612 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1613 } else {
1614 Collection = EmitScalarExpr(S.getCollection());
1615 }
Mike Stump11289f42009-09-09 15:08:12 +00001616
John McCall91e82dd2011-08-05 00:14:38 +00001617 // The 'continue' label needs to appear within the cleanup for the
1618 // collection object.
1619 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1620
John McCall1c926b72011-01-07 01:49:06 +00001621 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001622 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001623
1624 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001625 Args.add(RValue::get(StatePtr.getPointer()),
1626 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001627
John McCall1c926b72011-01-07 01:49:06 +00001628 // The second argument is a temporary array with space for NumItems
1629 // pointers. We'll actually be loading elements from the array
1630 // pointer written into the control state; this buffer is so that
1631 // collections that *aren't* backed by arrays can still queue up
1632 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001633 Args.add(RValue::get(ItemsPtr.getPointer()),
1634 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001635
John McCall1c926b72011-01-07 01:49:06 +00001636 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001637 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1638 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1639 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001640
John McCall1c926b72011-01-07 01:49:06 +00001641 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001642 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001643 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1644 getContext().getNSUIntegerType(),
1645 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001646
John McCall1c926b72011-01-07 01:49:06 +00001647 // The initial number of objects that were returned in the buffer.
1648 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001649
John McCall1c926b72011-01-07 01:49:06 +00001650 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1651 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001652
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001653 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001654
John McCall1c926b72011-01-07 01:49:06 +00001655 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001656 // empty; skip all this. Set the branch weight assuming this has the same
1657 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001658 uint64_t EntryCount = getCurrentProfileCount();
1659 Builder.CreateCondBr(
1660 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1661 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001662 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001663
John McCall1c926b72011-01-07 01:49:06 +00001664 // Otherwise, initialize the loop.
1665 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001666
John McCall1c926b72011-01-07 01:49:06 +00001667 // Save the initial mutations value. This is the value at an
1668 // address that was written into the state object by
1669 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001670 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1671 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1672 llvm::Value *StateMutationsPtr
1673 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001674
John McCall1c926b72011-01-07 01:49:06 +00001675 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001676 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1677 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001678
John McCall1c926b72011-01-07 01:49:06 +00001679 // Start looping. This is the point we return to whenever we have a
1680 // fresh, non-empty batch of objects.
1681 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1682 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001683
John McCall1c926b72011-01-07 01:49:06 +00001684 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001685 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001686 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001687
John McCall1c926b72011-01-07 01:49:06 +00001688 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001689 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001690 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Justin Bogner66242d62015-04-23 23:06:47 +00001692 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001693
John McCall1c926b72011-01-07 01:49:06 +00001694 // Check whether the mutations value has changed from where it was
1695 // at start. StateMutationsPtr should actually be invariant between
1696 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001697 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001698 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001699 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1700 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001701
John McCall1c926b72011-01-07 01:49:06 +00001702 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001703 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001704
John McCall1c926b72011-01-07 01:49:06 +00001705 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1706 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001707
John McCall1c926b72011-01-07 01:49:06 +00001708 // If so, call the enumeration-mutation function.
1709 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001710 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001711 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001712 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001713 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001714 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001715 // FIXME: We shouldn't need to get the function info here, the runtime already
1716 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001717 EmitCall(
1718 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001719 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001720
John McCall1c926b72011-01-07 01:49:06 +00001721 // Otherwise, or if the mutation function returns, just continue.
1722 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001723
John McCall1c926b72011-01-07 01:49:06 +00001724 // Initialize the element variable.
1725 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001726 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001727 LValue elementLValue;
1728 QualType elementType;
1729 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001730 // Initialize the variable, in case it's a __block variable or something.
1731 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001732
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001733 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1734 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1735 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001736 elementLValue = EmitLValue(&tempDRE);
1737 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001738 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001739
1740 if (D->isARCPseudoStrong())
1741 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001742 } else {
1743 elementLValue = LValue(); // suppress warning
1744 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001745 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001746 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001747 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001748
1749 // Fetch the buffer out of the enumeration state.
1750 // TODO: this pointer should actually be invariant between
1751 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001752 Address StateItemsPtr = Builder.CreateStructGEP(
1753 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001754 llvm::Value *EnumStateItems =
1755 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001756
John McCall1c926b72011-01-07 01:49:06 +00001757 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001758 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001759 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001760 llvm::Value *CurrentItem =
1761 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001762
John McCall1c926b72011-01-07 01:49:06 +00001763 // Cast that value to the right type.
1764 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1765 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001766
John McCall1c926b72011-01-07 01:49:06 +00001767 // Make sure we have an l-value. Yes, this gets evaluated every
1768 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001769 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001770 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001771 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001772 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001773 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1774 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001775 }
Mike Stump11289f42009-09-09 15:08:12 +00001776
John McCall9e2e22f2011-02-22 07:16:58 +00001777 // If we do have an element variable, this assignment is the end of
1778 // its initialization.
1779 if (elementIsVariable)
1780 EmitAutoVarCleanups(variable);
1781
John McCall1c926b72011-01-07 01:49:06 +00001782 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001783 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001784 {
1785 RunCleanupsScope Scope(*this);
1786 EmitStmt(S.getBody());
1787 }
Anders Carlsson75658592008-08-31 02:33:12 +00001788 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001789
John McCall1c926b72011-01-07 01:49:06 +00001790 // Destroy the element variable now.
1791 elementVariableScope.ForceCleanup();
1792
1793 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001794 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001795
John McCall1c926b72011-01-07 01:49:06 +00001796 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001797
John McCall1c926b72011-01-07 01:49:06 +00001798 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001799 llvm::Value *indexPlusOne =
1800 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001801
John McCall1c926b72011-01-07 01:49:06 +00001802 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001803 // Set the branch weights based on the simplifying assumption that this is
1804 // like a while-loop, i.e., ignoring that the false branch fetches more
1805 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001806 Builder.CreateCondBr(
1807 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001808 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001809
1810 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1811 count->addIncoming(count, AfterBody.getBlock());
1812
1813 // Otherwise, we have to fetch more elements.
1814 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001815
1816 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001817 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1818 getContext().getNSUIntegerType(),
1819 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001820
John McCall1c926b72011-01-07 01:49:06 +00001821 // If we got a zero count, we're done.
1822 llvm::Value *refetchCount = CountRV.getScalarVal();
1823
1824 // (note that the message send might split FetchMoreBB)
1825 index->addIncoming(zero, Builder.GetInsertBlock());
1826 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1827
1828 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1829 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001830
Anders Carlsson75658592008-08-31 02:33:12 +00001831 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001832 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001833
John McCall9e2e22f2011-02-22 07:16:58 +00001834 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001835 // If the element was not a declaration, set it to be null.
1836
John McCall1c926b72011-01-07 01:49:06 +00001837 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1838 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001839 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001840 }
1841
Eric Christopher7cdf9482011-10-13 21:45:18 +00001842 if (DI)
1843 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001844
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001845 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001846 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001847}
1848
Mike Stump11289f42009-09-09 15:08:12 +00001849void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001850 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001851}
1852
Mike Stump11289f42009-09-09 15:08:12 +00001853void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001854 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1855}
1856
Chris Lattnere132e242008-11-15 21:26:17 +00001857void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001858 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001859 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001860}
1861
John McCall31168b02011-06-15 23:02:42 +00001862namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001863 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001864 CallObjCRelease(llvm::Value *object) : object(object) {}
1865 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001866
Craig Topper4f12f102014-03-12 06:41:41 +00001867 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001868 // Releases at the end of the full-expression are imprecise.
1869 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001870 }
1871 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001872}
John McCall31168b02011-06-15 23:02:42 +00001873
John McCall2d637d22011-09-10 06:18:15 +00001874/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001875/// release at the end of the full-expression.
1876llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1877 llvm::Value *object) {
1878 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001879 // conditional.
1880 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001881 return object;
1882}
1883
1884llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1885 llvm::Value *value) {
1886 return EmitARCRetainAutorelease(type, value);
1887}
1888
John McCalleff18842013-03-23 02:35:54 +00001889/// Given a number of pointers, inform the optimizer that they're
1890/// being intrinsically used up until this point in the program.
1891void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
John McCallb04ecb72015-10-21 18:06:43 +00001892 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001893 if (!fn)
1894 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001895
1896 // This isn't really a "runtime" function, but as an intrinsic it
1897 // doesn't really matter as long as we align things up.
1898 EmitNounwindRuntimeCall(fn, values);
1899}
1900
Pete Cooper2cd35962018-12-18 20:33:00 +00001901static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1902 llvm::Constant *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001903 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001904 // If the target runtime doesn't naturally support ARC, emit weak
1905 // references to the runtime support library. We don't really
1906 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001907 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1908 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001909 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001910 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001911 }
John McCall31168b02011-06-15 23:02:42 +00001912}
1913
1914/// Perform an operation having the signature
1915/// i8* (i8*)
1916/// where a null input causes a no-op and returns null.
1917static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1918 llvm::Value *value,
Pete Coopere3886802018-12-08 05:13:50 +00001919 llvm::Type *returnType,
John McCall31168b02011-06-15 23:02:42 +00001920 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001921 llvm::Intrinsic::ID IntID,
Chad Rosier13799b32012-12-12 17:52:21 +00001922 bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001923 if (isa<llvm::ConstantPointerNull>(value))
1924 return value;
John McCall31168b02011-06-15 23:02:42 +00001925
1926 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001927 fn = CGF.CGM.getIntrinsic(IntID);
1928 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001929 }
1930
1931 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001932 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001933 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1934
1935 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001936 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001937 if (isTailCall)
1938 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001939
1940 // Cast the result back to the original type.
1941 return CGF.Builder.CreateBitCast(call, origType);
1942}
1943
1944/// Perform an operation having the following signature:
1945/// i8* (i8**)
1946static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001947 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001948 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001949 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00001950 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001951 fn = CGF.CGM.getIntrinsic(IntID);
1952 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001953 }
1954
1955 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001956 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001957 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1958
1959 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001960 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001961
1962 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001963 if (origType != CGF.Int8PtrTy)
1964 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001965
1966 return result;
1967}
1968
1969/// Perform an operation having the following signature:
1970/// i8* (i8**, i8*)
1971static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001972 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001973 llvm::Value *value,
1974 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001975 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00001976 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001977 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001978
1979 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001980 fn = CGF.CGM.getIntrinsic(IntID);
1981 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001982 }
1983
Chris Lattner2192fe52011-07-18 04:24:23 +00001984 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001985
John McCall882987f2013-02-28 19:01:20 +00001986 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001987 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001988 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1989 };
1990 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001991
Craig Topper8a13c412014-05-21 05:09:00 +00001992 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001993
1994 return CGF.Builder.CreateBitCast(result, origType);
1995}
1996
1997/// Perform an operation having the following signature:
1998/// void (i8**, i8**)
1999static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002000 Address dst,
2001 Address src,
John McCall31168b02011-06-15 23:02:42 +00002002 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002003 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002004 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002005
2006 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002007 fn = CGF.CGM.getIntrinsic(IntID);
2008 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002009 }
2010
John McCall882987f2013-02-28 19:01:20 +00002011 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002012 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2013 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002014 };
2015 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002016}
2017
Pete Cooper2cd35962018-12-18 20:33:00 +00002018/// Perform an operation having the signature
2019/// i8* (i8*)
2020/// where a null input causes a no-op and returns null.
2021static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2022 llvm::Value *value,
2023 llvm::Type *returnType,
2024 llvm::Constant *&fn,
2025 StringRef fnName) {
2026 if (isa<llvm::ConstantPointerNull>(value))
2027 return value;
2028
2029 if (!fn) {
2030 llvm::FunctionType *fnType =
2031 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2032 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002033
2034 // We have Native ARC, so set nonlazybind attribute for performance
2035 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
2036 if (fnName == "objc_retain")
2037 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002038 }
2039
2040 // Cast the argument to 'id'.
2041 llvm::Type *origType = returnType ? returnType : value->getType();
2042 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2043
2044 // Call the function.
2045 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2046
2047 // Cast the result back to the original type.
2048 return CGF.Builder.CreateBitCast(call, origType);
2049}
2050
John McCall31168b02011-06-15 23:02:42 +00002051/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002052/// call i8* \@objc_retain(i8* %value)
2053/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002054llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2055 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002056 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002057 else
2058 return EmitARCRetainNonBlock(value);
2059}
2060
2061/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002062/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002063llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002064 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002065 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002066 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002067}
2068
2069/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002070/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002071///
2072/// \param mandatory - If false, emit the call with metadata
2073/// indicating that it's okay for the optimizer to eliminate this call
2074/// if it can prove that the block never escapes except down the stack.
2075llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2076 bool mandatory) {
2077 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002078 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002079 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002080 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002081
2082 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2083 // tell the optimizer that it doesn't need to do this copy if the
2084 // block doesn't escape, where being passed as an argument doesn't
2085 // count as escaping.
2086 if (!mandatory && isa<llvm::Instruction>(result)) {
2087 llvm::CallInst *call
2088 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002089 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002090
John McCallff613032011-10-04 06:23:45 +00002091 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002092 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002093 }
2094
2095 return result;
John McCall31168b02011-06-15 23:02:42 +00002096}
2097
John McCalle399e5b2016-01-27 18:32:30 +00002098static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002099 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002100 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002101 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002102 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002103 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002104 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002105 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002106 .getARCRetainAutoreleasedReturnValueMarker();
2107
2108 // If we have an empty assembly string, there's nothing to do.
2109 if (assembly.empty()) {
2110
2111 // Otherwise, at -O0, build an inline asm that we're going to call
2112 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002113 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002114 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002115 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002116
John McCall31168b02011-06-15 23:02:42 +00002117 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2118
2119 // If we're at -O1 and above, we don't want to litter the code
2120 // with this marker yet, so leave a breadcrumb for the ARC
2121 // optimizer to pick up.
2122 } else {
2123 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002124 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002125 "clang.arc.retainAutoreleasedReturnValueMarker");
2126 assert(metadata->getNumOperands() <= 1);
2127 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002128 auto &ctx = CGF.getLLVMContext();
2129 metadata->addOperand(llvm::MDNode::get(ctx,
2130 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002131 }
2132 }
2133 }
2134
2135 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002136 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002137 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002138}
John McCall31168b02011-06-15 23:02:42 +00002139
John McCalle399e5b2016-01-27 18:32:30 +00002140/// Retain the given object which is the result of a function call.
2141/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2142///
2143/// Yes, this function name is one character away from a different
2144/// call with completely different semantics.
2145llvm::Value *
2146CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2147 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002148 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002149 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002150 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
John McCall31168b02011-06-15 23:02:42 +00002151}
2152
John McCalle399e5b2016-01-27 18:32:30 +00002153/// Claim a possibly-autoreleased return value at +0. This is only
2154/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002155/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002156/// the value is ignored, or when it is being assigned to an
2157/// __unsafe_unretained variable.
2158///
2159/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2160llvm::Value *
2161CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2162 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002163 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002164 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002165 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002166}
2167
John McCall31168b02011-06-15 23:02:42 +00002168/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002169/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002170void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2171 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002172 if (isa<llvm::ConstantPointerNull>(value)) return;
2173
John McCallb04ecb72015-10-21 18:06:43 +00002174 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002175 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002176 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2177 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002178 }
2179
2180 // Cast the argument to 'id'.
2181 value = Builder.CreateBitCast(value, Int8PtrTy);
2182
2183 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002184 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002185
John McCallcdda29c2013-03-13 03:10:54 +00002186 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002187 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002188 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002189 }
2190}
2191
John McCalle68b8f42012-10-17 02:28:37 +00002192/// Destroy a __strong variable.
2193///
2194/// At -O0, emit a call to store 'null' into the address;
2195/// instrumenting tools prefer this because the address is exposed,
2196/// but it's relatively cumbersome to optimize.
2197///
2198/// At -O1 and above, just load and call objc_release.
2199///
2200/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002201void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002202 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002203 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002204 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002205 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2206 return;
2207 }
2208
2209 llvm::Value *value = Builder.CreateLoad(addr);
2210 EmitARCRelease(value, precise);
2211}
2212
John McCall31168b02011-06-15 23:02:42 +00002213/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002214/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002215llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002216 llvm::Value *value,
2217 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002218 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002219
John McCallb04ecb72015-10-21 18:06:43 +00002220 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002221 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002222 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2223 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002224 }
2225
John McCall882987f2013-02-28 19:01:20 +00002226 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002227 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002228 Builder.CreateBitCast(value, Int8PtrTy)
2229 };
2230 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002231
Craig Topper8a13c412014-05-21 05:09:00 +00002232 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002233 return value;
2234}
2235
2236/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002237/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002238/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002239llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002240 llvm::Value *newValue,
2241 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002242 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002243 bool isBlock = type->isBlockPointerType();
2244
2245 // Use a store barrier at -O0 unless this is a block type or the
2246 // lvalue is inadequately aligned.
2247 if (shouldUseFusedARCCalls() &&
2248 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002249 (dst.getAlignment().isZero() ||
2250 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002251 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2252 }
2253
2254 // Otherwise, split it out.
2255
2256 // Retain the new value.
2257 newValue = EmitARCRetain(type, newValue);
2258
2259 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002260 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002261
2262 // Store. We do this before the release so that any deallocs won't
2263 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002264 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002265
2266 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002267 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002268
2269 return newValue;
2270}
2271
2272/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002273/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002274llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002275 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002276 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002277 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002278}
2279
2280/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002281/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002282llvm::Value *
2283CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002284 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002285 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002286 llvm::Intrinsic::objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002287 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002288}
2289
2290/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002291/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002292llvm::Value *
2293CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002294 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002295 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002296 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002297 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002298}
2299
2300/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002301/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002302/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002303/// %retain = call i8* \@objc_retainBlock(i8* %value)
2304/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002305llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2306 llvm::Value *value) {
2307 if (!type->isBlockPointerType())
2308 return EmitARCRetainAutoreleaseNonBlock(value);
2309
2310 if (isa<llvm::ConstantPointerNull>(value)) return value;
2311
Chris Lattner2192fe52011-07-18 04:24:23 +00002312 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002313 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002314 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002315 value = EmitARCAutorelease(value);
2316 return Builder.CreateBitCast(value, origType);
2317}
2318
2319/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002320/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002321llvm::Value *
2322CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002323 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002324 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002325 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002326}
2327
John McCallb04ecb72015-10-21 18:06:43 +00002328/// i8* \@objc_loadWeak(i8** %addr)
2329/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2330llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2331 return emitARCLoadOperation(*this, addr,
2332 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002333 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002334}
2335
James Dennett14c41ea2012-06-22 05:41:30 +00002336/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002337llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002338 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002339 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002340 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002341}
2342
James Dennett14c41ea2012-06-22 05:41:30 +00002343/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002344/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002345llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002346 llvm::Value *value,
2347 bool ignored) {
2348 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002349 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002350 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002351}
2352
James Dennett14c41ea2012-06-22 05:41:30 +00002353/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002354/// Returns %value. %addr is known to not have a current weak entry.
2355/// Essentially equivalent to:
2356/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002357void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002358 // If we're initializing to null, just write null to memory; no need
2359 // to get the runtime involved. But don't do this if optimization
2360 // is enabled, because accounting for this would make the optimizer
2361 // much more complicated.
2362 if (isa<llvm::ConstantPointerNull>(value) &&
2363 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2364 Builder.CreateStore(value, addr);
2365 return;
2366 }
2367
2368 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002369 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002370 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002371}
2372
James Dennett14c41ea2012-06-22 05:41:30 +00002373/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002374/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002375void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCallb04ecb72015-10-21 18:06:43 +00002376 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002377 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002378 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2379 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002380 }
2381
2382 // Cast the argument to 'id*'.
2383 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2384
John McCall7f416cc2015-09-08 08:05:57 +00002385 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002386}
2387
James Dennett14c41ea2012-06-22 05:41:30 +00002388/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002389/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2390/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002391void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002392 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002393 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002394 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002395}
2396
James Dennett14c41ea2012-06-22 05:41:30 +00002397/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002398/// Disregards the current value in %dest. Essentially
2399/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002400void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002401 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002402 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002403 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002404}
2405
Akira Hatanakad791e922018-03-19 17:38:40 +00002406void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2407 Address SrcAddr) {
2408 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2409 Object = EmitObjCConsumeObject(Ty, Object);
2410 EmitARCStoreWeak(DstAddr, Object, false);
2411}
2412
2413void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2414 Address SrcAddr) {
2415 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2416 Object = EmitObjCConsumeObject(Ty, Object);
2417 EmitARCStoreWeak(DstAddr, Object, false);
2418 EmitARCDestroyWeak(SrcAddr);
2419}
2420
John McCall31168b02011-06-15 23:02:42 +00002421/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002422/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002423llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
John McCallb04ecb72015-10-21 18:06:43 +00002424 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002425 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002426 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2427 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002428 }
2429
John McCall882987f2013-02-28 19:01:20 +00002430 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002431}
2432
2433/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002434/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002435void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2436 assert(value->getType() == Int8PtrTy);
2437
Pete Cooper2cd35962018-12-18 20:33:00 +00002438 if (getInvokeDest()) {
2439 // Call the runtime method not the intrinsic if we are handling exceptions
2440 llvm::Constant *&fn =
2441 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2442 if (!fn) {
2443 llvm::FunctionType *fnType =
2444 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2445 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2446 setARCRuntimeFunctionLinkage(CGM, fn);
2447 }
John McCall31168b02011-06-15 23:02:42 +00002448
Pete Cooper2cd35962018-12-18 20:33:00 +00002449 // objc_autoreleasePoolPop can throw.
2450 EmitRuntimeCallOrInvoke(fn, value);
2451 } else {
2452 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2453 if (!fn) {
2454 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2455 setARCRuntimeFunctionLinkage(CGM, fn);
2456 }
2457
2458 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002459 }
John McCall31168b02011-06-15 23:02:42 +00002460}
2461
2462/// Produce the code to do an MRR version objc_autoreleasepool_push.
2463/// Which is: [[NSAutoreleasePool alloc] init];
2464/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2465/// init is declared as: - (id) init; in its NSObject super class.
2466///
2467llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2468 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002469 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002470 // [NSAutoreleasePool alloc]
2471 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2472 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2473 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002474 RValue AllocRV =
2475 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002476 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002477 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002478
2479 // [Receiver init]
2480 Receiver = AllocRV.getScalarVal();
2481 II = &CGM.getContext().Idents.get("init");
2482 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2483 RValue InitRV =
2484 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2485 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002486 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002487 return InitRV.getScalarVal();
2488}
2489
Pete Coopere3886802018-12-08 05:13:50 +00002490/// Allocate the given objc object.
2491/// call i8* \@objc_alloc(i8* %value)
2492llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2493 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002494 return emitObjCValueOperation(*this, value, resultType,
2495 CGM.getObjCEntrypoints().objc_alloc,
2496 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002497}
2498
2499/// Allocate the given objc object.
2500/// call i8* \@objc_allocWithZone(i8* %value)
2501llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2502 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002503 return emitObjCValueOperation(*this, value, resultType,
2504 CGM.getObjCEntrypoints().objc_allocWithZone,
2505 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002506}
2507
John McCall31168b02011-06-15 23:02:42 +00002508/// Produce the code to do a primitive release.
2509/// [tmp drain];
2510void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2511 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2512 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2513 CallArgList Args;
2514 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002515 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002516}
2517
John McCall82fe67b2011-07-09 01:37:26 +00002518void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002519 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002520 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002521 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002522}
2523
2524void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002525 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002526 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002527 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002528}
2529
2530void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002531 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002532 QualType type) {
2533 CGF.EmitARCDestroyWeak(addr);
2534}
2535
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002536void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2537 QualType type) {
2538 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2539 CGF.EmitARCIntrinsicUse(value);
2540}
2541
Pete Coopere5b64ea2018-12-21 21:00:32 +00002542/// Autorelease the given object.
2543/// call i8* \@objc_autorelease(i8* %value)
2544llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2545 llvm::Type *returnType) {
2546 return emitObjCValueOperation(*this, value, returnType,
2547 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2548 "objc_autorelease");
2549}
2550
2551/// Retain the given object, with normal retain semantics.
2552/// call i8* \@objc_retain(i8* %value)
2553llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2554 llvm::Type *returnType) {
2555 return emitObjCValueOperation(*this, value, returnType,
2556 CGM.getObjCEntrypoints().objc_retainRuntimeFunction,
2557 "objc_retain");
2558}
2559
2560/// Release the given object.
2561/// call void \@objc_release(i8* %value)
2562void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2563 ARCPreciseLifetime_t precise) {
2564 if (isa<llvm::ConstantPointerNull>(value)) return;
2565
2566 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
2567 if (!fn) {
2568 if (!fn) {
2569 llvm::FunctionType *fnType =
2570 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2571 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2572 setARCRuntimeFunctionLinkage(CGM, fn);
2573 // We have Native ARC, so set nonlazybind attribute for performance
2574 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
2575 f->addFnAttr(llvm::Attribute::NonLazyBind);
2576 }
2577 }
2578
2579 // Cast the argument to 'id'.
2580 value = Builder.CreateBitCast(value, Int8PtrTy);
2581
2582 // Call objc_release.
2583 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2584
2585 if (precise == ARCImpreciseLifetime) {
2586 call->setMetadata("clang.imprecise_release",
2587 llvm::MDNode::get(Builder.getContext(), None));
2588 }
2589}
2590
John McCall31168b02011-06-15 23:02:42 +00002591namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002592 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002593 llvm::Value *Token;
2594
2595 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2596
Craig Topper4f12f102014-03-12 06:41:41 +00002597 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002598 CGF.EmitObjCAutoreleasePoolPop(Token);
2599 }
2600 };
David Blaikie7e70d682015-08-18 22:40:54 +00002601 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002602 llvm::Value *Token;
2603
2604 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2605
Craig Topper4f12f102014-03-12 06:41:41 +00002606 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002607 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2608 }
2609 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002610}
John McCall31168b02011-06-15 23:02:42 +00002611
2612void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002613 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002614 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2615 else
2616 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2617}
2618
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002619static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2620 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002621 case Qualifiers::OCL_None:
2622 case Qualifiers::OCL_ExplicitNone:
2623 case Qualifiers::OCL_Strong:
2624 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002625 return true;
John McCall31168b02011-06-15 23:02:42 +00002626
2627 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002628 return false;
John McCall31168b02011-06-15 23:02:42 +00002629 }
2630
2631 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002632}
2633
2634static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002635 LValue lvalue,
2636 QualType type) {
2637 llvm::Value *result;
2638 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2639 if (shouldRetain) {
2640 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2641 } else {
2642 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2643 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2644 }
2645 return TryEmitResult(result, !shouldRetain);
2646}
2647
2648static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002649 const Expr *e) {
2650 e = e->IgnoreParens();
2651 QualType type = e->getType();
2652
Fangrui Song6907ce22018-07-30 19:24:48 +00002653 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002654 // an extra retain/release pair by zeroing out the source of this
2655 // "move" operation.
2656 if (e->isXValue() &&
2657 !type.isConstQualified() &&
2658 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2659 // Emit the lvalue.
2660 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002661
John McCall154a2fd2011-08-30 00:57:29 +00002662 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002663 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2664 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002665
John McCall154a2fd2011-08-30 00:57:29 +00002666 // Set the source pointer to NULL.
2667 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002668
John McCall154a2fd2011-08-30 00:57:29 +00002669 return TryEmitResult(result, true);
2670 }
2671
John McCall31168b02011-06-15 23:02:42 +00002672 // As a very special optimization, in ARC++, if the l-value is the
2673 // result of a non-volatile assignment, do a simple retain of the
2674 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002675 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002676 !type.isVolatileQualified() &&
2677 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2678 isa<BinaryOperator>(e) &&
2679 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2680 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2681
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002682 // Try to emit code for scalar constant instead of emitting LValue and
2683 // loading it because we are not guaranteed to have an l-value. One of such
2684 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2685 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2686 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2687 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2688 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2689 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2690 }
2691
John McCall31168b02011-06-15 23:02:42 +00002692 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2693}
2694
John McCalle399e5b2016-01-27 18:32:30 +00002695typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2696 llvm::Value *value)>
2697 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002698
John McCalle399e5b2016-01-27 18:32:30 +00002699/// Insert code immediately after a call.
2700static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2701 llvm::Value *value,
2702 ValueTransform doAfterCall,
2703 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002704 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2705 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2706
2707 // Place the retain immediately following the call.
2708 CGF.Builder.SetInsertPoint(call->getParent(),
2709 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002710 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002711
2712 CGF.Builder.restoreIP(ip);
2713 return value;
2714 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2715 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2716
2717 // Place the retain at the beginning of the normal destination block.
2718 llvm::BasicBlock *BB = invoke->getNormalDest();
2719 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002720 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002721
2722 CGF.Builder.restoreIP(ip);
2723 return value;
2724
2725 // Bitcasts can arise because of related-result returns. Rewrite
2726 // the operand.
2727 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2728 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002729 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002730 bitcast->setOperand(0, operand);
2731 return bitcast;
2732
2733 // Generic fall-back case.
2734 } else {
2735 // Retain using the non-block variant: we never need to do a copy
2736 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002737 return doFallback(CGF, value);
2738 }
2739}
2740
2741/// Given that the given expression is some sort of call (which does
2742/// not return retained), emit a retain following it.
2743static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2744 const Expr *e) {
2745 llvm::Value *value = CGF.EmitScalarExpr(e);
2746 return emitARCOperationAfterCall(CGF, value,
2747 [](CodeGenFunction &CGF, llvm::Value *value) {
2748 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2749 },
2750 [](CodeGenFunction &CGF, llvm::Value *value) {
2751 return CGF.EmitARCRetainNonBlock(value);
2752 });
2753}
2754
2755/// Given that the given expression is some sort of call (which does
2756/// not return retained), perform an unsafeClaim following it.
2757static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2758 const Expr *e) {
2759 llvm::Value *value = CGF.EmitScalarExpr(e);
2760 return emitARCOperationAfterCall(CGF, value,
2761 [](CodeGenFunction &CGF, llvm::Value *value) {
2762 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2763 },
2764 [](CodeGenFunction &CGF, llvm::Value *value) {
2765 return value;
2766 });
2767}
2768
2769llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2770 bool allowUnsafeClaim) {
2771 if (allowUnsafeClaim &&
2772 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2773 return emitARCUnsafeClaimCallResult(*this, E);
2774 } else {
2775 llvm::Value *value = emitARCRetainCallResult(*this, E);
2776 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002777 }
2778}
2779
John McCallcd78e802011-09-10 01:16:55 +00002780/// Determine whether it might be important to emit a separate
2781/// objc_retain_block on the result of the given expression, or
2782/// whether it's okay to just emit it in a +1 context.
2783static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2784 assert(e->getType()->isBlockPointerType());
2785 e = e->IgnoreParens();
2786
2787 // For future goodness, emit block expressions directly in +1
2788 // contexts if we can.
2789 if (isa<BlockExpr>(e))
2790 return false;
2791
2792 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2793 switch (cast->getCastKind()) {
2794 // Emitting these operations in +1 contexts is goodness.
2795 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002796 case CK_ARCReclaimReturnedObject:
2797 case CK_ARCConsumeObject:
2798 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002799 return false;
2800
2801 // These operations preserve a block type.
2802 case CK_NoOp:
2803 case CK_BitCast:
2804 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2805
2806 // These operations are known to be bad (or haven't been considered).
2807 case CK_AnyPointerToBlockPointerCast:
2808 default:
2809 return true;
2810 }
2811 }
2812
2813 return true;
2814}
2815
John McCalle399e5b2016-01-27 18:32:30 +00002816namespace {
2817/// A CRTP base class for emitting expressions of retainable object
2818/// pointer type in ARC.
2819template <typename Impl, typename Result> class ARCExprEmitter {
2820protected:
2821 CodeGenFunction &CGF;
2822 Impl &asImpl() { return *static_cast<Impl*>(this); }
2823
2824 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2825
2826public:
2827 Result visit(const Expr *e);
2828 Result visitCastExpr(const CastExpr *e);
2829 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2830 Result visitBinaryOperator(const BinaryOperator *e);
2831 Result visitBinAssign(const BinaryOperator *e);
2832 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2833 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2834 Result visitBinAssignWeak(const BinaryOperator *e);
2835 Result visitBinAssignStrong(const BinaryOperator *e);
2836
2837 // Minimal implementation:
2838 // Result visitLValueToRValue(const Expr *e)
2839 // Result visitConsumeObject(const Expr *e)
2840 // Result visitExtendBlockObject(const Expr *e)
2841 // Result visitReclaimReturnedObject(const Expr *e)
2842 // Result visitCall(const Expr *e)
2843 // Result visitExpr(const Expr *e)
2844 //
2845 // Result emitBitCast(Result result, llvm::Type *resultType)
2846 // llvm::Value *getValueOfResult(Result result)
2847};
2848}
2849
2850/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002851///
2852/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002853template <typename Impl, typename Result>
2854Result
2855ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002856 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002857
2858 // Find the result expression.
2859 const Expr *resultExpr = E->getResultExpr();
2860 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002861 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002862
2863 for (PseudoObjectExpr::const_semantics_iterator
2864 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2865 const Expr *semantic = *i;
2866
2867 // If this semantic expression is an opaque value, bind it
2868 // to the result of its source expression.
2869 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2870 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2871 OVMA opaqueData;
2872
2873 // If this semantic is the result of the pseudo-object
2874 // expression, try to evaluate the source as +1.
2875 if (ov == resultExpr) {
2876 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002877 result = asImpl().visit(ov->getSourceExpr());
2878 opaqueData = OVMA::bind(CGF, ov,
2879 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002880
2881 // Otherwise, just bind it.
2882 } else {
2883 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2884 }
2885 opaques.push_back(opaqueData);
2886
2887 // Otherwise, if the expression is the result, evaluate it
2888 // and remember the result.
2889 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002890 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002891
2892 // Otherwise, evaluate the expression in an ignored context.
2893 } else {
2894 CGF.EmitIgnoredExpr(semantic);
2895 }
2896 }
2897
2898 // Unbind all the opaques now.
2899 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2900 opaques[i].unbind(CGF);
2901
2902 return result;
2903}
2904
John McCalle399e5b2016-01-27 18:32:30 +00002905template <typename Impl, typename Result>
2906Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2907 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002908
John McCalle399e5b2016-01-27 18:32:30 +00002909 // No-op casts don't change the type, so we just ignore them.
2910 case CK_NoOp:
2911 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002912
John McCalle399e5b2016-01-27 18:32:30 +00002913 // These casts can change the type.
2914 case CK_CPointerToObjCPointerCast:
2915 case CK_BlockPointerToObjCPointerCast:
2916 case CK_AnyPointerToBlockPointerCast:
2917 case CK_BitCast: {
2918 llvm::Type *resultType = CGF.ConvertType(e->getType());
2919 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2920 Result result = asImpl().visit(e->getSubExpr());
2921 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002922 }
2923
John McCalle399e5b2016-01-27 18:32:30 +00002924 // Handle some casts specially.
2925 case CK_LValueToRValue:
2926 return asImpl().visitLValueToRValue(e->getSubExpr());
2927 case CK_ARCConsumeObject:
2928 return asImpl().visitConsumeObject(e->getSubExpr());
2929 case CK_ARCExtendBlockObject:
2930 return asImpl().visitExtendBlockObject(e->getSubExpr());
2931 case CK_ARCReclaimReturnedObject:
2932 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2933
2934 // Otherwise, use the default logic.
2935 default:
2936 return asImpl().visitExpr(e);
2937 }
2938}
2939
2940template <typename Impl, typename Result>
2941Result
2942ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2943 switch (e->getOpcode()) {
2944 case BO_Comma:
2945 CGF.EmitIgnoredExpr(e->getLHS());
2946 CGF.EnsureInsertPoint();
2947 return asImpl().visit(e->getRHS());
2948
2949 case BO_Assign:
2950 return asImpl().visitBinAssign(e);
2951
2952 default:
2953 return asImpl().visitExpr(e);
2954 }
2955}
2956
2957template <typename Impl, typename Result>
2958Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2959 switch (e->getLHS()->getType().getObjCLifetime()) {
2960 case Qualifiers::OCL_ExplicitNone:
2961 return asImpl().visitBinAssignUnsafeUnretained(e);
2962
2963 case Qualifiers::OCL_Weak:
2964 return asImpl().visitBinAssignWeak(e);
2965
2966 case Qualifiers::OCL_Autoreleasing:
2967 return asImpl().visitBinAssignAutoreleasing(e);
2968
2969 case Qualifiers::OCL_Strong:
2970 return asImpl().visitBinAssignStrong(e);
2971
2972 case Qualifiers::OCL_None:
2973 return asImpl().visitExpr(e);
2974 }
2975 llvm_unreachable("bad ObjC ownership qualifier");
2976}
2977
2978/// The default rule for __unsafe_unretained emits the RHS recursively,
2979/// stores into the unsafe variable, and propagates the result outward.
2980template <typename Impl, typename Result>
2981Result ARCExprEmitter<Impl,Result>::
2982 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2983 // Recursively emit the RHS.
2984 // For __block safety, do this before emitting the LHS.
2985 Result result = asImpl().visit(e->getRHS());
2986
2987 // Perform the store.
2988 LValue lvalue =
2989 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2990 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2991 lvalue);
2992
2993 return result;
2994}
2995
2996template <typename Impl, typename Result>
2997Result
2998ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2999 return asImpl().visitExpr(e);
3000}
3001
3002template <typename Impl, typename Result>
3003Result
3004ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3005 return asImpl().visitExpr(e);
3006}
3007
3008template <typename Impl, typename Result>
3009Result
3010ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3011 return asImpl().visitExpr(e);
3012}
3013
3014/// The general expression-emission logic.
3015template <typename Impl, typename Result>
3016Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3017 // We should *never* see a nested full-expression here, because if
3018 // we fail to emit at +1, our caller must not retain after we close
3019 // out the full-expression. This isn't as important in the unsafe
3020 // emitter.
3021 assert(!isa<ExprWithCleanups>(e));
3022
3023 // Look through parens, __extension__, generic selection, etc.
3024 e = e->IgnoreParens();
3025
3026 // Handle certain kinds of casts.
3027 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3028 return asImpl().visitCastExpr(ce);
3029
3030 // Handle the comma operator.
3031 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3032 return asImpl().visitBinaryOperator(op);
3033
3034 // TODO: handle conditional operators here
3035
3036 // For calls and message sends, use the retained-call logic.
3037 // Delegate inits are a special case in that they're the only
3038 // returns-retained expression that *isn't* surrounded by
3039 // a consume.
3040 } else if (isa<CallExpr>(e) ||
3041 (isa<ObjCMessageExpr>(e) &&
3042 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3043 return asImpl().visitCall(e);
3044
3045 // Look through pseudo-object expressions.
3046 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3047 return asImpl().visitPseudoObjectExpr(pseudo);
3048 }
3049
3050 return asImpl().visitExpr(e);
3051}
3052
3053namespace {
3054
3055/// An emitter for +1 results.
3056struct ARCRetainExprEmitter :
3057 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3058
3059 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3060
3061 llvm::Value *getValueOfResult(TryEmitResult result) {
3062 return result.getPointer();
3063 }
3064
3065 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3066 llvm::Value *value = result.getPointer();
3067 value = CGF.Builder.CreateBitCast(value, resultType);
3068 result.setPointer(value);
3069 return result;
3070 }
3071
3072 TryEmitResult visitLValueToRValue(const Expr *e) {
3073 return tryEmitARCRetainLoadOfScalar(CGF, e);
3074 }
3075
3076 /// For consumptions, just emit the subexpression and thus elide
3077 /// the retain/release pair.
3078 TryEmitResult visitConsumeObject(const Expr *e) {
3079 llvm::Value *result = CGF.EmitScalarExpr(e);
3080 return TryEmitResult(result, true);
3081 }
3082
3083 /// Block extends are net +0. Naively, we could just recurse on
3084 /// the subexpression, but actually we need to ensure that the
3085 /// value is copied as a block, so there's a little filter here.
3086 TryEmitResult visitExtendBlockObject(const Expr *e) {
3087 llvm::Value *result; // will be a +0 value
3088
3089 // If we can't safely assume the sub-expression will produce a
3090 // block-copied value, emit the sub-expression at +0.
3091 if (shouldEmitSeparateBlockRetain(e)) {
3092 result = CGF.EmitScalarExpr(e);
3093
3094 // Otherwise, try to emit the sub-expression at +1 recursively.
3095 } else {
3096 TryEmitResult subresult = asImpl().visit(e);
3097
3098 // If that produced a retained value, just use that.
3099 if (subresult.getInt()) {
3100 return subresult;
3101 }
3102
3103 // Otherwise it's +0.
3104 result = subresult.getPointer();
3105 }
3106
3107 // Retain the object as a block.
3108 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3109 return TryEmitResult(result, true);
3110 }
3111
3112 /// For reclaims, emit the subexpression as a retained call and
3113 /// skip the consumption.
3114 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3115 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3116 return TryEmitResult(result, true);
3117 }
3118
3119 /// When we have an undecorated call, retroactively do a claim.
3120 TryEmitResult visitCall(const Expr *e) {
3121 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3122 return TryEmitResult(result, true);
3123 }
3124
3125 // TODO: maybe special-case visitBinAssignWeak?
3126
3127 TryEmitResult visitExpr(const Expr *e) {
3128 // We didn't find an obvious production, so emit what we've got and
3129 // tell the caller that we didn't manage to retain.
3130 llvm::Value *result = CGF.EmitScalarExpr(e);
3131 return TryEmitResult(result, false);
3132 }
3133};
3134}
3135
3136static TryEmitResult
3137tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3138 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003139}
3140
3141static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3142 LValue lvalue,
3143 QualType type) {
3144 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3145 llvm::Value *value = result.getPointer();
3146 if (!result.getInt())
3147 value = CGF.EmitARCRetain(type, value);
3148 return value;
3149}
3150
3151/// EmitARCRetainScalarExpr - Semantically equivalent to
3152/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3153/// best-effort attempt to peephole expressions that naturally produce
3154/// retained objects.
3155llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003156 // The retain needs to happen within the full-expression.
3157 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3158 enterFullExpression(cleanups);
3159 RunCleanupsScope scope(*this);
3160 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3161 }
3162
John McCall31168b02011-06-15 23:02:42 +00003163 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3164 llvm::Value *value = result.getPointer();
3165 if (!result.getInt())
3166 value = EmitARCRetain(e->getType(), value);
3167 return value;
3168}
3169
3170llvm::Value *
3171CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003172 // The retain needs to happen within the full-expression.
3173 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3174 enterFullExpression(cleanups);
3175 RunCleanupsScope scope(*this);
3176 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3177 }
3178
John McCall31168b02011-06-15 23:02:42 +00003179 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3180 llvm::Value *value = result.getPointer();
3181 if (result.getInt())
3182 value = EmitARCAutorelease(value);
3183 else
3184 value = EmitARCRetainAutorelease(e->getType(), value);
3185 return value;
3186}
3187
John McCallff613032011-10-04 06:23:45 +00003188llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3189 llvm::Value *result;
3190 bool doRetain;
3191
3192 if (shouldEmitSeparateBlockRetain(e)) {
3193 result = EmitScalarExpr(e);
3194 doRetain = true;
3195 } else {
3196 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3197 result = subresult.getPointer();
3198 doRetain = !subresult.getInt();
3199 }
3200
3201 if (doRetain)
3202 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3203 return EmitObjCConsumeObject(e->getType(), result);
3204}
3205
John McCall248512a2011-10-01 10:32:24 +00003206llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3207 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003208 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003209 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003210 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003211 return EmitARCRetainAutoreleaseScalarExpr(expr);
3212 }
3213
3214 // Otherwise, use the normal scalar-expression emission. The
3215 // exception machinery doesn't do anything special with the
3216 // exception like retaining it, so there's no safety associated with
3217 // only running cleanups after the throw has started, and when it
3218 // matters it tends to be substantially inferior code.
3219 return EmitScalarExpr(expr);
3220}
3221
John McCalle399e5b2016-01-27 18:32:30 +00003222namespace {
3223
3224/// An emitter for assigning into an __unsafe_unretained context.
3225struct ARCUnsafeUnretainedExprEmitter :
3226 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3227
3228 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3229
3230 llvm::Value *getValueOfResult(llvm::Value *value) {
3231 return value;
3232 }
3233
3234 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3235 return CGF.Builder.CreateBitCast(value, resultType);
3236 }
3237
3238 llvm::Value *visitLValueToRValue(const Expr *e) {
3239 return CGF.EmitScalarExpr(e);
3240 }
3241
3242 /// For consumptions, just emit the subexpression and perform the
3243 /// consumption like normal.
3244 llvm::Value *visitConsumeObject(const Expr *e) {
3245 llvm::Value *value = CGF.EmitScalarExpr(e);
3246 return CGF.EmitObjCConsumeObject(e->getType(), value);
3247 }
3248
3249 /// No special logic for block extensions. (This probably can't
3250 /// actually happen in this emitter, though.)
3251 llvm::Value *visitExtendBlockObject(const Expr *e) {
3252 return CGF.EmitARCExtendBlockObject(e);
3253 }
3254
3255 /// For reclaims, perform an unsafeClaim if that's enabled.
3256 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3257 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3258 }
3259
3260 /// When we have an undecorated call, just emit it without adding
3261 /// the unsafeClaim.
3262 llvm::Value *visitCall(const Expr *e) {
3263 return CGF.EmitScalarExpr(e);
3264 }
3265
3266 /// Just do normal scalar emission in the default case.
3267 llvm::Value *visitExpr(const Expr *e) {
3268 return CGF.EmitScalarExpr(e);
3269 }
3270};
3271}
3272
3273static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3274 const Expr *e) {
3275 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3276}
3277
3278/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3279/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3280/// avoiding any spurious retains, including by performing reclaims
3281/// with objc_unsafeClaimAutoreleasedReturnValue.
3282llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3283 // Look through full-expressions.
3284 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3285 enterFullExpression(cleanups);
3286 RunCleanupsScope scope(*this);
3287 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3288 }
3289
3290 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3291}
3292
3293std::pair<LValue,llvm::Value*>
3294CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3295 bool ignored) {
3296 // Evaluate the RHS first. If we're ignoring the result, assume
3297 // that we can emit at an unsafe +0.
3298 llvm::Value *value;
3299 if (ignored) {
3300 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3301 } else {
3302 value = EmitScalarExpr(e->getRHS());
3303 }
3304
3305 // Emit the LHS and perform the store.
3306 LValue lvalue = EmitLValue(e->getLHS());
3307 EmitStoreOfScalar(value, lvalue);
3308
3309 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3310}
3311
John McCall31168b02011-06-15 23:02:42 +00003312std::pair<LValue,llvm::Value*>
3313CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3314 bool ignored) {
3315 // Evaluate the RHS first.
3316 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3317 llvm::Value *value = result.getPointer();
3318
John McCallb726a552011-07-28 07:23:35 +00003319 bool hasImmediateRetain = result.getInt();
3320
3321 // If we didn't emit a retained object, and the l-value is of block
3322 // type, then we need to emit the block-retain immediately in case
3323 // it invalidates the l-value.
3324 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003325 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003326 hasImmediateRetain = true;
3327 }
3328
John McCall31168b02011-06-15 23:02:42 +00003329 LValue lvalue = EmitLValue(e->getLHS());
3330
3331 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003332 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003333 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003334 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003335 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003336 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003337 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003338 }
3339
3340 return std::pair<LValue,llvm::Value*>(lvalue, value);
3341}
3342
3343std::pair<LValue,llvm::Value*>
3344CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3345 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3346 LValue lvalue = EmitLValue(e->getLHS());
3347
Eli Friedmana0544d62011-12-03 04:14:32 +00003348 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003349
3350 return std::pair<LValue,llvm::Value*>(lvalue, value);
3351}
3352
3353void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003354 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003355 const Stmt *subStmt = ARPS.getSubStmt();
3356 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3357
3358 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003359 if (DI)
3360 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003361
3362 // Keep track of the current cleanup stack depth.
3363 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003364 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003365 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3366 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3367 } else {
3368 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3369 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3370 }
3371
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003372 for (const auto *I : S.body())
3373 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003374
Eric Christopher7cdf9482011-10-13 21:45:18 +00003375 if (DI)
3376 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003377}
John McCall1bd25562011-06-24 23:21:27 +00003378
3379/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3380/// make sure it survives garbage collection until this point.
3381void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3382 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003383 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003384 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00003385 llvm::Value *extender
3386 = llvm::InlineAsm::get(extenderType,
3387 /* assembly */ "",
3388 /* constraints */ "r",
3389 /* side effects */ true);
3390
3391 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003392 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003393}
3394
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003395/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003396/// non-trivial copy assignment function, produce following helper function.
3397/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3398///
3399llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003400CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3401 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003402 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003403 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003404 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003405 QualType Ty = PID->getPropertyIvarDecl()->getType();
3406 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003407 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003408 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003409 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003410 return nullptr;
3411 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003412 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003413 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003414 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3415 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3416 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003417
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003418 ASTContext &C = getContext();
3419 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003420 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003421
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003422 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003423 QualType DestTy = C.getPointerType(Ty);
3424 QualType SrcTy = Ty;
3425 SrcTy.addConst();
3426 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003427
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003428 SmallVector<QualType, 2> ArgTys;
3429 ArgTys.push_back(DestTy);
3430 ArgTys.push_back(SrcTy);
3431 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3432
3433 FunctionDecl *FD = FunctionDecl::Create(
3434 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3435 FunctionTy, nullptr, SC_Static, false, false);
3436
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003437 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003438 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3439 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003440 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003441 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3442 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003443 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003444
John McCallc56a8b32016-03-11 04:30:31 +00003445 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003446 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003447
John McCalla729c622012-02-17 03:33:10 +00003448 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003449
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003450 llvm::Function *Fn =
3451 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003452 "__assign_helper_atomic_property_",
3453 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003454
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003455 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003456
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003457 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003458
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003459 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3460 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003461 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003462 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003463
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003464 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3465 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003466 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003467 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003468
John McCall113bee02012-03-10 09:33:50 +00003469 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003470 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003471 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3472 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3473 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003474
Bruno Riccic5885cf2018-12-21 15:20:32 +00003475 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003476
3477 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003478 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003479 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003480 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003481}
3482
3483llvm::Constant *
3484CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3485 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003486 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003487 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003488 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003489 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3490 QualType Ty = PD->getType();
3491 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003492 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003493 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003494 return nullptr;
3495 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003496 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003497 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003498 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3499 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3500 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003501
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003502 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003503 IdentifierInfo *II =
3504 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003505
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003506 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003507 QualType DestTy = C.getPointerType(Ty);
3508 QualType SrcTy = Ty;
3509 SrcTy.addConst();
3510 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003511
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003512 SmallVector<QualType, 2> ArgTys;
3513 ArgTys.push_back(DestTy);
3514 ArgTys.push_back(SrcTy);
3515 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3516
3517 FunctionDecl *FD = FunctionDecl::Create(
3518 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3519 FunctionTy, nullptr, SC_Static, false, false);
3520
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003521 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003522 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3523 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003524 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003525 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3526 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003527 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003528
John McCallc56a8b32016-03-11 04:30:31 +00003529 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003530 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003531
John McCalla729c622012-02-17 03:33:10 +00003532 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003533
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003534 llvm::Function *Fn = llvm::Function::Create(
3535 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3536 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003537
3538 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003539
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003540 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003541
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003542 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3543 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003544
John McCall113bee02012-03-10 09:33:50 +00003545 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003546 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003547
3548 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003549 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003550
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003551 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003552 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003553 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3554 CXXConstExpr->arg_end());
3555
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003556 CXXConstructExpr *TheCXXConstructExpr =
3557 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3558 CXXConstExpr->getConstructor(),
3559 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003560 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003561 CXXConstExpr->hadMultipleCandidates(),
3562 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003563 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003564 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003565 CXXConstExpr->getConstructionKind(),
3566 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003567
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003568 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3569 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003570
John McCall113bee02012-03-10 09:33:50 +00003571 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003572 CharUnits Alignment
3573 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003574 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003575 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3576 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003577 AggValueSlot::IsDestructed,
3578 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003579 AggValueSlot::IsNotAliased,
3580 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003581
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003582 FinishFunction();
3583 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3584 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3585 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003586}
3587
Eli Friedmanec75fec2012-02-28 01:08:45 +00003588llvm::Value *
3589CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3590 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003591 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3592 Selector CopySelector =
3593 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003594 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3595 Selector AutoreleaseSelector =
3596 getContext().Selectors.getNullarySelector(AutoreleaseID);
3597
3598 // Emit calls to retain/autorelease.
3599 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3600 llvm::Value *Val = Block;
3601 RValue Result;
3602 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003603 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003604 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003605 Val = Result.getScalarVal();
3606 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3607 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003608 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003609 Val = Result.getScalarVal();
3610 return Val;
3611}
3612
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003613llvm::Value *
3614CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3615 assert(Args.size() == 3 && "Expected 3 argument here!");
3616
3617 if (!CGM.IsOSVersionAtLeastFn) {
3618 llvm::FunctionType *FTy =
3619 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3620 CGM.IsOSVersionAtLeastFn =
3621 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3622 }
3623
3624 llvm::Value *CallRes =
3625 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3626
3627 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3628}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003629
Alex Lorenza8fbef42017-03-23 11:14:27 +00003630void CodeGenModule::emitAtAvailableLinkGuard() {
3631 if (!IsOSVersionAtLeastFn)
3632 return;
3633 // @available requires CoreFoundation only on Darwin.
3634 if (!Target.getTriple().isOSDarwin())
3635 return;
3636 // Add -framework CoreFoundation to the linker commands. We still want to
3637 // emit the core foundation reference down below because otherwise if
3638 // CoreFoundation is not used in the code, the linker won't link the
3639 // framework.
3640 auto &Context = getLLVMContext();
3641 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3642 llvm::MDString::get(Context, "CoreFoundation")};
3643 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3644 // Emit a reference to a symbol from CoreFoundation to ensure that
3645 // CoreFoundation is linked into the final binary.
3646 llvm::FunctionType *FTy =
3647 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3648 llvm::Constant *CFFunc =
3649 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3650
3651 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3652 llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3653 CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3654 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3655 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3656 CodeGenFunction CGF(*this);
3657 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3658 CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3659 CGF.Builder.CreateUnreachable();
3660 addCompilerUsedGlobal(CFLinkCheckFunc);
3661}
3662
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003663CGObjCRuntime::~CGObjCRuntime() {}