blob: d2175f00b448cd9cbe321d513f56141c3ad814cc [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
David Chisnall481e3a82010-01-23 02:40:42 +000048 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000049 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Patrick Beard0caa3942012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000056/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000058///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000059llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000064 const Expr *SubExpr = E->getSubExpr();
Patrick Beard0caa3942012-04-19 00:25:12 +000065 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000070 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000077 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
79
80 // ObjCBoxedExpr supports boxing of structs and unions
81 // via [NSValue valueWithBytes:objCType:]
82 const QualType ValueType(SubExpr->getType().getCanonicalType());
83 if (ValueType->isObjCBoxableRecordType()) {
84 // Emit CodeGen for first parameter
85 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000086 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000087 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000088 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000090
91 // Create char array to store type encoding
92 std::string Str;
93 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000094 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Alex Denisovfde64952015-06-26 05:28:36 +000095
96 // Cast type encoding to correct type
97 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
100
101 Args.add(RValue::get(Cast), EncodingQT);
102 } else {
103 Args.add(EmitAnyExpr(SubExpr), ArgQT);
104 }
Alp Toker314cc812014-01-25 16:55:45 +0000105
106 RValue result = Runtime.GenerateMessageSend(
107 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108 Args, ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000109 return Builder.CreateBitCast(result.getScalarVal(),
110 ConvertType(E->getType()));
111}
112
113llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000114 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000116 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000117 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
118 if (!ALE)
119 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000120
121 // Optimize empty collections by referencing constants, when available.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000122 uint64_t NumElements =
123 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000124 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
125 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
126 QualType IdTy(CGM.getContext().getObjCIdType());
127 llvm::Constant *Constant =
128 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000129 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
130 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getLocStart());
131 cast<llvm::LoadInst>(Ptr)->setMetadata(
132 CGM.getModule().getMDKindID("invariant.load"),
133 llvm::MDNode::get(getLLVMContext(), None));
134 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000135 }
136
137 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000138 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
139 NumElements);
140 QualType ElementType = Context.getObjCIdType().withConst();
141 QualType ElementArrayType
142 = Context.getConstantArrayType(ElementType, APNumElements,
143 ArrayType::Normal, /*IndexTypeQuals=*/0);
144
145 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000146 Address Objects = CreateMemTemp(ElementArrayType, "objects");
147 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 if (DLE)
149 Keys = CreateMemTemp(ElementArrayType, "keys");
150
John McCall770a4c12013-04-04 00:20:38 +0000151 // In ARC, we may need to do extra work to keep all the keys and
152 // values alive until after the call.
153 SmallVector<llvm::Value *, 16> NeededObjects;
154 bool TrackNeededObjects =
155 (getLangOpts().ObjCAutoRefCount &&
156 CGM.getCodeGenOpts().OptimizationLevel != 0);
157
Ted Kremeneke65b0862012-03-06 20:05:56 +0000158 // Perform the actual initialialization of the array(s).
159 for (uint64_t i = 0; i < NumElements; i++) {
160 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000161 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000162 const Expr *Rhs = ALE->getElement(i);
John McCall7f416cc2015-09-08 08:05:57 +0000163 LValue LV = MakeAddrLValue(
164 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000165 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000166
167 llvm::Value *value = EmitScalarExpr(Rhs);
168 EmitStoreThroughLValue(RValue::get(value), LV, true);
169 if (TrackNeededObjects) {
170 NeededObjects.push_back(value);
171 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000172 } else {
John McCall770a4c12013-04-04 00:20:38 +0000173 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000174 const Expr *Key = DLE->getKeyValueElement(i).Key;
John McCall7f416cc2015-09-08 08:05:57 +0000175 LValue KeyLV = MakeAddrLValue(
176 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000177 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000178 llvm::Value *keyValue = EmitScalarExpr(Key);
179 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180
John McCall770a4c12013-04-04 00:20:38 +0000181 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000182 const Expr *Value = DLE->getKeyValueElement(i).Value;
John McCall7f416cc2015-09-08 08:05:57 +0000183 LValue ValueLV = MakeAddrLValue(
184 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000185 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000186 llvm::Value *valueValue = EmitScalarExpr(Value);
187 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
188 if (TrackNeededObjects) {
189 NeededObjects.push_back(keyValue);
190 NeededObjects.push_back(valueValue);
191 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000192 }
193 }
194
195 // Generate the argument list.
196 CallArgList Args;
197 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
198 const ParmVarDecl *argDecl = *PI++;
199 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000200 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000201 if (DLE) {
202 argDecl = *PI++;
203 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000204 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000205 }
206 argDecl = *PI;
207 ArgQT = argDecl->getType().getUnqualifiedType();
208 llvm::Value *Count =
209 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
210 Args.add(RValue::get(Count), ArgQT);
211
212 // Generate a reference to the class pointer, which will be the receiver.
213 Selector Sel = MethodWithObjects->getSelector();
214 QualType ResultType = E->getType();
215 const ObjCObjectPointerType *InterfacePointerType
216 = ResultType->getAsObjCInterfacePointerType();
217 ObjCInterfaceDecl *Class
218 = InterfacePointerType->getObjectType()->getInterface();
219 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000220 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000221
222 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000223 RValue result = Runtime.GenerateMessageSend(
224 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
225 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000226
227 // The above message send needs these objects, but in ARC they are
228 // passed in a buffer that is essentially __unsafe_unretained.
229 // Therefore we must prevent the optimizer from releasing them until
230 // after the call.
231 if (TrackNeededObjects) {
232 EmitARCIntrinsicUse(NeededObjects);
233 }
234
Ted Kremeneke65b0862012-03-06 20:05:56 +0000235 return Builder.CreateBitCast(result.getScalarVal(),
236 ConvertType(E->getType()));
237}
238
239llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000240 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000241}
242
243llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
244 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000245 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246}
247
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000248/// Emit a selector.
249llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
250 // Untyped selector.
251 // Note that this implementation allows for non-constant strings to be passed
252 // as arguments to @selector(). Currently, the only thing preventing this
253 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000254 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000255}
256
Daniel Dunbar66912a12008-08-20 00:28:19 +0000257llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
258 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000259 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000260}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000261
Douglas Gregore83b9562015-07-07 03:57:53 +0000262/// \brief Adjust the type of an Objective-C object that doesn't match up due
263/// to type erasure at various points, e.g., related result types or the use
264/// of parameterized classes.
265static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
266 RValue Result) {
267 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000268 return Result;
John McCall31168b02011-06-15 23:02:42 +0000269
Douglas Gregore83b9562015-07-07 03:57:53 +0000270 // If the converted types are the same, we're done.
271 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
272 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000273 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000274
275 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000276 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000277 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000278}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000279
John McCallcf166702011-07-22 08:53:00 +0000280/// Decide whether to extend the lifetime of the receiver of a
281/// returns-inner-pointer message.
282static bool
283shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
284 switch (message->getReceiverKind()) {
285
286 // For a normal instance message, we should extend unless the
287 // receiver is loaded from a variable with precise lifetime.
288 case ObjCMessageExpr::Instance: {
289 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000290
291 // Look through OVEs.
292 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
293 if (opaque->getSourceExpr())
294 receiver = opaque->getSourceExpr()->IgnoreParens();
295 }
296
John McCallcf166702011-07-22 08:53:00 +0000297 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
298 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
299 receiver = ice->getSubExpr()->IgnoreParens();
300
John McCall6380a282015-09-09 23:37:17 +0000301 // Look through OVEs.
302 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
303 if (opaque->getSourceExpr())
304 receiver = opaque->getSourceExpr()->IgnoreParens();
305 }
306
John McCallcf166702011-07-22 08:53:00 +0000307 // Only __strong variables.
308 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
309 return true;
310
311 // All ivars and fields have precise lifetime.
312 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
313 return false;
314
315 // Otherwise, check for variables.
316 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
317 if (!declRef) return true;
318 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
319 if (!var) return true;
320
321 // All variables have precise lifetime except local variables with
322 // automatic storage duration that aren't specially marked.
323 return (var->hasLocalStorage() &&
324 !var->hasAttr<ObjCPreciseLifetimeAttr>());
325 }
326
327 case ObjCMessageExpr::Class:
328 case ObjCMessageExpr::SuperClass:
329 // It's never necessary for class objects.
330 return false;
331
332 case ObjCMessageExpr::SuperInstance:
333 // We generally assume that 'self' lives throughout a method call.
334 return false;
335 }
336
337 llvm_unreachable("invalid receiver kind");
338}
339
John McCall460ce582015-10-22 18:38:17 +0000340/// Given an expression of ObjC pointer type, check whether it was
341/// immediately loaded from an ARC __weak l-value.
342static const Expr *findWeakLValue(const Expr *E) {
343 assert(E->getType()->isObjCRetainableType());
344 E = E->IgnoreParens();
345 if (auto CE = dyn_cast<CastExpr>(E)) {
346 if (CE->getCastKind() == CK_LValueToRValue) {
347 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
348 return CE->getSubExpr();
349 }
350 }
351
352 return nullptr;
353}
354
John McCall78a15112010-05-22 01:48:05 +0000355RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
356 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000357 // Only the lookup mechanism and first two arguments of the method
358 // implementation vary between runtimes. We can get the receiver and
359 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000360
John McCall31168b02011-06-15 23:02:42 +0000361 bool isDelegateInit = E->isDelegateInitCall();
362
John McCallcf166702011-07-22 08:53:00 +0000363 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000364
John McCall460ce582015-10-22 18:38:17 +0000365 // If the method is -retain, and the receiver's being loaded from
366 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
367 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
368 method->getMethodFamily() == OMF_retain) {
369 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
370 LValue lvalue = EmitLValue(lvalueExpr);
371 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
372 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
373 }
374 }
375
John McCall31168b02011-06-15 23:02:42 +0000376 // We don't retain the receiver in delegate init calls, and this is
377 // safe because the receiver value is always loaded from 'self',
378 // which we zero out. We don't want to Block_copy block receivers,
379 // though.
380 bool retainSelf =
381 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000382 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000383 method &&
384 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000385
Daniel Dunbar8d480592008-08-11 18:12:00 +0000386 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000387 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000388 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000389 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000390 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000391 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000392 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000393 switch (E->getReceiverKind()) {
394 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000395 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000396 if (retainSelf) {
397 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
398 E->getInstanceReceiver());
399 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000400 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000401 } else
402 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000403 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000404
Douglas Gregor9a129192010-04-21 00:45:42 +0000405 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000406 ReceiverType = E->getClassReceiver();
407 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000408 assert(ObjTy && "Invalid Objective-C class message send");
409 OID = ObjTy->getInterface();
410 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000411 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000412 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000413 break;
414 }
415
416 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000417 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000418 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000419 isSuperMessage = true;
420 break;
421
422 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000423 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000424 Receiver = LoadObjCSelf();
425 isSuperMessage = true;
426 isClassMessage = true;
427 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000428 }
429
John McCallcf166702011-07-22 08:53:00 +0000430 if (retainSelf)
431 Receiver = EmitARCRetainNonBlock(Receiver);
432
433 // In ARC, we sometimes want to "extend the lifetime"
434 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
435 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000436 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000437 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
438 shouldExtendReceiverForInnerPointerMessage(E))
439 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
440
Alp Toker314cc812014-01-25 16:55:45 +0000441 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000442
Daniel Dunbarc722b852008-08-30 03:02:31 +0000443 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000444 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000445
John McCall31168b02011-06-15 23:02:42 +0000446 // For delegate init calls in ARC, do an unsafe store of null into
447 // self. This represents the call taking direct ownership of that
448 // value. We have to do this after emitting the other call
449 // arguments because they might also reference self, but we don't
450 // have to worry about any of them modifying self because that would
451 // be an undefined read and write of an object in unordered
452 // expressions.
453 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000454 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000455 "delegate init calls should only be marked in ARC");
456
457 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000458 Address selfAddr =
459 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000460 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
461 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000462
Douglas Gregor33823722011-06-11 01:09:30 +0000463 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000464 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000465 // super is only valid in an Objective-C method
466 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000467 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000468 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
469 E->getSelector(),
470 OMD->getClassInterface(),
471 isCategoryImpl,
472 Receiver,
473 isClassMessage,
474 Args,
John McCallcf166702011-07-22 08:53:00 +0000475 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000476 } else {
Pete Cooper94867712016-03-21 20:50:03 +0000477 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
478 E->getSelector(),
479 Receiver, Args, OID,
480 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000481 }
John McCall31168b02011-06-15 23:02:42 +0000482
483 // For delegate init calls in ARC, implicitly store the result of
484 // the call back into self. This takes ownership of the value.
485 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000486 Address selfAddr =
487 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000488 llvm::Value *newSelf = result.getScalarVal();
489
490 // The delegate return type isn't necessarily a matching type; in
491 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000492 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000493 newSelf = Builder.CreateBitCast(newSelf, selfTy);
494
495 Builder.CreateStore(newSelf, selfAddr);
496 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000497
Douglas Gregore83b9562015-07-07 03:57:53 +0000498 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000499}
500
John McCall31168b02011-06-15 23:02:42 +0000501namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000502struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000503 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000504 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000505
506 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000507 const ObjCInterfaceDecl *iface = impl->getClassInterface();
508 if (!iface->getSuperClass()) return;
509
John McCalldffafde2011-07-13 18:26:47 +0000510 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
511
John McCall31168b02011-06-15 23:02:42 +0000512 // Call [super dealloc] if we have a superclass.
513 llvm::Value *self = CGF.LoadObjCSelf();
514
515 CallArgList args;
516 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
517 CGF.getContext().VoidTy,
518 method->getSelector(),
519 iface,
John McCalldffafde2011-07-13 18:26:47 +0000520 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000521 self,
522 /*is class msg*/ false,
523 args,
524 method);
525 }
526};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000527}
John McCall31168b02011-06-15 23:02:42 +0000528
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000529/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
530/// the LLVM function and sets the other context used by
531/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000532void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000533 const ObjCContainerDecl *CD) {
534 SourceLocation StartLoc = OMD->getLocStart();
John McCalla738c252011-03-09 04:27:21 +0000535 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000536 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000537 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000538 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000539
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000540 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000541
John McCalla729c622012-02-17 03:33:10 +0000542 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000543 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000544
John McCalla738c252011-03-09 04:27:21 +0000545 args.push_back(OMD->getSelfDecl());
546 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000547
Benjamin Kramerf9890422015-02-17 16:48:30 +0000548 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000549
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000550 CurGD = OMD;
David Blaikie47d28e02015-01-14 07:10:46 +0000551 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000552
Adrian Prantl42d71b92014-04-10 23:21:53 +0000553 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
554 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000555
556 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000557 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000558 OMD->isInstanceMethod() &&
559 OMD->getSelector().isUnarySelector()) {
560 const IdentifierInfo *ident =
561 OMD->getSelector().getIdentifierInfoForSlot(0);
562 if (ident->isStr("dealloc"))
563 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
564 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000565}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000566
John McCall31168b02011-06-15 23:02:42 +0000567static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
568 LValue lvalue, QualType type);
569
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000570/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000571/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000572void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000573 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000574 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000575 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000576 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000577 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000578 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000579}
580
John McCallb923ece2011-09-12 23:06:44 +0000581/// emitStructGetterCall - Call the runtime function to load a property
582/// into the return value slot.
583static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
584 bool isAtomic, bool hasStrong) {
585 ASTContext &Context = CGF.getContext();
586
John McCall7f416cc2015-09-08 08:05:57 +0000587 Address src =
588 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
589 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000590
591 // objc_copyStruct (ReturnValue, &structIvar,
592 // sizeof (Type of Ivar), isAtomic, false);
593 CallArgList args;
594
John McCall7f416cc2015-09-08 08:05:57 +0000595 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
596 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000597
598 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000599 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000600
601 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
602 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
603 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
604 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
605
John McCallb92ab1a2016-10-26 23:46:34 +0000606 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
607 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000608 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000609 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000610}
611
John McCallf4528ae2011-09-13 03:34:09 +0000612/// Determine whether the given architecture supports unaligned atomic
613/// accesses. They don't have to be fast, just faster than a function
614/// call and a mutex.
615static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000616 // FIXME: Allow unaligned atomic load/store on x86. (It is not
617 // currently supported by the backend.)
618 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000619}
620
621/// Return the maximum size that permits atomic accesses for the given
622/// architecture.
623static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
624 llvm::Triple::ArchType arch) {
625 // ARM has 8-byte atomic accesses, but it's not clear whether we
626 // want to rely on them here.
627
628 // In the default case, just assume that any size up to a pointer is
629 // fine given adequate alignment.
630 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
631}
632
633namespace {
634 class PropertyImplStrategy {
635 public:
636 enum StrategyKind {
637 /// The 'native' strategy is to use the architecture's provided
638 /// reads and writes.
639 Native,
640
641 /// Use objc_setProperty and objc_getProperty.
642 GetSetProperty,
643
644 /// Use objc_setProperty for the setter, but use expression
645 /// evaluation for the getter.
646 SetPropertyAndExpressionGet,
647
648 /// Use objc_copyStruct.
649 CopyStruct,
650
651 /// The 'expression' strategy is to emit normal assignment or
652 /// lvalue-to-rvalue expressions.
653 Expression
654 };
655
656 StrategyKind getKind() const { return StrategyKind(Kind); }
657
658 bool hasStrongMember() const { return HasStrong; }
659 bool isAtomic() const { return IsAtomic; }
660 bool isCopy() const { return IsCopy; }
661
662 CharUnits getIvarSize() const { return IvarSize; }
663 CharUnits getIvarAlignment() const { return IvarAlignment; }
664
665 PropertyImplStrategy(CodeGenModule &CGM,
666 const ObjCPropertyImplDecl *propImpl);
667
668 private:
669 unsigned Kind : 8;
670 unsigned IsAtomic : 1;
671 unsigned IsCopy : 1;
672 unsigned HasStrong : 1;
673
674 CharUnits IvarSize;
675 CharUnits IvarAlignment;
676 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000677}
John McCallf4528ae2011-09-13 03:34:09 +0000678
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000679/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000680PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
681 const ObjCPropertyImplDecl *propImpl) {
682 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000683 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000684
John McCall43192862011-09-13 18:31:23 +0000685 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
686 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000687 HasStrong = false; // doesn't matter here.
688
689 // Evaluate the ivar's size and alignment.
690 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
691 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000692 std::tie(IvarSize, IvarAlignment) =
693 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000694
695 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000696 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000697 if (IsCopy) {
698 Kind = GetSetProperty;
699 return;
700 }
701
John McCall43192862011-09-13 18:31:23 +0000702 // Handle retain.
703 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000704 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000705 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000706 // fallthrough
707
708 // In ARC, if the property is non-atomic, use expression emission,
709 // which translates to objc_storeStrong. This isn't required, but
710 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000711 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000712 // Using standard expression emission for the setter is only
713 // acceptable if the ivar is __strong, which won't be true if
714 // the property is annotated with __attribute__((NSObject)).
715 // TODO: falling all the way back to objc_setProperty here is
716 // just laziness, though; we could still use objc_storeStrong
717 // if we hacked it right.
718 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
719 Kind = Expression;
720 else
721 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000722 return;
723
724 // Otherwise, we need to at least use setProperty. However, if
725 // the property isn't atomic, we can use normal expression
726 // emission for the getter.
727 } else if (!IsAtomic) {
728 Kind = SetPropertyAndExpressionGet;
729 return;
730
731 // Otherwise, we have to use both setProperty and getProperty.
732 } else {
733 Kind = GetSetProperty;
734 return;
735 }
736 }
737
738 // If we're not atomic, just use expression accesses.
739 if (!IsAtomic) {
740 Kind = Expression;
741 return;
742 }
743
John McCall0e5c0862011-09-13 05:36:29 +0000744 // Properties on bitfield ivars need to be emitted using expression
745 // accesses even if they're nominally atomic.
746 if (ivar->isBitField()) {
747 Kind = Expression;
748 return;
749 }
750
John McCallf4528ae2011-09-13 03:34:09 +0000751 // GC-qualified or ARC-qualified ivars need to be emitted as
752 // expressions. This actually works out to being atomic anyway,
753 // except for ARC __strong, but that should trigger the above code.
754 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000755 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000756 CGM.getContext().getObjCGCAttrKind(ivarType))) {
757 Kind = Expression;
758 return;
759 }
760
761 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000762 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000763 if (const RecordType *recordType = ivarType->getAs<RecordType>())
764 HasStrong = recordType->getDecl()->hasObjectMember();
765
766 // We can never access structs with object members with a native
767 // access, because we need to use write barriers. This is what
768 // objc_copyStruct is for.
769 if (HasStrong) {
770 Kind = CopyStruct;
771 return;
772 }
773
774 // Otherwise, this is target-dependent and based on the size and
775 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000776
777 // If the size of the ivar is not a power of two, give up. We don't
778 // want to get into the business of doing compare-and-swaps.
779 if (!IvarSize.isPowerOfTwo()) {
780 Kind = CopyStruct;
781 return;
782 }
783
John McCallf4528ae2011-09-13 03:34:09 +0000784 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000785 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000786
787 // Most architectures require memory to fit within a single cache
788 // line, so the alignment has to be at least the size of the access.
789 // Otherwise we have to grab a lock.
790 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
791 Kind = CopyStruct;
792 return;
793 }
794
795 // If the ivar's size exceeds the architecture's maximum atomic
796 // access size, we have to use CopyStruct.
797 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
798 Kind = CopyStruct;
799 return;
800 }
801
802 // Otherwise, we can use native loads and stores.
803 Kind = Native;
804}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000805
James Dennettbe302452012-06-15 22:10:14 +0000806/// \brief Generate an Objective-C property getter function.
807///
808/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000809/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000810void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
811 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000812 llvm::Constant *AtomicHelperFn =
813 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000814 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
815 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
816 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000817 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000818
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000819 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000820
821 FinishFunction();
822}
823
John McCallbdd81852011-09-13 06:00:03 +0000824static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
825 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000826 if (!getter) return true;
827
828 // Sema only makes only of these when the ivar has a C++ class type,
829 // so the form is pretty constrained.
830
John McCallbdd81852011-09-13 06:00:03 +0000831 // If the property has a reference type, we might just be binding a
832 // reference, in which case the result will be a gl-value. We should
833 // treat this as a non-trivial operation.
834 if (getter->isGLValue())
835 return false;
836
John McCallf4528ae2011-09-13 03:34:09 +0000837 // If we selected a trivial copy-constructor, we're okay.
838 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
839 return (construct->getConstructor()->isTrivial());
840
841 // The constructor might require cleanups (in which case it's never
842 // trivial).
843 assert(isa<ExprWithCleanups>(getter));
844 return false;
845}
846
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000847/// emitCPPObjectAtomicGetterCall - Call the runtime function to
848/// copy the ivar into the resturn slot.
849static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
850 llvm::Value *returnAddr,
851 ObjCIvarDecl *ivar,
852 llvm::Constant *AtomicHelperFn) {
853 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
854 // AtomicHelperFn);
855 CallArgList args;
856
857 // The 1st argument is the return Slot.
858 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
859
860 // The 2nd argument is the address of the ivar.
861 llvm::Value *ivarAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000862 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
863 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000864 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
865 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
866
867 // Third argument is the helper function.
868 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
869
John McCallb92ab1a2016-10-26 23:46:34 +0000870 llvm::Constant *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000871 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000872 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000873 CGF.EmitCall(
874 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000875 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000876}
877
John McCallf4528ae2011-09-13 03:34:09 +0000878void
879CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000880 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000881 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000882 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000883 // If there's a non-trivial 'get' expression, we just have to emit that.
884 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000885 if (!AtomicHelperFn) {
886 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000887 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000888 EmitReturnStmt(ret);
889 }
890 else {
891 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f416cc2015-09-08 08:05:57 +0000892 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000893 ivar, AtomicHelperFn);
894 }
John McCallf4528ae2011-09-13 03:34:09 +0000895 return;
896 }
897
898 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
899 QualType propType = prop->getType();
900 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
901
902 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
903
904 // Pick an implementation strategy.
905 PropertyImplStrategy strategy(CGM, propImpl);
906 switch (strategy.getKind()) {
907 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000908 // We don't need to do anything for a zero-size struct.
909 if (strategy.getIvarSize().isZero())
910 return;
911
John McCallf4528ae2011-09-13 03:34:09 +0000912 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
913
914 // Currently, all atomic accesses have to be through integer
915 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000916 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
917 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +0000918 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
919
920 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +0000921 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +0000922 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
923 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +0000924 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +0000925
926 // Store that value into the return address. Doing this with a
927 // bitcast is likely to produce some pretty ugly IR, but it's not
928 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000929 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
930 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
931 llvm::Value *ivarVal = load;
932 if (ivarSize > retTySize) {
933 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
934 ivarVal = Builder.CreateTrunc(load, newTy);
935 bitcastType = newTy->getPointerTo();
936 }
937 Builder.CreateStore(ivarVal,
938 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +0000939
940 // Make sure we don't do an autorelease.
941 AutoreleaseResult = false;
942 return;
943 }
944
945 case PropertyImplStrategy::GetSetProperty: {
John McCallb92ab1a2016-10-26 23:46:34 +0000946 llvm::Constant *getPropertyFn =
John McCallf4528ae2011-09-13 03:34:09 +0000947 CGM.getObjCRuntime().GetPropertyGetFunction();
948 if (!getPropertyFn) {
949 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000950 return;
951 }
John McCallb92ab1a2016-10-26 23:46:34 +0000952 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +0000953
954 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
955 // FIXME: Can't this be simpler? This might even be worse than the
956 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000957 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +0000958 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +0000959 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
960 llvm::Value *ivarOffset =
961 EmitIvarOffset(classImpl->getClassInterface(), ivar);
962
963 CallArgList args;
964 args.add(RValue::get(self), getContext().getObjCIdType());
965 args.add(RValue::get(cmd), getContext().getObjCSelType());
966 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000967 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
968 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000969
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000970 // FIXME: We shouldn't need to get the function info here, the
971 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000972 llvm::Instruction *CallInstruction;
Samuel Antao798f11c2015-11-23 22:04:44 +0000973 RValue RV = EmitCall(
John McCallc56a8b32016-03-11 04:30:31 +0000974 getTypes().arrangeBuiltinFunctionCall(propType, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000975 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000976 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
977 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000978
Daniel Dunbara08dff12008-09-24 04:04:31 +0000979 // We need to fix the type here. Ivars with copy & retain are
980 // always objects so we don't need to worry about complex or
981 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000982 RV = RValue::get(Builder.CreateBitCast(
983 RV.getScalarVal(),
984 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000985
986 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000987
988 // objc_getProperty does an autorelease, so we should suppress ours.
989 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000990
John McCallf4528ae2011-09-13 03:34:09 +0000991 return;
992 }
993
994 case PropertyImplStrategy::CopyStruct:
995 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
996 strategy.hasStrongMember());
997 return;
998
999 case PropertyImplStrategy::Expression:
1000 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1001 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1002
1003 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001004 switch (getEvaluationKind(ivarType)) {
1005 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001006 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001007 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001008 /*init*/ true);
1009 return;
1010 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001011 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001012 // The return value slot is guaranteed to not be aliased, but
1013 // that's not necessarily the same as "on the stack", so
1014 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001015 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1016 /* Src= */ LV, ivarType);
1017 return; }
John McCall47fb9502013-03-07 21:37:08 +00001018 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001019 llvm::Value *value;
1020 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001021 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001022 } else {
1023 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1024 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001025 if (getLangOpts().ObjCAutoRefCount) {
1026 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1027 } else {
1028 value = EmitARCLoadWeak(LV.getAddress());
1029 }
John McCall24fada12011-07-22 05:23:13 +00001030
1031 // Otherwise we want to do a simple load, suppressing the
1032 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001033 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001034 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001035 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001036 }
John McCall31168b02011-06-15 23:02:42 +00001037
Alp Toker314cc812014-01-25 16:55:45 +00001038 value = Builder.CreateBitCast(
1039 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001040 }
1041
1042 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001043 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001044 }
John McCall47fb9502013-03-07 21:37:08 +00001045 }
1046 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001047 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001048
John McCallf4528ae2011-09-13 03:34:09 +00001049 }
1050 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001051}
1052
John McCallb923ece2011-09-12 23:06:44 +00001053/// emitStructSetterCall - Call the runtime function to store the value
1054/// from the first formal parameter into the given ivar.
1055static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1056 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001057 // objc_copyStruct (&structIvar, &Arg,
1058 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001059 CallArgList args;
1060
1061 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001062 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1063 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001064 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001065 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1066 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001067
1068 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001069 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001070 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +00001071 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001072 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001073 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1074 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001075
1076 // The third argument is the sizeof the type.
1077 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001078 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1079 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001080
John McCallb923ece2011-09-12 23:06:44 +00001081 // The fourth argument is the 'isAtomic' flag.
1082 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001083
John McCallb923ece2011-09-12 23:06:44 +00001084 // The fifth argument is the 'hasStrong' flag.
1085 // FIXME: should this really always be false?
1086 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1087
John McCallb92ab1a2016-10-26 23:46:34 +00001088 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1089 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001090 CGF.EmitCall(
1091 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001092 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001093}
1094
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001095/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1096/// the value from the first formal parameter into the given ivar, using
1097/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1098static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1099 ObjCMethodDecl *OMD,
1100 ObjCIvarDecl *ivar,
1101 llvm::Constant *AtomicHelperFn) {
1102 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1103 // AtomicHelperFn);
1104 CallArgList args;
1105
1106 // The first argument is the address of the ivar.
1107 llvm::Value *ivarAddr =
1108 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001109 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001110 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1111 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1112
1113 // The second argument is the address of the parameter variable.
1114 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001115 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001116 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001117 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001118 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1119 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1120
1121 // Third argument is the helper function.
1122 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1123
John McCallb92ab1a2016-10-26 23:46:34 +00001124 llvm::Constant *fn =
David Chisnall0d75e062012-12-17 18:54:24 +00001125 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001126 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001127 CGF.EmitCall(
1128 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001129 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001130}
1131
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001132
John McCallf4528ae2011-09-13 03:34:09 +00001133static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1134 Expr *setter = PID->getSetterCXXAssignment();
1135 if (!setter) return true;
1136
1137 // Sema only makes only of these when the ivar has a C++ class type,
1138 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001139
1140 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001141 // This also implies that there's nothing non-trivial going on with
1142 // the arguments, because operator= can only be trivial if it's a
1143 // synthesized assignment operator and therefore both parameters are
1144 // references.
1145 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001146 if (const FunctionDecl *callee
1147 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1148 if (callee->isTrivial())
1149 return true;
1150 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001151 }
John McCall7f16c422011-09-10 09:17:20 +00001152
John McCallf4528ae2011-09-13 03:34:09 +00001153 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001154 return false;
1155}
1156
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001157static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001159 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001160 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001161}
1162
John McCall7f16c422011-09-10 09:17:20 +00001163void
1164CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001165 const ObjCPropertyImplDecl *propImpl,
1166 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001167 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001168 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001169 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001170
1171 // Just use the setter expression if Sema gave us one and it's
1172 // non-trivial.
1173 if (!hasTrivialSetExpr(propImpl)) {
1174 if (!AtomicHelperFn)
1175 // If non-atomic, assignment is called directly.
1176 EmitStmt(propImpl->getSetterCXXAssignment());
1177 else
1178 // If atomic, assignment is called via a locking api.
1179 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1180 AtomicHelperFn);
1181 return;
1182 }
John McCall7f16c422011-09-10 09:17:20 +00001183
John McCallf4528ae2011-09-13 03:34:09 +00001184 PropertyImplStrategy strategy(CGM, propImpl);
1185 switch (strategy.getKind()) {
1186 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001187 // We don't need to do anything for a zero-size struct.
1188 if (strategy.getIvarSize().isZero())
1189 return;
1190
John McCall7f416cc2015-09-08 08:05:57 +00001191 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001192
John McCallf4528ae2011-09-13 03:34:09 +00001193 LValue ivarLValue =
1194 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001195 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001196
John McCallf4528ae2011-09-13 03:34:09 +00001197 // Currently, all atomic accesses have to be through integer
1198 // types, so there's no point in trying to pick a prettier type.
1199 llvm::Type *bitcastType =
1200 llvm::Type::getIntNTy(getLLVMContext(),
1201 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001202
1203 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001204 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1205 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001206
1207 // This bitcast load is likely to cause some nasty IR.
1208 llvm::Value *load = Builder.CreateLoad(argAddr);
1209
1210 // Perform an atomic store. There are no memory ordering requirements.
1211 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001212 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001213 return;
1214 }
1215
1216 case PropertyImplStrategy::GetSetProperty:
1217 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001218
John McCallb92ab1a2016-10-26 23:46:34 +00001219 llvm::Constant *setOptimizedPropertyFn = nullptr;
1220 llvm::Constant *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001221 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001222 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001223 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001224 CGM.getObjCRuntime()
1225 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1226 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001227 if (!setOptimizedPropertyFn) {
1228 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1229 return;
1230 }
John McCall7f16c422011-09-10 09:17:20 +00001231 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001232 else {
1233 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1234 if (!setPropertyFn) {
1235 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1236 return;
1237 }
1238 }
1239
John McCall7f16c422011-09-10 09:17:20 +00001240 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1241 // <is-atomic>, <is-copy>).
1242 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001243 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001244 llvm::Value *self =
1245 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1246 llvm::Value *ivarOffset =
1247 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001248 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1249 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1250 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001251
1252 CallArgList args;
1253 args.add(RValue::get(self), getContext().getObjCIdType());
1254 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001255 if (setOptimizedPropertyFn) {
1256 args.add(RValue::get(arg), getContext().getObjCIdType());
1257 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001258 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001259 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001260 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001261 } else {
1262 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1263 args.add(RValue::get(arg), getContext().getObjCIdType());
1264 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1265 getContext().BoolTy);
1266 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1267 getContext().BoolTy);
1268 // FIXME: We shouldn't need to get the function info here, the runtime
1269 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001270 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001271 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001272 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001273 }
1274
John McCall7f16c422011-09-10 09:17:20 +00001275 return;
1276 }
1277
John McCallf4528ae2011-09-13 03:34:09 +00001278 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001279 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001280 return;
John McCallf4528ae2011-09-13 03:34:09 +00001281
1282 case PropertyImplStrategy::Expression:
1283 break;
John McCall7f16c422011-09-10 09:17:20 +00001284 }
1285
1286 // Otherwise, fake up some ASTs and emit a normal assignment.
1287 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001288 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1289 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001290 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1291 selfDecl->getType(), CK_LValueToRValue, &self,
1292 VK_RValue);
1293 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001294 SourceLocation(), SourceLocation(),
1295 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001296
1297 ParmVarDecl *argDecl = *setterMethod->param_begin();
1298 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001299 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001300 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1301 argType.getUnqualifiedType(), CK_LValueToRValue,
1302 &arg, VK_RValue);
1303
1304 // The property type can differ from the ivar type in some situations with
1305 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1306 // The following absurdity is just to ensure well-formed IR.
1307 CastKind argCK = CK_NoOp;
1308 if (ivarRef.getType()->isObjCObjectPointerType()) {
1309 if (argLoad.getType()->isObjCObjectPointerType())
1310 argCK = CK_BitCast;
1311 else if (argLoad.getType()->isBlockPointerType())
1312 argCK = CK_BlockPointerToObjCPointerCast;
1313 else
1314 argCK = CK_CPointerToObjCPointerCast;
1315 } else if (ivarRef.getType()->isBlockPointerType()) {
1316 if (argLoad.getType()->isBlockPointerType())
1317 argCK = CK_BitCast;
1318 else
1319 argCK = CK_AnyPointerToBlockPointerCast;
1320 } else if (ivarRef.getType()->isPointerType()) {
1321 argCK = CK_BitCast;
1322 }
1323 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1324 ivarRef.getType(), argCK, &argLoad,
1325 VK_RValue);
1326 Expr *finalArg = &argLoad;
1327 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1328 argLoad.getType()))
1329 finalArg = &argCast;
1330
1331
1332 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1333 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001334 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001335 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001336}
1337
James Dennettbe302452012-06-15 22:10:14 +00001338/// \brief Generate an Objective-C property setter function.
1339///
1340/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001341/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001342void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1343 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001344 llvm::Constant *AtomicHelperFn =
1345 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001346 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1347 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1348 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001349 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001350
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001351 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001352
1353 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001354}
1355
John McCall6a4fa522011-03-22 07:05:39 +00001356namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001357 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001358 private:
1359 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001360 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001361 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001362 bool useEHCleanupForArray;
1363 public:
1364 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1365 CodeGenFunction::Destroyer *destroyer,
1366 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001367 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001368 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001369
Craig Topper4f12f102014-03-12 06:41:41 +00001370 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001371 LValue lvalue
1372 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1373 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001374 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001375 }
1376 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001377}
John McCall6a4fa522011-03-22 07:05:39 +00001378
John McCall4bd0fb12011-07-12 16:41:08 +00001379/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1380static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001381 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001382 QualType type) {
1383 llvm::Value *null = getNullForVariable(addr);
1384 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1385}
John McCall31168b02011-06-15 23:02:42 +00001386
John McCall6a4fa522011-03-22 07:05:39 +00001387static void emitCXXDestructMethod(CodeGenFunction &CGF,
1388 ObjCImplementationDecl *impl) {
1389 CodeGenFunction::RunCleanupsScope scope(CGF);
1390
1391 llvm::Value *self = CGF.LoadObjCSelf();
1392
Jordy Rosea91768e2011-07-22 02:08:32 +00001393 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1394 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001395 ivar; ivar = ivar->getNextIvar()) {
1396 QualType type = ivar->getType();
1397
John McCall6a4fa522011-03-22 07:05:39 +00001398 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001399 QualType::DestructionKind dtorKind = type.isDestructedType();
1400 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001401
Craig Topper8a13c412014-05-21 05:09:00 +00001402 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001403
John McCall4bd0fb12011-07-12 16:41:08 +00001404 // Use a call to objc_storeStrong to destroy strong ivars, for the
1405 // general benefit of the tools.
1406 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001407 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001408
John McCall4bd0fb12011-07-12 16:41:08 +00001409 // Otherwise use the default for the destruction kind.
1410 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001411 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001412 }
John McCall4bd0fb12011-07-12 16:41:08 +00001413
1414 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1415
1416 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1417 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001418 }
1419
1420 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1421}
1422
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001423void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1424 ObjCMethodDecl *MD,
1425 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001426 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001427 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001428
1429 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001430 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001431 // Suppress the final autorelease in ARC.
1432 AutoreleaseResult = false;
1433
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001434 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001435 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001436 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001437 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1438 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001439 EmitAggExpr(IvarInit->getInit(),
1440 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001441 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001442 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001443 }
1444 // constructor returns 'self'.
1445 CodeGenTypes &Types = CGM.getTypes();
1446 QualType IdTy(CGM.getContext().getObjCIdType());
1447 llvm::Value *SelfAsId =
1448 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1449 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001450
1451 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001452 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001453 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001454 }
1455 FinishFunction();
1456}
1457
Daniel Dunbara08dff12008-09-24 04:04:31 +00001458llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001459 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1460 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1461 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001462 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001463}
1464
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001465QualType CodeGenFunction::TypeOfSelfObject() {
1466 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1467 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001468 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1469 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001470 return PTy->getPointeeType();
1471}
1472
Chris Lattnerd4808922009-03-22 21:03:39 +00001473void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
John McCallb92ab1a2016-10-26 23:46:34 +00001474 llvm::Constant *EnumerationMutationFnPtr =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001475 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001476 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001477 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1478 return;
1479 }
John McCallb92ab1a2016-10-26 23:46:34 +00001480 CGCallee EnumerationMutationFn =
1481 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001482
Devang Pateld2d66652011-01-19 01:36:36 +00001483 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001484 if (DI)
1485 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001486
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001487 RunCleanupsScope ForScope(*this);
1488
Kuba Mracek82c21752017-04-14 01:00:03 +00001489 // The local variable comes into scope immediately.
1490 AutoVarEmission variable = AutoVarEmission::invalid();
1491 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1492 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1493
John McCall1c926b72011-01-07 01:49:06 +00001494 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001495
Anders Carlsson75658592008-08-31 02:33:12 +00001496 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001497 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001498 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001499 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001500
Anders Carlsson75658592008-08-31 02:33:12 +00001501 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001502 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001503
John McCall1c926b72011-01-07 01:49:06 +00001504 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001505 IdentifierInfo *II[] = {
1506 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1507 &CGM.getContext().Idents.get("objects"),
1508 &CGM.getContext().Idents.get("count")
1509 };
1510 Selector FastEnumSel =
1511 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001512
1513 QualType ItemsTy =
1514 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001515 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001516 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001517 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCall53848232011-07-27 01:07:15 +00001519 // Emit the collection pointer. In ARC, we do a retain.
1520 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001521 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001522 Collection = EmitARCRetainScalarExpr(S.getCollection());
1523
1524 // Enter a cleanup to do the release.
1525 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1526 } else {
1527 Collection = EmitScalarExpr(S.getCollection());
1528 }
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall91e82dd2011-08-05 00:14:38 +00001530 // The 'continue' label needs to appear within the cleanup for the
1531 // collection object.
1532 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1533
John McCall1c926b72011-01-07 01:49:06 +00001534 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001535 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001536
1537 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001538 Args.add(RValue::get(StatePtr.getPointer()),
1539 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001540
John McCall1c926b72011-01-07 01:49:06 +00001541 // The second argument is a temporary array with space for NumItems
1542 // pointers. We'll actually be loading elements from the array
1543 // pointer written into the control state; this buffer is so that
1544 // collections that *aren't* backed by arrays can still queue up
1545 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001546 Args.add(RValue::get(ItemsPtr.getPointer()),
1547 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCall1c926b72011-01-07 01:49:06 +00001549 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001550 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1551 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1552 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001553
John McCall1c926b72011-01-07 01:49:06 +00001554 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001555 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001556 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1557 getContext().getNSUIntegerType(),
1558 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001559
John McCall1c926b72011-01-07 01:49:06 +00001560 // The initial number of objects that were returned in the buffer.
1561 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001562
John McCall1c926b72011-01-07 01:49:06 +00001563 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1564 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001565
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001566 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001567
John McCall1c926b72011-01-07 01:49:06 +00001568 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001569 // empty; skip all this. Set the branch weight assuming this has the same
1570 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001571 uint64_t EntryCount = getCurrentProfileCount();
1572 Builder.CreateCondBr(
1573 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1574 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001575 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001576
John McCall1c926b72011-01-07 01:49:06 +00001577 // Otherwise, initialize the loop.
1578 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001579
John McCall1c926b72011-01-07 01:49:06 +00001580 // Save the initial mutations value. This is the value at an
1581 // address that was written into the state object by
1582 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001583 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1584 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1585 llvm::Value *StateMutationsPtr
1586 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCall1c926b72011-01-07 01:49:06 +00001588 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001589 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1590 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001591
John McCall1c926b72011-01-07 01:49:06 +00001592 // Start looping. This is the point we return to whenever we have a
1593 // fresh, non-empty batch of objects.
1594 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1595 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001596
John McCall1c926b72011-01-07 01:49:06 +00001597 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001598 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001599 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001600
John McCall1c926b72011-01-07 01:49:06 +00001601 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001602 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001603 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001604
Justin Bogner66242d62015-04-23 23:06:47 +00001605 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001606
John McCall1c926b72011-01-07 01:49:06 +00001607 // Check whether the mutations value has changed from where it was
1608 // at start. StateMutationsPtr should actually be invariant between
1609 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001610 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001611 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001612 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1613 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001614
John McCall1c926b72011-01-07 01:49:06 +00001615 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001616 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001617
John McCall1c926b72011-01-07 01:49:06 +00001618 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1619 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall1c926b72011-01-07 01:49:06 +00001621 // If so, call the enumeration-mutation function.
1622 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001623 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001624 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001625 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001626 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001627 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001628 // FIXME: We shouldn't need to get the function info here, the runtime already
1629 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001630 EmitCall(
1631 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001632 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001633
John McCall1c926b72011-01-07 01:49:06 +00001634 // Otherwise, or if the mutation function returns, just continue.
1635 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001636
John McCall1c926b72011-01-07 01:49:06 +00001637 // Initialize the element variable.
1638 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001639 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001640 LValue elementLValue;
1641 QualType elementType;
1642 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001643 // Initialize the variable, in case it's a __block variable or something.
1644 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001645
John McCall9e2e22f2011-02-22 07:16:58 +00001646 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001647 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001648 VK_LValue, SourceLocation());
1649 elementLValue = EmitLValue(&tempDRE);
1650 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001651 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001652
1653 if (D->isARCPseudoStrong())
1654 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001655 } else {
1656 elementLValue = LValue(); // suppress warning
1657 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001658 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001659 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001660 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001661
1662 // Fetch the buffer out of the enumeration state.
1663 // TODO: this pointer should actually be invariant between
1664 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001665 Address StateItemsPtr = Builder.CreateStructGEP(
1666 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001667 llvm::Value *EnumStateItems =
1668 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001669
John McCall1c926b72011-01-07 01:49:06 +00001670 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001671 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001672 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001673 llvm::Value *CurrentItem =
1674 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001675
John McCall1c926b72011-01-07 01:49:06 +00001676 // Cast that value to the right type.
1677 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1678 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001679
John McCall1c926b72011-01-07 01:49:06 +00001680 // Make sure we have an l-value. Yes, this gets evaluated every
1681 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001682 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001683 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001684 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001685 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001686 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1687 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall9e2e22f2011-02-22 07:16:58 +00001690 // If we do have an element variable, this assignment is the end of
1691 // its initialization.
1692 if (elementIsVariable)
1693 EmitAutoVarCleanups(variable);
1694
John McCall1c926b72011-01-07 01:49:06 +00001695 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001696 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001697 {
1698 RunCleanupsScope Scope(*this);
1699 EmitStmt(S.getBody());
1700 }
Anders Carlsson75658592008-08-31 02:33:12 +00001701 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCall1c926b72011-01-07 01:49:06 +00001703 // Destroy the element variable now.
1704 elementVariableScope.ForceCleanup();
1705
1706 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001707 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001708
John McCall1c926b72011-01-07 01:49:06 +00001709 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001710
John McCall1c926b72011-01-07 01:49:06 +00001711 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001712 llvm::Value *indexPlusOne =
1713 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001714
John McCall1c926b72011-01-07 01:49:06 +00001715 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001716 // Set the branch weights based on the simplifying assumption that this is
1717 // like a while-loop, i.e., ignoring that the false branch fetches more
1718 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001719 Builder.CreateCondBr(
1720 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001721 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001722
1723 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1724 count->addIncoming(count, AfterBody.getBlock());
1725
1726 // Otherwise, we have to fetch more elements.
1727 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001728
1729 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001730 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1731 getContext().getNSUIntegerType(),
1732 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001733
John McCall1c926b72011-01-07 01:49:06 +00001734 // If we got a zero count, we're done.
1735 llvm::Value *refetchCount = CountRV.getScalarVal();
1736
1737 // (note that the message send might split FetchMoreBB)
1738 index->addIncoming(zero, Builder.GetInsertBlock());
1739 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1740
1741 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1742 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001743
Anders Carlsson75658592008-08-31 02:33:12 +00001744 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001745 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001746
John McCall9e2e22f2011-02-22 07:16:58 +00001747 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001748 // If the element was not a declaration, set it to be null.
1749
John McCall1c926b72011-01-07 01:49:06 +00001750 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1751 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001752 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001753 }
1754
Eric Christopher7cdf9482011-10-13 21:45:18 +00001755 if (DI)
1756 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001757
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001758 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001759 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001760}
1761
Mike Stump11289f42009-09-09 15:08:12 +00001762void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001763 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001764}
1765
Mike Stump11289f42009-09-09 15:08:12 +00001766void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001767 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1768}
1769
Chris Lattnere132e242008-11-15 21:26:17 +00001770void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001771 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001772 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001773}
1774
John McCall31168b02011-06-15 23:02:42 +00001775namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001776 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001777 CallObjCRelease(llvm::Value *object) : object(object) {}
1778 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001779
Craig Topper4f12f102014-03-12 06:41:41 +00001780 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001781 // Releases at the end of the full-expression are imprecise.
1782 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001783 }
1784 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001785}
John McCall31168b02011-06-15 23:02:42 +00001786
John McCall2d637d22011-09-10 06:18:15 +00001787/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001788/// release at the end of the full-expression.
1789llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1790 llvm::Value *object) {
1791 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001792 // conditional.
1793 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001794 return object;
1795}
1796
1797llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1798 llvm::Value *value) {
1799 return EmitARCRetainAutorelease(type, value);
1800}
1801
John McCalleff18842013-03-23 02:35:54 +00001802/// Given a number of pointers, inform the optimizer that they're
1803/// being intrinsically used up until this point in the program.
1804void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
John McCallb04ecb72015-10-21 18:06:43 +00001805 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
John McCalleff18842013-03-23 02:35:54 +00001806 if (!fn) {
1807 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001808 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001809 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1810 }
1811
1812 // This isn't really a "runtime" function, but as an intrinsic it
1813 // doesn't really matter as long as we align things up.
1814 EmitNounwindRuntimeCall(fn, values);
1815}
1816
John McCall31168b02011-06-15 23:02:42 +00001817
1818static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001819 llvm::FunctionType *FTy,
1820 StringRef Name) {
1821 llvm::Constant *RTF = CGM.CreateRuntimeFunction(FTy, Name);
John McCall31168b02011-06-15 23:02:42 +00001822
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001823 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001824 // If the target runtime doesn't naturally support ARC, emit weak
1825 // references to the runtime support library. We don't really
1826 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001827 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1828 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001829 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1830 } else if (Name == "objc_retain" || Name == "objc_release") {
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001831 // If we have Native ARC, set nonlazybind attribute for these APIs for
1832 // performance.
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001833 F->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001834 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001835 }
John McCall31168b02011-06-15 23:02:42 +00001836
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001837 return RTF;
John McCall31168b02011-06-15 23:02:42 +00001838}
1839
1840/// Perform an operation having the signature
1841/// i8* (i8*)
1842/// where a null input causes a no-op and returns null.
1843static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1844 llvm::Value *value,
1845 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001846 StringRef fnName,
1847 bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001848 if (isa<llvm::ConstantPointerNull>(value))
1849 return value;
John McCall31168b02011-06-15 23:02:42 +00001850
1851 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001852 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001853 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001854 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1855 }
1856
1857 // Cast the argument to 'id'.
Pete Cooper94867712016-03-21 20:50:03 +00001858 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001859 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1860
1861 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001862 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001863 if (isTailCall)
1864 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001865
1866 // Cast the result back to the original type.
1867 return CGF.Builder.CreateBitCast(call, origType);
1868}
1869
1870/// Perform an operation having the following signature:
1871/// i8* (i8**)
1872static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001873 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001874 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001875 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001876 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001877 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001878 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001879 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1880 }
1881
1882 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001883 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001884 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1885
1886 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001887 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001888
1889 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001890 if (origType != CGF.Int8PtrTy)
1891 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001892
1893 return result;
1894}
1895
1896/// Perform an operation having the following signature:
1897/// i8* (i8**, i8*)
1898static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001899 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001900 llvm::Value *value,
1901 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001902 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001903 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001904 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001905
1906 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001907 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001908
Chris Lattner2192fe52011-07-18 04:24:23 +00001909 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001910 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1911 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1912 }
1913
Chris Lattner2192fe52011-07-18 04:24:23 +00001914 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001915
John McCall882987f2013-02-28 19:01:20 +00001916 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001917 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001918 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1919 };
1920 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001921
Craig Topper8a13c412014-05-21 05:09:00 +00001922 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001923
1924 return CGF.Builder.CreateBitCast(result, origType);
1925}
1926
1927/// Perform an operation having the following signature:
1928/// void (i8**, i8**)
1929static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001930 Address dst,
1931 Address src,
John McCall31168b02011-06-15 23:02:42 +00001932 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001933 StringRef fnName) {
John McCall7f416cc2015-09-08 08:05:57 +00001934 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00001935
1936 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001937 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1938
Chris Lattner2192fe52011-07-18 04:24:23 +00001939 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001940 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1941 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1942 }
1943
John McCall882987f2013-02-28 19:01:20 +00001944 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001945 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1946 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00001947 };
1948 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001949}
1950
1951/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001952/// call i8* \@objc_retain(i8* %value)
1953/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001954llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1955 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001956 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001957 else
1958 return EmitARCRetainNonBlock(value);
1959}
1960
1961/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001962/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00001963llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1964 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00001965 CGM.getObjCEntrypoints().objc_retain,
John McCall31168b02011-06-15 23:02:42 +00001966 "objc_retain");
1967}
1968
1969/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001970/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001971///
1972/// \param mandatory - If false, emit the call with metadata
1973/// indicating that it's okay for the optimizer to eliminate this call
1974/// if it can prove that the block never escapes except down the stack.
1975llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1976 bool mandatory) {
1977 llvm::Value *result
Pete Cooper94867712016-03-21 20:50:03 +00001978 = emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00001979 CGM.getObjCEntrypoints().objc_retainBlock,
John McCallff613032011-10-04 06:23:45 +00001980 "objc_retainBlock");
1981
1982 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1983 // tell the optimizer that it doesn't need to do this copy if the
1984 // block doesn't escape, where being passed as an argument doesn't
1985 // count as escaping.
1986 if (!mandatory && isa<llvm::Instruction>(result)) {
1987 llvm::CallInst *call
1988 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00001989 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00001990
John McCallff613032011-10-04 06:23:45 +00001991 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001992 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00001993 }
1994
1995 return result;
John McCall31168b02011-06-15 23:02:42 +00001996}
1997
John McCalle399e5b2016-01-27 18:32:30 +00001998static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00001999 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002000 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002001 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002002 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002003 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002004 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002005 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002006 .getARCRetainAutoreleasedReturnValueMarker();
2007
2008 // If we have an empty assembly string, there's nothing to do.
2009 if (assembly.empty()) {
2010
2011 // Otherwise, at -O0, build an inline asm that we're going to call
2012 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002013 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002014 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002015 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00002016
2017 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2018
2019 // If we're at -O1 and above, we don't want to litter the code
2020 // with this marker yet, so leave a breadcrumb for the ARC
2021 // optimizer to pick up.
2022 } else {
2023 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002024 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002025 "clang.arc.retainAutoreleasedReturnValueMarker");
2026 assert(metadata->getNumOperands() <= 1);
2027 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002028 auto &ctx = CGF.getLLVMContext();
2029 metadata->addOperand(llvm::MDNode::get(ctx,
2030 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002031 }
2032 }
2033 }
2034
2035 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002036 if (marker)
John McCalle399e5b2016-01-27 18:32:30 +00002037 CGF.Builder.CreateCall(marker);
2038}
John McCall31168b02011-06-15 23:02:42 +00002039
John McCalle399e5b2016-01-27 18:32:30 +00002040/// Retain the given object which is the result of a function call.
2041/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2042///
2043/// Yes, this function name is one character away from a different
2044/// call with completely different semantics.
2045llvm::Value *
2046CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2047 emitAutoreleasedReturnValueMarker(*this);
Pete Cooper94867712016-03-21 20:50:03 +00002048 return emitARCValueOperation(*this, value,
John McCalle399e5b2016-01-27 18:32:30 +00002049 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
John McCall31168b02011-06-15 23:02:42 +00002050 "objc_retainAutoreleasedReturnValue");
2051}
2052
John McCalle399e5b2016-01-27 18:32:30 +00002053/// Claim a possibly-autoreleased return value at +0. This is only
2054/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002055/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002056/// the value is ignored, or when it is being assigned to an
2057/// __unsafe_unretained variable.
2058///
2059/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2060llvm::Value *
2061CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2062 emitAutoreleasedReturnValueMarker(*this);
Pete Cooper94867712016-03-21 20:50:03 +00002063 return emitARCValueOperation(*this, value,
John McCalle399e5b2016-01-27 18:32:30 +00002064 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
2065 "objc_unsafeClaimAutoreleasedReturnValue");
2066}
2067
John McCall31168b02011-06-15 23:02:42 +00002068/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002069/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002070void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2071 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002072 if (isa<llvm::ConstantPointerNull>(value)) return;
2073
John McCallb04ecb72015-10-21 18:06:43 +00002074 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002075 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002076 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002077 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002078 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2079 }
2080
2081 // Cast the argument to 'id'.
2082 value = Builder.CreateBitCast(value, Int8PtrTy);
2083
2084 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002085 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002086
John McCallcdda29c2013-03-13 03:10:54 +00002087 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002088 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002089 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002090 }
2091}
2092
John McCalle68b8f42012-10-17 02:28:37 +00002093/// Destroy a __strong variable.
2094///
2095/// At -O0, emit a call to store 'null' into the address;
2096/// instrumenting tools prefer this because the address is exposed,
2097/// but it's relatively cumbersome to optimize.
2098///
2099/// At -O1 and above, just load and call objc_release.
2100///
2101/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002102void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002103 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002104 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002105 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002106 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2107 return;
2108 }
2109
2110 llvm::Value *value = Builder.CreateLoad(addr);
2111 EmitARCRelease(value, precise);
2112}
2113
John McCall31168b02011-06-15 23:02:42 +00002114/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002115/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002116llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002117 llvm::Value *value,
2118 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002119 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002120
John McCallb04ecb72015-10-21 18:06:43 +00002121 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002122 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002123 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002124 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002125 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2126 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2127 }
2128
John McCall882987f2013-02-28 19:01:20 +00002129 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002130 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002131 Builder.CreateBitCast(value, Int8PtrTy)
2132 };
2133 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002134
Craig Topper8a13c412014-05-21 05:09:00 +00002135 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002136 return value;
2137}
2138
2139/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002140/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002141/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002142llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002143 llvm::Value *newValue,
2144 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002145 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002146 bool isBlock = type->isBlockPointerType();
2147
2148 // Use a store barrier at -O0 unless this is a block type or the
2149 // lvalue is inadequately aligned.
2150 if (shouldUseFusedARCCalls() &&
2151 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002152 (dst.getAlignment().isZero() ||
2153 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002154 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2155 }
2156
2157 // Otherwise, split it out.
2158
2159 // Retain the new value.
2160 newValue = EmitARCRetain(type, newValue);
2161
2162 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002163 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002164
2165 // Store. We do this before the release so that any deallocs won't
2166 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002167 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002168
2169 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002170 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002171
2172 return newValue;
2173}
2174
2175/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002176/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002177llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2178 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002179 CGM.getObjCEntrypoints().objc_autorelease,
John McCall31168b02011-06-15 23:02:42 +00002180 "objc_autorelease");
2181}
2182
2183/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002184/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002185llvm::Value *
2186CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Cooper94867712016-03-21 20:50:03 +00002187 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002188 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002189 "objc_autoreleaseReturnValue",
2190 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002191}
2192
2193/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002194/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002195llvm::Value *
2196CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Cooper94867712016-03-21 20:50:03 +00002197 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002198 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002199 "objc_retainAutoreleaseReturnValue",
2200 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002201}
2202
2203/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002204/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002205/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002206/// %retain = call i8* \@objc_retainBlock(i8* %value)
2207/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002208llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2209 llvm::Value *value) {
2210 if (!type->isBlockPointerType())
2211 return EmitARCRetainAutoreleaseNonBlock(value);
2212
2213 if (isa<llvm::ConstantPointerNull>(value)) return value;
2214
Chris Lattner2192fe52011-07-18 04:24:23 +00002215 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002216 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002217 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002218 value = EmitARCAutorelease(value);
2219 return Builder.CreateBitCast(value, origType);
2220}
2221
2222/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002223/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002224llvm::Value *
2225CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Cooper94867712016-03-21 20:50:03 +00002226 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002227 CGM.getObjCEntrypoints().objc_retainAutorelease,
John McCall31168b02011-06-15 23:02:42 +00002228 "objc_retainAutorelease");
2229}
2230
John McCallb04ecb72015-10-21 18:06:43 +00002231/// i8* \@objc_loadWeak(i8** %addr)
2232/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2233llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2234 return emitARCLoadOperation(*this, addr,
2235 CGM.getObjCEntrypoints().objc_loadWeak,
2236 "objc_loadWeak");
2237}
2238
James Dennett14c41ea2012-06-22 05:41:30 +00002239/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002240llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002241 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002242 CGM.getObjCEntrypoints().objc_loadWeakRetained,
John McCall31168b02011-06-15 23:02:42 +00002243 "objc_loadWeakRetained");
2244}
2245
James Dennett14c41ea2012-06-22 05:41:30 +00002246/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002247/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002248llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002249 llvm::Value *value,
2250 bool ignored) {
2251 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002252 CGM.getObjCEntrypoints().objc_storeWeak,
John McCall31168b02011-06-15 23:02:42 +00002253 "objc_storeWeak", ignored);
2254}
2255
James Dennett14c41ea2012-06-22 05:41:30 +00002256/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002257/// Returns %value. %addr is known to not have a current weak entry.
2258/// Essentially equivalent to:
2259/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002260void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002261 // If we're initializing to null, just write null to memory; no need
2262 // to get the runtime involved. But don't do this if optimization
2263 // is enabled, because accounting for this would make the optimizer
2264 // much more complicated.
2265 if (isa<llvm::ConstantPointerNull>(value) &&
2266 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2267 Builder.CreateStore(value, addr);
2268 return;
2269 }
2270
2271 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002272 CGM.getObjCEntrypoints().objc_initWeak,
John McCall31168b02011-06-15 23:02:42 +00002273 "objc_initWeak", /*ignored*/ true);
2274}
2275
James Dennett14c41ea2012-06-22 05:41:30 +00002276/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002277/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002278void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCallb04ecb72015-10-21 18:06:43 +00002279 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002280 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002281 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002282 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002283 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2284 }
2285
2286 // Cast the argument to 'id*'.
2287 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2288
John McCall7f416cc2015-09-08 08:05:57 +00002289 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002290}
2291
James Dennett14c41ea2012-06-22 05:41:30 +00002292/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002293/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2294/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002295void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002296 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002297 CGM.getObjCEntrypoints().objc_moveWeak,
John McCall31168b02011-06-15 23:02:42 +00002298 "objc_moveWeak");
2299}
2300
James Dennett14c41ea2012-06-22 05:41:30 +00002301/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002302/// Disregards the current value in %dest. Essentially
2303/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002304void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002305 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002306 CGM.getObjCEntrypoints().objc_copyWeak,
John McCall31168b02011-06-15 23:02:42 +00002307 "objc_copyWeak");
2308}
2309
2310/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002311/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002312llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
John McCallb04ecb72015-10-21 18:06:43 +00002313 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002314 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002315 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002316 llvm::FunctionType::get(Int8PtrTy, false);
2317 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2318 }
2319
John McCall882987f2013-02-28 19:01:20 +00002320 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002321}
2322
2323/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002324/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002325void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2326 assert(value->getType() == Int8PtrTy);
2327
John McCallb04ecb72015-10-21 18:06:43 +00002328 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
John McCall31168b02011-06-15 23:02:42 +00002329 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002330 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002331 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002332
2333 // We don't want to use a weak import here; instead we should not
2334 // fall into this path.
2335 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2336 }
2337
John McCallb7ff6db2013-04-16 21:29:40 +00002338 // objc_autoreleasePoolPop can throw.
2339 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002340}
2341
2342/// Produce the code to do an MRR version objc_autoreleasepool_push.
2343/// Which is: [[NSAutoreleasePool alloc] init];
2344/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2345/// init is declared as: - (id) init; in its NSObject super class.
2346///
2347llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2348 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002349 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002350 // [NSAutoreleasePool alloc]
2351 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2352 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2353 CallArgList Args;
2354 RValue AllocRV =
2355 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2356 getContext().getObjCIdType(),
2357 AllocSel, Receiver, Args);
2358
2359 // [Receiver init]
2360 Receiver = AllocRV.getScalarVal();
2361 II = &CGM.getContext().Idents.get("init");
2362 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2363 RValue InitRV =
2364 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2365 getContext().getObjCIdType(),
2366 InitSel, Receiver, Args);
2367 return InitRV.getScalarVal();
2368}
2369
2370/// Produce the code to do a primitive release.
2371/// [tmp drain];
2372void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2373 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2374 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2375 CallArgList Args;
2376 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2377 getContext().VoidTy, DrainSel, Arg, Args);
2378}
2379
John McCall82fe67b2011-07-09 01:37:26 +00002380void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002381 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002382 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002383 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002384}
2385
2386void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002387 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002388 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002389 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002390}
2391
2392void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002393 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002394 QualType type) {
2395 CGF.EmitARCDestroyWeak(addr);
2396}
2397
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002398void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2399 QualType type) {
2400 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2401 CGF.EmitARCIntrinsicUse(value);
2402}
2403
John McCall31168b02011-06-15 23:02:42 +00002404namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002405 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002406 llvm::Value *Token;
2407
2408 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2409
Craig Topper4f12f102014-03-12 06:41:41 +00002410 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002411 CGF.EmitObjCAutoreleasePoolPop(Token);
2412 }
2413 };
David Blaikie7e70d682015-08-18 22:40:54 +00002414 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002415 llvm::Value *Token;
2416
2417 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2418
Craig Topper4f12f102014-03-12 06:41:41 +00002419 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002420 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2421 }
2422 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002423}
John McCall31168b02011-06-15 23:02:42 +00002424
2425void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002426 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002427 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2428 else
2429 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2430}
2431
John McCall31168b02011-06-15 23:02:42 +00002432static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2433 LValue lvalue,
2434 QualType type) {
2435 switch (type.getObjCLifetime()) {
2436 case Qualifiers::OCL_None:
2437 case Qualifiers::OCL_ExplicitNone:
2438 case Qualifiers::OCL_Strong:
2439 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002440 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2441 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002442 false);
2443
2444 case Qualifiers::OCL_Weak:
2445 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2446 true);
2447 }
2448
2449 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002450}
2451
2452static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2453 const Expr *e) {
2454 e = e->IgnoreParens();
2455 QualType type = e->getType();
2456
John McCall154a2fd2011-08-30 00:57:29 +00002457 // If we're loading retained from a __strong xvalue, we can avoid
2458 // an extra retain/release pair by zeroing out the source of this
2459 // "move" operation.
2460 if (e->isXValue() &&
2461 !type.isConstQualified() &&
2462 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2463 // Emit the lvalue.
2464 LValue lv = CGF.EmitLValue(e);
2465
2466 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002467 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2468 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002469
2470 // Set the source pointer to NULL.
2471 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2472
2473 return TryEmitResult(result, true);
2474 }
2475
John McCall31168b02011-06-15 23:02:42 +00002476 // As a very special optimization, in ARC++, if the l-value is the
2477 // result of a non-volatile assignment, do a simple retain of the
2478 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002479 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002480 !type.isVolatileQualified() &&
2481 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2482 isa<BinaryOperator>(e) &&
2483 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2484 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2485
2486 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2487}
2488
John McCalle399e5b2016-01-27 18:32:30 +00002489typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2490 llvm::Value *value)>
2491 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002492
John McCalle399e5b2016-01-27 18:32:30 +00002493/// Insert code immediately after a call.
2494static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2495 llvm::Value *value,
2496 ValueTransform doAfterCall,
2497 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002498 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2499 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2500
2501 // Place the retain immediately following the call.
2502 CGF.Builder.SetInsertPoint(call->getParent(),
2503 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002504 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002505
2506 CGF.Builder.restoreIP(ip);
2507 return value;
2508 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2509 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2510
2511 // Place the retain at the beginning of the normal destination block.
2512 llvm::BasicBlock *BB = invoke->getNormalDest();
2513 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002514 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002515
2516 CGF.Builder.restoreIP(ip);
2517 return value;
2518
2519 // Bitcasts can arise because of related-result returns. Rewrite
2520 // the operand.
2521 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2522 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002523 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002524 bitcast->setOperand(0, operand);
2525 return bitcast;
2526
2527 // Generic fall-back case.
2528 } else {
2529 // Retain using the non-block variant: we never need to do a copy
2530 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002531 return doFallback(CGF, value);
2532 }
2533}
2534
2535/// Given that the given expression is some sort of call (which does
2536/// not return retained), emit a retain following it.
2537static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2538 const Expr *e) {
2539 llvm::Value *value = CGF.EmitScalarExpr(e);
2540 return emitARCOperationAfterCall(CGF, value,
2541 [](CodeGenFunction &CGF, llvm::Value *value) {
2542 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2543 },
2544 [](CodeGenFunction &CGF, llvm::Value *value) {
2545 return CGF.EmitARCRetainNonBlock(value);
2546 });
2547}
2548
2549/// Given that the given expression is some sort of call (which does
2550/// not return retained), perform an unsafeClaim following it.
2551static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2552 const Expr *e) {
2553 llvm::Value *value = CGF.EmitScalarExpr(e);
2554 return emitARCOperationAfterCall(CGF, value,
2555 [](CodeGenFunction &CGF, llvm::Value *value) {
2556 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2557 },
2558 [](CodeGenFunction &CGF, llvm::Value *value) {
2559 return value;
2560 });
2561}
2562
2563llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2564 bool allowUnsafeClaim) {
2565 if (allowUnsafeClaim &&
2566 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2567 return emitARCUnsafeClaimCallResult(*this, E);
2568 } else {
2569 llvm::Value *value = emitARCRetainCallResult(*this, E);
2570 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002571 }
2572}
2573
John McCallcd78e802011-09-10 01:16:55 +00002574/// Determine whether it might be important to emit a separate
2575/// objc_retain_block on the result of the given expression, or
2576/// whether it's okay to just emit it in a +1 context.
2577static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2578 assert(e->getType()->isBlockPointerType());
2579 e = e->IgnoreParens();
2580
2581 // For future goodness, emit block expressions directly in +1
2582 // contexts if we can.
2583 if (isa<BlockExpr>(e))
2584 return false;
2585
2586 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2587 switch (cast->getCastKind()) {
2588 // Emitting these operations in +1 contexts is goodness.
2589 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002590 case CK_ARCReclaimReturnedObject:
2591 case CK_ARCConsumeObject:
2592 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002593 return false;
2594
2595 // These operations preserve a block type.
2596 case CK_NoOp:
2597 case CK_BitCast:
2598 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2599
2600 // These operations are known to be bad (or haven't been considered).
2601 case CK_AnyPointerToBlockPointerCast:
2602 default:
2603 return true;
2604 }
2605 }
2606
2607 return true;
2608}
2609
John McCalle399e5b2016-01-27 18:32:30 +00002610namespace {
2611/// A CRTP base class for emitting expressions of retainable object
2612/// pointer type in ARC.
2613template <typename Impl, typename Result> class ARCExprEmitter {
2614protected:
2615 CodeGenFunction &CGF;
2616 Impl &asImpl() { return *static_cast<Impl*>(this); }
2617
2618 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2619
2620public:
2621 Result visit(const Expr *e);
2622 Result visitCastExpr(const CastExpr *e);
2623 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2624 Result visitBinaryOperator(const BinaryOperator *e);
2625 Result visitBinAssign(const BinaryOperator *e);
2626 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2627 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2628 Result visitBinAssignWeak(const BinaryOperator *e);
2629 Result visitBinAssignStrong(const BinaryOperator *e);
2630
2631 // Minimal implementation:
2632 // Result visitLValueToRValue(const Expr *e)
2633 // Result visitConsumeObject(const Expr *e)
2634 // Result visitExtendBlockObject(const Expr *e)
2635 // Result visitReclaimReturnedObject(const Expr *e)
2636 // Result visitCall(const Expr *e)
2637 // Result visitExpr(const Expr *e)
2638 //
2639 // Result emitBitCast(Result result, llvm::Type *resultType)
2640 // llvm::Value *getValueOfResult(Result result)
2641};
2642}
2643
2644/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002645///
2646/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002647template <typename Impl, typename Result>
2648Result
2649ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002650 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002651
2652 // Find the result expression.
2653 const Expr *resultExpr = E->getResultExpr();
2654 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002655 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002656
2657 for (PseudoObjectExpr::const_semantics_iterator
2658 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2659 const Expr *semantic = *i;
2660
2661 // If this semantic expression is an opaque value, bind it
2662 // to the result of its source expression.
2663 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2664 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2665 OVMA opaqueData;
2666
2667 // If this semantic is the result of the pseudo-object
2668 // expression, try to evaluate the source as +1.
2669 if (ov == resultExpr) {
2670 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002671 result = asImpl().visit(ov->getSourceExpr());
2672 opaqueData = OVMA::bind(CGF, ov,
2673 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002674
2675 // Otherwise, just bind it.
2676 } else {
2677 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2678 }
2679 opaques.push_back(opaqueData);
2680
2681 // Otherwise, if the expression is the result, evaluate it
2682 // and remember the result.
2683 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002684 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002685
2686 // Otherwise, evaluate the expression in an ignored context.
2687 } else {
2688 CGF.EmitIgnoredExpr(semantic);
2689 }
2690 }
2691
2692 // Unbind all the opaques now.
2693 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2694 opaques[i].unbind(CGF);
2695
2696 return result;
2697}
2698
John McCalle399e5b2016-01-27 18:32:30 +00002699template <typename Impl, typename Result>
2700Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2701 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002702
John McCalle399e5b2016-01-27 18:32:30 +00002703 // No-op casts don't change the type, so we just ignore them.
2704 case CK_NoOp:
2705 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002706
John McCalle399e5b2016-01-27 18:32:30 +00002707 // These casts can change the type.
2708 case CK_CPointerToObjCPointerCast:
2709 case CK_BlockPointerToObjCPointerCast:
2710 case CK_AnyPointerToBlockPointerCast:
2711 case CK_BitCast: {
2712 llvm::Type *resultType = CGF.ConvertType(e->getType());
2713 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2714 Result result = asImpl().visit(e->getSubExpr());
2715 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002716 }
2717
John McCalle399e5b2016-01-27 18:32:30 +00002718 // Handle some casts specially.
2719 case CK_LValueToRValue:
2720 return asImpl().visitLValueToRValue(e->getSubExpr());
2721 case CK_ARCConsumeObject:
2722 return asImpl().visitConsumeObject(e->getSubExpr());
2723 case CK_ARCExtendBlockObject:
2724 return asImpl().visitExtendBlockObject(e->getSubExpr());
2725 case CK_ARCReclaimReturnedObject:
2726 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2727
2728 // Otherwise, use the default logic.
2729 default:
2730 return asImpl().visitExpr(e);
2731 }
2732}
2733
2734template <typename Impl, typename Result>
2735Result
2736ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2737 switch (e->getOpcode()) {
2738 case BO_Comma:
2739 CGF.EmitIgnoredExpr(e->getLHS());
2740 CGF.EnsureInsertPoint();
2741 return asImpl().visit(e->getRHS());
2742
2743 case BO_Assign:
2744 return asImpl().visitBinAssign(e);
2745
2746 default:
2747 return asImpl().visitExpr(e);
2748 }
2749}
2750
2751template <typename Impl, typename Result>
2752Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2753 switch (e->getLHS()->getType().getObjCLifetime()) {
2754 case Qualifiers::OCL_ExplicitNone:
2755 return asImpl().visitBinAssignUnsafeUnretained(e);
2756
2757 case Qualifiers::OCL_Weak:
2758 return asImpl().visitBinAssignWeak(e);
2759
2760 case Qualifiers::OCL_Autoreleasing:
2761 return asImpl().visitBinAssignAutoreleasing(e);
2762
2763 case Qualifiers::OCL_Strong:
2764 return asImpl().visitBinAssignStrong(e);
2765
2766 case Qualifiers::OCL_None:
2767 return asImpl().visitExpr(e);
2768 }
2769 llvm_unreachable("bad ObjC ownership qualifier");
2770}
2771
2772/// The default rule for __unsafe_unretained emits the RHS recursively,
2773/// stores into the unsafe variable, and propagates the result outward.
2774template <typename Impl, typename Result>
2775Result ARCExprEmitter<Impl,Result>::
2776 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2777 // Recursively emit the RHS.
2778 // For __block safety, do this before emitting the LHS.
2779 Result result = asImpl().visit(e->getRHS());
2780
2781 // Perform the store.
2782 LValue lvalue =
2783 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2784 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2785 lvalue);
2786
2787 return result;
2788}
2789
2790template <typename Impl, typename Result>
2791Result
2792ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2793 return asImpl().visitExpr(e);
2794}
2795
2796template <typename Impl, typename Result>
2797Result
2798ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
2799 return asImpl().visitExpr(e);
2800}
2801
2802template <typename Impl, typename Result>
2803Result
2804ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
2805 return asImpl().visitExpr(e);
2806}
2807
2808/// The general expression-emission logic.
2809template <typename Impl, typename Result>
2810Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
2811 // We should *never* see a nested full-expression here, because if
2812 // we fail to emit at +1, our caller must not retain after we close
2813 // out the full-expression. This isn't as important in the unsafe
2814 // emitter.
2815 assert(!isa<ExprWithCleanups>(e));
2816
2817 // Look through parens, __extension__, generic selection, etc.
2818 e = e->IgnoreParens();
2819
2820 // Handle certain kinds of casts.
2821 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2822 return asImpl().visitCastExpr(ce);
2823
2824 // Handle the comma operator.
2825 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
2826 return asImpl().visitBinaryOperator(op);
2827
2828 // TODO: handle conditional operators here
2829
2830 // For calls and message sends, use the retained-call logic.
2831 // Delegate inits are a special case in that they're the only
2832 // returns-retained expression that *isn't* surrounded by
2833 // a consume.
2834 } else if (isa<CallExpr>(e) ||
2835 (isa<ObjCMessageExpr>(e) &&
2836 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2837 return asImpl().visitCall(e);
2838
2839 // Look through pseudo-object expressions.
2840 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2841 return asImpl().visitPseudoObjectExpr(pseudo);
2842 }
2843
2844 return asImpl().visitExpr(e);
2845}
2846
2847namespace {
2848
2849/// An emitter for +1 results.
2850struct ARCRetainExprEmitter :
2851 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
2852
2853 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
2854
2855 llvm::Value *getValueOfResult(TryEmitResult result) {
2856 return result.getPointer();
2857 }
2858
2859 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
2860 llvm::Value *value = result.getPointer();
2861 value = CGF.Builder.CreateBitCast(value, resultType);
2862 result.setPointer(value);
2863 return result;
2864 }
2865
2866 TryEmitResult visitLValueToRValue(const Expr *e) {
2867 return tryEmitARCRetainLoadOfScalar(CGF, e);
2868 }
2869
2870 /// For consumptions, just emit the subexpression and thus elide
2871 /// the retain/release pair.
2872 TryEmitResult visitConsumeObject(const Expr *e) {
2873 llvm::Value *result = CGF.EmitScalarExpr(e);
2874 return TryEmitResult(result, true);
2875 }
2876
2877 /// Block extends are net +0. Naively, we could just recurse on
2878 /// the subexpression, but actually we need to ensure that the
2879 /// value is copied as a block, so there's a little filter here.
2880 TryEmitResult visitExtendBlockObject(const Expr *e) {
2881 llvm::Value *result; // will be a +0 value
2882
2883 // If we can't safely assume the sub-expression will produce a
2884 // block-copied value, emit the sub-expression at +0.
2885 if (shouldEmitSeparateBlockRetain(e)) {
2886 result = CGF.EmitScalarExpr(e);
2887
2888 // Otherwise, try to emit the sub-expression at +1 recursively.
2889 } else {
2890 TryEmitResult subresult = asImpl().visit(e);
2891
2892 // If that produced a retained value, just use that.
2893 if (subresult.getInt()) {
2894 return subresult;
2895 }
2896
2897 // Otherwise it's +0.
2898 result = subresult.getPointer();
2899 }
2900
2901 // Retain the object as a block.
2902 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2903 return TryEmitResult(result, true);
2904 }
2905
2906 /// For reclaims, emit the subexpression as a retained call and
2907 /// skip the consumption.
2908 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
2909 llvm::Value *result = emitARCRetainCallResult(CGF, e);
2910 return TryEmitResult(result, true);
2911 }
2912
2913 /// When we have an undecorated call, retroactively do a claim.
2914 TryEmitResult visitCall(const Expr *e) {
2915 llvm::Value *result = emitARCRetainCallResult(CGF, e);
2916 return TryEmitResult(result, true);
2917 }
2918
2919 // TODO: maybe special-case visitBinAssignWeak?
2920
2921 TryEmitResult visitExpr(const Expr *e) {
2922 // We didn't find an obvious production, so emit what we've got and
2923 // tell the caller that we didn't manage to retain.
2924 llvm::Value *result = CGF.EmitScalarExpr(e);
2925 return TryEmitResult(result, false);
2926 }
2927};
2928}
2929
2930static TryEmitResult
2931tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2932 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00002933}
2934
2935static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2936 LValue lvalue,
2937 QualType type) {
2938 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2939 llvm::Value *value = result.getPointer();
2940 if (!result.getInt())
2941 value = CGF.EmitARCRetain(type, value);
2942 return value;
2943}
2944
2945/// EmitARCRetainScalarExpr - Semantically equivalent to
2946/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2947/// best-effort attempt to peephole expressions that naturally produce
2948/// retained objects.
2949llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002950 // The retain needs to happen within the full-expression.
2951 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2952 enterFullExpression(cleanups);
2953 RunCleanupsScope scope(*this);
2954 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2955 }
2956
John McCall31168b02011-06-15 23:02:42 +00002957 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2958 llvm::Value *value = result.getPointer();
2959 if (!result.getInt())
2960 value = EmitARCRetain(e->getType(), value);
2961 return value;
2962}
2963
2964llvm::Value *
2965CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002966 // The retain needs to happen within the full-expression.
2967 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2968 enterFullExpression(cleanups);
2969 RunCleanupsScope scope(*this);
2970 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2971 }
2972
John McCall31168b02011-06-15 23:02:42 +00002973 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2974 llvm::Value *value = result.getPointer();
2975 if (result.getInt())
2976 value = EmitARCAutorelease(value);
2977 else
2978 value = EmitARCRetainAutorelease(e->getType(), value);
2979 return value;
2980}
2981
John McCallff613032011-10-04 06:23:45 +00002982llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2983 llvm::Value *result;
2984 bool doRetain;
2985
2986 if (shouldEmitSeparateBlockRetain(e)) {
2987 result = EmitScalarExpr(e);
2988 doRetain = true;
2989 } else {
2990 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2991 result = subresult.getPointer();
2992 doRetain = !subresult.getInt();
2993 }
2994
2995 if (doRetain)
2996 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2997 return EmitObjCConsumeObject(e->getType(), result);
2998}
2999
John McCall248512a2011-10-01 10:32:24 +00003000llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3001 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003002 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003003 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003004 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003005 return EmitARCRetainAutoreleaseScalarExpr(expr);
3006 }
3007
3008 // Otherwise, use the normal scalar-expression emission. The
3009 // exception machinery doesn't do anything special with the
3010 // exception like retaining it, so there's no safety associated with
3011 // only running cleanups after the throw has started, and when it
3012 // matters it tends to be substantially inferior code.
3013 return EmitScalarExpr(expr);
3014}
3015
John McCalle399e5b2016-01-27 18:32:30 +00003016namespace {
3017
3018/// An emitter for assigning into an __unsafe_unretained context.
3019struct ARCUnsafeUnretainedExprEmitter :
3020 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3021
3022 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3023
3024 llvm::Value *getValueOfResult(llvm::Value *value) {
3025 return value;
3026 }
3027
3028 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3029 return CGF.Builder.CreateBitCast(value, resultType);
3030 }
3031
3032 llvm::Value *visitLValueToRValue(const Expr *e) {
3033 return CGF.EmitScalarExpr(e);
3034 }
3035
3036 /// For consumptions, just emit the subexpression and perform the
3037 /// consumption like normal.
3038 llvm::Value *visitConsumeObject(const Expr *e) {
3039 llvm::Value *value = CGF.EmitScalarExpr(e);
3040 return CGF.EmitObjCConsumeObject(e->getType(), value);
3041 }
3042
3043 /// No special logic for block extensions. (This probably can't
3044 /// actually happen in this emitter, though.)
3045 llvm::Value *visitExtendBlockObject(const Expr *e) {
3046 return CGF.EmitARCExtendBlockObject(e);
3047 }
3048
3049 /// For reclaims, perform an unsafeClaim if that's enabled.
3050 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3051 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3052 }
3053
3054 /// When we have an undecorated call, just emit it without adding
3055 /// the unsafeClaim.
3056 llvm::Value *visitCall(const Expr *e) {
3057 return CGF.EmitScalarExpr(e);
3058 }
3059
3060 /// Just do normal scalar emission in the default case.
3061 llvm::Value *visitExpr(const Expr *e) {
3062 return CGF.EmitScalarExpr(e);
3063 }
3064};
3065}
3066
3067static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3068 const Expr *e) {
3069 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3070}
3071
3072/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3073/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3074/// avoiding any spurious retains, including by performing reclaims
3075/// with objc_unsafeClaimAutoreleasedReturnValue.
3076llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3077 // Look through full-expressions.
3078 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3079 enterFullExpression(cleanups);
3080 RunCleanupsScope scope(*this);
3081 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3082 }
3083
3084 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3085}
3086
3087std::pair<LValue,llvm::Value*>
3088CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3089 bool ignored) {
3090 // Evaluate the RHS first. If we're ignoring the result, assume
3091 // that we can emit at an unsafe +0.
3092 llvm::Value *value;
3093 if (ignored) {
3094 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3095 } else {
3096 value = EmitScalarExpr(e->getRHS());
3097 }
3098
3099 // Emit the LHS and perform the store.
3100 LValue lvalue = EmitLValue(e->getLHS());
3101 EmitStoreOfScalar(value, lvalue);
3102
3103 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3104}
3105
John McCall31168b02011-06-15 23:02:42 +00003106std::pair<LValue,llvm::Value*>
3107CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3108 bool ignored) {
3109 // Evaluate the RHS first.
3110 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3111 llvm::Value *value = result.getPointer();
3112
John McCallb726a552011-07-28 07:23:35 +00003113 bool hasImmediateRetain = result.getInt();
3114
3115 // If we didn't emit a retained object, and the l-value is of block
3116 // type, then we need to emit the block-retain immediately in case
3117 // it invalidates the l-value.
3118 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003119 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003120 hasImmediateRetain = true;
3121 }
3122
John McCall31168b02011-06-15 23:02:42 +00003123 LValue lvalue = EmitLValue(e->getLHS());
3124
3125 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003126 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003127 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003128 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003129 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003130 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003131 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003132 }
3133
3134 return std::pair<LValue,llvm::Value*>(lvalue, value);
3135}
3136
3137std::pair<LValue,llvm::Value*>
3138CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3139 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3140 LValue lvalue = EmitLValue(e->getLHS());
3141
Eli Friedmana0544d62011-12-03 04:14:32 +00003142 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003143
3144 return std::pair<LValue,llvm::Value*>(lvalue, value);
3145}
3146
3147void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003148 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003149 const Stmt *subStmt = ARPS.getSubStmt();
3150 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3151
3152 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003153 if (DI)
3154 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003155
3156 // Keep track of the current cleanup stack depth.
3157 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003158 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003159 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3160 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3161 } else {
3162 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3163 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3164 }
3165
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003166 for (const auto *I : S.body())
3167 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003168
Eric Christopher7cdf9482011-10-13 21:45:18 +00003169 if (DI)
3170 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003171}
John McCall1bd25562011-06-24 23:21:27 +00003172
3173/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3174/// make sure it survives garbage collection until this point.
3175void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3176 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003177 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003178 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00003179 llvm::Value *extender
3180 = llvm::InlineAsm::get(extenderType,
3181 /* assembly */ "",
3182 /* constraints */ "r",
3183 /* side effects */ true);
3184
3185 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003186 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003187}
3188
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003189/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003190/// non-trivial copy assignment function, produce following helper function.
3191/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3192///
3193llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003194CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3195 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003196 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003197 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003198 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003199 QualType Ty = PID->getPropertyIvarDecl()->getType();
3200 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003201 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003202 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003203 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003204 return nullptr;
3205 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003206 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003207 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003208 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3209 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3210 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003211
3212 ASTContext &C = getContext();
3213 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003214 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003215 FunctionDecl *FD = FunctionDecl::Create(C,
3216 C.getTranslationUnitDecl(),
3217 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003218 SourceLocation(), II, C.VoidTy,
3219 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003220 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00003221 false);
Craig Topper8a13c412014-05-21 05:09:00 +00003222
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003223 QualType DestTy = C.getPointerType(Ty);
3224 QualType SrcTy = Ty;
3225 SrcTy.addConst();
3226 SrcTy = C.getPointerType(SrcTy);
3227
3228 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00003229 ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3230 DestTy, ImplicitParamDecl::Other);
3231 args.push_back(&DstDecl);
3232 ImplicitParamDecl SrcDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3233 SrcTy, ImplicitParamDecl::Other);
3234 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003235
John McCallc56a8b32016-03-11 04:30:31 +00003236 const CGFunctionInfo &FI =
3237 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003238
John McCalla729c622012-02-17 03:33:10 +00003239 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003240
3241 llvm::Function *Fn =
3242 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003243 "__assign_helper_atomic_property_",
3244 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003245
3246 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3247
Adrian Prantl22e66b42014-04-11 01:13:04 +00003248 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003249
Alexey Bataev56223232017-06-09 13:40:18 +00003250 DeclRefExpr DstExpr(&DstDecl, false, DestTy,
John McCall113bee02012-03-10 09:33:50 +00003251 VK_RValue, SourceLocation());
3252 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003253 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003254
Alexey Bataev56223232017-06-09 13:40:18 +00003255 DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy,
John McCall113bee02012-03-10 09:33:50 +00003256 VK_RValue, SourceLocation());
3257 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003258 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003259
John McCall113bee02012-03-10 09:33:50 +00003260 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003261 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00003262 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003263 Args, DestTy->getPointeeType(),
Adam Nemet484aa452017-03-27 19:17:25 +00003264 VK_LValue, SourceLocation(), FPOptions());
John McCall113bee02012-03-10 09:33:50 +00003265
3266 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003267
3268 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003269 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003270 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003271 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003272}
3273
3274llvm::Constant *
3275CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3276 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003277 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003278 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003279 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003280 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3281 QualType Ty = PD->getType();
3282 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003283 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003284 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003285 return nullptr;
3286 llvm::Constant *HelperFn = nullptr;
3287
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003288 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003289 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003290 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3291 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3292 return HelperFn;
3293
3294
3295 ASTContext &C = getContext();
3296 IdentifierInfo *II
3297 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3298 FunctionDecl *FD = FunctionDecl::Create(C,
3299 C.getTranslationUnitDecl(),
3300 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003301 SourceLocation(), II, C.VoidTy,
3302 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003303 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00003304 false);
Craig Topper8a13c412014-05-21 05:09:00 +00003305
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003306 QualType DestTy = C.getPointerType(Ty);
3307 QualType SrcTy = Ty;
3308 SrcTy.addConst();
3309 SrcTy = C.getPointerType(SrcTy);
3310
3311 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00003312 ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3313 DestTy, ImplicitParamDecl::Other);
3314 args.push_back(&DstDecl);
3315 ImplicitParamDecl SrcDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3316 SrcTy, ImplicitParamDecl::Other);
3317 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003318
John McCallc56a8b32016-03-11 04:30:31 +00003319 const CGFunctionInfo &FI =
3320 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003321
John McCalla729c622012-02-17 03:33:10 +00003322 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003323
3324 llvm::Function *Fn =
3325 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3326 "__copy_helper_atomic_property_", &CGM.getModule());
3327
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003328 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3329
Adrian Prantl22e66b42014-04-11 01:13:04 +00003330 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003331
Alexey Bataev56223232017-06-09 13:40:18 +00003332 DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003333 VK_RValue, SourceLocation());
3334
John McCall113bee02012-03-10 09:33:50 +00003335 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003336 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003337
3338 CXXConstructExpr *CXXConstExpr =
3339 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3340
3341 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003342 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003343 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3344 CXXConstExpr->arg_end());
3345
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003346 CXXConstructExpr *TheCXXConstructExpr =
3347 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3348 CXXConstExpr->getConstructor(),
3349 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003350 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003351 CXXConstExpr->hadMultipleCandidates(),
3352 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003353 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003354 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003355 CXXConstExpr->getConstructionKind(),
3356 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003357
Alexey Bataev56223232017-06-09 13:40:18 +00003358 DeclRefExpr DstExpr(&DstDecl, false, DestTy,
John McCall113bee02012-03-10 09:33:50 +00003359 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003360
John McCall113bee02012-03-10 09:33:50 +00003361 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003362 CharUnits Alignment
3363 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003364 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003365 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3366 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003367 AggValueSlot::IsDestructed,
3368 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003369 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003370
3371 FinishFunction();
3372 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3373 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3374 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003375}
3376
Eli Friedmanec75fec2012-02-28 01:08:45 +00003377llvm::Value *
3378CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3379 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003380 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3381 Selector CopySelector =
3382 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003383 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3384 Selector AutoreleaseSelector =
3385 getContext().Selectors.getNullarySelector(AutoreleaseID);
3386
3387 // Emit calls to retain/autorelease.
3388 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3389 llvm::Value *Val = Block;
3390 RValue Result;
3391 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003392 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003393 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003394 Val = Result.getScalarVal();
3395 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3396 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003397 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003398 Val = Result.getScalarVal();
3399 return Val;
3400}
3401
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003402llvm::Value *
3403CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3404 assert(Args.size() == 3 && "Expected 3 argument here!");
3405
3406 if (!CGM.IsOSVersionAtLeastFn) {
3407 llvm::FunctionType *FTy =
3408 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3409 CGM.IsOSVersionAtLeastFn =
3410 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3411 }
3412
3413 llvm::Value *CallRes =
3414 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3415
3416 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3417}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003418
Alex Lorenza8fbef42017-03-23 11:14:27 +00003419void CodeGenModule::emitAtAvailableLinkGuard() {
3420 if (!IsOSVersionAtLeastFn)
3421 return;
3422 // @available requires CoreFoundation only on Darwin.
3423 if (!Target.getTriple().isOSDarwin())
3424 return;
3425 // Add -framework CoreFoundation to the linker commands. We still want to
3426 // emit the core foundation reference down below because otherwise if
3427 // CoreFoundation is not used in the code, the linker won't link the
3428 // framework.
3429 auto &Context = getLLVMContext();
3430 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3431 llvm::MDString::get(Context, "CoreFoundation")};
3432 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3433 // Emit a reference to a symbol from CoreFoundation to ensure that
3434 // CoreFoundation is linked into the final binary.
3435 llvm::FunctionType *FTy =
3436 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3437 llvm::Constant *CFFunc =
3438 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3439
3440 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3441 llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3442 CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3443 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3444 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3445 CodeGenFunction CGF(*this);
3446 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3447 CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3448 CGF.Builder.CreateUnreachable();
3449 addCompilerUsedGlobal(CFLinkCheckFunc);
3450}
3451
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003452CGObjCRuntime::~CGObjCRuntime() {}