1e5dd7070Spatrick //===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code to emit Objective-C code as LLVM code.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick
13e5dd7070Spatrick #include "CGDebugInfo.h"
14e5dd7070Spatrick #include "CGObjCRuntime.h"
15e5dd7070Spatrick #include "CodeGenFunction.h"
16e5dd7070Spatrick #include "CodeGenModule.h"
17e5dd7070Spatrick #include "ConstantEmitter.h"
18e5dd7070Spatrick #include "TargetInfo.h"
19e5dd7070Spatrick #include "clang/AST/ASTContext.h"
20e5dd7070Spatrick #include "clang/AST/Attr.h"
21e5dd7070Spatrick #include "clang/AST/DeclObjC.h"
22e5dd7070Spatrick #include "clang/AST/StmtObjC.h"
23e5dd7070Spatrick #include "clang/Basic/Diagnostic.h"
24e5dd7070Spatrick #include "clang/CodeGen/CGFunctionInfo.h"
25*12c85518Srobert #include "clang/CodeGen/CodeGenABITypes.h"
26e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
27a9ac8606Spatrick #include "llvm/Analysis/ObjCARCUtil.h"
28a9ac8606Spatrick #include "llvm/BinaryFormat/MachO.h"
29*12c85518Srobert #include "llvm/IR/Constants.h"
30e5dd7070Spatrick #include "llvm/IR/DataLayout.h"
31e5dd7070Spatrick #include "llvm/IR/InlineAsm.h"
32*12c85518Srobert #include <optional>
33e5dd7070Spatrick using namespace clang;
34e5dd7070Spatrick using namespace CodeGen;
35e5dd7070Spatrick
36e5dd7070Spatrick typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
37e5dd7070Spatrick static TryEmitResult
38e5dd7070Spatrick tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
39e5dd7070Spatrick static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
40e5dd7070Spatrick QualType ET,
41e5dd7070Spatrick RValue Result);
42e5dd7070Spatrick
43e5dd7070Spatrick /// Given the address of a variable of pointer type, find the correct
44e5dd7070Spatrick /// null to store into it.
getNullForVariable(Address addr)45e5dd7070Spatrick static llvm::Constant *getNullForVariable(Address addr) {
46e5dd7070Spatrick llvm::Type *type = addr.getElementType();
47e5dd7070Spatrick return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
48e5dd7070Spatrick }
49e5dd7070Spatrick
50e5dd7070Spatrick /// Emits an instance of NSConstantString representing the object.
EmitObjCStringLiteral(const ObjCStringLiteral * E)51e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
52e5dd7070Spatrick {
53e5dd7070Spatrick llvm::Constant *C =
54e5dd7070Spatrick CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
55e5dd7070Spatrick // FIXME: This bitcast should just be made an invariant on the Runtime.
56e5dd7070Spatrick return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
57e5dd7070Spatrick }
58e5dd7070Spatrick
59e5dd7070Spatrick /// EmitObjCBoxedExpr - This routine generates code to call
60e5dd7070Spatrick /// the appropriate expression boxing method. This will either be
61e5dd7070Spatrick /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
62e5dd7070Spatrick /// or [NSValue valueWithBytes:objCType:].
63e5dd7070Spatrick ///
64e5dd7070Spatrick llvm::Value *
EmitObjCBoxedExpr(const ObjCBoxedExpr * E)65e5dd7070Spatrick CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
66e5dd7070Spatrick // Generate the correct selector for this literal's concrete type.
67e5dd7070Spatrick // Get the method.
68e5dd7070Spatrick const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
69e5dd7070Spatrick const Expr *SubExpr = E->getSubExpr();
70e5dd7070Spatrick
71e5dd7070Spatrick if (E->isExpressibleAsConstantInitializer()) {
72e5dd7070Spatrick ConstantEmitter ConstEmitter(CGM);
73e5dd7070Spatrick return ConstEmitter.tryEmitAbstract(E, E->getType());
74e5dd7070Spatrick }
75e5dd7070Spatrick
76e5dd7070Spatrick assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
77e5dd7070Spatrick Selector Sel = BoxingMethod->getSelector();
78e5dd7070Spatrick
79e5dd7070Spatrick // Generate a reference to the class pointer, which will be the receiver.
80e5dd7070Spatrick // Assumes that the method was introduced in the class that should be
81e5dd7070Spatrick // messaged (avoids pulling it out of the result type).
82e5dd7070Spatrick CGObjCRuntime &Runtime = CGM.getObjCRuntime();
83e5dd7070Spatrick const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
84e5dd7070Spatrick llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
85e5dd7070Spatrick
86e5dd7070Spatrick CallArgList Args;
87e5dd7070Spatrick const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
88e5dd7070Spatrick QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
89e5dd7070Spatrick
90e5dd7070Spatrick // ObjCBoxedExpr supports boxing of structs and unions
91e5dd7070Spatrick // via [NSValue valueWithBytes:objCType:]
92e5dd7070Spatrick const QualType ValueType(SubExpr->getType().getCanonicalType());
93e5dd7070Spatrick if (ValueType->isObjCBoxableRecordType()) {
94e5dd7070Spatrick // Emit CodeGen for first parameter
95e5dd7070Spatrick // and cast value to correct type
96e5dd7070Spatrick Address Temporary = CreateMemTemp(SubExpr->getType());
97e5dd7070Spatrick EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
98*12c85518Srobert llvm::Value *BitCast =
99*12c85518Srobert Builder.CreateBitCast(Temporary.getPointer(), ConvertType(ArgQT));
100*12c85518Srobert Args.add(RValue::get(BitCast), ArgQT);
101e5dd7070Spatrick
102e5dd7070Spatrick // Create char array to store type encoding
103e5dd7070Spatrick std::string Str;
104e5dd7070Spatrick getContext().getObjCEncodingForType(ValueType, Str);
105e5dd7070Spatrick llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
106e5dd7070Spatrick
107e5dd7070Spatrick // Cast type encoding to correct type
108e5dd7070Spatrick const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
109e5dd7070Spatrick QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
110e5dd7070Spatrick llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
111e5dd7070Spatrick
112e5dd7070Spatrick Args.add(RValue::get(Cast), EncodingQT);
113e5dd7070Spatrick } else {
114e5dd7070Spatrick Args.add(EmitAnyExpr(SubExpr), ArgQT);
115e5dd7070Spatrick }
116e5dd7070Spatrick
117e5dd7070Spatrick RValue result = Runtime.GenerateMessageSend(
118e5dd7070Spatrick *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
119e5dd7070Spatrick Args, ClassDecl, BoxingMethod);
120e5dd7070Spatrick return Builder.CreateBitCast(result.getScalarVal(),
121e5dd7070Spatrick ConvertType(E->getType()));
122e5dd7070Spatrick }
123e5dd7070Spatrick
EmitObjCCollectionLiteral(const Expr * E,const ObjCMethodDecl * MethodWithObjects)124e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
125e5dd7070Spatrick const ObjCMethodDecl *MethodWithObjects) {
126e5dd7070Spatrick ASTContext &Context = CGM.getContext();
127e5dd7070Spatrick const ObjCDictionaryLiteral *DLE = nullptr;
128e5dd7070Spatrick const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
129e5dd7070Spatrick if (!ALE)
130e5dd7070Spatrick DLE = cast<ObjCDictionaryLiteral>(E);
131e5dd7070Spatrick
132e5dd7070Spatrick // Optimize empty collections by referencing constants, when available.
133e5dd7070Spatrick uint64_t NumElements =
134e5dd7070Spatrick ALE ? ALE->getNumElements() : DLE->getNumElements();
135e5dd7070Spatrick if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
136e5dd7070Spatrick StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
137e5dd7070Spatrick QualType IdTy(CGM.getContext().getObjCIdType());
138e5dd7070Spatrick llvm::Constant *Constant =
139e5dd7070Spatrick CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
140e5dd7070Spatrick LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
141e5dd7070Spatrick llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
142e5dd7070Spatrick cast<llvm::LoadInst>(Ptr)->setMetadata(
143e5dd7070Spatrick CGM.getModule().getMDKindID("invariant.load"),
144*12c85518Srobert llvm::MDNode::get(getLLVMContext(), std::nullopt));
145e5dd7070Spatrick return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
146e5dd7070Spatrick }
147e5dd7070Spatrick
148e5dd7070Spatrick // Compute the type of the array we're initializing.
149e5dd7070Spatrick llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
150e5dd7070Spatrick NumElements);
151e5dd7070Spatrick QualType ElementType = Context.getObjCIdType().withConst();
152e5dd7070Spatrick QualType ElementArrayType
153e5dd7070Spatrick = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
154e5dd7070Spatrick ArrayType::Normal, /*IndexTypeQuals=*/0);
155e5dd7070Spatrick
156e5dd7070Spatrick // Allocate the temporary array(s).
157e5dd7070Spatrick Address Objects = CreateMemTemp(ElementArrayType, "objects");
158e5dd7070Spatrick Address Keys = Address::invalid();
159e5dd7070Spatrick if (DLE)
160e5dd7070Spatrick Keys = CreateMemTemp(ElementArrayType, "keys");
161e5dd7070Spatrick
162e5dd7070Spatrick // In ARC, we may need to do extra work to keep all the keys and
163e5dd7070Spatrick // values alive until after the call.
164e5dd7070Spatrick SmallVector<llvm::Value *, 16> NeededObjects;
165e5dd7070Spatrick bool TrackNeededObjects =
166e5dd7070Spatrick (getLangOpts().ObjCAutoRefCount &&
167e5dd7070Spatrick CGM.getCodeGenOpts().OptimizationLevel != 0);
168e5dd7070Spatrick
169e5dd7070Spatrick // Perform the actual initialialization of the array(s).
170e5dd7070Spatrick for (uint64_t i = 0; i < NumElements; i++) {
171e5dd7070Spatrick if (ALE) {
172e5dd7070Spatrick // Emit the element and store it to the appropriate array slot.
173e5dd7070Spatrick const Expr *Rhs = ALE->getElement(i);
174e5dd7070Spatrick LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
175e5dd7070Spatrick ElementType, AlignmentSource::Decl);
176e5dd7070Spatrick
177e5dd7070Spatrick llvm::Value *value = EmitScalarExpr(Rhs);
178e5dd7070Spatrick EmitStoreThroughLValue(RValue::get(value), LV, true);
179e5dd7070Spatrick if (TrackNeededObjects) {
180e5dd7070Spatrick NeededObjects.push_back(value);
181e5dd7070Spatrick }
182e5dd7070Spatrick } else {
183e5dd7070Spatrick // Emit the key and store it to the appropriate array slot.
184e5dd7070Spatrick const Expr *Key = DLE->getKeyValueElement(i).Key;
185e5dd7070Spatrick LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
186e5dd7070Spatrick ElementType, AlignmentSource::Decl);
187e5dd7070Spatrick llvm::Value *keyValue = EmitScalarExpr(Key);
188e5dd7070Spatrick EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
189e5dd7070Spatrick
190e5dd7070Spatrick // Emit the value and store it to the appropriate array slot.
191e5dd7070Spatrick const Expr *Value = DLE->getKeyValueElement(i).Value;
192e5dd7070Spatrick LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
193e5dd7070Spatrick ElementType, AlignmentSource::Decl);
194e5dd7070Spatrick llvm::Value *valueValue = EmitScalarExpr(Value);
195e5dd7070Spatrick EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
196e5dd7070Spatrick if (TrackNeededObjects) {
197e5dd7070Spatrick NeededObjects.push_back(keyValue);
198e5dd7070Spatrick NeededObjects.push_back(valueValue);
199e5dd7070Spatrick }
200e5dd7070Spatrick }
201e5dd7070Spatrick }
202e5dd7070Spatrick
203e5dd7070Spatrick // Generate the argument list.
204e5dd7070Spatrick CallArgList Args;
205e5dd7070Spatrick ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
206e5dd7070Spatrick const ParmVarDecl *argDecl = *PI++;
207e5dd7070Spatrick QualType ArgQT = argDecl->getType().getUnqualifiedType();
208e5dd7070Spatrick Args.add(RValue::get(Objects.getPointer()), ArgQT);
209e5dd7070Spatrick if (DLE) {
210e5dd7070Spatrick argDecl = *PI++;
211e5dd7070Spatrick ArgQT = argDecl->getType().getUnqualifiedType();
212e5dd7070Spatrick Args.add(RValue::get(Keys.getPointer()), ArgQT);
213e5dd7070Spatrick }
214e5dd7070Spatrick argDecl = *PI;
215e5dd7070Spatrick ArgQT = argDecl->getType().getUnqualifiedType();
216e5dd7070Spatrick llvm::Value *Count =
217e5dd7070Spatrick llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
218e5dd7070Spatrick Args.add(RValue::get(Count), ArgQT);
219e5dd7070Spatrick
220e5dd7070Spatrick // Generate a reference to the class pointer, which will be the receiver.
221e5dd7070Spatrick Selector Sel = MethodWithObjects->getSelector();
222e5dd7070Spatrick QualType ResultType = E->getType();
223e5dd7070Spatrick const ObjCObjectPointerType *InterfacePointerType
224e5dd7070Spatrick = ResultType->getAsObjCInterfacePointerType();
225e5dd7070Spatrick ObjCInterfaceDecl *Class
226e5dd7070Spatrick = InterfacePointerType->getObjectType()->getInterface();
227e5dd7070Spatrick CGObjCRuntime &Runtime = CGM.getObjCRuntime();
228e5dd7070Spatrick llvm::Value *Receiver = Runtime.GetClass(*this, Class);
229e5dd7070Spatrick
230e5dd7070Spatrick // Generate the message send.
231e5dd7070Spatrick RValue result = Runtime.GenerateMessageSend(
232e5dd7070Spatrick *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
233e5dd7070Spatrick Receiver, Args, Class, MethodWithObjects);
234e5dd7070Spatrick
235e5dd7070Spatrick // The above message send needs these objects, but in ARC they are
236e5dd7070Spatrick // passed in a buffer that is essentially __unsafe_unretained.
237e5dd7070Spatrick // Therefore we must prevent the optimizer from releasing them until
238e5dd7070Spatrick // after the call.
239e5dd7070Spatrick if (TrackNeededObjects) {
240e5dd7070Spatrick EmitARCIntrinsicUse(NeededObjects);
241e5dd7070Spatrick }
242e5dd7070Spatrick
243e5dd7070Spatrick return Builder.CreateBitCast(result.getScalarVal(),
244e5dd7070Spatrick ConvertType(E->getType()));
245e5dd7070Spatrick }
246e5dd7070Spatrick
EmitObjCArrayLiteral(const ObjCArrayLiteral * E)247e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
248e5dd7070Spatrick return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
249e5dd7070Spatrick }
250e5dd7070Spatrick
EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral * E)251e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
252e5dd7070Spatrick const ObjCDictionaryLiteral *E) {
253e5dd7070Spatrick return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
254e5dd7070Spatrick }
255e5dd7070Spatrick
256e5dd7070Spatrick /// Emit a selector.
EmitObjCSelectorExpr(const ObjCSelectorExpr * E)257e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
258e5dd7070Spatrick // Untyped selector.
259e5dd7070Spatrick // Note that this implementation allows for non-constant strings to be passed
260e5dd7070Spatrick // as arguments to @selector(). Currently, the only thing preventing this
261e5dd7070Spatrick // behaviour is the type checking in the front end.
262e5dd7070Spatrick return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
263e5dd7070Spatrick }
264e5dd7070Spatrick
EmitObjCProtocolExpr(const ObjCProtocolExpr * E)265e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
266e5dd7070Spatrick // FIXME: This should pass the Decl not the name.
267e5dd7070Spatrick return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
268e5dd7070Spatrick }
269e5dd7070Spatrick
270e5dd7070Spatrick /// Adjust the type of an Objective-C object that doesn't match up due
271e5dd7070Spatrick /// to type erasure at various points, e.g., related result types or the use
272e5dd7070Spatrick /// of parameterized classes.
AdjustObjCObjectType(CodeGenFunction & CGF,QualType ExpT,RValue Result)273e5dd7070Spatrick static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
274e5dd7070Spatrick RValue Result) {
275e5dd7070Spatrick if (!ExpT->isObjCRetainableType())
276e5dd7070Spatrick return Result;
277e5dd7070Spatrick
278e5dd7070Spatrick // If the converted types are the same, we're done.
279e5dd7070Spatrick llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
280e5dd7070Spatrick if (ExpLLVMTy == Result.getScalarVal()->getType())
281e5dd7070Spatrick return Result;
282e5dd7070Spatrick
283e5dd7070Spatrick // We have applied a substitution. Cast the rvalue appropriately.
284e5dd7070Spatrick return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
285e5dd7070Spatrick ExpLLVMTy));
286e5dd7070Spatrick }
287e5dd7070Spatrick
288e5dd7070Spatrick /// Decide whether to extend the lifetime of the receiver of a
289e5dd7070Spatrick /// returns-inner-pointer message.
290e5dd7070Spatrick static bool
shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr * message)291e5dd7070Spatrick shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
292e5dd7070Spatrick switch (message->getReceiverKind()) {
293e5dd7070Spatrick
294e5dd7070Spatrick // For a normal instance message, we should extend unless the
295e5dd7070Spatrick // receiver is loaded from a variable with precise lifetime.
296e5dd7070Spatrick case ObjCMessageExpr::Instance: {
297e5dd7070Spatrick const Expr *receiver = message->getInstanceReceiver();
298e5dd7070Spatrick
299e5dd7070Spatrick // Look through OVEs.
300e5dd7070Spatrick if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
301e5dd7070Spatrick if (opaque->getSourceExpr())
302e5dd7070Spatrick receiver = opaque->getSourceExpr()->IgnoreParens();
303e5dd7070Spatrick }
304e5dd7070Spatrick
305e5dd7070Spatrick const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
306e5dd7070Spatrick if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
307e5dd7070Spatrick receiver = ice->getSubExpr()->IgnoreParens();
308e5dd7070Spatrick
309e5dd7070Spatrick // Look through OVEs.
310e5dd7070Spatrick if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
311e5dd7070Spatrick if (opaque->getSourceExpr())
312e5dd7070Spatrick receiver = opaque->getSourceExpr()->IgnoreParens();
313e5dd7070Spatrick }
314e5dd7070Spatrick
315e5dd7070Spatrick // Only __strong variables.
316e5dd7070Spatrick if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
317e5dd7070Spatrick return true;
318e5dd7070Spatrick
319e5dd7070Spatrick // All ivars and fields have precise lifetime.
320e5dd7070Spatrick if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
321e5dd7070Spatrick return false;
322e5dd7070Spatrick
323e5dd7070Spatrick // Otherwise, check for variables.
324e5dd7070Spatrick const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
325e5dd7070Spatrick if (!declRef) return true;
326e5dd7070Spatrick const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
327e5dd7070Spatrick if (!var) return true;
328e5dd7070Spatrick
329e5dd7070Spatrick // All variables have precise lifetime except local variables with
330e5dd7070Spatrick // automatic storage duration that aren't specially marked.
331e5dd7070Spatrick return (var->hasLocalStorage() &&
332e5dd7070Spatrick !var->hasAttr<ObjCPreciseLifetimeAttr>());
333e5dd7070Spatrick }
334e5dd7070Spatrick
335e5dd7070Spatrick case ObjCMessageExpr::Class:
336e5dd7070Spatrick case ObjCMessageExpr::SuperClass:
337e5dd7070Spatrick // It's never necessary for class objects.
338e5dd7070Spatrick return false;
339e5dd7070Spatrick
340e5dd7070Spatrick case ObjCMessageExpr::SuperInstance:
341e5dd7070Spatrick // We generally assume that 'self' lives throughout a method call.
342e5dd7070Spatrick return false;
343e5dd7070Spatrick }
344e5dd7070Spatrick
345e5dd7070Spatrick llvm_unreachable("invalid receiver kind");
346e5dd7070Spatrick }
347e5dd7070Spatrick
348e5dd7070Spatrick /// Given an expression of ObjC pointer type, check whether it was
349e5dd7070Spatrick /// immediately loaded from an ARC __weak l-value.
findWeakLValue(const Expr * E)350e5dd7070Spatrick static const Expr *findWeakLValue(const Expr *E) {
351e5dd7070Spatrick assert(E->getType()->isObjCRetainableType());
352e5dd7070Spatrick E = E->IgnoreParens();
353e5dd7070Spatrick if (auto CE = dyn_cast<CastExpr>(E)) {
354e5dd7070Spatrick if (CE->getCastKind() == CK_LValueToRValue) {
355e5dd7070Spatrick if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
356e5dd7070Spatrick return CE->getSubExpr();
357e5dd7070Spatrick }
358e5dd7070Spatrick }
359e5dd7070Spatrick
360e5dd7070Spatrick return nullptr;
361e5dd7070Spatrick }
362e5dd7070Spatrick
363e5dd7070Spatrick /// The ObjC runtime may provide entrypoints that are likely to be faster
364e5dd7070Spatrick /// than an ordinary message send of the appropriate selector.
365e5dd7070Spatrick ///
366e5dd7070Spatrick /// The entrypoints are guaranteed to be equivalent to just sending the
367e5dd7070Spatrick /// corresponding message. If the entrypoint is implemented naively as just a
368e5dd7070Spatrick /// message send, using it is a trade-off: it sacrifices a few cycles of
369e5dd7070Spatrick /// overhead to save a small amount of code. However, it's possible for
370e5dd7070Spatrick /// runtimes to detect and special-case classes that use "standard"
371e5dd7070Spatrick /// behavior; if that's dynamically a large proportion of all objects, using
372e5dd7070Spatrick /// the entrypoint will also be faster than using a message send.
373e5dd7070Spatrick ///
374e5dd7070Spatrick /// If the runtime does support a required entrypoint, then this method will
375e5dd7070Spatrick /// generate a call and return the resulting value. Otherwise it will return
376*12c85518Srobert /// std::nullopt and the caller can generate a msgSend instead.
tryGenerateSpecializedMessageSend(CodeGenFunction & CGF,QualType ResultType,llvm::Value * Receiver,const CallArgList & Args,Selector Sel,const ObjCMethodDecl * method,bool isClassMessage)377*12c85518Srobert static std::optional<llvm::Value *> tryGenerateSpecializedMessageSend(
378*12c85518Srobert CodeGenFunction &CGF, QualType ResultType, llvm::Value *Receiver,
379*12c85518Srobert const CallArgList &Args, Selector Sel, const ObjCMethodDecl *method,
380e5dd7070Spatrick bool isClassMessage) {
381e5dd7070Spatrick auto &CGM = CGF.CGM;
382e5dd7070Spatrick if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
383*12c85518Srobert return std::nullopt;
384e5dd7070Spatrick
385e5dd7070Spatrick auto &Runtime = CGM.getLangOpts().ObjCRuntime;
386e5dd7070Spatrick switch (Sel.getMethodFamily()) {
387e5dd7070Spatrick case OMF_alloc:
388e5dd7070Spatrick if (isClassMessage &&
389e5dd7070Spatrick Runtime.shouldUseRuntimeFunctionsForAlloc() &&
390e5dd7070Spatrick ResultType->isObjCObjectPointerType()) {
391e5dd7070Spatrick // [Foo alloc] -> objc_alloc(Foo) or
392e5dd7070Spatrick // [self alloc] -> objc_alloc(self)
393e5dd7070Spatrick if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
394e5dd7070Spatrick return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
395e5dd7070Spatrick // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
396e5dd7070Spatrick // [self allocWithZone:nil] -> objc_allocWithZone(self)
397e5dd7070Spatrick if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
398e5dd7070Spatrick Args.size() == 1 && Args.front().getType()->isPointerType() &&
399e5dd7070Spatrick Sel.getNameForSlot(0) == "allocWithZone") {
400e5dd7070Spatrick const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
401e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(arg))
402e5dd7070Spatrick return CGF.EmitObjCAllocWithZone(Receiver,
403e5dd7070Spatrick CGF.ConvertType(ResultType));
404*12c85518Srobert return std::nullopt;
405e5dd7070Spatrick }
406e5dd7070Spatrick }
407e5dd7070Spatrick break;
408e5dd7070Spatrick
409e5dd7070Spatrick case OMF_autorelease:
410e5dd7070Spatrick if (ResultType->isObjCObjectPointerType() &&
411e5dd7070Spatrick CGM.getLangOpts().getGC() == LangOptions::NonGC &&
412e5dd7070Spatrick Runtime.shouldUseARCFunctionsForRetainRelease())
413e5dd7070Spatrick return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
414e5dd7070Spatrick break;
415e5dd7070Spatrick
416e5dd7070Spatrick case OMF_retain:
417e5dd7070Spatrick if (ResultType->isObjCObjectPointerType() &&
418e5dd7070Spatrick CGM.getLangOpts().getGC() == LangOptions::NonGC &&
419e5dd7070Spatrick Runtime.shouldUseARCFunctionsForRetainRelease())
420e5dd7070Spatrick return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
421e5dd7070Spatrick break;
422e5dd7070Spatrick
423e5dd7070Spatrick case OMF_release:
424e5dd7070Spatrick if (ResultType->isVoidType() &&
425e5dd7070Spatrick CGM.getLangOpts().getGC() == LangOptions::NonGC &&
426e5dd7070Spatrick Runtime.shouldUseARCFunctionsForRetainRelease()) {
427e5dd7070Spatrick CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
428e5dd7070Spatrick return nullptr;
429e5dd7070Spatrick }
430e5dd7070Spatrick break;
431e5dd7070Spatrick
432e5dd7070Spatrick default:
433e5dd7070Spatrick break;
434e5dd7070Spatrick }
435*12c85518Srobert return std::nullopt;
436e5dd7070Spatrick }
437e5dd7070Spatrick
GeneratePossiblySpecializedMessageSend(CodeGenFunction & CGF,ReturnValueSlot Return,QualType ResultType,Selector Sel,llvm::Value * Receiver,const CallArgList & Args,const ObjCInterfaceDecl * OID,const ObjCMethodDecl * Method,bool isClassMessage)438e5dd7070Spatrick CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
439e5dd7070Spatrick CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
440e5dd7070Spatrick Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
441e5dd7070Spatrick const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
442e5dd7070Spatrick bool isClassMessage) {
443*12c85518Srobert if (std::optional<llvm::Value *> SpecializedResult =
444e5dd7070Spatrick tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
445e5dd7070Spatrick Sel, Method, isClassMessage)) {
446*12c85518Srobert return RValue::get(*SpecializedResult);
447e5dd7070Spatrick }
448e5dd7070Spatrick return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
449e5dd7070Spatrick Method);
450e5dd7070Spatrick }
451e5dd7070Spatrick
AppendFirstImpliedRuntimeProtocols(const ObjCProtocolDecl * PD,llvm::UniqueVector<const ObjCProtocolDecl * > & PDs)452a9ac8606Spatrick static void AppendFirstImpliedRuntimeProtocols(
453a9ac8606Spatrick const ObjCProtocolDecl *PD,
454a9ac8606Spatrick llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {
455a9ac8606Spatrick if (!PD->isNonRuntimeProtocol()) {
456a9ac8606Spatrick const auto *Can = PD->getCanonicalDecl();
457a9ac8606Spatrick PDs.insert(Can);
458a9ac8606Spatrick return;
459a9ac8606Spatrick }
460a9ac8606Spatrick
461a9ac8606Spatrick for (const auto *ParentPD : PD->protocols())
462a9ac8606Spatrick AppendFirstImpliedRuntimeProtocols(ParentPD, PDs);
463a9ac8606Spatrick }
464a9ac8606Spatrick
465a9ac8606Spatrick std::vector<const ObjCProtocolDecl *>
GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,ObjCProtocolDecl::protocol_iterator end)466a9ac8606Spatrick CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,
467a9ac8606Spatrick ObjCProtocolDecl::protocol_iterator end) {
468a9ac8606Spatrick std::vector<const ObjCProtocolDecl *> RuntimePds;
469a9ac8606Spatrick llvm::DenseSet<const ObjCProtocolDecl *> NonRuntimePDs;
470a9ac8606Spatrick
471a9ac8606Spatrick for (; begin != end; ++begin) {
472a9ac8606Spatrick const auto *It = *begin;
473a9ac8606Spatrick const auto *Can = It->getCanonicalDecl();
474a9ac8606Spatrick if (Can->isNonRuntimeProtocol())
475a9ac8606Spatrick NonRuntimePDs.insert(Can);
476a9ac8606Spatrick else
477a9ac8606Spatrick RuntimePds.push_back(Can);
478a9ac8606Spatrick }
479a9ac8606Spatrick
480a9ac8606Spatrick // If there are no non-runtime protocols then we can just stop now.
481a9ac8606Spatrick if (NonRuntimePDs.empty())
482a9ac8606Spatrick return RuntimePds;
483a9ac8606Spatrick
484a9ac8606Spatrick // Else we have to search through the non-runtime protocol's inheritancy
485a9ac8606Spatrick // hierarchy DAG stopping whenever a branch either finds a runtime protocol or
486a9ac8606Spatrick // a non-runtime protocol without any parents. These are the "first-implied"
487a9ac8606Spatrick // protocols from a non-runtime protocol.
488a9ac8606Spatrick llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;
489a9ac8606Spatrick for (const auto *PD : NonRuntimePDs)
490a9ac8606Spatrick AppendFirstImpliedRuntimeProtocols(PD, FirstImpliedProtos);
491a9ac8606Spatrick
492a9ac8606Spatrick // Walk the Runtime list to get all protocols implied via the inclusion of
493a9ac8606Spatrick // this protocol, e.g. all protocols it inherits from including itself.
494a9ac8606Spatrick llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;
495a9ac8606Spatrick for (const auto *PD : RuntimePds) {
496a9ac8606Spatrick const auto *Can = PD->getCanonicalDecl();
497a9ac8606Spatrick AllImpliedProtocols.insert(Can);
498a9ac8606Spatrick Can->getImpliedProtocols(AllImpliedProtocols);
499a9ac8606Spatrick }
500a9ac8606Spatrick
501a9ac8606Spatrick // Similar to above, walk the list of first-implied protocols to find the set
502a9ac8606Spatrick // all the protocols implied excluding the listed protocols themselves since
503a9ac8606Spatrick // they are not yet a part of the `RuntimePds` list.
504a9ac8606Spatrick for (const auto *PD : FirstImpliedProtos) {
505a9ac8606Spatrick PD->getImpliedProtocols(AllImpliedProtocols);
506a9ac8606Spatrick }
507a9ac8606Spatrick
508a9ac8606Spatrick // From the first-implied list we have to finish building the final protocol
509a9ac8606Spatrick // list. If a protocol in the first-implied list was already implied via some
510a9ac8606Spatrick // inheritance path through some other protocols then it would be redundant to
511a9ac8606Spatrick // add it here and so we skip over it.
512a9ac8606Spatrick for (const auto *PD : FirstImpliedProtos) {
513a9ac8606Spatrick if (!AllImpliedProtocols.contains(PD)) {
514a9ac8606Spatrick RuntimePds.push_back(PD);
515a9ac8606Spatrick }
516a9ac8606Spatrick }
517a9ac8606Spatrick
518a9ac8606Spatrick return RuntimePds;
519a9ac8606Spatrick }
520a9ac8606Spatrick
521e5dd7070Spatrick /// Instead of '[[MyClass alloc] init]', try to generate
522e5dd7070Spatrick /// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
523e5dd7070Spatrick /// caller side, as well as the optimized objc_alloc.
524*12c85518Srobert static std::optional<llvm::Value *>
tryEmitSpecializedAllocInit(CodeGenFunction & CGF,const ObjCMessageExpr * OME)525e5dd7070Spatrick tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
526e5dd7070Spatrick auto &Runtime = CGF.getLangOpts().ObjCRuntime;
527e5dd7070Spatrick if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
528*12c85518Srobert return std::nullopt;
529e5dd7070Spatrick
530e5dd7070Spatrick // Match the exact pattern '[[MyClass alloc] init]'.
531e5dd7070Spatrick Selector Sel = OME->getSelector();
532e5dd7070Spatrick if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
533e5dd7070Spatrick !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
534e5dd7070Spatrick Sel.getNameForSlot(0) != "init")
535*12c85518Srobert return std::nullopt;
536e5dd7070Spatrick
537e5dd7070Spatrick // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
538e5dd7070Spatrick // with 'cls' a Class.
539e5dd7070Spatrick auto *SubOME =
540e5dd7070Spatrick dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
541e5dd7070Spatrick if (!SubOME)
542*12c85518Srobert return std::nullopt;
543e5dd7070Spatrick Selector SubSel = SubOME->getSelector();
544e5dd7070Spatrick
545e5dd7070Spatrick if (!SubOME->getType()->isObjCObjectPointerType() ||
546e5dd7070Spatrick !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
547*12c85518Srobert return std::nullopt;
548e5dd7070Spatrick
549e5dd7070Spatrick llvm::Value *Receiver = nullptr;
550e5dd7070Spatrick switch (SubOME->getReceiverKind()) {
551e5dd7070Spatrick case ObjCMessageExpr::Instance:
552e5dd7070Spatrick if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
553*12c85518Srobert return std::nullopt;
554e5dd7070Spatrick Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
555e5dd7070Spatrick break;
556e5dd7070Spatrick
557e5dd7070Spatrick case ObjCMessageExpr::Class: {
558e5dd7070Spatrick QualType ReceiverType = SubOME->getClassReceiver();
559e5dd7070Spatrick const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
560e5dd7070Spatrick const ObjCInterfaceDecl *ID = ObjTy->getInterface();
561e5dd7070Spatrick assert(ID && "null interface should be impossible here");
562e5dd7070Spatrick Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
563e5dd7070Spatrick break;
564e5dd7070Spatrick }
565e5dd7070Spatrick case ObjCMessageExpr::SuperInstance:
566e5dd7070Spatrick case ObjCMessageExpr::SuperClass:
567*12c85518Srobert return std::nullopt;
568e5dd7070Spatrick }
569e5dd7070Spatrick
570e5dd7070Spatrick return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
571e5dd7070Spatrick }
572e5dd7070Spatrick
EmitObjCMessageExpr(const ObjCMessageExpr * E,ReturnValueSlot Return)573e5dd7070Spatrick RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
574e5dd7070Spatrick ReturnValueSlot Return) {
575e5dd7070Spatrick // Only the lookup mechanism and first two arguments of the method
576e5dd7070Spatrick // implementation vary between runtimes. We can get the receiver and
577e5dd7070Spatrick // arguments in generic code.
578e5dd7070Spatrick
579e5dd7070Spatrick bool isDelegateInit = E->isDelegateInitCall();
580e5dd7070Spatrick
581e5dd7070Spatrick const ObjCMethodDecl *method = E->getMethodDecl();
582e5dd7070Spatrick
583e5dd7070Spatrick // If the method is -retain, and the receiver's being loaded from
584e5dd7070Spatrick // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
585e5dd7070Spatrick if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
586e5dd7070Spatrick method->getMethodFamily() == OMF_retain) {
587e5dd7070Spatrick if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
588e5dd7070Spatrick LValue lvalue = EmitLValue(lvalueExpr);
589e5dd7070Spatrick llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
590e5dd7070Spatrick return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
591e5dd7070Spatrick }
592e5dd7070Spatrick }
593e5dd7070Spatrick
594*12c85518Srobert if (std::optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
595e5dd7070Spatrick return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
596e5dd7070Spatrick
597e5dd7070Spatrick // We don't retain the receiver in delegate init calls, and this is
598e5dd7070Spatrick // safe because the receiver value is always loaded from 'self',
599e5dd7070Spatrick // which we zero out. We don't want to Block_copy block receivers,
600e5dd7070Spatrick // though.
601e5dd7070Spatrick bool retainSelf =
602e5dd7070Spatrick (!isDelegateInit &&
603e5dd7070Spatrick CGM.getLangOpts().ObjCAutoRefCount &&
604e5dd7070Spatrick method &&
605e5dd7070Spatrick method->hasAttr<NSConsumesSelfAttr>());
606e5dd7070Spatrick
607e5dd7070Spatrick CGObjCRuntime &Runtime = CGM.getObjCRuntime();
608e5dd7070Spatrick bool isSuperMessage = false;
609e5dd7070Spatrick bool isClassMessage = false;
610e5dd7070Spatrick ObjCInterfaceDecl *OID = nullptr;
611e5dd7070Spatrick // Find the receiver
612e5dd7070Spatrick QualType ReceiverType;
613e5dd7070Spatrick llvm::Value *Receiver = nullptr;
614e5dd7070Spatrick switch (E->getReceiverKind()) {
615e5dd7070Spatrick case ObjCMessageExpr::Instance:
616e5dd7070Spatrick ReceiverType = E->getInstanceReceiver()->getType();
617e5dd7070Spatrick isClassMessage = ReceiverType->isObjCClassType();
618e5dd7070Spatrick if (retainSelf) {
619e5dd7070Spatrick TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
620e5dd7070Spatrick E->getInstanceReceiver());
621e5dd7070Spatrick Receiver = ter.getPointer();
622e5dd7070Spatrick if (ter.getInt()) retainSelf = false;
623e5dd7070Spatrick } else
624e5dd7070Spatrick Receiver = EmitScalarExpr(E->getInstanceReceiver());
625e5dd7070Spatrick break;
626e5dd7070Spatrick
627e5dd7070Spatrick case ObjCMessageExpr::Class: {
628e5dd7070Spatrick ReceiverType = E->getClassReceiver();
629e5dd7070Spatrick OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
630e5dd7070Spatrick assert(OID && "Invalid Objective-C class message send");
631e5dd7070Spatrick Receiver = Runtime.GetClass(*this, OID);
632e5dd7070Spatrick isClassMessage = true;
633e5dd7070Spatrick break;
634e5dd7070Spatrick }
635e5dd7070Spatrick
636e5dd7070Spatrick case ObjCMessageExpr::SuperInstance:
637e5dd7070Spatrick ReceiverType = E->getSuperType();
638e5dd7070Spatrick Receiver = LoadObjCSelf();
639e5dd7070Spatrick isSuperMessage = true;
640e5dd7070Spatrick break;
641e5dd7070Spatrick
642e5dd7070Spatrick case ObjCMessageExpr::SuperClass:
643e5dd7070Spatrick ReceiverType = E->getSuperType();
644e5dd7070Spatrick Receiver = LoadObjCSelf();
645e5dd7070Spatrick isSuperMessage = true;
646e5dd7070Spatrick isClassMessage = true;
647e5dd7070Spatrick break;
648e5dd7070Spatrick }
649e5dd7070Spatrick
650e5dd7070Spatrick if (retainSelf)
651e5dd7070Spatrick Receiver = EmitARCRetainNonBlock(Receiver);
652e5dd7070Spatrick
653e5dd7070Spatrick // In ARC, we sometimes want to "extend the lifetime"
654e5dd7070Spatrick // (i.e. retain+autorelease) of receivers of returns-inner-pointer
655e5dd7070Spatrick // messages.
656e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount && method &&
657e5dd7070Spatrick method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
658e5dd7070Spatrick shouldExtendReceiverForInnerPointerMessage(E))
659e5dd7070Spatrick Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
660e5dd7070Spatrick
661e5dd7070Spatrick QualType ResultType = method ? method->getReturnType() : E->getType();
662e5dd7070Spatrick
663e5dd7070Spatrick CallArgList Args;
664e5dd7070Spatrick EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
665e5dd7070Spatrick
666e5dd7070Spatrick // For delegate init calls in ARC, do an unsafe store of null into
667e5dd7070Spatrick // self. This represents the call taking direct ownership of that
668e5dd7070Spatrick // value. We have to do this after emitting the other call
669e5dd7070Spatrick // arguments because they might also reference self, but we don't
670e5dd7070Spatrick // have to worry about any of them modifying self because that would
671e5dd7070Spatrick // be an undefined read and write of an object in unordered
672e5dd7070Spatrick // expressions.
673e5dd7070Spatrick if (isDelegateInit) {
674e5dd7070Spatrick assert(getLangOpts().ObjCAutoRefCount &&
675e5dd7070Spatrick "delegate init calls should only be marked in ARC");
676e5dd7070Spatrick
677e5dd7070Spatrick // Do an unsafe store of null into self.
678e5dd7070Spatrick Address selfAddr =
679e5dd7070Spatrick GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
680e5dd7070Spatrick Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
681e5dd7070Spatrick }
682e5dd7070Spatrick
683e5dd7070Spatrick RValue result;
684e5dd7070Spatrick if (isSuperMessage) {
685e5dd7070Spatrick // super is only valid in an Objective-C method
686e5dd7070Spatrick const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
687e5dd7070Spatrick bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
688e5dd7070Spatrick result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
689e5dd7070Spatrick E->getSelector(),
690e5dd7070Spatrick OMD->getClassInterface(),
691e5dd7070Spatrick isCategoryImpl,
692e5dd7070Spatrick Receiver,
693e5dd7070Spatrick isClassMessage,
694e5dd7070Spatrick Args,
695e5dd7070Spatrick method);
696e5dd7070Spatrick } else {
697e5dd7070Spatrick // Call runtime methods directly if we can.
698e5dd7070Spatrick result = Runtime.GeneratePossiblySpecializedMessageSend(
699e5dd7070Spatrick *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
700e5dd7070Spatrick method, isClassMessage);
701e5dd7070Spatrick }
702e5dd7070Spatrick
703e5dd7070Spatrick // For delegate init calls in ARC, implicitly store the result of
704e5dd7070Spatrick // the call back into self. This takes ownership of the value.
705e5dd7070Spatrick if (isDelegateInit) {
706e5dd7070Spatrick Address selfAddr =
707e5dd7070Spatrick GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
708e5dd7070Spatrick llvm::Value *newSelf = result.getScalarVal();
709e5dd7070Spatrick
710e5dd7070Spatrick // The delegate return type isn't necessarily a matching type; in
711e5dd7070Spatrick // fact, it's quite likely to be 'id'.
712e5dd7070Spatrick llvm::Type *selfTy = selfAddr.getElementType();
713e5dd7070Spatrick newSelf = Builder.CreateBitCast(newSelf, selfTy);
714e5dd7070Spatrick
715e5dd7070Spatrick Builder.CreateStore(newSelf, selfAddr);
716e5dd7070Spatrick }
717e5dd7070Spatrick
718e5dd7070Spatrick return AdjustObjCObjectType(*this, E->getType(), result);
719e5dd7070Spatrick }
720e5dd7070Spatrick
721e5dd7070Spatrick namespace {
722e5dd7070Spatrick struct FinishARCDealloc final : EHScopeStack::Cleanup {
Emit__anonb505f9fd0111::FinishARCDealloc723e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override {
724e5dd7070Spatrick const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
725e5dd7070Spatrick
726e5dd7070Spatrick const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
727e5dd7070Spatrick const ObjCInterfaceDecl *iface = impl->getClassInterface();
728e5dd7070Spatrick if (!iface->getSuperClass()) return;
729e5dd7070Spatrick
730e5dd7070Spatrick bool isCategory = isa<ObjCCategoryImplDecl>(impl);
731e5dd7070Spatrick
732e5dd7070Spatrick // Call [super dealloc] if we have a superclass.
733e5dd7070Spatrick llvm::Value *self = CGF.LoadObjCSelf();
734e5dd7070Spatrick
735e5dd7070Spatrick CallArgList args;
736e5dd7070Spatrick CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
737e5dd7070Spatrick CGF.getContext().VoidTy,
738e5dd7070Spatrick method->getSelector(),
739e5dd7070Spatrick iface,
740e5dd7070Spatrick isCategory,
741e5dd7070Spatrick self,
742e5dd7070Spatrick /*is class msg*/ false,
743e5dd7070Spatrick args,
744e5dd7070Spatrick method);
745e5dd7070Spatrick }
746e5dd7070Spatrick };
747e5dd7070Spatrick }
748e5dd7070Spatrick
749e5dd7070Spatrick /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
750e5dd7070Spatrick /// the LLVM function and sets the other context used by
751e5dd7070Spatrick /// CodeGenFunction.
StartObjCMethod(const ObjCMethodDecl * OMD,const ObjCContainerDecl * CD)752e5dd7070Spatrick void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
753e5dd7070Spatrick const ObjCContainerDecl *CD) {
754e5dd7070Spatrick SourceLocation StartLoc = OMD->getBeginLoc();
755e5dd7070Spatrick FunctionArgList args;
756e5dd7070Spatrick // Check if we should generate debug info for this method.
757e5dd7070Spatrick if (OMD->hasAttr<NoDebugAttr>())
758e5dd7070Spatrick DebugInfo = nullptr; // disable debug info indefinitely for this function
759e5dd7070Spatrick
760e5dd7070Spatrick llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
761e5dd7070Spatrick
762e5dd7070Spatrick const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
763e5dd7070Spatrick if (OMD->isDirectMethod()) {
764e5dd7070Spatrick Fn->setVisibility(llvm::Function::HiddenVisibility);
765a9ac8606Spatrick CGM.SetLLVMFunctionAttributes(OMD, FI, Fn, /*IsThunk=*/false);
766e5dd7070Spatrick CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
767e5dd7070Spatrick } else {
768e5dd7070Spatrick CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
769e5dd7070Spatrick }
770e5dd7070Spatrick
771e5dd7070Spatrick args.push_back(OMD->getSelfDecl());
772*12c85518Srobert if (!OMD->isDirectMethod())
773e5dd7070Spatrick args.push_back(OMD->getCmdDecl());
774e5dd7070Spatrick
775e5dd7070Spatrick args.append(OMD->param_begin(), OMD->param_end());
776e5dd7070Spatrick
777e5dd7070Spatrick CurGD = OMD;
778e5dd7070Spatrick CurEHLocation = OMD->getEndLoc();
779e5dd7070Spatrick
780e5dd7070Spatrick StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
781e5dd7070Spatrick OMD->getLocation(), StartLoc);
782e5dd7070Spatrick
783e5dd7070Spatrick if (OMD->isDirectMethod()) {
784e5dd7070Spatrick // This function is a direct call, it has to implement a nil check
785e5dd7070Spatrick // on entry.
786e5dd7070Spatrick //
787e5dd7070Spatrick // TODO: possibly have several entry points to elide the check
788e5dd7070Spatrick CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
789e5dd7070Spatrick }
790e5dd7070Spatrick
791e5dd7070Spatrick // In ARC, certain methods get an extra cleanup.
792e5dd7070Spatrick if (CGM.getLangOpts().ObjCAutoRefCount &&
793e5dd7070Spatrick OMD->isInstanceMethod() &&
794e5dd7070Spatrick OMD->getSelector().isUnarySelector()) {
795e5dd7070Spatrick const IdentifierInfo *ident =
796e5dd7070Spatrick OMD->getSelector().getIdentifierInfoForSlot(0);
797e5dd7070Spatrick if (ident->isStr("dealloc"))
798e5dd7070Spatrick EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
799e5dd7070Spatrick }
800e5dd7070Spatrick }
801e5dd7070Spatrick
802e5dd7070Spatrick static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
803e5dd7070Spatrick LValue lvalue, QualType type);
804e5dd7070Spatrick
805e5dd7070Spatrick /// Generate an Objective-C method. An Objective-C method is a C function with
806e5dd7070Spatrick /// its pointer, name, and types registered in the class structure.
GenerateObjCMethod(const ObjCMethodDecl * OMD)807e5dd7070Spatrick void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
808e5dd7070Spatrick StartObjCMethod(OMD, OMD->getClassInterface());
809e5dd7070Spatrick PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
810e5dd7070Spatrick assert(isa<CompoundStmt>(OMD->getBody()));
811e5dd7070Spatrick incrementProfileCounter(OMD->getBody());
812e5dd7070Spatrick EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
813e5dd7070Spatrick FinishFunction(OMD->getBodyRBrace());
814e5dd7070Spatrick }
815e5dd7070Spatrick
816e5dd7070Spatrick /// emitStructGetterCall - Call the runtime function to load a property
817e5dd7070Spatrick /// into the return value slot.
emitStructGetterCall(CodeGenFunction & CGF,ObjCIvarDecl * ivar,bool isAtomic,bool hasStrong)818e5dd7070Spatrick static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
819e5dd7070Spatrick bool isAtomic, bool hasStrong) {
820e5dd7070Spatrick ASTContext &Context = CGF.getContext();
821e5dd7070Spatrick
822*12c85518Srobert llvm::Value *src =
823e5dd7070Spatrick CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
824*12c85518Srobert .getPointer(CGF);
825e5dd7070Spatrick
826e5dd7070Spatrick // objc_copyStruct (ReturnValue, &structIvar,
827e5dd7070Spatrick // sizeof (Type of Ivar), isAtomic, false);
828e5dd7070Spatrick CallArgList args;
829e5dd7070Spatrick
830*12c85518Srobert llvm::Value *dest =
831*12c85518Srobert CGF.Builder.CreateBitCast(CGF.ReturnValue.getPointer(), CGF.VoidPtrTy);
832*12c85518Srobert args.add(RValue::get(dest), Context.VoidPtrTy);
833e5dd7070Spatrick
834e5dd7070Spatrick src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
835*12c85518Srobert args.add(RValue::get(src), Context.VoidPtrTy);
836e5dd7070Spatrick
837e5dd7070Spatrick CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
838e5dd7070Spatrick args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
839e5dd7070Spatrick args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
840e5dd7070Spatrick args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
841e5dd7070Spatrick
842e5dd7070Spatrick llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
843e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(fn);
844e5dd7070Spatrick CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
845e5dd7070Spatrick callee, ReturnValueSlot(), args);
846e5dd7070Spatrick }
847e5dd7070Spatrick
848e5dd7070Spatrick /// Determine whether the given architecture supports unaligned atomic
849e5dd7070Spatrick /// accesses. They don't have to be fast, just faster than a function
850e5dd7070Spatrick /// call and a mutex.
hasUnalignedAtomics(llvm::Triple::ArchType arch)851e5dd7070Spatrick static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
852e5dd7070Spatrick // FIXME: Allow unaligned atomic load/store on x86. (It is not
853e5dd7070Spatrick // currently supported by the backend.)
854*12c85518Srobert return false;
855e5dd7070Spatrick }
856e5dd7070Spatrick
857e5dd7070Spatrick /// Return the maximum size that permits atomic accesses for the given
858e5dd7070Spatrick /// architecture.
getMaxAtomicAccessSize(CodeGenModule & CGM,llvm::Triple::ArchType arch)859e5dd7070Spatrick static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
860e5dd7070Spatrick llvm::Triple::ArchType arch) {
861e5dd7070Spatrick // ARM has 8-byte atomic accesses, but it's not clear whether we
862e5dd7070Spatrick // want to rely on them here.
863e5dd7070Spatrick
864e5dd7070Spatrick // In the default case, just assume that any size up to a pointer is
865e5dd7070Spatrick // fine given adequate alignment.
866e5dd7070Spatrick return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
867e5dd7070Spatrick }
868e5dd7070Spatrick
869e5dd7070Spatrick namespace {
870e5dd7070Spatrick class PropertyImplStrategy {
871e5dd7070Spatrick public:
872e5dd7070Spatrick enum StrategyKind {
873e5dd7070Spatrick /// The 'native' strategy is to use the architecture's provided
874e5dd7070Spatrick /// reads and writes.
875e5dd7070Spatrick Native,
876e5dd7070Spatrick
877e5dd7070Spatrick /// Use objc_setProperty and objc_getProperty.
878e5dd7070Spatrick GetSetProperty,
879e5dd7070Spatrick
880e5dd7070Spatrick /// Use objc_setProperty for the setter, but use expression
881e5dd7070Spatrick /// evaluation for the getter.
882e5dd7070Spatrick SetPropertyAndExpressionGet,
883e5dd7070Spatrick
884e5dd7070Spatrick /// Use objc_copyStruct.
885e5dd7070Spatrick CopyStruct,
886e5dd7070Spatrick
887e5dd7070Spatrick /// The 'expression' strategy is to emit normal assignment or
888e5dd7070Spatrick /// lvalue-to-rvalue expressions.
889e5dd7070Spatrick Expression
890e5dd7070Spatrick };
891e5dd7070Spatrick
getKind() const892e5dd7070Spatrick StrategyKind getKind() const { return StrategyKind(Kind); }
893e5dd7070Spatrick
hasStrongMember() const894e5dd7070Spatrick bool hasStrongMember() const { return HasStrong; }
isAtomic() const895e5dd7070Spatrick bool isAtomic() const { return IsAtomic; }
isCopy() const896e5dd7070Spatrick bool isCopy() const { return IsCopy; }
897e5dd7070Spatrick
getIvarSize() const898e5dd7070Spatrick CharUnits getIvarSize() const { return IvarSize; }
getIvarAlignment() const899e5dd7070Spatrick CharUnits getIvarAlignment() const { return IvarAlignment; }
900e5dd7070Spatrick
901e5dd7070Spatrick PropertyImplStrategy(CodeGenModule &CGM,
902e5dd7070Spatrick const ObjCPropertyImplDecl *propImpl);
903e5dd7070Spatrick
904e5dd7070Spatrick private:
905e5dd7070Spatrick unsigned Kind : 8;
906e5dd7070Spatrick unsigned IsAtomic : 1;
907e5dd7070Spatrick unsigned IsCopy : 1;
908e5dd7070Spatrick unsigned HasStrong : 1;
909e5dd7070Spatrick
910e5dd7070Spatrick CharUnits IvarSize;
911e5dd7070Spatrick CharUnits IvarAlignment;
912e5dd7070Spatrick };
913e5dd7070Spatrick }
914e5dd7070Spatrick
915e5dd7070Spatrick /// Pick an implementation strategy for the given property synthesis.
PropertyImplStrategy(CodeGenModule & CGM,const ObjCPropertyImplDecl * propImpl)916e5dd7070Spatrick PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
917e5dd7070Spatrick const ObjCPropertyImplDecl *propImpl) {
918e5dd7070Spatrick const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
919e5dd7070Spatrick ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
920e5dd7070Spatrick
921e5dd7070Spatrick IsCopy = (setterKind == ObjCPropertyDecl::Copy);
922e5dd7070Spatrick IsAtomic = prop->isAtomic();
923e5dd7070Spatrick HasStrong = false; // doesn't matter here.
924e5dd7070Spatrick
925e5dd7070Spatrick // Evaluate the ivar's size and alignment.
926e5dd7070Spatrick ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
927e5dd7070Spatrick QualType ivarType = ivar->getType();
928a9ac8606Spatrick auto TInfo = CGM.getContext().getTypeInfoInChars(ivarType);
929a9ac8606Spatrick IvarSize = TInfo.Width;
930a9ac8606Spatrick IvarAlignment = TInfo.Align;
931e5dd7070Spatrick
932a9ac8606Spatrick // If we have a copy property, we always have to use setProperty.
933a9ac8606Spatrick // If the property is atomic we need to use getProperty, but in
934a9ac8606Spatrick // the nonatomic case we can just use expression.
935e5dd7070Spatrick if (IsCopy) {
936a9ac8606Spatrick Kind = IsAtomic ? GetSetProperty : SetPropertyAndExpressionGet;
937e5dd7070Spatrick return;
938e5dd7070Spatrick }
939e5dd7070Spatrick
940e5dd7070Spatrick // Handle retain.
941e5dd7070Spatrick if (setterKind == ObjCPropertyDecl::Retain) {
942e5dd7070Spatrick // In GC-only, there's nothing special that needs to be done.
943e5dd7070Spatrick if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
944e5dd7070Spatrick // fallthrough
945e5dd7070Spatrick
946e5dd7070Spatrick // In ARC, if the property is non-atomic, use expression emission,
947e5dd7070Spatrick // which translates to objc_storeStrong. This isn't required, but
948e5dd7070Spatrick // it's slightly nicer.
949e5dd7070Spatrick } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
950e5dd7070Spatrick // Using standard expression emission for the setter is only
951e5dd7070Spatrick // acceptable if the ivar is __strong, which won't be true if
952e5dd7070Spatrick // the property is annotated with __attribute__((NSObject)).
953e5dd7070Spatrick // TODO: falling all the way back to objc_setProperty here is
954e5dd7070Spatrick // just laziness, though; we could still use objc_storeStrong
955e5dd7070Spatrick // if we hacked it right.
956e5dd7070Spatrick if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
957e5dd7070Spatrick Kind = Expression;
958e5dd7070Spatrick else
959e5dd7070Spatrick Kind = SetPropertyAndExpressionGet;
960e5dd7070Spatrick return;
961e5dd7070Spatrick
962e5dd7070Spatrick // Otherwise, we need to at least use setProperty. However, if
963e5dd7070Spatrick // the property isn't atomic, we can use normal expression
964e5dd7070Spatrick // emission for the getter.
965e5dd7070Spatrick } else if (!IsAtomic) {
966e5dd7070Spatrick Kind = SetPropertyAndExpressionGet;
967e5dd7070Spatrick return;
968e5dd7070Spatrick
969e5dd7070Spatrick // Otherwise, we have to use both setProperty and getProperty.
970e5dd7070Spatrick } else {
971e5dd7070Spatrick Kind = GetSetProperty;
972e5dd7070Spatrick return;
973e5dd7070Spatrick }
974e5dd7070Spatrick }
975e5dd7070Spatrick
976e5dd7070Spatrick // If we're not atomic, just use expression accesses.
977e5dd7070Spatrick if (!IsAtomic) {
978e5dd7070Spatrick Kind = Expression;
979e5dd7070Spatrick return;
980e5dd7070Spatrick }
981e5dd7070Spatrick
982e5dd7070Spatrick // Properties on bitfield ivars need to be emitted using expression
983e5dd7070Spatrick // accesses even if they're nominally atomic.
984e5dd7070Spatrick if (ivar->isBitField()) {
985e5dd7070Spatrick Kind = Expression;
986e5dd7070Spatrick return;
987e5dd7070Spatrick }
988e5dd7070Spatrick
989e5dd7070Spatrick // GC-qualified or ARC-qualified ivars need to be emitted as
990e5dd7070Spatrick // expressions. This actually works out to being atomic anyway,
991e5dd7070Spatrick // except for ARC __strong, but that should trigger the above code.
992e5dd7070Spatrick if (ivarType.hasNonTrivialObjCLifetime() ||
993e5dd7070Spatrick (CGM.getLangOpts().getGC() &&
994e5dd7070Spatrick CGM.getContext().getObjCGCAttrKind(ivarType))) {
995e5dd7070Spatrick Kind = Expression;
996e5dd7070Spatrick return;
997e5dd7070Spatrick }
998e5dd7070Spatrick
999e5dd7070Spatrick // Compute whether the ivar has strong members.
1000e5dd7070Spatrick if (CGM.getLangOpts().getGC())
1001e5dd7070Spatrick if (const RecordType *recordType = ivarType->getAs<RecordType>())
1002e5dd7070Spatrick HasStrong = recordType->getDecl()->hasObjectMember();
1003e5dd7070Spatrick
1004e5dd7070Spatrick // We can never access structs with object members with a native
1005e5dd7070Spatrick // access, because we need to use write barriers. This is what
1006e5dd7070Spatrick // objc_copyStruct is for.
1007e5dd7070Spatrick if (HasStrong) {
1008e5dd7070Spatrick Kind = CopyStruct;
1009e5dd7070Spatrick return;
1010e5dd7070Spatrick }
1011e5dd7070Spatrick
1012e5dd7070Spatrick // Otherwise, this is target-dependent and based on the size and
1013e5dd7070Spatrick // alignment of the ivar.
1014e5dd7070Spatrick
1015e5dd7070Spatrick // If the size of the ivar is not a power of two, give up. We don't
1016e5dd7070Spatrick // want to get into the business of doing compare-and-swaps.
1017e5dd7070Spatrick if (!IvarSize.isPowerOfTwo()) {
1018e5dd7070Spatrick Kind = CopyStruct;
1019e5dd7070Spatrick return;
1020e5dd7070Spatrick }
1021e5dd7070Spatrick
1022e5dd7070Spatrick llvm::Triple::ArchType arch =
1023e5dd7070Spatrick CGM.getTarget().getTriple().getArch();
1024e5dd7070Spatrick
1025e5dd7070Spatrick // Most architectures require memory to fit within a single cache
1026e5dd7070Spatrick // line, so the alignment has to be at least the size of the access.
1027e5dd7070Spatrick // Otherwise we have to grab a lock.
1028e5dd7070Spatrick if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
1029e5dd7070Spatrick Kind = CopyStruct;
1030e5dd7070Spatrick return;
1031e5dd7070Spatrick }
1032e5dd7070Spatrick
1033e5dd7070Spatrick // If the ivar's size exceeds the architecture's maximum atomic
1034e5dd7070Spatrick // access size, we have to use CopyStruct.
1035e5dd7070Spatrick if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
1036e5dd7070Spatrick Kind = CopyStruct;
1037e5dd7070Spatrick return;
1038e5dd7070Spatrick }
1039e5dd7070Spatrick
1040e5dd7070Spatrick // Otherwise, we can use native loads and stores.
1041e5dd7070Spatrick Kind = Native;
1042e5dd7070Spatrick }
1043e5dd7070Spatrick
1044e5dd7070Spatrick /// Generate an Objective-C property getter function.
1045e5dd7070Spatrick ///
1046e5dd7070Spatrick /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1047e5dd7070Spatrick /// is illegal within a category.
GenerateObjCGetter(ObjCImplementationDecl * IMP,const ObjCPropertyImplDecl * PID)1048e5dd7070Spatrick void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
1049e5dd7070Spatrick const ObjCPropertyImplDecl *PID) {
1050e5dd7070Spatrick llvm::Constant *AtomicHelperFn =
1051e5dd7070Spatrick CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
1052e5dd7070Spatrick ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
1053e5dd7070Spatrick assert(OMD && "Invalid call to generate getter (empty method)");
1054e5dd7070Spatrick StartObjCMethod(OMD, IMP->getClassInterface());
1055e5dd7070Spatrick
1056e5dd7070Spatrick generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
1057e5dd7070Spatrick
1058e5dd7070Spatrick FinishFunction(OMD->getEndLoc());
1059e5dd7070Spatrick }
1060e5dd7070Spatrick
hasTrivialGetExpr(const ObjCPropertyImplDecl * propImpl)1061e5dd7070Spatrick static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
1062e5dd7070Spatrick const Expr *getter = propImpl->getGetterCXXConstructor();
1063e5dd7070Spatrick if (!getter) return true;
1064e5dd7070Spatrick
1065e5dd7070Spatrick // Sema only makes only of these when the ivar has a C++ class type,
1066e5dd7070Spatrick // so the form is pretty constrained.
1067e5dd7070Spatrick
1068e5dd7070Spatrick // If the property has a reference type, we might just be binding a
1069e5dd7070Spatrick // reference, in which case the result will be a gl-value. We should
1070e5dd7070Spatrick // treat this as a non-trivial operation.
1071e5dd7070Spatrick if (getter->isGLValue())
1072e5dd7070Spatrick return false;
1073e5dd7070Spatrick
1074e5dd7070Spatrick // If we selected a trivial copy-constructor, we're okay.
1075e5dd7070Spatrick if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1076e5dd7070Spatrick return (construct->getConstructor()->isTrivial());
1077e5dd7070Spatrick
1078e5dd7070Spatrick // The constructor might require cleanups (in which case it's never
1079e5dd7070Spatrick // trivial).
1080e5dd7070Spatrick assert(isa<ExprWithCleanups>(getter));
1081e5dd7070Spatrick return false;
1082e5dd7070Spatrick }
1083e5dd7070Spatrick
1084e5dd7070Spatrick /// emitCPPObjectAtomicGetterCall - Call the runtime function to
1085e5dd7070Spatrick /// copy the ivar into the resturn slot.
emitCPPObjectAtomicGetterCall(CodeGenFunction & CGF,llvm::Value * returnAddr,ObjCIvarDecl * ivar,llvm::Constant * AtomicHelperFn)1086e5dd7070Spatrick static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
1087e5dd7070Spatrick llvm::Value *returnAddr,
1088e5dd7070Spatrick ObjCIvarDecl *ivar,
1089e5dd7070Spatrick llvm::Constant *AtomicHelperFn) {
1090e5dd7070Spatrick // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1091e5dd7070Spatrick // AtomicHelperFn);
1092e5dd7070Spatrick CallArgList args;
1093e5dd7070Spatrick
1094e5dd7070Spatrick // The 1st argument is the return Slot.
1095e5dd7070Spatrick args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1096e5dd7070Spatrick
1097e5dd7070Spatrick // The 2nd argument is the address of the ivar.
1098e5dd7070Spatrick llvm::Value *ivarAddr =
1099e5dd7070Spatrick CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1100e5dd7070Spatrick .getPointer(CGF);
1101e5dd7070Spatrick ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1102e5dd7070Spatrick args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1103e5dd7070Spatrick
1104e5dd7070Spatrick // Third argument is the helper function.
1105e5dd7070Spatrick args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1106e5dd7070Spatrick
1107e5dd7070Spatrick llvm::FunctionCallee copyCppAtomicObjectFn =
1108e5dd7070Spatrick CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
1109e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1110e5dd7070Spatrick CGF.EmitCall(
1111e5dd7070Spatrick CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1112e5dd7070Spatrick callee, ReturnValueSlot(), args);
1113e5dd7070Spatrick }
1114e5dd7070Spatrick
1115*12c85518Srobert // emitCmdValueForGetterSetterBody - Handle emitting the load necessary for
1116*12c85518Srobert // the `_cmd` selector argument for getter/setter bodies. For direct methods,
1117*12c85518Srobert // this returns an undefined/poison value; this matches behavior prior to `_cmd`
1118*12c85518Srobert // being removed from the direct method ABI as the getter/setter caller would
1119*12c85518Srobert // never load one. For non-direct methods, this emits a load of the implicit
1120*12c85518Srobert // `_cmd` storage.
emitCmdValueForGetterSetterBody(CodeGenFunction & CGF,ObjCMethodDecl * MD)1121*12c85518Srobert static llvm::Value *emitCmdValueForGetterSetterBody(CodeGenFunction &CGF,
1122*12c85518Srobert ObjCMethodDecl *MD) {
1123*12c85518Srobert if (MD->isDirectMethod()) {
1124*12c85518Srobert // Direct methods do not have a `_cmd` argument. Emit an undefined/poison
1125*12c85518Srobert // value. This will be passed to objc_getProperty/objc_setProperty, which
1126*12c85518Srobert // has not appeared bothered by the `_cmd` argument being undefined before.
1127*12c85518Srobert llvm::Type *selType = CGF.ConvertType(CGF.getContext().getObjCSelType());
1128*12c85518Srobert return llvm::PoisonValue::get(selType);
1129*12c85518Srobert }
1130*12c85518Srobert
1131*12c85518Srobert return CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(MD->getCmdDecl()), "cmd");
1132*12c85518Srobert }
1133*12c85518Srobert
1134e5dd7070Spatrick void
generateObjCGetterBody(const ObjCImplementationDecl * classImpl,const ObjCPropertyImplDecl * propImpl,const ObjCMethodDecl * GetterMethodDecl,llvm::Constant * AtomicHelperFn)1135e5dd7070Spatrick CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1136e5dd7070Spatrick const ObjCPropertyImplDecl *propImpl,
1137e5dd7070Spatrick const ObjCMethodDecl *GetterMethodDecl,
1138e5dd7070Spatrick llvm::Constant *AtomicHelperFn) {
1139*12c85518Srobert
1140*12c85518Srobert ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1141*12c85518Srobert
1142*12c85518Srobert if (ivar->getType().isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
1143*12c85518Srobert if (!AtomicHelperFn) {
1144*12c85518Srobert LValue Src =
1145*12c85518Srobert EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1146*12c85518Srobert LValue Dst = MakeAddrLValue(ReturnValue, ivar->getType());
1147*12c85518Srobert callCStructCopyConstructor(Dst, Src);
1148*12c85518Srobert } else {
1149*12c85518Srobert ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1150*12c85518Srobert emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(), ivar,
1151*12c85518Srobert AtomicHelperFn);
1152*12c85518Srobert }
1153*12c85518Srobert return;
1154*12c85518Srobert }
1155*12c85518Srobert
1156e5dd7070Spatrick // If there's a non-trivial 'get' expression, we just have to emit that.
1157e5dd7070Spatrick if (!hasTrivialGetExpr(propImpl)) {
1158e5dd7070Spatrick if (!AtomicHelperFn) {
1159e5dd7070Spatrick auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1160e5dd7070Spatrick propImpl->getGetterCXXConstructor(),
1161e5dd7070Spatrick /* NRVOCandidate=*/nullptr);
1162e5dd7070Spatrick EmitReturnStmt(*ret);
1163e5dd7070Spatrick }
1164e5dd7070Spatrick else {
1165e5dd7070Spatrick ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1166e5dd7070Spatrick emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
1167e5dd7070Spatrick ivar, AtomicHelperFn);
1168e5dd7070Spatrick }
1169e5dd7070Spatrick return;
1170e5dd7070Spatrick }
1171e5dd7070Spatrick
1172e5dd7070Spatrick const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1173e5dd7070Spatrick QualType propType = prop->getType();
1174e5dd7070Spatrick ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1175e5dd7070Spatrick
1176e5dd7070Spatrick // Pick an implementation strategy.
1177e5dd7070Spatrick PropertyImplStrategy strategy(CGM, propImpl);
1178e5dd7070Spatrick switch (strategy.getKind()) {
1179e5dd7070Spatrick case PropertyImplStrategy::Native: {
1180e5dd7070Spatrick // We don't need to do anything for a zero-size struct.
1181e5dd7070Spatrick if (strategy.getIvarSize().isZero())
1182e5dd7070Spatrick return;
1183e5dd7070Spatrick
1184e5dd7070Spatrick LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1185e5dd7070Spatrick
1186e5dd7070Spatrick // Currently, all atomic accesses have to be through integer
1187e5dd7070Spatrick // types, so there's no point in trying to pick a prettier type.
1188e5dd7070Spatrick uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1189e5dd7070Spatrick llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1190e5dd7070Spatrick
1191e5dd7070Spatrick // Perform an atomic load. This does not impose ordering constraints.
1192e5dd7070Spatrick Address ivarAddr = LV.getAddress(*this);
1193*12c85518Srobert ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1194e5dd7070Spatrick llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1195e5dd7070Spatrick load->setAtomic(llvm::AtomicOrdering::Unordered);
1196e5dd7070Spatrick
1197e5dd7070Spatrick // Store that value into the return address. Doing this with a
1198e5dd7070Spatrick // bitcast is likely to produce some pretty ugly IR, but it's not
1199e5dd7070Spatrick // the *most* terrible thing in the world.
1200e5dd7070Spatrick llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1201e5dd7070Spatrick uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1202e5dd7070Spatrick llvm::Value *ivarVal = load;
1203e5dd7070Spatrick if (ivarSize > retTySize) {
1204*12c85518Srobert bitcastType = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1205*12c85518Srobert ivarVal = Builder.CreateTrunc(load, bitcastType);
1206e5dd7070Spatrick }
1207e5dd7070Spatrick Builder.CreateStore(ivarVal,
1208*12c85518Srobert Builder.CreateElementBitCast(ReturnValue, bitcastType));
1209e5dd7070Spatrick
1210e5dd7070Spatrick // Make sure we don't do an autorelease.
1211e5dd7070Spatrick AutoreleaseResult = false;
1212e5dd7070Spatrick return;
1213e5dd7070Spatrick }
1214e5dd7070Spatrick
1215e5dd7070Spatrick case PropertyImplStrategy::GetSetProperty: {
1216e5dd7070Spatrick llvm::FunctionCallee getPropertyFn =
1217e5dd7070Spatrick CGM.getObjCRuntime().GetPropertyGetFunction();
1218e5dd7070Spatrick if (!getPropertyFn) {
1219e5dd7070Spatrick CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1220e5dd7070Spatrick return;
1221e5dd7070Spatrick }
1222e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(getPropertyFn);
1223e5dd7070Spatrick
1224e5dd7070Spatrick // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1225e5dd7070Spatrick // FIXME: Can't this be simpler? This might even be worse than the
1226e5dd7070Spatrick // corresponding gcc code.
1227*12c85518Srobert llvm::Value *cmd = emitCmdValueForGetterSetterBody(*this, getterMethod);
1228e5dd7070Spatrick llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1229e5dd7070Spatrick llvm::Value *ivarOffset =
1230*12c85518Srobert EmitIvarOffsetAsPointerDiff(classImpl->getClassInterface(), ivar);
1231e5dd7070Spatrick
1232e5dd7070Spatrick CallArgList args;
1233e5dd7070Spatrick args.add(RValue::get(self), getContext().getObjCIdType());
1234e5dd7070Spatrick args.add(RValue::get(cmd), getContext().getObjCSelType());
1235e5dd7070Spatrick args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1236e5dd7070Spatrick args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1237e5dd7070Spatrick getContext().BoolTy);
1238e5dd7070Spatrick
1239e5dd7070Spatrick // FIXME: We shouldn't need to get the function info here, the
1240e5dd7070Spatrick // runtime already should have computed it to build the function.
1241e5dd7070Spatrick llvm::CallBase *CallInstruction;
1242e5dd7070Spatrick RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1243e5dd7070Spatrick getContext().getObjCIdType(), args),
1244e5dd7070Spatrick callee, ReturnValueSlot(), args, &CallInstruction);
1245e5dd7070Spatrick if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1246e5dd7070Spatrick call->setTailCall();
1247e5dd7070Spatrick
1248e5dd7070Spatrick // We need to fix the type here. Ivars with copy & retain are
1249e5dd7070Spatrick // always objects so we don't need to worry about complex or
1250e5dd7070Spatrick // aggregates.
1251e5dd7070Spatrick RV = RValue::get(Builder.CreateBitCast(
1252e5dd7070Spatrick RV.getScalarVal(),
1253e5dd7070Spatrick getTypes().ConvertType(getterMethod->getReturnType())));
1254e5dd7070Spatrick
1255e5dd7070Spatrick EmitReturnOfRValue(RV, propType);
1256e5dd7070Spatrick
1257e5dd7070Spatrick // objc_getProperty does an autorelease, so we should suppress ours.
1258e5dd7070Spatrick AutoreleaseResult = false;
1259e5dd7070Spatrick
1260e5dd7070Spatrick return;
1261e5dd7070Spatrick }
1262e5dd7070Spatrick
1263e5dd7070Spatrick case PropertyImplStrategy::CopyStruct:
1264e5dd7070Spatrick emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1265e5dd7070Spatrick strategy.hasStrongMember());
1266e5dd7070Spatrick return;
1267e5dd7070Spatrick
1268e5dd7070Spatrick case PropertyImplStrategy::Expression:
1269e5dd7070Spatrick case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1270e5dd7070Spatrick LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1271e5dd7070Spatrick
1272e5dd7070Spatrick QualType ivarType = ivar->getType();
1273e5dd7070Spatrick switch (getEvaluationKind(ivarType)) {
1274e5dd7070Spatrick case TEK_Complex: {
1275e5dd7070Spatrick ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
1276e5dd7070Spatrick EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
1277e5dd7070Spatrick /*init*/ true);
1278e5dd7070Spatrick return;
1279e5dd7070Spatrick }
1280e5dd7070Spatrick case TEK_Aggregate: {
1281e5dd7070Spatrick // The return value slot is guaranteed to not be aliased, but
1282e5dd7070Spatrick // that's not necessarily the same as "on the stack", so
1283e5dd7070Spatrick // we still potentially need objc_memmove_collectable.
1284e5dd7070Spatrick EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1285e5dd7070Spatrick /* Src= */ LV, ivarType, getOverlapForReturnValue());
1286e5dd7070Spatrick return;
1287e5dd7070Spatrick }
1288e5dd7070Spatrick case TEK_Scalar: {
1289e5dd7070Spatrick llvm::Value *value;
1290e5dd7070Spatrick if (propType->isReferenceType()) {
1291e5dd7070Spatrick value = LV.getAddress(*this).getPointer();
1292e5dd7070Spatrick } else {
1293e5dd7070Spatrick // We want to load and autoreleaseReturnValue ARC __weak ivars.
1294e5dd7070Spatrick if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1295e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount) {
1296e5dd7070Spatrick value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1297e5dd7070Spatrick } else {
1298e5dd7070Spatrick value = EmitARCLoadWeak(LV.getAddress(*this));
1299e5dd7070Spatrick }
1300e5dd7070Spatrick
1301e5dd7070Spatrick // Otherwise we want to do a simple load, suppressing the
1302e5dd7070Spatrick // final autorelease.
1303e5dd7070Spatrick } else {
1304e5dd7070Spatrick value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1305e5dd7070Spatrick AutoreleaseResult = false;
1306e5dd7070Spatrick }
1307e5dd7070Spatrick
1308e5dd7070Spatrick value = Builder.CreateBitCast(
1309e5dd7070Spatrick value, ConvertType(GetterMethodDecl->getReturnType()));
1310e5dd7070Spatrick }
1311e5dd7070Spatrick
1312e5dd7070Spatrick EmitReturnOfRValue(RValue::get(value), propType);
1313e5dd7070Spatrick return;
1314e5dd7070Spatrick }
1315e5dd7070Spatrick }
1316e5dd7070Spatrick llvm_unreachable("bad evaluation kind");
1317e5dd7070Spatrick }
1318e5dd7070Spatrick
1319e5dd7070Spatrick }
1320e5dd7070Spatrick llvm_unreachable("bad @property implementation strategy!");
1321e5dd7070Spatrick }
1322e5dd7070Spatrick
1323e5dd7070Spatrick /// emitStructSetterCall - Call the runtime function to store the value
1324e5dd7070Spatrick /// from the first formal parameter into the given ivar.
emitStructSetterCall(CodeGenFunction & CGF,ObjCMethodDecl * OMD,ObjCIvarDecl * ivar)1325e5dd7070Spatrick static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1326e5dd7070Spatrick ObjCIvarDecl *ivar) {
1327e5dd7070Spatrick // objc_copyStruct (&structIvar, &Arg,
1328e5dd7070Spatrick // sizeof (struct something), true, false);
1329e5dd7070Spatrick CallArgList args;
1330e5dd7070Spatrick
1331e5dd7070Spatrick // The first argument is the address of the ivar.
1332e5dd7070Spatrick llvm::Value *ivarAddr =
1333e5dd7070Spatrick CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1334e5dd7070Spatrick .getPointer(CGF);
1335e5dd7070Spatrick ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1336e5dd7070Spatrick args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1337e5dd7070Spatrick
1338e5dd7070Spatrick // The second argument is the address of the parameter variable.
1339e5dd7070Spatrick ParmVarDecl *argVar = *OMD->param_begin();
1340e5dd7070Spatrick DeclRefExpr argRef(CGF.getContext(), argVar, false,
1341e5dd7070Spatrick argVar->getType().getNonReferenceType(), VK_LValue,
1342e5dd7070Spatrick SourceLocation());
1343e5dd7070Spatrick llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1344e5dd7070Spatrick argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1345e5dd7070Spatrick args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1346e5dd7070Spatrick
1347e5dd7070Spatrick // The third argument is the sizeof the type.
1348e5dd7070Spatrick llvm::Value *size =
1349e5dd7070Spatrick CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1350e5dd7070Spatrick args.add(RValue::get(size), CGF.getContext().getSizeType());
1351e5dd7070Spatrick
1352e5dd7070Spatrick // The fourth argument is the 'isAtomic' flag.
1353e5dd7070Spatrick args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1354e5dd7070Spatrick
1355e5dd7070Spatrick // The fifth argument is the 'hasStrong' flag.
1356e5dd7070Spatrick // FIXME: should this really always be false?
1357e5dd7070Spatrick args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1358e5dd7070Spatrick
1359e5dd7070Spatrick llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1360e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(fn);
1361e5dd7070Spatrick CGF.EmitCall(
1362e5dd7070Spatrick CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1363e5dd7070Spatrick callee, ReturnValueSlot(), args);
1364e5dd7070Spatrick }
1365e5dd7070Spatrick
1366e5dd7070Spatrick /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1367e5dd7070Spatrick /// the value from the first formal parameter into the given ivar, using
1368e5dd7070Spatrick /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
emitCPPObjectAtomicSetterCall(CodeGenFunction & CGF,ObjCMethodDecl * OMD,ObjCIvarDecl * ivar,llvm::Constant * AtomicHelperFn)1369e5dd7070Spatrick static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1370e5dd7070Spatrick ObjCMethodDecl *OMD,
1371e5dd7070Spatrick ObjCIvarDecl *ivar,
1372e5dd7070Spatrick llvm::Constant *AtomicHelperFn) {
1373e5dd7070Spatrick // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1374e5dd7070Spatrick // AtomicHelperFn);
1375e5dd7070Spatrick CallArgList args;
1376e5dd7070Spatrick
1377e5dd7070Spatrick // The first argument is the address of the ivar.
1378e5dd7070Spatrick llvm::Value *ivarAddr =
1379e5dd7070Spatrick CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1380e5dd7070Spatrick .getPointer(CGF);
1381e5dd7070Spatrick ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1382e5dd7070Spatrick args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1383e5dd7070Spatrick
1384e5dd7070Spatrick // The second argument is the address of the parameter variable.
1385e5dd7070Spatrick ParmVarDecl *argVar = *OMD->param_begin();
1386e5dd7070Spatrick DeclRefExpr argRef(CGF.getContext(), argVar, false,
1387e5dd7070Spatrick argVar->getType().getNonReferenceType(), VK_LValue,
1388e5dd7070Spatrick SourceLocation());
1389e5dd7070Spatrick llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1390e5dd7070Spatrick argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1391e5dd7070Spatrick args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1392e5dd7070Spatrick
1393e5dd7070Spatrick // Third argument is the helper function.
1394e5dd7070Spatrick args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1395e5dd7070Spatrick
1396e5dd7070Spatrick llvm::FunctionCallee fn =
1397e5dd7070Spatrick CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1398e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(fn);
1399e5dd7070Spatrick CGF.EmitCall(
1400e5dd7070Spatrick CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1401e5dd7070Spatrick callee, ReturnValueSlot(), args);
1402e5dd7070Spatrick }
1403e5dd7070Spatrick
1404e5dd7070Spatrick
hasTrivialSetExpr(const ObjCPropertyImplDecl * PID)1405e5dd7070Spatrick static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1406e5dd7070Spatrick Expr *setter = PID->getSetterCXXAssignment();
1407e5dd7070Spatrick if (!setter) return true;
1408e5dd7070Spatrick
1409e5dd7070Spatrick // Sema only makes only of these when the ivar has a C++ class type,
1410e5dd7070Spatrick // so the form is pretty constrained.
1411e5dd7070Spatrick
1412e5dd7070Spatrick // An operator call is trivial if the function it calls is trivial.
1413e5dd7070Spatrick // This also implies that there's nothing non-trivial going on with
1414e5dd7070Spatrick // the arguments, because operator= can only be trivial if it's a
1415e5dd7070Spatrick // synthesized assignment operator and therefore both parameters are
1416e5dd7070Spatrick // references.
1417e5dd7070Spatrick if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1418e5dd7070Spatrick if (const FunctionDecl *callee
1419e5dd7070Spatrick = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1420e5dd7070Spatrick if (callee->isTrivial())
1421e5dd7070Spatrick return true;
1422e5dd7070Spatrick return false;
1423e5dd7070Spatrick }
1424e5dd7070Spatrick
1425e5dd7070Spatrick assert(isa<ExprWithCleanups>(setter));
1426e5dd7070Spatrick return false;
1427e5dd7070Spatrick }
1428e5dd7070Spatrick
UseOptimizedSetter(CodeGenModule & CGM)1429e5dd7070Spatrick static bool UseOptimizedSetter(CodeGenModule &CGM) {
1430e5dd7070Spatrick if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1431e5dd7070Spatrick return false;
1432e5dd7070Spatrick return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1433e5dd7070Spatrick }
1434e5dd7070Spatrick
1435e5dd7070Spatrick void
generateObjCSetterBody(const ObjCImplementationDecl * classImpl,const ObjCPropertyImplDecl * propImpl,llvm::Constant * AtomicHelperFn)1436e5dd7070Spatrick CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1437e5dd7070Spatrick const ObjCPropertyImplDecl *propImpl,
1438e5dd7070Spatrick llvm::Constant *AtomicHelperFn) {
1439e5dd7070Spatrick ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1440e5dd7070Spatrick ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1441e5dd7070Spatrick
1442*12c85518Srobert if (ivar->getType().isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
1443*12c85518Srobert ParmVarDecl *PVD = *setterMethod->param_begin();
1444*12c85518Srobert if (!AtomicHelperFn) {
1445*12c85518Srobert // Call the move assignment operator instead of calling the copy
1446*12c85518Srobert // assignment operator and destructor.
1447*12c85518Srobert LValue Dst = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar,
1448*12c85518Srobert /*quals*/ 0);
1449*12c85518Srobert LValue Src = MakeAddrLValue(GetAddrOfLocalVar(PVD), ivar->getType());
1450*12c85518Srobert callCStructMoveAssignmentOperator(Dst, Src);
1451*12c85518Srobert } else {
1452*12c85518Srobert // If atomic, assignment is called via a locking api.
1453*12c85518Srobert emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar, AtomicHelperFn);
1454*12c85518Srobert }
1455*12c85518Srobert // Decativate the destructor for the setter parameter.
1456*12c85518Srobert DeactivateCleanupBlock(CalleeDestructedParamCleanups[PVD], AllocaInsertPt);
1457*12c85518Srobert return;
1458*12c85518Srobert }
1459*12c85518Srobert
1460e5dd7070Spatrick // Just use the setter expression if Sema gave us one and it's
1461e5dd7070Spatrick // non-trivial.
1462e5dd7070Spatrick if (!hasTrivialSetExpr(propImpl)) {
1463e5dd7070Spatrick if (!AtomicHelperFn)
1464e5dd7070Spatrick // If non-atomic, assignment is called directly.
1465e5dd7070Spatrick EmitStmt(propImpl->getSetterCXXAssignment());
1466e5dd7070Spatrick else
1467e5dd7070Spatrick // If atomic, assignment is called via a locking api.
1468e5dd7070Spatrick emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1469e5dd7070Spatrick AtomicHelperFn);
1470e5dd7070Spatrick return;
1471e5dd7070Spatrick }
1472e5dd7070Spatrick
1473e5dd7070Spatrick PropertyImplStrategy strategy(CGM, propImpl);
1474e5dd7070Spatrick switch (strategy.getKind()) {
1475e5dd7070Spatrick case PropertyImplStrategy::Native: {
1476e5dd7070Spatrick // We don't need to do anything for a zero-size struct.
1477e5dd7070Spatrick if (strategy.getIvarSize().isZero())
1478e5dd7070Spatrick return;
1479e5dd7070Spatrick
1480e5dd7070Spatrick Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1481e5dd7070Spatrick
1482e5dd7070Spatrick LValue ivarLValue =
1483e5dd7070Spatrick EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1484e5dd7070Spatrick Address ivarAddr = ivarLValue.getAddress(*this);
1485e5dd7070Spatrick
1486e5dd7070Spatrick // Currently, all atomic accesses have to be through integer
1487e5dd7070Spatrick // types, so there's no point in trying to pick a prettier type.
1488e5dd7070Spatrick llvm::Type *bitcastType =
1489e5dd7070Spatrick llvm::Type::getIntNTy(getLLVMContext(),
1490e5dd7070Spatrick getContext().toBits(strategy.getIvarSize()));
1491e5dd7070Spatrick
1492e5dd7070Spatrick // Cast both arguments to the chosen operation type.
1493e5dd7070Spatrick argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1494e5dd7070Spatrick ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1495e5dd7070Spatrick
1496e5dd7070Spatrick // This bitcast load is likely to cause some nasty IR.
1497e5dd7070Spatrick llvm::Value *load = Builder.CreateLoad(argAddr);
1498e5dd7070Spatrick
1499e5dd7070Spatrick // Perform an atomic store. There are no memory ordering requirements.
1500e5dd7070Spatrick llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1501e5dd7070Spatrick store->setAtomic(llvm::AtomicOrdering::Unordered);
1502e5dd7070Spatrick return;
1503e5dd7070Spatrick }
1504e5dd7070Spatrick
1505e5dd7070Spatrick case PropertyImplStrategy::GetSetProperty:
1506e5dd7070Spatrick case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1507e5dd7070Spatrick
1508e5dd7070Spatrick llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1509e5dd7070Spatrick llvm::FunctionCallee setPropertyFn = nullptr;
1510e5dd7070Spatrick if (UseOptimizedSetter(CGM)) {
1511e5dd7070Spatrick // 10.8 and iOS 6.0 code and GC is off
1512e5dd7070Spatrick setOptimizedPropertyFn =
1513e5dd7070Spatrick CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1514e5dd7070Spatrick strategy.isAtomic(), strategy.isCopy());
1515e5dd7070Spatrick if (!setOptimizedPropertyFn) {
1516e5dd7070Spatrick CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1517e5dd7070Spatrick return;
1518e5dd7070Spatrick }
1519e5dd7070Spatrick }
1520e5dd7070Spatrick else {
1521e5dd7070Spatrick setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1522e5dd7070Spatrick if (!setPropertyFn) {
1523e5dd7070Spatrick CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1524e5dd7070Spatrick return;
1525e5dd7070Spatrick }
1526e5dd7070Spatrick }
1527e5dd7070Spatrick
1528e5dd7070Spatrick // Emit objc_setProperty((id) self, _cmd, offset, arg,
1529e5dd7070Spatrick // <is-atomic>, <is-copy>).
1530*12c85518Srobert llvm::Value *cmd = emitCmdValueForGetterSetterBody(*this, setterMethod);
1531e5dd7070Spatrick llvm::Value *self =
1532e5dd7070Spatrick Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1533e5dd7070Spatrick llvm::Value *ivarOffset =
1534*12c85518Srobert EmitIvarOffsetAsPointerDiff(classImpl->getClassInterface(), ivar);
1535e5dd7070Spatrick Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1536e5dd7070Spatrick llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1537e5dd7070Spatrick arg = Builder.CreateBitCast(arg, VoidPtrTy);
1538e5dd7070Spatrick
1539e5dd7070Spatrick CallArgList args;
1540e5dd7070Spatrick args.add(RValue::get(self), getContext().getObjCIdType());
1541e5dd7070Spatrick args.add(RValue::get(cmd), getContext().getObjCSelType());
1542e5dd7070Spatrick if (setOptimizedPropertyFn) {
1543e5dd7070Spatrick args.add(RValue::get(arg), getContext().getObjCIdType());
1544e5dd7070Spatrick args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1545e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1546e5dd7070Spatrick EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1547e5dd7070Spatrick callee, ReturnValueSlot(), args);
1548e5dd7070Spatrick } else {
1549e5dd7070Spatrick args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1550e5dd7070Spatrick args.add(RValue::get(arg), getContext().getObjCIdType());
1551e5dd7070Spatrick args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1552e5dd7070Spatrick getContext().BoolTy);
1553e5dd7070Spatrick args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1554e5dd7070Spatrick getContext().BoolTy);
1555e5dd7070Spatrick // FIXME: We shouldn't need to get the function info here, the runtime
1556e5dd7070Spatrick // already should have computed it to build the function.
1557e5dd7070Spatrick CGCallee callee = CGCallee::forDirect(setPropertyFn);
1558e5dd7070Spatrick EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1559e5dd7070Spatrick callee, ReturnValueSlot(), args);
1560e5dd7070Spatrick }
1561e5dd7070Spatrick
1562e5dd7070Spatrick return;
1563e5dd7070Spatrick }
1564e5dd7070Spatrick
1565e5dd7070Spatrick case PropertyImplStrategy::CopyStruct:
1566e5dd7070Spatrick emitStructSetterCall(*this, setterMethod, ivar);
1567e5dd7070Spatrick return;
1568e5dd7070Spatrick
1569e5dd7070Spatrick case PropertyImplStrategy::Expression:
1570e5dd7070Spatrick break;
1571e5dd7070Spatrick }
1572e5dd7070Spatrick
1573e5dd7070Spatrick // Otherwise, fake up some ASTs and emit a normal assignment.
1574e5dd7070Spatrick ValueDecl *selfDecl = setterMethod->getSelfDecl();
1575e5dd7070Spatrick DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1576e5dd7070Spatrick VK_LValue, SourceLocation());
1577a9ac8606Spatrick ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
1578a9ac8606Spatrick CK_LValueToRValue, &self, VK_PRValue,
1579a9ac8606Spatrick FPOptionsOverride());
1580e5dd7070Spatrick ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1581e5dd7070Spatrick SourceLocation(), SourceLocation(),
1582e5dd7070Spatrick &selfLoad, true, true);
1583e5dd7070Spatrick
1584e5dd7070Spatrick ParmVarDecl *argDecl = *setterMethod->param_begin();
1585e5dd7070Spatrick QualType argType = argDecl->getType().getNonReferenceType();
1586e5dd7070Spatrick DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1587e5dd7070Spatrick SourceLocation());
1588e5dd7070Spatrick ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1589e5dd7070Spatrick argType.getUnqualifiedType(), CK_LValueToRValue,
1590a9ac8606Spatrick &arg, VK_PRValue, FPOptionsOverride());
1591e5dd7070Spatrick
1592e5dd7070Spatrick // The property type can differ from the ivar type in some situations with
1593e5dd7070Spatrick // Objective-C pointer types, we can always bit cast the RHS in these cases.
1594e5dd7070Spatrick // The following absurdity is just to ensure well-formed IR.
1595e5dd7070Spatrick CastKind argCK = CK_NoOp;
1596e5dd7070Spatrick if (ivarRef.getType()->isObjCObjectPointerType()) {
1597e5dd7070Spatrick if (argLoad.getType()->isObjCObjectPointerType())
1598e5dd7070Spatrick argCK = CK_BitCast;
1599e5dd7070Spatrick else if (argLoad.getType()->isBlockPointerType())
1600e5dd7070Spatrick argCK = CK_BlockPointerToObjCPointerCast;
1601e5dd7070Spatrick else
1602e5dd7070Spatrick argCK = CK_CPointerToObjCPointerCast;
1603e5dd7070Spatrick } else if (ivarRef.getType()->isBlockPointerType()) {
1604e5dd7070Spatrick if (argLoad.getType()->isBlockPointerType())
1605e5dd7070Spatrick argCK = CK_BitCast;
1606e5dd7070Spatrick else
1607e5dd7070Spatrick argCK = CK_AnyPointerToBlockPointerCast;
1608e5dd7070Spatrick } else if (ivarRef.getType()->isPointerType()) {
1609e5dd7070Spatrick argCK = CK_BitCast;
1610*12c85518Srobert } else if (argLoad.getType()->isAtomicType() &&
1611*12c85518Srobert !ivarRef.getType()->isAtomicType()) {
1612*12c85518Srobert argCK = CK_AtomicToNonAtomic;
1613*12c85518Srobert } else if (!argLoad.getType()->isAtomicType() &&
1614*12c85518Srobert ivarRef.getType()->isAtomicType()) {
1615*12c85518Srobert argCK = CK_NonAtomicToAtomic;
1616e5dd7070Spatrick }
1617a9ac8606Spatrick ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
1618a9ac8606Spatrick &argLoad, VK_PRValue, FPOptionsOverride());
1619e5dd7070Spatrick Expr *finalArg = &argLoad;
1620e5dd7070Spatrick if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1621e5dd7070Spatrick argLoad.getType()))
1622e5dd7070Spatrick finalArg = &argCast;
1623e5dd7070Spatrick
1624ec727ea7Spatrick BinaryOperator *assign = BinaryOperator::Create(
1625a9ac8606Spatrick getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(),
1626a9ac8606Spatrick VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride());
1627ec727ea7Spatrick EmitStmt(assign);
1628e5dd7070Spatrick }
1629e5dd7070Spatrick
1630e5dd7070Spatrick /// Generate an Objective-C property setter function.
1631e5dd7070Spatrick ///
1632e5dd7070Spatrick /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1633e5dd7070Spatrick /// is illegal within a category.
GenerateObjCSetter(ObjCImplementationDecl * IMP,const ObjCPropertyImplDecl * PID)1634e5dd7070Spatrick void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1635e5dd7070Spatrick const ObjCPropertyImplDecl *PID) {
1636e5dd7070Spatrick llvm::Constant *AtomicHelperFn =
1637e5dd7070Spatrick CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1638e5dd7070Spatrick ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1639e5dd7070Spatrick assert(OMD && "Invalid call to generate setter (empty method)");
1640e5dd7070Spatrick StartObjCMethod(OMD, IMP->getClassInterface());
1641e5dd7070Spatrick
1642e5dd7070Spatrick generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1643e5dd7070Spatrick
1644e5dd7070Spatrick FinishFunction(OMD->getEndLoc());
1645e5dd7070Spatrick }
1646e5dd7070Spatrick
1647e5dd7070Spatrick namespace {
1648e5dd7070Spatrick struct DestroyIvar final : EHScopeStack::Cleanup {
1649e5dd7070Spatrick private:
1650e5dd7070Spatrick llvm::Value *addr;
1651e5dd7070Spatrick const ObjCIvarDecl *ivar;
1652e5dd7070Spatrick CodeGenFunction::Destroyer *destroyer;
1653e5dd7070Spatrick bool useEHCleanupForArray;
1654e5dd7070Spatrick public:
DestroyIvar__anonb505f9fd0311::DestroyIvar1655e5dd7070Spatrick DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1656e5dd7070Spatrick CodeGenFunction::Destroyer *destroyer,
1657e5dd7070Spatrick bool useEHCleanupForArray)
1658e5dd7070Spatrick : addr(addr), ivar(ivar), destroyer(destroyer),
1659e5dd7070Spatrick useEHCleanupForArray(useEHCleanupForArray) {}
1660e5dd7070Spatrick
Emit__anonb505f9fd0311::DestroyIvar1661e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override {
1662e5dd7070Spatrick LValue lvalue
1663e5dd7070Spatrick = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1664e5dd7070Spatrick CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
1665e5dd7070Spatrick flags.isForNormalCleanup() && useEHCleanupForArray);
1666e5dd7070Spatrick }
1667e5dd7070Spatrick };
1668e5dd7070Spatrick }
1669e5dd7070Spatrick
1670e5dd7070Spatrick /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
destroyARCStrongWithStore(CodeGenFunction & CGF,Address addr,QualType type)1671e5dd7070Spatrick static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1672e5dd7070Spatrick Address addr,
1673e5dd7070Spatrick QualType type) {
1674e5dd7070Spatrick llvm::Value *null = getNullForVariable(addr);
1675e5dd7070Spatrick CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1676e5dd7070Spatrick }
1677e5dd7070Spatrick
emitCXXDestructMethod(CodeGenFunction & CGF,ObjCImplementationDecl * impl)1678e5dd7070Spatrick static void emitCXXDestructMethod(CodeGenFunction &CGF,
1679e5dd7070Spatrick ObjCImplementationDecl *impl) {
1680e5dd7070Spatrick CodeGenFunction::RunCleanupsScope scope(CGF);
1681e5dd7070Spatrick
1682e5dd7070Spatrick llvm::Value *self = CGF.LoadObjCSelf();
1683e5dd7070Spatrick
1684e5dd7070Spatrick const ObjCInterfaceDecl *iface = impl->getClassInterface();
1685e5dd7070Spatrick for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1686e5dd7070Spatrick ivar; ivar = ivar->getNextIvar()) {
1687e5dd7070Spatrick QualType type = ivar->getType();
1688e5dd7070Spatrick
1689e5dd7070Spatrick // Check whether the ivar is a destructible type.
1690e5dd7070Spatrick QualType::DestructionKind dtorKind = type.isDestructedType();
1691e5dd7070Spatrick if (!dtorKind) continue;
1692e5dd7070Spatrick
1693e5dd7070Spatrick CodeGenFunction::Destroyer *destroyer = nullptr;
1694e5dd7070Spatrick
1695e5dd7070Spatrick // Use a call to objc_storeStrong to destroy strong ivars, for the
1696e5dd7070Spatrick // general benefit of the tools.
1697e5dd7070Spatrick if (dtorKind == QualType::DK_objc_strong_lifetime) {
1698e5dd7070Spatrick destroyer = destroyARCStrongWithStore;
1699e5dd7070Spatrick
1700e5dd7070Spatrick // Otherwise use the default for the destruction kind.
1701e5dd7070Spatrick } else {
1702e5dd7070Spatrick destroyer = CGF.getDestroyer(dtorKind);
1703e5dd7070Spatrick }
1704e5dd7070Spatrick
1705e5dd7070Spatrick CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1706e5dd7070Spatrick
1707e5dd7070Spatrick CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1708e5dd7070Spatrick cleanupKind & EHCleanup);
1709e5dd7070Spatrick }
1710e5dd7070Spatrick
1711e5dd7070Spatrick assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1712e5dd7070Spatrick }
1713e5dd7070Spatrick
GenerateObjCCtorDtorMethod(ObjCImplementationDecl * IMP,ObjCMethodDecl * MD,bool ctor)1714e5dd7070Spatrick void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1715e5dd7070Spatrick ObjCMethodDecl *MD,
1716e5dd7070Spatrick bool ctor) {
1717e5dd7070Spatrick MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1718e5dd7070Spatrick StartObjCMethod(MD, IMP->getClassInterface());
1719e5dd7070Spatrick
1720e5dd7070Spatrick // Emit .cxx_construct.
1721e5dd7070Spatrick if (ctor) {
1722e5dd7070Spatrick // Suppress the final autorelease in ARC.
1723e5dd7070Spatrick AutoreleaseResult = false;
1724e5dd7070Spatrick
1725e5dd7070Spatrick for (const auto *IvarInit : IMP->inits()) {
1726e5dd7070Spatrick FieldDecl *Field = IvarInit->getAnyMember();
1727e5dd7070Spatrick ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1728e5dd7070Spatrick LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1729e5dd7070Spatrick LoadObjCSelf(), Ivar, 0);
1730e5dd7070Spatrick EmitAggExpr(IvarInit->getInit(),
1731e5dd7070Spatrick AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
1732e5dd7070Spatrick AggValueSlot::DoesNotNeedGCBarriers,
1733e5dd7070Spatrick AggValueSlot::IsNotAliased,
1734e5dd7070Spatrick AggValueSlot::DoesNotOverlap));
1735e5dd7070Spatrick }
1736e5dd7070Spatrick // constructor returns 'self'.
1737e5dd7070Spatrick CodeGenTypes &Types = CGM.getTypes();
1738e5dd7070Spatrick QualType IdTy(CGM.getContext().getObjCIdType());
1739e5dd7070Spatrick llvm::Value *SelfAsId =
1740e5dd7070Spatrick Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1741e5dd7070Spatrick EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1742e5dd7070Spatrick
1743e5dd7070Spatrick // Emit .cxx_destruct.
1744e5dd7070Spatrick } else {
1745e5dd7070Spatrick emitCXXDestructMethod(*this, IMP);
1746e5dd7070Spatrick }
1747e5dd7070Spatrick FinishFunction();
1748e5dd7070Spatrick }
1749e5dd7070Spatrick
LoadObjCSelf()1750e5dd7070Spatrick llvm::Value *CodeGenFunction::LoadObjCSelf() {
1751e5dd7070Spatrick VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1752e5dd7070Spatrick DeclRefExpr DRE(getContext(), Self,
1753e5dd7070Spatrick /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1754e5dd7070Spatrick Self->getType(), VK_LValue, SourceLocation());
1755e5dd7070Spatrick return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1756e5dd7070Spatrick }
1757e5dd7070Spatrick
TypeOfSelfObject()1758e5dd7070Spatrick QualType CodeGenFunction::TypeOfSelfObject() {
1759e5dd7070Spatrick const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1760e5dd7070Spatrick ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1761e5dd7070Spatrick const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1762e5dd7070Spatrick getContext().getCanonicalType(selfDecl->getType()));
1763e5dd7070Spatrick return PTy->getPointeeType();
1764e5dd7070Spatrick }
1765e5dd7070Spatrick
EmitObjCForCollectionStmt(const ObjCForCollectionStmt & S)1766e5dd7070Spatrick void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1767e5dd7070Spatrick llvm::FunctionCallee EnumerationMutationFnPtr =
1768e5dd7070Spatrick CGM.getObjCRuntime().EnumerationMutationFunction();
1769e5dd7070Spatrick if (!EnumerationMutationFnPtr) {
1770e5dd7070Spatrick CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1771e5dd7070Spatrick return;
1772e5dd7070Spatrick }
1773e5dd7070Spatrick CGCallee EnumerationMutationFn =
1774e5dd7070Spatrick CGCallee::forDirect(EnumerationMutationFnPtr);
1775e5dd7070Spatrick
1776e5dd7070Spatrick CGDebugInfo *DI = getDebugInfo();
1777e5dd7070Spatrick if (DI)
1778e5dd7070Spatrick DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1779e5dd7070Spatrick
1780e5dd7070Spatrick RunCleanupsScope ForScope(*this);
1781e5dd7070Spatrick
1782e5dd7070Spatrick // The local variable comes into scope immediately.
1783e5dd7070Spatrick AutoVarEmission variable = AutoVarEmission::invalid();
1784e5dd7070Spatrick if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1785e5dd7070Spatrick variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1786e5dd7070Spatrick
1787e5dd7070Spatrick JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1788e5dd7070Spatrick
1789e5dd7070Spatrick // Fast enumeration state.
1790e5dd7070Spatrick QualType StateTy = CGM.getObjCFastEnumerationStateType();
1791e5dd7070Spatrick Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1792e5dd7070Spatrick EmitNullInitialization(StatePtr, StateTy);
1793e5dd7070Spatrick
1794e5dd7070Spatrick // Number of elements in the items array.
1795e5dd7070Spatrick static const unsigned NumItems = 16;
1796e5dd7070Spatrick
1797e5dd7070Spatrick // Fetch the countByEnumeratingWithState:objects:count: selector.
1798e5dd7070Spatrick IdentifierInfo *II[] = {
1799e5dd7070Spatrick &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1800e5dd7070Spatrick &CGM.getContext().Idents.get("objects"),
1801e5dd7070Spatrick &CGM.getContext().Idents.get("count")
1802e5dd7070Spatrick };
1803e5dd7070Spatrick Selector FastEnumSel =
1804*12c85518Srobert CGM.getContext().Selectors.getSelector(std::size(II), &II[0]);
1805e5dd7070Spatrick
1806e5dd7070Spatrick QualType ItemsTy =
1807e5dd7070Spatrick getContext().getConstantArrayType(getContext().getObjCIdType(),
1808e5dd7070Spatrick llvm::APInt(32, NumItems), nullptr,
1809e5dd7070Spatrick ArrayType::Normal, 0);
1810e5dd7070Spatrick Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1811e5dd7070Spatrick
1812e5dd7070Spatrick // Emit the collection pointer. In ARC, we do a retain.
1813e5dd7070Spatrick llvm::Value *Collection;
1814e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount) {
1815e5dd7070Spatrick Collection = EmitARCRetainScalarExpr(S.getCollection());
1816e5dd7070Spatrick
1817e5dd7070Spatrick // Enter a cleanup to do the release.
1818e5dd7070Spatrick EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1819e5dd7070Spatrick } else {
1820e5dd7070Spatrick Collection = EmitScalarExpr(S.getCollection());
1821e5dd7070Spatrick }
1822e5dd7070Spatrick
1823e5dd7070Spatrick // The 'continue' label needs to appear within the cleanup for the
1824e5dd7070Spatrick // collection object.
1825e5dd7070Spatrick JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1826e5dd7070Spatrick
1827e5dd7070Spatrick // Send it our message:
1828e5dd7070Spatrick CallArgList Args;
1829e5dd7070Spatrick
1830e5dd7070Spatrick // The first argument is a temporary of the enumeration-state type.
1831e5dd7070Spatrick Args.add(RValue::get(StatePtr.getPointer()),
1832e5dd7070Spatrick getContext().getPointerType(StateTy));
1833e5dd7070Spatrick
1834e5dd7070Spatrick // The second argument is a temporary array with space for NumItems
1835e5dd7070Spatrick // pointers. We'll actually be loading elements from the array
1836e5dd7070Spatrick // pointer written into the control state; this buffer is so that
1837e5dd7070Spatrick // collections that *aren't* backed by arrays can still queue up
1838e5dd7070Spatrick // batches of elements.
1839e5dd7070Spatrick Args.add(RValue::get(ItemsPtr.getPointer()),
1840e5dd7070Spatrick getContext().getPointerType(ItemsTy));
1841e5dd7070Spatrick
1842e5dd7070Spatrick // The third argument is the capacity of that temporary array.
1843e5dd7070Spatrick llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1844e5dd7070Spatrick llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1845e5dd7070Spatrick Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1846e5dd7070Spatrick
1847e5dd7070Spatrick // Start the enumeration.
1848e5dd7070Spatrick RValue CountRV =
1849e5dd7070Spatrick CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1850e5dd7070Spatrick getContext().getNSUIntegerType(),
1851e5dd7070Spatrick FastEnumSel, Collection, Args);
1852e5dd7070Spatrick
1853e5dd7070Spatrick // The initial number of objects that were returned in the buffer.
1854e5dd7070Spatrick llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1855e5dd7070Spatrick
1856e5dd7070Spatrick llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1857e5dd7070Spatrick llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1858e5dd7070Spatrick
1859e5dd7070Spatrick llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1860e5dd7070Spatrick
1861e5dd7070Spatrick // If the limit pointer was zero to begin with, the collection is
1862e5dd7070Spatrick // empty; skip all this. Set the branch weight assuming this has the same
1863e5dd7070Spatrick // probability of exiting the loop as any other loop exit.
1864e5dd7070Spatrick uint64_t EntryCount = getCurrentProfileCount();
1865e5dd7070Spatrick Builder.CreateCondBr(
1866e5dd7070Spatrick Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1867e5dd7070Spatrick LoopInitBB,
1868e5dd7070Spatrick createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1869e5dd7070Spatrick
1870e5dd7070Spatrick // Otherwise, initialize the loop.
1871e5dd7070Spatrick EmitBlock(LoopInitBB);
1872e5dd7070Spatrick
1873e5dd7070Spatrick // Save the initial mutations value. This is the value at an
1874e5dd7070Spatrick // address that was written into the state object by
1875e5dd7070Spatrick // countByEnumeratingWithState:objects:count:.
1876e5dd7070Spatrick Address StateMutationsPtrPtr =
1877e5dd7070Spatrick Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1878e5dd7070Spatrick llvm::Value *StateMutationsPtr
1879e5dd7070Spatrick = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1880e5dd7070Spatrick
1881a9ac8606Spatrick llvm::Type *UnsignedLongTy = ConvertType(getContext().UnsignedLongTy);
1882e5dd7070Spatrick llvm::Value *initialMutations =
1883a9ac8606Spatrick Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1884a9ac8606Spatrick getPointerAlign(), "forcoll.initial-mutations");
1885e5dd7070Spatrick
1886e5dd7070Spatrick // Start looping. This is the point we return to whenever we have a
1887e5dd7070Spatrick // fresh, non-empty batch of objects.
1888e5dd7070Spatrick llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1889e5dd7070Spatrick EmitBlock(LoopBodyBB);
1890e5dd7070Spatrick
1891e5dd7070Spatrick // The current index into the buffer.
1892e5dd7070Spatrick llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1893e5dd7070Spatrick index->addIncoming(zero, LoopInitBB);
1894e5dd7070Spatrick
1895e5dd7070Spatrick // The current buffer size.
1896e5dd7070Spatrick llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1897e5dd7070Spatrick count->addIncoming(initialBufferLimit, LoopInitBB);
1898e5dd7070Spatrick
1899e5dd7070Spatrick incrementProfileCounter(&S);
1900e5dd7070Spatrick
1901e5dd7070Spatrick // Check whether the mutations value has changed from where it was
1902e5dd7070Spatrick // at start. StateMutationsPtr should actually be invariant between
1903e5dd7070Spatrick // refreshes.
1904e5dd7070Spatrick StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1905e5dd7070Spatrick llvm::Value *currentMutations
1906a9ac8606Spatrick = Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1907a9ac8606Spatrick getPointerAlign(), "statemutations");
1908e5dd7070Spatrick
1909e5dd7070Spatrick llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1910e5dd7070Spatrick llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1911e5dd7070Spatrick
1912e5dd7070Spatrick Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1913e5dd7070Spatrick WasNotMutatedBB, WasMutatedBB);
1914e5dd7070Spatrick
1915e5dd7070Spatrick // If so, call the enumeration-mutation function.
1916e5dd7070Spatrick EmitBlock(WasMutatedBB);
1917a9ac8606Spatrick llvm::Type *ObjCIdType = ConvertType(getContext().getObjCIdType());
1918e5dd7070Spatrick llvm::Value *V =
1919a9ac8606Spatrick Builder.CreateBitCast(Collection, ObjCIdType);
1920e5dd7070Spatrick CallArgList Args2;
1921e5dd7070Spatrick Args2.add(RValue::get(V), getContext().getObjCIdType());
1922e5dd7070Spatrick // FIXME: We shouldn't need to get the function info here, the runtime already
1923e5dd7070Spatrick // should have computed it to build the function.
1924e5dd7070Spatrick EmitCall(
1925e5dd7070Spatrick CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
1926e5dd7070Spatrick EnumerationMutationFn, ReturnValueSlot(), Args2);
1927e5dd7070Spatrick
1928e5dd7070Spatrick // Otherwise, or if the mutation function returns, just continue.
1929e5dd7070Spatrick EmitBlock(WasNotMutatedBB);
1930e5dd7070Spatrick
1931e5dd7070Spatrick // Initialize the element variable.
1932e5dd7070Spatrick RunCleanupsScope elementVariableScope(*this);
1933e5dd7070Spatrick bool elementIsVariable;
1934e5dd7070Spatrick LValue elementLValue;
1935e5dd7070Spatrick QualType elementType;
1936e5dd7070Spatrick if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1937e5dd7070Spatrick // Initialize the variable, in case it's a __block variable or something.
1938e5dd7070Spatrick EmitAutoVarInit(variable);
1939e5dd7070Spatrick
1940e5dd7070Spatrick const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1941e5dd7070Spatrick DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1942e5dd7070Spatrick D->getType(), VK_LValue, SourceLocation());
1943e5dd7070Spatrick elementLValue = EmitLValue(&tempDRE);
1944e5dd7070Spatrick elementType = D->getType();
1945e5dd7070Spatrick elementIsVariable = true;
1946e5dd7070Spatrick
1947e5dd7070Spatrick if (D->isARCPseudoStrong())
1948e5dd7070Spatrick elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1949e5dd7070Spatrick } else {
1950e5dd7070Spatrick elementLValue = LValue(); // suppress warning
1951e5dd7070Spatrick elementType = cast<Expr>(S.getElement())->getType();
1952e5dd7070Spatrick elementIsVariable = false;
1953e5dd7070Spatrick }
1954e5dd7070Spatrick llvm::Type *convertedElementType = ConvertType(elementType);
1955e5dd7070Spatrick
1956e5dd7070Spatrick // Fetch the buffer out of the enumeration state.
1957e5dd7070Spatrick // TODO: this pointer should actually be invariant between
1958e5dd7070Spatrick // refreshes, which would help us do certain loop optimizations.
1959e5dd7070Spatrick Address StateItemsPtr =
1960e5dd7070Spatrick Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1961e5dd7070Spatrick llvm::Value *EnumStateItems =
1962e5dd7070Spatrick Builder.CreateLoad(StateItemsPtr, "stateitems");
1963e5dd7070Spatrick
1964e5dd7070Spatrick // Fetch the value at the current index from the buffer.
1965a9ac8606Spatrick llvm::Value *CurrentItemPtr = Builder.CreateGEP(
1966*12c85518Srobert ObjCIdType, EnumStateItems, index, "currentitem.ptr");
1967e5dd7070Spatrick llvm::Value *CurrentItem =
1968a9ac8606Spatrick Builder.CreateAlignedLoad(ObjCIdType, CurrentItemPtr, getPointerAlign());
1969e5dd7070Spatrick
1970ec727ea7Spatrick if (SanOpts.has(SanitizerKind::ObjCCast)) {
1971ec727ea7Spatrick // Before using an item from the collection, check that the implicit cast
1972ec727ea7Spatrick // from id to the element type is valid. This is done with instrumentation
1973ec727ea7Spatrick // roughly corresponding to:
1974ec727ea7Spatrick //
1975ec727ea7Spatrick // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
1976ec727ea7Spatrick const ObjCObjectPointerType *ObjPtrTy =
1977ec727ea7Spatrick elementType->getAsObjCInterfacePointerType();
1978ec727ea7Spatrick const ObjCInterfaceType *InterfaceTy =
1979ec727ea7Spatrick ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
1980ec727ea7Spatrick if (InterfaceTy) {
1981ec727ea7Spatrick SanitizerScope SanScope(this);
1982ec727ea7Spatrick auto &C = CGM.getContext();
1983ec727ea7Spatrick assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
1984ec727ea7Spatrick Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
1985ec727ea7Spatrick CallArgList IsKindOfClassArgs;
1986ec727ea7Spatrick llvm::Value *Cls =
1987ec727ea7Spatrick CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
1988ec727ea7Spatrick IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
1989ec727ea7Spatrick llvm::Value *IsClass =
1990ec727ea7Spatrick CGM.getObjCRuntime()
1991ec727ea7Spatrick .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
1992ec727ea7Spatrick IsKindOfClassSel, CurrentItem,
1993ec727ea7Spatrick IsKindOfClassArgs)
1994ec727ea7Spatrick .getScalarVal();
1995ec727ea7Spatrick llvm::Constant *StaticData[] = {
1996ec727ea7Spatrick EmitCheckSourceLocation(S.getBeginLoc()),
1997ec727ea7Spatrick EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
1998ec727ea7Spatrick EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
1999ec727ea7Spatrick SanitizerHandler::InvalidObjCCast,
2000ec727ea7Spatrick ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
2001ec727ea7Spatrick }
2002ec727ea7Spatrick }
2003ec727ea7Spatrick
2004e5dd7070Spatrick // Cast that value to the right type.
2005e5dd7070Spatrick CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
2006e5dd7070Spatrick "currentitem");
2007e5dd7070Spatrick
2008e5dd7070Spatrick // Make sure we have an l-value. Yes, this gets evaluated every
2009e5dd7070Spatrick // time through the loop.
2010e5dd7070Spatrick if (!elementIsVariable) {
2011e5dd7070Spatrick elementLValue = EmitLValue(cast<Expr>(S.getElement()));
2012e5dd7070Spatrick EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
2013e5dd7070Spatrick } else {
2014e5dd7070Spatrick EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
2015e5dd7070Spatrick /*isInit*/ true);
2016e5dd7070Spatrick }
2017e5dd7070Spatrick
2018e5dd7070Spatrick // If we do have an element variable, this assignment is the end of
2019e5dd7070Spatrick // its initialization.
2020e5dd7070Spatrick if (elementIsVariable)
2021e5dd7070Spatrick EmitAutoVarCleanups(variable);
2022e5dd7070Spatrick
2023e5dd7070Spatrick // Perform the loop body, setting up break and continue labels.
2024e5dd7070Spatrick BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
2025e5dd7070Spatrick {
2026e5dd7070Spatrick RunCleanupsScope Scope(*this);
2027e5dd7070Spatrick EmitStmt(S.getBody());
2028e5dd7070Spatrick }
2029e5dd7070Spatrick BreakContinueStack.pop_back();
2030e5dd7070Spatrick
2031e5dd7070Spatrick // Destroy the element variable now.
2032e5dd7070Spatrick elementVariableScope.ForceCleanup();
2033e5dd7070Spatrick
2034e5dd7070Spatrick // Check whether there are more elements.
2035e5dd7070Spatrick EmitBlock(AfterBody.getBlock());
2036e5dd7070Spatrick
2037e5dd7070Spatrick llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
2038e5dd7070Spatrick
2039e5dd7070Spatrick // First we check in the local buffer.
2040e5dd7070Spatrick llvm::Value *indexPlusOne =
2041e5dd7070Spatrick Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
2042e5dd7070Spatrick
2043e5dd7070Spatrick // If we haven't overrun the buffer yet, we can continue.
2044e5dd7070Spatrick // Set the branch weights based on the simplifying assumption that this is
2045e5dd7070Spatrick // like a while-loop, i.e., ignoring that the false branch fetches more
2046e5dd7070Spatrick // elements and then returns to the loop.
2047e5dd7070Spatrick Builder.CreateCondBr(
2048e5dd7070Spatrick Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
2049e5dd7070Spatrick createProfileWeights(getProfileCount(S.getBody()), EntryCount));
2050e5dd7070Spatrick
2051e5dd7070Spatrick index->addIncoming(indexPlusOne, AfterBody.getBlock());
2052e5dd7070Spatrick count->addIncoming(count, AfterBody.getBlock());
2053e5dd7070Spatrick
2054e5dd7070Spatrick // Otherwise, we have to fetch more elements.
2055e5dd7070Spatrick EmitBlock(FetchMoreBB);
2056e5dd7070Spatrick
2057e5dd7070Spatrick CountRV =
2058e5dd7070Spatrick CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2059e5dd7070Spatrick getContext().getNSUIntegerType(),
2060e5dd7070Spatrick FastEnumSel, Collection, Args);
2061e5dd7070Spatrick
2062e5dd7070Spatrick // If we got a zero count, we're done.
2063e5dd7070Spatrick llvm::Value *refetchCount = CountRV.getScalarVal();
2064e5dd7070Spatrick
2065e5dd7070Spatrick // (note that the message send might split FetchMoreBB)
2066e5dd7070Spatrick index->addIncoming(zero, Builder.GetInsertBlock());
2067e5dd7070Spatrick count->addIncoming(refetchCount, Builder.GetInsertBlock());
2068e5dd7070Spatrick
2069e5dd7070Spatrick Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
2070e5dd7070Spatrick EmptyBB, LoopBodyBB);
2071e5dd7070Spatrick
2072e5dd7070Spatrick // No more elements.
2073e5dd7070Spatrick EmitBlock(EmptyBB);
2074e5dd7070Spatrick
2075e5dd7070Spatrick if (!elementIsVariable) {
2076e5dd7070Spatrick // If the element was not a declaration, set it to be null.
2077e5dd7070Spatrick
2078e5dd7070Spatrick llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
2079e5dd7070Spatrick elementLValue = EmitLValue(cast<Expr>(S.getElement()));
2080e5dd7070Spatrick EmitStoreThroughLValue(RValue::get(null), elementLValue);
2081e5dd7070Spatrick }
2082e5dd7070Spatrick
2083e5dd7070Spatrick if (DI)
2084e5dd7070Spatrick DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
2085e5dd7070Spatrick
2086e5dd7070Spatrick ForScope.ForceCleanup();
2087e5dd7070Spatrick EmitBlock(LoopEnd.getBlock());
2088e5dd7070Spatrick }
2089e5dd7070Spatrick
EmitObjCAtTryStmt(const ObjCAtTryStmt & S)2090e5dd7070Spatrick void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
2091e5dd7070Spatrick CGM.getObjCRuntime().EmitTryStmt(*this, S);
2092e5dd7070Spatrick }
2093e5dd7070Spatrick
EmitObjCAtThrowStmt(const ObjCAtThrowStmt & S)2094e5dd7070Spatrick void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
2095e5dd7070Spatrick CGM.getObjCRuntime().EmitThrowStmt(*this, S);
2096e5dd7070Spatrick }
2097e5dd7070Spatrick
EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt & S)2098e5dd7070Spatrick void CodeGenFunction::EmitObjCAtSynchronizedStmt(
2099e5dd7070Spatrick const ObjCAtSynchronizedStmt &S) {
2100e5dd7070Spatrick CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
2101e5dd7070Spatrick }
2102e5dd7070Spatrick
2103e5dd7070Spatrick namespace {
2104e5dd7070Spatrick struct CallObjCRelease final : EHScopeStack::Cleanup {
CallObjCRelease__anonb505f9fd0411::CallObjCRelease2105e5dd7070Spatrick CallObjCRelease(llvm::Value *object) : object(object) {}
2106e5dd7070Spatrick llvm::Value *object;
2107e5dd7070Spatrick
Emit__anonb505f9fd0411::CallObjCRelease2108e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override {
2109e5dd7070Spatrick // Releases at the end of the full-expression are imprecise.
2110e5dd7070Spatrick CGF.EmitARCRelease(object, ARCImpreciseLifetime);
2111e5dd7070Spatrick }
2112e5dd7070Spatrick };
2113e5dd7070Spatrick }
2114e5dd7070Spatrick
2115e5dd7070Spatrick /// Produce the code for a CK_ARCConsumeObject. Does a primitive
2116e5dd7070Spatrick /// release at the end of the full-expression.
EmitObjCConsumeObject(QualType type,llvm::Value * object)2117e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
2118e5dd7070Spatrick llvm::Value *object) {
2119e5dd7070Spatrick // If we're in a conditional branch, we need to make the cleanup
2120e5dd7070Spatrick // conditional.
2121e5dd7070Spatrick pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
2122e5dd7070Spatrick return object;
2123e5dd7070Spatrick }
2124e5dd7070Spatrick
EmitObjCExtendObjectLifetime(QualType type,llvm::Value * value)2125e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
2126e5dd7070Spatrick llvm::Value *value) {
2127e5dd7070Spatrick return EmitARCRetainAutorelease(type, value);
2128e5dd7070Spatrick }
2129e5dd7070Spatrick
2130e5dd7070Spatrick /// Given a number of pointers, inform the optimizer that they're
2131e5dd7070Spatrick /// being intrinsically used up until this point in the program.
EmitARCIntrinsicUse(ArrayRef<llvm::Value * > values)2132e5dd7070Spatrick void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
2133e5dd7070Spatrick llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
2134e5dd7070Spatrick if (!fn)
2135e5dd7070Spatrick fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
2136e5dd7070Spatrick
2137e5dd7070Spatrick // This isn't really a "runtime" function, but as an intrinsic it
2138e5dd7070Spatrick // doesn't really matter as long as we align things up.
2139e5dd7070Spatrick EmitNounwindRuntimeCall(fn, values);
2140e5dd7070Spatrick }
2141e5dd7070Spatrick
2142a9ac8606Spatrick /// Emit a call to "clang.arc.noop.use", which consumes the result of a call
2143a9ac8606Spatrick /// that has operand bundle "clang.arc.attachedcall".
EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value * > values)2144a9ac8606Spatrick void CodeGenFunction::EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values) {
2145a9ac8606Spatrick llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;
2146a9ac8606Spatrick if (!fn)
2147a9ac8606Spatrick fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_noop_use);
2148a9ac8606Spatrick EmitNounwindRuntimeCall(fn, values);
2149a9ac8606Spatrick }
2150a9ac8606Spatrick
setARCRuntimeFunctionLinkage(CodeGenModule & CGM,llvm::Value * RTF)2151e5dd7070Spatrick static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
2152e5dd7070Spatrick if (auto *F = dyn_cast<llvm::Function>(RTF)) {
2153e5dd7070Spatrick // If the target runtime doesn't naturally support ARC, emit weak
2154e5dd7070Spatrick // references to the runtime support library. We don't really
2155e5dd7070Spatrick // permit this to fail, but we need a particular relocation style.
2156e5dd7070Spatrick if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
2157e5dd7070Spatrick !CGM.getTriple().isOSBinFormatCOFF()) {
2158e5dd7070Spatrick F->setLinkage(llvm::Function::ExternalWeakLinkage);
2159e5dd7070Spatrick }
2160e5dd7070Spatrick }
2161e5dd7070Spatrick }
2162e5dd7070Spatrick
setARCRuntimeFunctionLinkage(CodeGenModule & CGM,llvm::FunctionCallee RTF)2163e5dd7070Spatrick static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
2164e5dd7070Spatrick llvm::FunctionCallee RTF) {
2165e5dd7070Spatrick setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
2166e5dd7070Spatrick }
2167e5dd7070Spatrick
getARCIntrinsic(llvm::Intrinsic::ID IntID,CodeGenModule & CGM)2168*12c85518Srobert static llvm::Function *getARCIntrinsic(llvm::Intrinsic::ID IntID,
2169*12c85518Srobert CodeGenModule &CGM) {
2170*12c85518Srobert llvm::Function *fn = CGM.getIntrinsic(IntID);
2171*12c85518Srobert setARCRuntimeFunctionLinkage(CGM, fn);
2172*12c85518Srobert return fn;
2173*12c85518Srobert }
2174*12c85518Srobert
2175e5dd7070Spatrick /// Perform an operation having the signature
2176e5dd7070Spatrick /// i8* (i8*)
2177e5dd7070Spatrick /// where a null input causes a no-op and returns null.
emitARCValueOperation(CodeGenFunction & CGF,llvm::Value * value,llvm::Type * returnType,llvm::Function * & fn,llvm::Intrinsic::ID IntID,llvm::CallInst::TailCallKind tailKind=llvm::CallInst::TCK_None)2178e5dd7070Spatrick static llvm::Value *emitARCValueOperation(
2179e5dd7070Spatrick CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2180e5dd7070Spatrick llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2181e5dd7070Spatrick llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
2182e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(value))
2183e5dd7070Spatrick return value;
2184e5dd7070Spatrick
2185*12c85518Srobert if (!fn)
2186*12c85518Srobert fn = getARCIntrinsic(IntID, CGF.CGM);
2187e5dd7070Spatrick
2188e5dd7070Spatrick // Cast the argument to 'id'.
2189e5dd7070Spatrick llvm::Type *origType = returnType ? returnType : value->getType();
2190e5dd7070Spatrick value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2191e5dd7070Spatrick
2192e5dd7070Spatrick // Call the function.
2193e5dd7070Spatrick llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2194e5dd7070Spatrick call->setTailCallKind(tailKind);
2195e5dd7070Spatrick
2196e5dd7070Spatrick // Cast the result back to the original type.
2197e5dd7070Spatrick return CGF.Builder.CreateBitCast(call, origType);
2198e5dd7070Spatrick }
2199e5dd7070Spatrick
2200e5dd7070Spatrick /// Perform an operation having the following signature:
2201e5dd7070Spatrick /// i8* (i8**)
emitARCLoadOperation(CodeGenFunction & CGF,Address addr,llvm::Function * & fn,llvm::Intrinsic::ID IntID)2202e5dd7070Spatrick static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2203e5dd7070Spatrick llvm::Function *&fn,
2204e5dd7070Spatrick llvm::Intrinsic::ID IntID) {
2205*12c85518Srobert if (!fn)
2206*12c85518Srobert fn = getARCIntrinsic(IntID, CGF.CGM);
2207e5dd7070Spatrick
2208e5dd7070Spatrick // Cast the argument to 'id*'.
2209e5dd7070Spatrick llvm::Type *origType = addr.getElementType();
2210*12c85518Srobert addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8PtrTy);
2211e5dd7070Spatrick
2212e5dd7070Spatrick // Call the function.
2213e5dd7070Spatrick llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
2214e5dd7070Spatrick
2215e5dd7070Spatrick // Cast the result back to a dereference of the original type.
2216e5dd7070Spatrick if (origType != CGF.Int8PtrTy)
2217e5dd7070Spatrick result = CGF.Builder.CreateBitCast(result, origType);
2218e5dd7070Spatrick
2219e5dd7070Spatrick return result;
2220e5dd7070Spatrick }
2221e5dd7070Spatrick
2222e5dd7070Spatrick /// Perform an operation having the following signature:
2223e5dd7070Spatrick /// i8* (i8**, i8*)
emitARCStoreOperation(CodeGenFunction & CGF,Address addr,llvm::Value * value,llvm::Function * & fn,llvm::Intrinsic::ID IntID,bool ignored)2224e5dd7070Spatrick static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
2225e5dd7070Spatrick llvm::Value *value,
2226e5dd7070Spatrick llvm::Function *&fn,
2227e5dd7070Spatrick llvm::Intrinsic::ID IntID,
2228e5dd7070Spatrick bool ignored) {
2229e5dd7070Spatrick assert(addr.getElementType() == value->getType());
2230e5dd7070Spatrick
2231*12c85518Srobert if (!fn)
2232*12c85518Srobert fn = getARCIntrinsic(IntID, CGF.CGM);
2233e5dd7070Spatrick
2234e5dd7070Spatrick llvm::Type *origType = value->getType();
2235e5dd7070Spatrick
2236e5dd7070Spatrick llvm::Value *args[] = {
2237e5dd7070Spatrick CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
2238e5dd7070Spatrick CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2239e5dd7070Spatrick };
2240e5dd7070Spatrick llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
2241e5dd7070Spatrick
2242e5dd7070Spatrick if (ignored) return nullptr;
2243e5dd7070Spatrick
2244e5dd7070Spatrick return CGF.Builder.CreateBitCast(result, origType);
2245e5dd7070Spatrick }
2246e5dd7070Spatrick
2247e5dd7070Spatrick /// Perform an operation having the following signature:
2248e5dd7070Spatrick /// void (i8**, i8**)
emitARCCopyOperation(CodeGenFunction & CGF,Address dst,Address src,llvm::Function * & fn,llvm::Intrinsic::ID IntID)2249e5dd7070Spatrick static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2250e5dd7070Spatrick llvm::Function *&fn,
2251e5dd7070Spatrick llvm::Intrinsic::ID IntID) {
2252e5dd7070Spatrick assert(dst.getType() == src.getType());
2253e5dd7070Spatrick
2254*12c85518Srobert if (!fn)
2255*12c85518Srobert fn = getARCIntrinsic(IntID, CGF.CGM);
2256e5dd7070Spatrick
2257e5dd7070Spatrick llvm::Value *args[] = {
2258e5dd7070Spatrick CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2259e5dd7070Spatrick CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
2260e5dd7070Spatrick };
2261e5dd7070Spatrick CGF.EmitNounwindRuntimeCall(fn, args);
2262e5dd7070Spatrick }
2263e5dd7070Spatrick
2264e5dd7070Spatrick /// Perform an operation having the signature
2265e5dd7070Spatrick /// i8* (i8*)
2266e5dd7070Spatrick /// where a null input causes a no-op and returns null.
emitObjCValueOperation(CodeGenFunction & CGF,llvm::Value * value,llvm::Type * returnType,llvm::FunctionCallee & fn,StringRef fnName)2267e5dd7070Spatrick static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2268e5dd7070Spatrick llvm::Value *value,
2269e5dd7070Spatrick llvm::Type *returnType,
2270e5dd7070Spatrick llvm::FunctionCallee &fn,
2271e5dd7070Spatrick StringRef fnName) {
2272e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(value))
2273e5dd7070Spatrick return value;
2274e5dd7070Spatrick
2275e5dd7070Spatrick if (!fn) {
2276e5dd7070Spatrick llvm::FunctionType *fnType =
2277e5dd7070Spatrick llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2278e5dd7070Spatrick fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2279e5dd7070Spatrick
2280e5dd7070Spatrick // We have Native ARC, so set nonlazybind attribute for performance
2281e5dd7070Spatrick if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2282e5dd7070Spatrick if (fnName == "objc_retain")
2283e5dd7070Spatrick f->addFnAttr(llvm::Attribute::NonLazyBind);
2284e5dd7070Spatrick }
2285e5dd7070Spatrick
2286e5dd7070Spatrick // Cast the argument to 'id'.
2287e5dd7070Spatrick llvm::Type *origType = returnType ? returnType : value->getType();
2288e5dd7070Spatrick value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2289e5dd7070Spatrick
2290e5dd7070Spatrick // Call the function.
2291e5dd7070Spatrick llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
2292e5dd7070Spatrick
2293a9ac8606Spatrick // Mark calls to objc_autorelease as tail on the assumption that methods
2294a9ac8606Spatrick // overriding autorelease do not touch anything on the stack.
2295a9ac8606Spatrick if (fnName == "objc_autorelease")
2296a9ac8606Spatrick if (auto *Call = dyn_cast<llvm::CallInst>(Inst))
2297a9ac8606Spatrick Call->setTailCall();
2298a9ac8606Spatrick
2299e5dd7070Spatrick // Cast the result back to the original type.
2300e5dd7070Spatrick return CGF.Builder.CreateBitCast(Inst, origType);
2301e5dd7070Spatrick }
2302e5dd7070Spatrick
2303e5dd7070Spatrick /// Produce the code to do a retain. Based on the type, calls one of:
2304e5dd7070Spatrick /// call i8* \@objc_retain(i8* %value)
2305e5dd7070Spatrick /// call i8* \@objc_retainBlock(i8* %value)
EmitARCRetain(QualType type,llvm::Value * value)2306e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2307e5dd7070Spatrick if (type->isBlockPointerType())
2308e5dd7070Spatrick return EmitARCRetainBlock(value, /*mandatory*/ false);
2309e5dd7070Spatrick else
2310e5dd7070Spatrick return EmitARCRetainNonBlock(value);
2311e5dd7070Spatrick }
2312e5dd7070Spatrick
2313e5dd7070Spatrick /// Retain the given object, with normal retain semantics.
2314e5dd7070Spatrick /// call i8* \@objc_retain(i8* %value)
EmitARCRetainNonBlock(llvm::Value * value)2315e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2316e5dd7070Spatrick return emitARCValueOperation(*this, value, nullptr,
2317e5dd7070Spatrick CGM.getObjCEntrypoints().objc_retain,
2318e5dd7070Spatrick llvm::Intrinsic::objc_retain);
2319e5dd7070Spatrick }
2320e5dd7070Spatrick
2321e5dd7070Spatrick /// Retain the given block, with _Block_copy semantics.
2322e5dd7070Spatrick /// call i8* \@objc_retainBlock(i8* %value)
2323e5dd7070Spatrick ///
2324e5dd7070Spatrick /// \param mandatory - If false, emit the call with metadata
2325e5dd7070Spatrick /// indicating that it's okay for the optimizer to eliminate this call
2326e5dd7070Spatrick /// if it can prove that the block never escapes except down the stack.
EmitARCRetainBlock(llvm::Value * value,bool mandatory)2327e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2328e5dd7070Spatrick bool mandatory) {
2329e5dd7070Spatrick llvm::Value *result
2330e5dd7070Spatrick = emitARCValueOperation(*this, value, nullptr,
2331e5dd7070Spatrick CGM.getObjCEntrypoints().objc_retainBlock,
2332e5dd7070Spatrick llvm::Intrinsic::objc_retainBlock);
2333e5dd7070Spatrick
2334e5dd7070Spatrick // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2335e5dd7070Spatrick // tell the optimizer that it doesn't need to do this copy if the
2336e5dd7070Spatrick // block doesn't escape, where being passed as an argument doesn't
2337e5dd7070Spatrick // count as escaping.
2338e5dd7070Spatrick if (!mandatory && isa<llvm::Instruction>(result)) {
2339e5dd7070Spatrick llvm::CallInst *call
2340e5dd7070Spatrick = cast<llvm::CallInst>(result->stripPointerCasts());
2341ec727ea7Spatrick assert(call->getCalledOperand() ==
2342ec727ea7Spatrick CGM.getObjCEntrypoints().objc_retainBlock);
2343e5dd7070Spatrick
2344e5dd7070Spatrick call->setMetadata("clang.arc.copy_on_escape",
2345*12c85518Srobert llvm::MDNode::get(Builder.getContext(), std::nullopt));
2346e5dd7070Spatrick }
2347e5dd7070Spatrick
2348e5dd7070Spatrick return result;
2349e5dd7070Spatrick }
2350e5dd7070Spatrick
emitAutoreleasedReturnValueMarker(CodeGenFunction & CGF)2351e5dd7070Spatrick static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
2352e5dd7070Spatrick // Fetch the void(void) inline asm which marks that we're going to
2353e5dd7070Spatrick // do something with the autoreleased return value.
2354e5dd7070Spatrick llvm::InlineAsm *&marker
2355e5dd7070Spatrick = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
2356e5dd7070Spatrick if (!marker) {
2357e5dd7070Spatrick StringRef assembly
2358e5dd7070Spatrick = CGF.CGM.getTargetCodeGenInfo()
2359e5dd7070Spatrick .getARCRetainAutoreleasedReturnValueMarker();
2360e5dd7070Spatrick
2361e5dd7070Spatrick // If we have an empty assembly string, there's nothing to do.
2362e5dd7070Spatrick if (assembly.empty()) {
2363e5dd7070Spatrick
2364e5dd7070Spatrick // Otherwise, at -O0, build an inline asm that we're going to call
2365e5dd7070Spatrick // in a moment.
2366e5dd7070Spatrick } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2367e5dd7070Spatrick llvm::FunctionType *type =
2368e5dd7070Spatrick llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2369e5dd7070Spatrick
2370e5dd7070Spatrick marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2371e5dd7070Spatrick
2372e5dd7070Spatrick // If we're at -O1 and above, we don't want to litter the code
2373e5dd7070Spatrick // with this marker yet, so leave a breadcrumb for the ARC
2374e5dd7070Spatrick // optimizer to pick up.
2375e5dd7070Spatrick } else {
2376a9ac8606Spatrick const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();
2377a9ac8606Spatrick if (!CGF.CGM.getModule().getModuleFlag(retainRVMarkerKey)) {
2378e5dd7070Spatrick auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2379a9ac8606Spatrick CGF.CGM.getModule().addModuleFlag(llvm::Module::Error,
2380a9ac8606Spatrick retainRVMarkerKey, str);
2381e5dd7070Spatrick }
2382e5dd7070Spatrick }
2383e5dd7070Spatrick }
2384e5dd7070Spatrick
2385e5dd7070Spatrick // Call the marker asm if we made one, which we do only at -O0.
2386e5dd7070Spatrick if (marker)
2387*12c85518Srobert CGF.Builder.CreateCall(marker, std::nullopt,
2388*12c85518Srobert CGF.getBundlesForFunclet(marker));
2389e5dd7070Spatrick }
2390e5dd7070Spatrick
emitOptimizedARCReturnCall(llvm::Value * value,bool IsRetainRV,CodeGenFunction & CGF)2391a9ac8606Spatrick static llvm::Value *emitOptimizedARCReturnCall(llvm::Value *value,
2392a9ac8606Spatrick bool IsRetainRV,
2393a9ac8606Spatrick CodeGenFunction &CGF) {
2394a9ac8606Spatrick emitAutoreleasedReturnValueMarker(CGF);
2395a9ac8606Spatrick
2396a9ac8606Spatrick // Add operand bundle "clang.arc.attachedcall" to the call instead of emitting
2397a9ac8606Spatrick // retainRV or claimRV calls in the IR. We currently do this only when the
2398a9ac8606Spatrick // optimization level isn't -O0 since global-isel, which is currently run at
2399a9ac8606Spatrick // -O0, doesn't know about the operand bundle.
2400*12c85518Srobert ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();
2401*12c85518Srobert llvm::Function *&EP = IsRetainRV
2402*12c85518Srobert ? EPs.objc_retainAutoreleasedReturnValue
2403*12c85518Srobert : EPs.objc_unsafeClaimAutoreleasedReturnValue;
2404*12c85518Srobert llvm::Intrinsic::ID IID =
2405*12c85518Srobert IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue
2406*12c85518Srobert : llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;
2407*12c85518Srobert EP = getARCIntrinsic(IID, CGF.CGM);
2408a9ac8606Spatrick
2409*12c85518Srobert llvm::Triple::ArchType Arch = CGF.CGM.getTriple().getArch();
2410*12c85518Srobert
2411*12c85518Srobert // FIXME: Do this on all targets and at -O0 too. This can be enabled only if
2412*12c85518Srobert // the target backend knows how to handle the operand bundle.
2413a9ac8606Spatrick if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2414*12c85518Srobert (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::x86_64)) {
2415*12c85518Srobert llvm::Value *bundleArgs[] = {EP};
2416a9ac8606Spatrick llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);
2417a9ac8606Spatrick auto *oldCall = cast<llvm::CallBase>(value);
2418a9ac8606Spatrick llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(
2419a9ac8606Spatrick oldCall, llvm::LLVMContext::OB_clang_arc_attachedcall, OB, oldCall);
2420a9ac8606Spatrick newCall->copyMetadata(*oldCall);
2421a9ac8606Spatrick oldCall->replaceAllUsesWith(newCall);
2422a9ac8606Spatrick oldCall->eraseFromParent();
2423a9ac8606Spatrick CGF.EmitARCNoopIntrinsicUse(newCall);
2424a9ac8606Spatrick return newCall;
2425a9ac8606Spatrick }
2426a9ac8606Spatrick
2427a9ac8606Spatrick bool isNoTail =
2428a9ac8606Spatrick CGF.CGM.getTargetCodeGenInfo().markARCOptimizedReturnCallsAsNoTail();
2429a9ac8606Spatrick llvm::CallInst::TailCallKind tailKind =
2430a9ac8606Spatrick isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;
2431a9ac8606Spatrick return emitARCValueOperation(CGF, value, nullptr, EP, IID, tailKind);
2432a9ac8606Spatrick }
2433a9ac8606Spatrick
2434e5dd7070Spatrick /// Retain the given object which is the result of a function call.
2435e5dd7070Spatrick /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2436e5dd7070Spatrick ///
2437e5dd7070Spatrick /// Yes, this function name is one character away from a different
2438e5dd7070Spatrick /// call with completely different semantics.
2439e5dd7070Spatrick llvm::Value *
EmitARCRetainAutoreleasedReturnValue(llvm::Value * value)2440e5dd7070Spatrick CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2441a9ac8606Spatrick return emitOptimizedARCReturnCall(value, true, *this);
2442e5dd7070Spatrick }
2443e5dd7070Spatrick
2444e5dd7070Spatrick /// Claim a possibly-autoreleased return value at +0. This is only
2445e5dd7070Spatrick /// valid to do in contexts which do not rely on the retain to keep
2446e5dd7070Spatrick /// the object valid for all of its uses; for example, when
2447e5dd7070Spatrick /// the value is ignored, or when it is being assigned to an
2448e5dd7070Spatrick /// __unsafe_unretained variable.
2449e5dd7070Spatrick ///
2450e5dd7070Spatrick /// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2451e5dd7070Spatrick llvm::Value *
EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value * value)2452e5dd7070Spatrick CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2453a9ac8606Spatrick return emitOptimizedARCReturnCall(value, false, *this);
2454e5dd7070Spatrick }
2455e5dd7070Spatrick
2456e5dd7070Spatrick /// Release the given object.
2457e5dd7070Spatrick /// call void \@objc_release(i8* %value)
EmitARCRelease(llvm::Value * value,ARCPreciseLifetime_t precise)2458e5dd7070Spatrick void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2459e5dd7070Spatrick ARCPreciseLifetime_t precise) {
2460e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(value)) return;
2461e5dd7070Spatrick
2462e5dd7070Spatrick llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2463*12c85518Srobert if (!fn)
2464*12c85518Srobert fn = getARCIntrinsic(llvm::Intrinsic::objc_release, CGM);
2465e5dd7070Spatrick
2466e5dd7070Spatrick // Cast the argument to 'id'.
2467e5dd7070Spatrick value = Builder.CreateBitCast(value, Int8PtrTy);
2468e5dd7070Spatrick
2469e5dd7070Spatrick // Call objc_release.
2470e5dd7070Spatrick llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2471e5dd7070Spatrick
2472e5dd7070Spatrick if (precise == ARCImpreciseLifetime) {
2473e5dd7070Spatrick call->setMetadata("clang.imprecise_release",
2474*12c85518Srobert llvm::MDNode::get(Builder.getContext(), std::nullopt));
2475e5dd7070Spatrick }
2476e5dd7070Spatrick }
2477e5dd7070Spatrick
2478e5dd7070Spatrick /// Destroy a __strong variable.
2479e5dd7070Spatrick ///
2480e5dd7070Spatrick /// At -O0, emit a call to store 'null' into the address;
2481e5dd7070Spatrick /// instrumenting tools prefer this because the address is exposed,
2482e5dd7070Spatrick /// but it's relatively cumbersome to optimize.
2483e5dd7070Spatrick ///
2484e5dd7070Spatrick /// At -O1 and above, just load and call objc_release.
2485e5dd7070Spatrick ///
2486e5dd7070Spatrick /// call void \@objc_storeStrong(i8** %addr, i8* null)
EmitARCDestroyStrong(Address addr,ARCPreciseLifetime_t precise)2487e5dd7070Spatrick void CodeGenFunction::EmitARCDestroyStrong(Address addr,
2488e5dd7070Spatrick ARCPreciseLifetime_t precise) {
2489e5dd7070Spatrick if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2490e5dd7070Spatrick llvm::Value *null = getNullForVariable(addr);
2491e5dd7070Spatrick EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2492e5dd7070Spatrick return;
2493e5dd7070Spatrick }
2494e5dd7070Spatrick
2495e5dd7070Spatrick llvm::Value *value = Builder.CreateLoad(addr);
2496e5dd7070Spatrick EmitARCRelease(value, precise);
2497e5dd7070Spatrick }
2498e5dd7070Spatrick
2499e5dd7070Spatrick /// Store into a strong object. Always calls this:
2500e5dd7070Spatrick /// call void \@objc_storeStrong(i8** %addr, i8* %value)
EmitARCStoreStrongCall(Address addr,llvm::Value * value,bool ignored)2501e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
2502e5dd7070Spatrick llvm::Value *value,
2503e5dd7070Spatrick bool ignored) {
2504e5dd7070Spatrick assert(addr.getElementType() == value->getType());
2505e5dd7070Spatrick
2506e5dd7070Spatrick llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2507*12c85518Srobert if (!fn)
2508*12c85518Srobert fn = getARCIntrinsic(llvm::Intrinsic::objc_storeStrong, CGM);
2509e5dd7070Spatrick
2510e5dd7070Spatrick llvm::Value *args[] = {
2511e5dd7070Spatrick Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
2512e5dd7070Spatrick Builder.CreateBitCast(value, Int8PtrTy)
2513e5dd7070Spatrick };
2514e5dd7070Spatrick EmitNounwindRuntimeCall(fn, args);
2515e5dd7070Spatrick
2516e5dd7070Spatrick if (ignored) return nullptr;
2517e5dd7070Spatrick return value;
2518e5dd7070Spatrick }
2519e5dd7070Spatrick
2520e5dd7070Spatrick /// Store into a strong object. Sometimes calls this:
2521e5dd7070Spatrick /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2522e5dd7070Spatrick /// Other times, breaks it down into components.
EmitARCStoreStrong(LValue dst,llvm::Value * newValue,bool ignored)2523e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2524e5dd7070Spatrick llvm::Value *newValue,
2525e5dd7070Spatrick bool ignored) {
2526e5dd7070Spatrick QualType type = dst.getType();
2527e5dd7070Spatrick bool isBlock = type->isBlockPointerType();
2528e5dd7070Spatrick
2529e5dd7070Spatrick // Use a store barrier at -O0 unless this is a block type or the
2530e5dd7070Spatrick // lvalue is inadequately aligned.
2531e5dd7070Spatrick if (shouldUseFusedARCCalls() &&
2532e5dd7070Spatrick !isBlock &&
2533e5dd7070Spatrick (dst.getAlignment().isZero() ||
2534e5dd7070Spatrick dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2535e5dd7070Spatrick return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
2536e5dd7070Spatrick }
2537e5dd7070Spatrick
2538e5dd7070Spatrick // Otherwise, split it out.
2539e5dd7070Spatrick
2540e5dd7070Spatrick // Retain the new value.
2541e5dd7070Spatrick newValue = EmitARCRetain(type, newValue);
2542e5dd7070Spatrick
2543e5dd7070Spatrick // Read the old value.
2544e5dd7070Spatrick llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2545e5dd7070Spatrick
2546e5dd7070Spatrick // Store. We do this before the release so that any deallocs won't
2547e5dd7070Spatrick // see the old value.
2548e5dd7070Spatrick EmitStoreOfScalar(newValue, dst);
2549e5dd7070Spatrick
2550e5dd7070Spatrick // Finally, release the old value.
2551e5dd7070Spatrick EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2552e5dd7070Spatrick
2553e5dd7070Spatrick return newValue;
2554e5dd7070Spatrick }
2555e5dd7070Spatrick
2556e5dd7070Spatrick /// Autorelease the given object.
2557e5dd7070Spatrick /// call i8* \@objc_autorelease(i8* %value)
EmitARCAutorelease(llvm::Value * value)2558e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2559e5dd7070Spatrick return emitARCValueOperation(*this, value, nullptr,
2560e5dd7070Spatrick CGM.getObjCEntrypoints().objc_autorelease,
2561e5dd7070Spatrick llvm::Intrinsic::objc_autorelease);
2562e5dd7070Spatrick }
2563e5dd7070Spatrick
2564e5dd7070Spatrick /// Autorelease the given object.
2565e5dd7070Spatrick /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2566e5dd7070Spatrick llvm::Value *
EmitARCAutoreleaseReturnValue(llvm::Value * value)2567e5dd7070Spatrick CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2568e5dd7070Spatrick return emitARCValueOperation(*this, value, nullptr,
2569e5dd7070Spatrick CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
2570e5dd7070Spatrick llvm::Intrinsic::objc_autoreleaseReturnValue,
2571e5dd7070Spatrick llvm::CallInst::TCK_Tail);
2572e5dd7070Spatrick }
2573e5dd7070Spatrick
2574e5dd7070Spatrick /// Do a fused retain/autorelease of the given object.
2575e5dd7070Spatrick /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2576e5dd7070Spatrick llvm::Value *
EmitARCRetainAutoreleaseReturnValue(llvm::Value * value)2577e5dd7070Spatrick CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2578e5dd7070Spatrick return emitARCValueOperation(*this, value, nullptr,
2579e5dd7070Spatrick CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
2580e5dd7070Spatrick llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2581e5dd7070Spatrick llvm::CallInst::TCK_Tail);
2582e5dd7070Spatrick }
2583e5dd7070Spatrick
2584e5dd7070Spatrick /// Do a fused retain/autorelease of the given object.
2585e5dd7070Spatrick /// call i8* \@objc_retainAutorelease(i8* %value)
2586e5dd7070Spatrick /// or
2587e5dd7070Spatrick /// %retain = call i8* \@objc_retainBlock(i8* %value)
2588e5dd7070Spatrick /// call i8* \@objc_autorelease(i8* %retain)
EmitARCRetainAutorelease(QualType type,llvm::Value * value)2589e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2590e5dd7070Spatrick llvm::Value *value) {
2591e5dd7070Spatrick if (!type->isBlockPointerType())
2592e5dd7070Spatrick return EmitARCRetainAutoreleaseNonBlock(value);
2593e5dd7070Spatrick
2594e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(value)) return value;
2595e5dd7070Spatrick
2596e5dd7070Spatrick llvm::Type *origType = value->getType();
2597e5dd7070Spatrick value = Builder.CreateBitCast(value, Int8PtrTy);
2598e5dd7070Spatrick value = EmitARCRetainBlock(value, /*mandatory*/ true);
2599e5dd7070Spatrick value = EmitARCAutorelease(value);
2600e5dd7070Spatrick return Builder.CreateBitCast(value, origType);
2601e5dd7070Spatrick }
2602e5dd7070Spatrick
2603e5dd7070Spatrick /// Do a fused retain/autorelease of the given object.
2604e5dd7070Spatrick /// call i8* \@objc_retainAutorelease(i8* %value)
2605e5dd7070Spatrick llvm::Value *
EmitARCRetainAutoreleaseNonBlock(llvm::Value * value)2606e5dd7070Spatrick CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2607e5dd7070Spatrick return emitARCValueOperation(*this, value, nullptr,
2608e5dd7070Spatrick CGM.getObjCEntrypoints().objc_retainAutorelease,
2609e5dd7070Spatrick llvm::Intrinsic::objc_retainAutorelease);
2610e5dd7070Spatrick }
2611e5dd7070Spatrick
2612e5dd7070Spatrick /// i8* \@objc_loadWeak(i8** %addr)
2613e5dd7070Spatrick /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
EmitARCLoadWeak(Address addr)2614e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2615e5dd7070Spatrick return emitARCLoadOperation(*this, addr,
2616e5dd7070Spatrick CGM.getObjCEntrypoints().objc_loadWeak,
2617e5dd7070Spatrick llvm::Intrinsic::objc_loadWeak);
2618e5dd7070Spatrick }
2619e5dd7070Spatrick
2620e5dd7070Spatrick /// i8* \@objc_loadWeakRetained(i8** %addr)
EmitARCLoadWeakRetained(Address addr)2621e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
2622e5dd7070Spatrick return emitARCLoadOperation(*this, addr,
2623e5dd7070Spatrick CGM.getObjCEntrypoints().objc_loadWeakRetained,
2624e5dd7070Spatrick llvm::Intrinsic::objc_loadWeakRetained);
2625e5dd7070Spatrick }
2626e5dd7070Spatrick
2627e5dd7070Spatrick /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2628e5dd7070Spatrick /// Returns %value.
EmitARCStoreWeak(Address addr,llvm::Value * value,bool ignored)2629e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
2630e5dd7070Spatrick llvm::Value *value,
2631e5dd7070Spatrick bool ignored) {
2632e5dd7070Spatrick return emitARCStoreOperation(*this, addr, value,
2633e5dd7070Spatrick CGM.getObjCEntrypoints().objc_storeWeak,
2634e5dd7070Spatrick llvm::Intrinsic::objc_storeWeak, ignored);
2635e5dd7070Spatrick }
2636e5dd7070Spatrick
2637e5dd7070Spatrick /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2638e5dd7070Spatrick /// Returns %value. %addr is known to not have a current weak entry.
2639e5dd7070Spatrick /// Essentially equivalent to:
2640e5dd7070Spatrick /// *addr = nil; objc_storeWeak(addr, value);
EmitARCInitWeak(Address addr,llvm::Value * value)2641e5dd7070Spatrick void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2642e5dd7070Spatrick // If we're initializing to null, just write null to memory; no need
2643e5dd7070Spatrick // to get the runtime involved. But don't do this if optimization
2644e5dd7070Spatrick // is enabled, because accounting for this would make the optimizer
2645e5dd7070Spatrick // much more complicated.
2646e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(value) &&
2647e5dd7070Spatrick CGM.getCodeGenOpts().OptimizationLevel == 0) {
2648e5dd7070Spatrick Builder.CreateStore(value, addr);
2649e5dd7070Spatrick return;
2650e5dd7070Spatrick }
2651e5dd7070Spatrick
2652e5dd7070Spatrick emitARCStoreOperation(*this, addr, value,
2653e5dd7070Spatrick CGM.getObjCEntrypoints().objc_initWeak,
2654e5dd7070Spatrick llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2655e5dd7070Spatrick }
2656e5dd7070Spatrick
2657e5dd7070Spatrick /// void \@objc_destroyWeak(i8** %addr)
2658e5dd7070Spatrick /// Essentially objc_storeWeak(addr, nil).
EmitARCDestroyWeak(Address addr)2659e5dd7070Spatrick void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
2660e5dd7070Spatrick llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2661*12c85518Srobert if (!fn)
2662*12c85518Srobert fn = getARCIntrinsic(llvm::Intrinsic::objc_destroyWeak, CGM);
2663e5dd7070Spatrick
2664e5dd7070Spatrick // Cast the argument to 'id*'.
2665*12c85518Srobert addr = Builder.CreateElementBitCast(addr, Int8PtrTy);
2666e5dd7070Spatrick
2667e5dd7070Spatrick EmitNounwindRuntimeCall(fn, addr.getPointer());
2668e5dd7070Spatrick }
2669e5dd7070Spatrick
2670e5dd7070Spatrick /// void \@objc_moveWeak(i8** %dest, i8** %src)
2671e5dd7070Spatrick /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2672e5dd7070Spatrick /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
EmitARCMoveWeak(Address dst,Address src)2673e5dd7070Spatrick void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
2674e5dd7070Spatrick emitARCCopyOperation(*this, dst, src,
2675e5dd7070Spatrick CGM.getObjCEntrypoints().objc_moveWeak,
2676e5dd7070Spatrick llvm::Intrinsic::objc_moveWeak);
2677e5dd7070Spatrick }
2678e5dd7070Spatrick
2679e5dd7070Spatrick /// void \@objc_copyWeak(i8** %dest, i8** %src)
2680e5dd7070Spatrick /// Disregards the current value in %dest. Essentially
2681e5dd7070Spatrick /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
EmitARCCopyWeak(Address dst,Address src)2682e5dd7070Spatrick void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
2683e5dd7070Spatrick emitARCCopyOperation(*this, dst, src,
2684e5dd7070Spatrick CGM.getObjCEntrypoints().objc_copyWeak,
2685e5dd7070Spatrick llvm::Intrinsic::objc_copyWeak);
2686e5dd7070Spatrick }
2687e5dd7070Spatrick
emitARCCopyAssignWeak(QualType Ty,Address DstAddr,Address SrcAddr)2688e5dd7070Spatrick void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2689e5dd7070Spatrick Address SrcAddr) {
2690e5dd7070Spatrick llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2691e5dd7070Spatrick Object = EmitObjCConsumeObject(Ty, Object);
2692e5dd7070Spatrick EmitARCStoreWeak(DstAddr, Object, false);
2693e5dd7070Spatrick }
2694e5dd7070Spatrick
emitARCMoveAssignWeak(QualType Ty,Address DstAddr,Address SrcAddr)2695e5dd7070Spatrick void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2696e5dd7070Spatrick Address SrcAddr) {
2697e5dd7070Spatrick llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2698e5dd7070Spatrick Object = EmitObjCConsumeObject(Ty, Object);
2699e5dd7070Spatrick EmitARCStoreWeak(DstAddr, Object, false);
2700e5dd7070Spatrick EmitARCDestroyWeak(SrcAddr);
2701e5dd7070Spatrick }
2702e5dd7070Spatrick
2703e5dd7070Spatrick /// Produce the code to do a objc_autoreleasepool_push.
2704e5dd7070Spatrick /// call i8* \@objc_autoreleasePoolPush(void)
EmitObjCAutoreleasePoolPush()2705e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2706e5dd7070Spatrick llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2707*12c85518Srobert if (!fn)
2708*12c85518Srobert fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush, CGM);
2709e5dd7070Spatrick
2710e5dd7070Spatrick return EmitNounwindRuntimeCall(fn);
2711e5dd7070Spatrick }
2712e5dd7070Spatrick
2713e5dd7070Spatrick /// Produce the code to do a primitive release.
2714e5dd7070Spatrick /// call void \@objc_autoreleasePoolPop(i8* %ptr)
EmitObjCAutoreleasePoolPop(llvm::Value * value)2715e5dd7070Spatrick void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2716e5dd7070Spatrick assert(value->getType() == Int8PtrTy);
2717e5dd7070Spatrick
2718e5dd7070Spatrick if (getInvokeDest()) {
2719e5dd7070Spatrick // Call the runtime method not the intrinsic if we are handling exceptions
2720e5dd7070Spatrick llvm::FunctionCallee &fn =
2721e5dd7070Spatrick CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2722e5dd7070Spatrick if (!fn) {
2723e5dd7070Spatrick llvm::FunctionType *fnType =
2724e5dd7070Spatrick llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2725e5dd7070Spatrick fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2726e5dd7070Spatrick setARCRuntimeFunctionLinkage(CGM, fn);
2727e5dd7070Spatrick }
2728e5dd7070Spatrick
2729e5dd7070Spatrick // objc_autoreleasePoolPop can throw.
2730e5dd7070Spatrick EmitRuntimeCallOrInvoke(fn, value);
2731e5dd7070Spatrick } else {
2732e5dd7070Spatrick llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2733*12c85518Srobert if (!fn)
2734*12c85518Srobert fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop, CGM);
2735e5dd7070Spatrick
2736e5dd7070Spatrick EmitRuntimeCall(fn, value);
2737e5dd7070Spatrick }
2738e5dd7070Spatrick }
2739e5dd7070Spatrick
2740e5dd7070Spatrick /// Produce the code to do an MRR version objc_autoreleasepool_push.
2741e5dd7070Spatrick /// Which is: [[NSAutoreleasePool alloc] init];
2742e5dd7070Spatrick /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2743e5dd7070Spatrick /// init is declared as: - (id) init; in its NSObject super class.
2744e5dd7070Spatrick ///
EmitObjCMRRAutoreleasePoolPush()2745e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2746e5dd7070Spatrick CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2747e5dd7070Spatrick llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2748e5dd7070Spatrick // [NSAutoreleasePool alloc]
2749e5dd7070Spatrick IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2750e5dd7070Spatrick Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2751e5dd7070Spatrick CallArgList Args;
2752e5dd7070Spatrick RValue AllocRV =
2753e5dd7070Spatrick Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2754e5dd7070Spatrick getContext().getObjCIdType(),
2755e5dd7070Spatrick AllocSel, Receiver, Args);
2756e5dd7070Spatrick
2757e5dd7070Spatrick // [Receiver init]
2758e5dd7070Spatrick Receiver = AllocRV.getScalarVal();
2759e5dd7070Spatrick II = &CGM.getContext().Idents.get("init");
2760e5dd7070Spatrick Selector InitSel = getContext().Selectors.getSelector(0, &II);
2761e5dd7070Spatrick RValue InitRV =
2762e5dd7070Spatrick Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2763e5dd7070Spatrick getContext().getObjCIdType(),
2764e5dd7070Spatrick InitSel, Receiver, Args);
2765e5dd7070Spatrick return InitRV.getScalarVal();
2766e5dd7070Spatrick }
2767e5dd7070Spatrick
2768e5dd7070Spatrick /// Allocate the given objc object.
2769e5dd7070Spatrick /// call i8* \@objc_alloc(i8* %value)
EmitObjCAlloc(llvm::Value * value,llvm::Type * resultType)2770e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2771e5dd7070Spatrick llvm::Type *resultType) {
2772e5dd7070Spatrick return emitObjCValueOperation(*this, value, resultType,
2773e5dd7070Spatrick CGM.getObjCEntrypoints().objc_alloc,
2774e5dd7070Spatrick "objc_alloc");
2775e5dd7070Spatrick }
2776e5dd7070Spatrick
2777e5dd7070Spatrick /// Allocate the given objc object.
2778e5dd7070Spatrick /// call i8* \@objc_allocWithZone(i8* %value)
EmitObjCAllocWithZone(llvm::Value * value,llvm::Type * resultType)2779e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2780e5dd7070Spatrick llvm::Type *resultType) {
2781e5dd7070Spatrick return emitObjCValueOperation(*this, value, resultType,
2782e5dd7070Spatrick CGM.getObjCEntrypoints().objc_allocWithZone,
2783e5dd7070Spatrick "objc_allocWithZone");
2784e5dd7070Spatrick }
2785e5dd7070Spatrick
EmitObjCAllocInit(llvm::Value * value,llvm::Type * resultType)2786e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2787e5dd7070Spatrick llvm::Type *resultType) {
2788e5dd7070Spatrick return emitObjCValueOperation(*this, value, resultType,
2789e5dd7070Spatrick CGM.getObjCEntrypoints().objc_alloc_init,
2790e5dd7070Spatrick "objc_alloc_init");
2791e5dd7070Spatrick }
2792e5dd7070Spatrick
2793e5dd7070Spatrick /// Produce the code to do a primitive release.
2794e5dd7070Spatrick /// [tmp drain];
EmitObjCMRRAutoreleasePoolPop(llvm::Value * Arg)2795e5dd7070Spatrick void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2796e5dd7070Spatrick IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2797e5dd7070Spatrick Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2798e5dd7070Spatrick CallArgList Args;
2799e5dd7070Spatrick CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2800e5dd7070Spatrick getContext().VoidTy, DrainSel, Arg, Args);
2801e5dd7070Spatrick }
2802e5dd7070Spatrick
destroyARCStrongPrecise(CodeGenFunction & CGF,Address addr,QualType type)2803e5dd7070Spatrick void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2804e5dd7070Spatrick Address addr,
2805e5dd7070Spatrick QualType type) {
2806e5dd7070Spatrick CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2807e5dd7070Spatrick }
2808e5dd7070Spatrick
destroyARCStrongImprecise(CodeGenFunction & CGF,Address addr,QualType type)2809e5dd7070Spatrick void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2810e5dd7070Spatrick Address addr,
2811e5dd7070Spatrick QualType type) {
2812e5dd7070Spatrick CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2813e5dd7070Spatrick }
2814e5dd7070Spatrick
destroyARCWeak(CodeGenFunction & CGF,Address addr,QualType type)2815e5dd7070Spatrick void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2816e5dd7070Spatrick Address addr,
2817e5dd7070Spatrick QualType type) {
2818e5dd7070Spatrick CGF.EmitARCDestroyWeak(addr);
2819e5dd7070Spatrick }
2820e5dd7070Spatrick
emitARCIntrinsicUse(CodeGenFunction & CGF,Address addr,QualType type)2821e5dd7070Spatrick void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2822e5dd7070Spatrick QualType type) {
2823e5dd7070Spatrick llvm::Value *value = CGF.Builder.CreateLoad(addr);
2824e5dd7070Spatrick CGF.EmitARCIntrinsicUse(value);
2825e5dd7070Spatrick }
2826e5dd7070Spatrick
2827e5dd7070Spatrick /// Autorelease the given object.
2828e5dd7070Spatrick /// call i8* \@objc_autorelease(i8* %value)
EmitObjCAutorelease(llvm::Value * value,llvm::Type * returnType)2829e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2830e5dd7070Spatrick llvm::Type *returnType) {
2831e5dd7070Spatrick return emitObjCValueOperation(
2832e5dd7070Spatrick *this, value, returnType,
2833e5dd7070Spatrick CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2834e5dd7070Spatrick "objc_autorelease");
2835e5dd7070Spatrick }
2836e5dd7070Spatrick
2837e5dd7070Spatrick /// Retain the given object, with normal retain semantics.
2838e5dd7070Spatrick /// call i8* \@objc_retain(i8* %value)
EmitObjCRetainNonBlock(llvm::Value * value,llvm::Type * returnType)2839e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2840e5dd7070Spatrick llvm::Type *returnType) {
2841e5dd7070Spatrick return emitObjCValueOperation(
2842e5dd7070Spatrick *this, value, returnType,
2843e5dd7070Spatrick CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
2844e5dd7070Spatrick }
2845e5dd7070Spatrick
2846e5dd7070Spatrick /// Release the given object.
2847e5dd7070Spatrick /// call void \@objc_release(i8* %value)
EmitObjCRelease(llvm::Value * value,ARCPreciseLifetime_t precise)2848e5dd7070Spatrick void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2849e5dd7070Spatrick ARCPreciseLifetime_t precise) {
2850e5dd7070Spatrick if (isa<llvm::ConstantPointerNull>(value)) return;
2851e5dd7070Spatrick
2852e5dd7070Spatrick llvm::FunctionCallee &fn =
2853e5dd7070Spatrick CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
2854e5dd7070Spatrick if (!fn) {
2855e5dd7070Spatrick llvm::FunctionType *fnType =
2856e5dd7070Spatrick llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2857e5dd7070Spatrick fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2858e5dd7070Spatrick setARCRuntimeFunctionLinkage(CGM, fn);
2859e5dd7070Spatrick // We have Native ARC, so set nonlazybind attribute for performance
2860e5dd7070Spatrick if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2861e5dd7070Spatrick f->addFnAttr(llvm::Attribute::NonLazyBind);
2862e5dd7070Spatrick }
2863e5dd7070Spatrick
2864e5dd7070Spatrick // Cast the argument to 'id'.
2865e5dd7070Spatrick value = Builder.CreateBitCast(value, Int8PtrTy);
2866e5dd7070Spatrick
2867e5dd7070Spatrick // Call objc_release.
2868e5dd7070Spatrick llvm::CallBase *call = EmitCallOrInvoke(fn, value);
2869e5dd7070Spatrick
2870e5dd7070Spatrick if (precise == ARCImpreciseLifetime) {
2871e5dd7070Spatrick call->setMetadata("clang.imprecise_release",
2872*12c85518Srobert llvm::MDNode::get(Builder.getContext(), std::nullopt));
2873e5dd7070Spatrick }
2874e5dd7070Spatrick }
2875e5dd7070Spatrick
2876e5dd7070Spatrick namespace {
2877e5dd7070Spatrick struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2878e5dd7070Spatrick llvm::Value *Token;
2879e5dd7070Spatrick
CallObjCAutoreleasePoolObject__anonb505f9fd0511::CallObjCAutoreleasePoolObject2880e5dd7070Spatrick CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2881e5dd7070Spatrick
Emit__anonb505f9fd0511::CallObjCAutoreleasePoolObject2882e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override {
2883e5dd7070Spatrick CGF.EmitObjCAutoreleasePoolPop(Token);
2884e5dd7070Spatrick }
2885e5dd7070Spatrick };
2886e5dd7070Spatrick struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2887e5dd7070Spatrick llvm::Value *Token;
2888e5dd7070Spatrick
CallObjCMRRAutoreleasePoolObject__anonb505f9fd0511::CallObjCMRRAutoreleasePoolObject2889e5dd7070Spatrick CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2890e5dd7070Spatrick
Emit__anonb505f9fd0511::CallObjCMRRAutoreleasePoolObject2891e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override {
2892e5dd7070Spatrick CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2893e5dd7070Spatrick }
2894e5dd7070Spatrick };
2895e5dd7070Spatrick }
2896e5dd7070Spatrick
EmitObjCAutoreleasePoolCleanup(llvm::Value * Ptr)2897e5dd7070Spatrick void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2898e5dd7070Spatrick if (CGM.getLangOpts().ObjCAutoRefCount)
2899e5dd7070Spatrick EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2900e5dd7070Spatrick else
2901e5dd7070Spatrick EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2902e5dd7070Spatrick }
2903e5dd7070Spatrick
shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime)2904e5dd7070Spatrick static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2905e5dd7070Spatrick switch (lifetime) {
2906e5dd7070Spatrick case Qualifiers::OCL_None:
2907e5dd7070Spatrick case Qualifiers::OCL_ExplicitNone:
2908e5dd7070Spatrick case Qualifiers::OCL_Strong:
2909e5dd7070Spatrick case Qualifiers::OCL_Autoreleasing:
2910e5dd7070Spatrick return true;
2911e5dd7070Spatrick
2912e5dd7070Spatrick case Qualifiers::OCL_Weak:
2913e5dd7070Spatrick return false;
2914e5dd7070Spatrick }
2915e5dd7070Spatrick
2916e5dd7070Spatrick llvm_unreachable("impossible lifetime!");
2917e5dd7070Spatrick }
2918e5dd7070Spatrick
tryEmitARCRetainLoadOfScalar(CodeGenFunction & CGF,LValue lvalue,QualType type)2919e5dd7070Spatrick static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2920e5dd7070Spatrick LValue lvalue,
2921e5dd7070Spatrick QualType type) {
2922e5dd7070Spatrick llvm::Value *result;
2923e5dd7070Spatrick bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2924e5dd7070Spatrick if (shouldRetain) {
2925e5dd7070Spatrick result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2926e5dd7070Spatrick } else {
2927e5dd7070Spatrick assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2928e5dd7070Spatrick result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
2929e5dd7070Spatrick }
2930e5dd7070Spatrick return TryEmitResult(result, !shouldRetain);
2931e5dd7070Spatrick }
2932e5dd7070Spatrick
tryEmitARCRetainLoadOfScalar(CodeGenFunction & CGF,const Expr * e)2933e5dd7070Spatrick static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2934e5dd7070Spatrick const Expr *e) {
2935e5dd7070Spatrick e = e->IgnoreParens();
2936e5dd7070Spatrick QualType type = e->getType();
2937e5dd7070Spatrick
2938e5dd7070Spatrick // If we're loading retained from a __strong xvalue, we can avoid
2939e5dd7070Spatrick // an extra retain/release pair by zeroing out the source of this
2940e5dd7070Spatrick // "move" operation.
2941e5dd7070Spatrick if (e->isXValue() &&
2942e5dd7070Spatrick !type.isConstQualified() &&
2943e5dd7070Spatrick type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2944e5dd7070Spatrick // Emit the lvalue.
2945e5dd7070Spatrick LValue lv = CGF.EmitLValue(e);
2946e5dd7070Spatrick
2947e5dd7070Spatrick // Load the object pointer.
2948e5dd7070Spatrick llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2949e5dd7070Spatrick SourceLocation()).getScalarVal();
2950e5dd7070Spatrick
2951e5dd7070Spatrick // Set the source pointer to NULL.
2952e5dd7070Spatrick CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
2953e5dd7070Spatrick
2954e5dd7070Spatrick return TryEmitResult(result, true);
2955e5dd7070Spatrick }
2956e5dd7070Spatrick
2957e5dd7070Spatrick // As a very special optimization, in ARC++, if the l-value is the
2958e5dd7070Spatrick // result of a non-volatile assignment, do a simple retain of the
2959e5dd7070Spatrick // result of the call to objc_storeWeak instead of reloading.
2960e5dd7070Spatrick if (CGF.getLangOpts().CPlusPlus &&
2961e5dd7070Spatrick !type.isVolatileQualified() &&
2962e5dd7070Spatrick type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2963e5dd7070Spatrick isa<BinaryOperator>(e) &&
2964e5dd7070Spatrick cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2965e5dd7070Spatrick return TryEmitResult(CGF.EmitScalarExpr(e), false);
2966e5dd7070Spatrick
2967e5dd7070Spatrick // Try to emit code for scalar constant instead of emitting LValue and
2968e5dd7070Spatrick // loading it because we are not guaranteed to have an l-value. One of such
2969e5dd7070Spatrick // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2970e5dd7070Spatrick if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2971e5dd7070Spatrick auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2972e5dd7070Spatrick if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2973e5dd7070Spatrick return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2974e5dd7070Spatrick !shouldRetainObjCLifetime(type.getObjCLifetime()));
2975e5dd7070Spatrick }
2976e5dd7070Spatrick
2977e5dd7070Spatrick return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2978e5dd7070Spatrick }
2979e5dd7070Spatrick
2980e5dd7070Spatrick typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2981e5dd7070Spatrick llvm::Value *value)>
2982e5dd7070Spatrick ValueTransform;
2983e5dd7070Spatrick
2984e5dd7070Spatrick /// Insert code immediately after a call.
2985a9ac8606Spatrick
2986a9ac8606Spatrick // FIXME: We should find a way to emit the runtime call immediately
2987a9ac8606Spatrick // after the call is emitted to eliminate the need for this function.
emitARCOperationAfterCall(CodeGenFunction & CGF,llvm::Value * value,ValueTransform doAfterCall,ValueTransform doFallback)2988e5dd7070Spatrick static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2989e5dd7070Spatrick llvm::Value *value,
2990e5dd7070Spatrick ValueTransform doAfterCall,
2991e5dd7070Spatrick ValueTransform doFallback) {
2992e5dd7070Spatrick CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2993a9ac8606Spatrick auto *callBase = dyn_cast<llvm::CallBase>(value);
2994e5dd7070Spatrick
2995a9ac8606Spatrick if (callBase && llvm::objcarc::hasAttachedCallOpBundle(callBase)) {
2996a9ac8606Spatrick // Fall back if the call base has operand bundle "clang.arc.attachedcall".
2997a9ac8606Spatrick value = doFallback(CGF, value);
2998a9ac8606Spatrick } else if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2999e5dd7070Spatrick // Place the retain immediately following the call.
3000e5dd7070Spatrick CGF.Builder.SetInsertPoint(call->getParent(),
3001e5dd7070Spatrick ++llvm::BasicBlock::iterator(call));
3002e5dd7070Spatrick value = doAfterCall(CGF, value);
3003e5dd7070Spatrick } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
3004e5dd7070Spatrick // Place the retain at the beginning of the normal destination block.
3005e5dd7070Spatrick llvm::BasicBlock *BB = invoke->getNormalDest();
3006e5dd7070Spatrick CGF.Builder.SetInsertPoint(BB, BB->begin());
3007e5dd7070Spatrick value = doAfterCall(CGF, value);
3008e5dd7070Spatrick
3009e5dd7070Spatrick // Bitcasts can arise because of related-result returns. Rewrite
3010e5dd7070Spatrick // the operand.
3011e5dd7070Spatrick } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
3012a9ac8606Spatrick // Change the insert point to avoid emitting the fall-back call after the
3013a9ac8606Spatrick // bitcast.
3014a9ac8606Spatrick CGF.Builder.SetInsertPoint(bitcast->getParent(), bitcast->getIterator());
3015e5dd7070Spatrick llvm::Value *operand = bitcast->getOperand(0);
3016e5dd7070Spatrick operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
3017e5dd7070Spatrick bitcast->setOperand(0, operand);
3018a9ac8606Spatrick value = bitcast;
3019e5dd7070Spatrick } else {
3020a9ac8606Spatrick auto *phi = dyn_cast<llvm::PHINode>(value);
3021a9ac8606Spatrick if (phi && phi->getNumIncomingValues() == 2 &&
3022a9ac8606Spatrick isa<llvm::ConstantPointerNull>(phi->getIncomingValue(1)) &&
3023a9ac8606Spatrick isa<llvm::CallBase>(phi->getIncomingValue(0))) {
3024a9ac8606Spatrick // Handle phi instructions that are generated when it's necessary to check
3025a9ac8606Spatrick // whether the receiver of a message is null.
3026a9ac8606Spatrick llvm::Value *inVal = phi->getIncomingValue(0);
3027a9ac8606Spatrick inVal = emitARCOperationAfterCall(CGF, inVal, doAfterCall, doFallback);
3028a9ac8606Spatrick phi->setIncomingValue(0, inVal);
3029a9ac8606Spatrick value = phi;
3030a9ac8606Spatrick } else {
3031a9ac8606Spatrick // Generic fall-back case.
3032e5dd7070Spatrick // Retain using the non-block variant: we never need to do a copy
3033e5dd7070Spatrick // of a block that's been returned to us.
3034a9ac8606Spatrick value = doFallback(CGF, value);
3035e5dd7070Spatrick }
3036e5dd7070Spatrick }
3037e5dd7070Spatrick
3038a9ac8606Spatrick CGF.Builder.restoreIP(ip);
3039a9ac8606Spatrick return value;
3040a9ac8606Spatrick }
3041a9ac8606Spatrick
3042e5dd7070Spatrick /// Given that the given expression is some sort of call (which does
3043e5dd7070Spatrick /// not return retained), emit a retain following it.
emitARCRetainCallResult(CodeGenFunction & CGF,const Expr * e)3044e5dd7070Spatrick static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
3045e5dd7070Spatrick const Expr *e) {
3046e5dd7070Spatrick llvm::Value *value = CGF.EmitScalarExpr(e);
3047e5dd7070Spatrick return emitARCOperationAfterCall(CGF, value,
3048e5dd7070Spatrick [](CodeGenFunction &CGF, llvm::Value *value) {
3049e5dd7070Spatrick return CGF.EmitARCRetainAutoreleasedReturnValue(value);
3050e5dd7070Spatrick },
3051e5dd7070Spatrick [](CodeGenFunction &CGF, llvm::Value *value) {
3052e5dd7070Spatrick return CGF.EmitARCRetainNonBlock(value);
3053e5dd7070Spatrick });
3054e5dd7070Spatrick }
3055e5dd7070Spatrick
3056e5dd7070Spatrick /// Given that the given expression is some sort of call (which does
3057e5dd7070Spatrick /// not return retained), perform an unsafeClaim following it.
emitARCUnsafeClaimCallResult(CodeGenFunction & CGF,const Expr * e)3058e5dd7070Spatrick static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
3059e5dd7070Spatrick const Expr *e) {
3060e5dd7070Spatrick llvm::Value *value = CGF.EmitScalarExpr(e);
3061e5dd7070Spatrick return emitARCOperationAfterCall(CGF, value,
3062e5dd7070Spatrick [](CodeGenFunction &CGF, llvm::Value *value) {
3063e5dd7070Spatrick return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
3064e5dd7070Spatrick },
3065e5dd7070Spatrick [](CodeGenFunction &CGF, llvm::Value *value) {
3066e5dd7070Spatrick return value;
3067e5dd7070Spatrick });
3068e5dd7070Spatrick }
3069e5dd7070Spatrick
EmitARCReclaimReturnedObject(const Expr * E,bool allowUnsafeClaim)3070e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
3071e5dd7070Spatrick bool allowUnsafeClaim) {
3072e5dd7070Spatrick if (allowUnsafeClaim &&
3073e5dd7070Spatrick CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
3074e5dd7070Spatrick return emitARCUnsafeClaimCallResult(*this, E);
3075e5dd7070Spatrick } else {
3076e5dd7070Spatrick llvm::Value *value = emitARCRetainCallResult(*this, E);
3077e5dd7070Spatrick return EmitObjCConsumeObject(E->getType(), value);
3078e5dd7070Spatrick }
3079e5dd7070Spatrick }
3080e5dd7070Spatrick
3081e5dd7070Spatrick /// Determine whether it might be important to emit a separate
3082e5dd7070Spatrick /// objc_retain_block on the result of the given expression, or
3083e5dd7070Spatrick /// whether it's okay to just emit it in a +1 context.
shouldEmitSeparateBlockRetain(const Expr * e)3084e5dd7070Spatrick static bool shouldEmitSeparateBlockRetain(const Expr *e) {
3085e5dd7070Spatrick assert(e->getType()->isBlockPointerType());
3086e5dd7070Spatrick e = e->IgnoreParens();
3087e5dd7070Spatrick
3088e5dd7070Spatrick // For future goodness, emit block expressions directly in +1
3089e5dd7070Spatrick // contexts if we can.
3090e5dd7070Spatrick if (isa<BlockExpr>(e))
3091e5dd7070Spatrick return false;
3092e5dd7070Spatrick
3093e5dd7070Spatrick if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
3094e5dd7070Spatrick switch (cast->getCastKind()) {
3095e5dd7070Spatrick // Emitting these operations in +1 contexts is goodness.
3096e5dd7070Spatrick case CK_LValueToRValue:
3097e5dd7070Spatrick case CK_ARCReclaimReturnedObject:
3098e5dd7070Spatrick case CK_ARCConsumeObject:
3099e5dd7070Spatrick case CK_ARCProduceObject:
3100e5dd7070Spatrick return false;
3101e5dd7070Spatrick
3102e5dd7070Spatrick // These operations preserve a block type.
3103e5dd7070Spatrick case CK_NoOp:
3104e5dd7070Spatrick case CK_BitCast:
3105e5dd7070Spatrick return shouldEmitSeparateBlockRetain(cast->getSubExpr());
3106e5dd7070Spatrick
3107e5dd7070Spatrick // These operations are known to be bad (or haven't been considered).
3108e5dd7070Spatrick case CK_AnyPointerToBlockPointerCast:
3109e5dd7070Spatrick default:
3110e5dd7070Spatrick return true;
3111e5dd7070Spatrick }
3112e5dd7070Spatrick }
3113e5dd7070Spatrick
3114e5dd7070Spatrick return true;
3115e5dd7070Spatrick }
3116e5dd7070Spatrick
3117e5dd7070Spatrick namespace {
3118e5dd7070Spatrick /// A CRTP base class for emitting expressions of retainable object
3119e5dd7070Spatrick /// pointer type in ARC.
3120e5dd7070Spatrick template <typename Impl, typename Result> class ARCExprEmitter {
3121e5dd7070Spatrick protected:
3122e5dd7070Spatrick CodeGenFunction &CGF;
asImpl()3123e5dd7070Spatrick Impl &asImpl() { return *static_cast<Impl*>(this); }
3124e5dd7070Spatrick
ARCExprEmitter(CodeGenFunction & CGF)3125e5dd7070Spatrick ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
3126e5dd7070Spatrick
3127e5dd7070Spatrick public:
3128e5dd7070Spatrick Result visit(const Expr *e);
3129e5dd7070Spatrick Result visitCastExpr(const CastExpr *e);
3130e5dd7070Spatrick Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
3131e5dd7070Spatrick Result visitBlockExpr(const BlockExpr *e);
3132e5dd7070Spatrick Result visitBinaryOperator(const BinaryOperator *e);
3133e5dd7070Spatrick Result visitBinAssign(const BinaryOperator *e);
3134e5dd7070Spatrick Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
3135e5dd7070Spatrick Result visitBinAssignAutoreleasing(const BinaryOperator *e);
3136e5dd7070Spatrick Result visitBinAssignWeak(const BinaryOperator *e);
3137e5dd7070Spatrick Result visitBinAssignStrong(const BinaryOperator *e);
3138e5dd7070Spatrick
3139e5dd7070Spatrick // Minimal implementation:
3140e5dd7070Spatrick // Result visitLValueToRValue(const Expr *e)
3141e5dd7070Spatrick // Result visitConsumeObject(const Expr *e)
3142e5dd7070Spatrick // Result visitExtendBlockObject(const Expr *e)
3143e5dd7070Spatrick // Result visitReclaimReturnedObject(const Expr *e)
3144e5dd7070Spatrick // Result visitCall(const Expr *e)
3145e5dd7070Spatrick // Result visitExpr(const Expr *e)
3146e5dd7070Spatrick //
3147e5dd7070Spatrick // Result emitBitCast(Result result, llvm::Type *resultType)
3148e5dd7070Spatrick // llvm::Value *getValueOfResult(Result result)
3149e5dd7070Spatrick };
3150e5dd7070Spatrick }
3151e5dd7070Spatrick
3152e5dd7070Spatrick /// Try to emit a PseudoObjectExpr under special ARC rules.
3153e5dd7070Spatrick ///
3154e5dd7070Spatrick /// This massively duplicates emitPseudoObjectRValue.
3155e5dd7070Spatrick template <typename Impl, typename Result>
3156e5dd7070Spatrick Result
visitPseudoObjectExpr(const PseudoObjectExpr * E)3157e5dd7070Spatrick ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
3158e5dd7070Spatrick SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3159e5dd7070Spatrick
3160e5dd7070Spatrick // Find the result expression.
3161e5dd7070Spatrick const Expr *resultExpr = E->getResultExpr();
3162e5dd7070Spatrick assert(resultExpr);
3163e5dd7070Spatrick Result result;
3164e5dd7070Spatrick
3165e5dd7070Spatrick for (PseudoObjectExpr::const_semantics_iterator
3166e5dd7070Spatrick i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3167e5dd7070Spatrick const Expr *semantic = *i;
3168e5dd7070Spatrick
3169e5dd7070Spatrick // If this semantic expression is an opaque value, bind it
3170e5dd7070Spatrick // to the result of its source expression.
3171e5dd7070Spatrick if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3172e5dd7070Spatrick typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3173e5dd7070Spatrick OVMA opaqueData;
3174e5dd7070Spatrick
3175e5dd7070Spatrick // If this semantic is the result of the pseudo-object
3176e5dd7070Spatrick // expression, try to evaluate the source as +1.
3177e5dd7070Spatrick if (ov == resultExpr) {
3178e5dd7070Spatrick assert(!OVMA::shouldBindAsLValue(ov));
3179e5dd7070Spatrick result = asImpl().visit(ov->getSourceExpr());
3180e5dd7070Spatrick opaqueData = OVMA::bind(CGF, ov,
3181e5dd7070Spatrick RValue::get(asImpl().getValueOfResult(result)));
3182e5dd7070Spatrick
3183e5dd7070Spatrick // Otherwise, just bind it.
3184e5dd7070Spatrick } else {
3185e5dd7070Spatrick opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3186e5dd7070Spatrick }
3187e5dd7070Spatrick opaques.push_back(opaqueData);
3188e5dd7070Spatrick
3189e5dd7070Spatrick // Otherwise, if the expression is the result, evaluate it
3190e5dd7070Spatrick // and remember the result.
3191e5dd7070Spatrick } else if (semantic == resultExpr) {
3192e5dd7070Spatrick result = asImpl().visit(semantic);
3193e5dd7070Spatrick
3194e5dd7070Spatrick // Otherwise, evaluate the expression in an ignored context.
3195e5dd7070Spatrick } else {
3196e5dd7070Spatrick CGF.EmitIgnoredExpr(semantic);
3197e5dd7070Spatrick }
3198e5dd7070Spatrick }
3199e5dd7070Spatrick
3200e5dd7070Spatrick // Unbind all the opaques now.
3201e5dd7070Spatrick for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3202e5dd7070Spatrick opaques[i].unbind(CGF);
3203e5dd7070Spatrick
3204e5dd7070Spatrick return result;
3205e5dd7070Spatrick }
3206e5dd7070Spatrick
3207e5dd7070Spatrick template <typename Impl, typename Result>
visitBlockExpr(const BlockExpr * e)3208e5dd7070Spatrick Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
3209e5dd7070Spatrick // The default implementation just forwards the expression to visitExpr.
3210e5dd7070Spatrick return asImpl().visitExpr(e);
3211e5dd7070Spatrick }
3212e5dd7070Spatrick
3213e5dd7070Spatrick template <typename Impl, typename Result>
visitCastExpr(const CastExpr * e)3214e5dd7070Spatrick Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3215e5dd7070Spatrick switch (e->getCastKind()) {
3216e5dd7070Spatrick
3217e5dd7070Spatrick // No-op casts don't change the type, so we just ignore them.
3218e5dd7070Spatrick case CK_NoOp:
3219e5dd7070Spatrick return asImpl().visit(e->getSubExpr());
3220e5dd7070Spatrick
3221e5dd7070Spatrick // These casts can change the type.
3222e5dd7070Spatrick case CK_CPointerToObjCPointerCast:
3223e5dd7070Spatrick case CK_BlockPointerToObjCPointerCast:
3224e5dd7070Spatrick case CK_AnyPointerToBlockPointerCast:
3225e5dd7070Spatrick case CK_BitCast: {
3226e5dd7070Spatrick llvm::Type *resultType = CGF.ConvertType(e->getType());
3227e5dd7070Spatrick assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3228e5dd7070Spatrick Result result = asImpl().visit(e->getSubExpr());
3229e5dd7070Spatrick return asImpl().emitBitCast(result, resultType);
3230e5dd7070Spatrick }
3231e5dd7070Spatrick
3232e5dd7070Spatrick // Handle some casts specially.
3233e5dd7070Spatrick case CK_LValueToRValue:
3234e5dd7070Spatrick return asImpl().visitLValueToRValue(e->getSubExpr());
3235e5dd7070Spatrick case CK_ARCConsumeObject:
3236e5dd7070Spatrick return asImpl().visitConsumeObject(e->getSubExpr());
3237e5dd7070Spatrick case CK_ARCExtendBlockObject:
3238e5dd7070Spatrick return asImpl().visitExtendBlockObject(e->getSubExpr());
3239e5dd7070Spatrick case CK_ARCReclaimReturnedObject:
3240e5dd7070Spatrick return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3241e5dd7070Spatrick
3242e5dd7070Spatrick // Otherwise, use the default logic.
3243e5dd7070Spatrick default:
3244e5dd7070Spatrick return asImpl().visitExpr(e);
3245e5dd7070Spatrick }
3246e5dd7070Spatrick }
3247e5dd7070Spatrick
3248e5dd7070Spatrick template <typename Impl, typename Result>
3249e5dd7070Spatrick Result
visitBinaryOperator(const BinaryOperator * e)3250e5dd7070Spatrick ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3251e5dd7070Spatrick switch (e->getOpcode()) {
3252e5dd7070Spatrick case BO_Comma:
3253e5dd7070Spatrick CGF.EmitIgnoredExpr(e->getLHS());
3254e5dd7070Spatrick CGF.EnsureInsertPoint();
3255e5dd7070Spatrick return asImpl().visit(e->getRHS());
3256e5dd7070Spatrick
3257e5dd7070Spatrick case BO_Assign:
3258e5dd7070Spatrick return asImpl().visitBinAssign(e);
3259e5dd7070Spatrick
3260e5dd7070Spatrick default:
3261e5dd7070Spatrick return asImpl().visitExpr(e);
3262e5dd7070Spatrick }
3263e5dd7070Spatrick }
3264e5dd7070Spatrick
3265e5dd7070Spatrick template <typename Impl, typename Result>
visitBinAssign(const BinaryOperator * e)3266e5dd7070Spatrick Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3267e5dd7070Spatrick switch (e->getLHS()->getType().getObjCLifetime()) {
3268e5dd7070Spatrick case Qualifiers::OCL_ExplicitNone:
3269e5dd7070Spatrick return asImpl().visitBinAssignUnsafeUnretained(e);
3270e5dd7070Spatrick
3271e5dd7070Spatrick case Qualifiers::OCL_Weak:
3272e5dd7070Spatrick return asImpl().visitBinAssignWeak(e);
3273e5dd7070Spatrick
3274e5dd7070Spatrick case Qualifiers::OCL_Autoreleasing:
3275e5dd7070Spatrick return asImpl().visitBinAssignAutoreleasing(e);
3276e5dd7070Spatrick
3277e5dd7070Spatrick case Qualifiers::OCL_Strong:
3278e5dd7070Spatrick return asImpl().visitBinAssignStrong(e);
3279e5dd7070Spatrick
3280e5dd7070Spatrick case Qualifiers::OCL_None:
3281e5dd7070Spatrick return asImpl().visitExpr(e);
3282e5dd7070Spatrick }
3283e5dd7070Spatrick llvm_unreachable("bad ObjC ownership qualifier");
3284e5dd7070Spatrick }
3285e5dd7070Spatrick
3286e5dd7070Spatrick /// The default rule for __unsafe_unretained emits the RHS recursively,
3287e5dd7070Spatrick /// stores into the unsafe variable, and propagates the result outward.
3288e5dd7070Spatrick template <typename Impl, typename Result>
3289e5dd7070Spatrick Result ARCExprEmitter<Impl,Result>::
visitBinAssignUnsafeUnretained(const BinaryOperator * e)3290e5dd7070Spatrick visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3291e5dd7070Spatrick // Recursively emit the RHS.
3292e5dd7070Spatrick // For __block safety, do this before emitting the LHS.
3293e5dd7070Spatrick Result result = asImpl().visit(e->getRHS());
3294e5dd7070Spatrick
3295e5dd7070Spatrick // Perform the store.
3296e5dd7070Spatrick LValue lvalue =
3297e5dd7070Spatrick CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3298e5dd7070Spatrick CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3299e5dd7070Spatrick lvalue);
3300e5dd7070Spatrick
3301e5dd7070Spatrick return result;
3302e5dd7070Spatrick }
3303e5dd7070Spatrick
3304e5dd7070Spatrick template <typename Impl, typename Result>
3305e5dd7070Spatrick Result
visitBinAssignAutoreleasing(const BinaryOperator * e)3306e5dd7070Spatrick ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3307e5dd7070Spatrick return asImpl().visitExpr(e);
3308e5dd7070Spatrick }
3309e5dd7070Spatrick
3310e5dd7070Spatrick template <typename Impl, typename Result>
3311e5dd7070Spatrick Result
visitBinAssignWeak(const BinaryOperator * e)3312e5dd7070Spatrick ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3313e5dd7070Spatrick return asImpl().visitExpr(e);
3314e5dd7070Spatrick }
3315e5dd7070Spatrick
3316e5dd7070Spatrick template <typename Impl, typename Result>
3317e5dd7070Spatrick Result
visitBinAssignStrong(const BinaryOperator * e)3318e5dd7070Spatrick ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3319e5dd7070Spatrick return asImpl().visitExpr(e);
3320e5dd7070Spatrick }
3321e5dd7070Spatrick
3322e5dd7070Spatrick /// The general expression-emission logic.
3323e5dd7070Spatrick template <typename Impl, typename Result>
visit(const Expr * e)3324e5dd7070Spatrick Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3325e5dd7070Spatrick // We should *never* see a nested full-expression here, because if
3326e5dd7070Spatrick // we fail to emit at +1, our caller must not retain after we close
3327e5dd7070Spatrick // out the full-expression. This isn't as important in the unsafe
3328e5dd7070Spatrick // emitter.
3329e5dd7070Spatrick assert(!isa<ExprWithCleanups>(e));
3330e5dd7070Spatrick
3331e5dd7070Spatrick // Look through parens, __extension__, generic selection, etc.
3332e5dd7070Spatrick e = e->IgnoreParens();
3333e5dd7070Spatrick
3334e5dd7070Spatrick // Handle certain kinds of casts.
3335e5dd7070Spatrick if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3336e5dd7070Spatrick return asImpl().visitCastExpr(ce);
3337e5dd7070Spatrick
3338e5dd7070Spatrick // Handle the comma operator.
3339e5dd7070Spatrick } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3340e5dd7070Spatrick return asImpl().visitBinaryOperator(op);
3341e5dd7070Spatrick
3342e5dd7070Spatrick // TODO: handle conditional operators here
3343e5dd7070Spatrick
3344e5dd7070Spatrick // For calls and message sends, use the retained-call logic.
3345e5dd7070Spatrick // Delegate inits are a special case in that they're the only
3346e5dd7070Spatrick // returns-retained expression that *isn't* surrounded by
3347e5dd7070Spatrick // a consume.
3348e5dd7070Spatrick } else if (isa<CallExpr>(e) ||
3349e5dd7070Spatrick (isa<ObjCMessageExpr>(e) &&
3350e5dd7070Spatrick !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3351e5dd7070Spatrick return asImpl().visitCall(e);
3352e5dd7070Spatrick
3353e5dd7070Spatrick // Look through pseudo-object expressions.
3354e5dd7070Spatrick } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3355e5dd7070Spatrick return asImpl().visitPseudoObjectExpr(pseudo);
3356e5dd7070Spatrick } else if (auto *be = dyn_cast<BlockExpr>(e))
3357e5dd7070Spatrick return asImpl().visitBlockExpr(be);
3358e5dd7070Spatrick
3359e5dd7070Spatrick return asImpl().visitExpr(e);
3360e5dd7070Spatrick }
3361e5dd7070Spatrick
3362e5dd7070Spatrick namespace {
3363e5dd7070Spatrick
3364e5dd7070Spatrick /// An emitter for +1 results.
3365e5dd7070Spatrick struct ARCRetainExprEmitter :
3366e5dd7070Spatrick public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3367e5dd7070Spatrick
ARCRetainExprEmitter__anonb505f9fd0b11::ARCRetainExprEmitter3368e5dd7070Spatrick ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3369e5dd7070Spatrick
getValueOfResult__anonb505f9fd0b11::ARCRetainExprEmitter3370e5dd7070Spatrick llvm::Value *getValueOfResult(TryEmitResult result) {
3371e5dd7070Spatrick return result.getPointer();
3372e5dd7070Spatrick }
3373e5dd7070Spatrick
emitBitCast__anonb505f9fd0b11::ARCRetainExprEmitter3374e5dd7070Spatrick TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3375e5dd7070Spatrick llvm::Value *value = result.getPointer();
3376e5dd7070Spatrick value = CGF.Builder.CreateBitCast(value, resultType);
3377e5dd7070Spatrick result.setPointer(value);
3378e5dd7070Spatrick return result;
3379e5dd7070Spatrick }
3380e5dd7070Spatrick
visitLValueToRValue__anonb505f9fd0b11::ARCRetainExprEmitter3381e5dd7070Spatrick TryEmitResult visitLValueToRValue(const Expr *e) {
3382e5dd7070Spatrick return tryEmitARCRetainLoadOfScalar(CGF, e);
3383e5dd7070Spatrick }
3384e5dd7070Spatrick
3385e5dd7070Spatrick /// For consumptions, just emit the subexpression and thus elide
3386e5dd7070Spatrick /// the retain/release pair.
visitConsumeObject__anonb505f9fd0b11::ARCRetainExprEmitter3387e5dd7070Spatrick TryEmitResult visitConsumeObject(const Expr *e) {
3388e5dd7070Spatrick llvm::Value *result = CGF.EmitScalarExpr(e);
3389e5dd7070Spatrick return TryEmitResult(result, true);
3390e5dd7070Spatrick }
3391e5dd7070Spatrick
visitBlockExpr__anonb505f9fd0b11::ARCRetainExprEmitter3392e5dd7070Spatrick TryEmitResult visitBlockExpr(const BlockExpr *e) {
3393e5dd7070Spatrick TryEmitResult result = visitExpr(e);
3394e5dd7070Spatrick // Avoid the block-retain if this is a block literal that doesn't need to be
3395e5dd7070Spatrick // copied to the heap.
3396*12c85518Srobert if (CGF.CGM.getCodeGenOpts().ObjCAvoidHeapifyLocalBlocks &&
3397*12c85518Srobert e->getBlockDecl()->canAvoidCopyToHeap())
3398e5dd7070Spatrick result.setInt(true);
3399e5dd7070Spatrick return result;
3400e5dd7070Spatrick }
3401e5dd7070Spatrick
3402e5dd7070Spatrick /// Block extends are net +0. Naively, we could just recurse on
3403e5dd7070Spatrick /// the subexpression, but actually we need to ensure that the
3404e5dd7070Spatrick /// value is copied as a block, so there's a little filter here.
visitExtendBlockObject__anonb505f9fd0b11::ARCRetainExprEmitter3405e5dd7070Spatrick TryEmitResult visitExtendBlockObject(const Expr *e) {
3406e5dd7070Spatrick llvm::Value *result; // will be a +0 value
3407e5dd7070Spatrick
3408e5dd7070Spatrick // If we can't safely assume the sub-expression will produce a
3409e5dd7070Spatrick // block-copied value, emit the sub-expression at +0.
3410e5dd7070Spatrick if (shouldEmitSeparateBlockRetain(e)) {
3411e5dd7070Spatrick result = CGF.EmitScalarExpr(e);
3412e5dd7070Spatrick
3413e5dd7070Spatrick // Otherwise, try to emit the sub-expression at +1 recursively.
3414e5dd7070Spatrick } else {
3415e5dd7070Spatrick TryEmitResult subresult = asImpl().visit(e);
3416e5dd7070Spatrick
3417e5dd7070Spatrick // If that produced a retained value, just use that.
3418e5dd7070Spatrick if (subresult.getInt()) {
3419e5dd7070Spatrick return subresult;
3420e5dd7070Spatrick }
3421e5dd7070Spatrick
3422e5dd7070Spatrick // Otherwise it's +0.
3423e5dd7070Spatrick result = subresult.getPointer();
3424e5dd7070Spatrick }
3425e5dd7070Spatrick
3426e5dd7070Spatrick // Retain the object as a block.
3427e5dd7070Spatrick result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3428e5dd7070Spatrick return TryEmitResult(result, true);
3429e5dd7070Spatrick }
3430e5dd7070Spatrick
3431e5dd7070Spatrick /// For reclaims, emit the subexpression as a retained call and
3432e5dd7070Spatrick /// skip the consumption.
visitReclaimReturnedObject__anonb505f9fd0b11::ARCRetainExprEmitter3433e5dd7070Spatrick TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3434e5dd7070Spatrick llvm::Value *result = emitARCRetainCallResult(CGF, e);
3435e5dd7070Spatrick return TryEmitResult(result, true);
3436e5dd7070Spatrick }
3437e5dd7070Spatrick
3438e5dd7070Spatrick /// When we have an undecorated call, retroactively do a claim.
visitCall__anonb505f9fd0b11::ARCRetainExprEmitter3439e5dd7070Spatrick TryEmitResult visitCall(const Expr *e) {
3440e5dd7070Spatrick llvm::Value *result = emitARCRetainCallResult(CGF, e);
3441e5dd7070Spatrick return TryEmitResult(result, true);
3442e5dd7070Spatrick }
3443e5dd7070Spatrick
3444e5dd7070Spatrick // TODO: maybe special-case visitBinAssignWeak?
3445e5dd7070Spatrick
visitExpr__anonb505f9fd0b11::ARCRetainExprEmitter3446e5dd7070Spatrick TryEmitResult visitExpr(const Expr *e) {
3447e5dd7070Spatrick // We didn't find an obvious production, so emit what we've got and
3448e5dd7070Spatrick // tell the caller that we didn't manage to retain.
3449e5dd7070Spatrick llvm::Value *result = CGF.EmitScalarExpr(e);
3450e5dd7070Spatrick return TryEmitResult(result, false);
3451e5dd7070Spatrick }
3452e5dd7070Spatrick };
3453e5dd7070Spatrick }
3454e5dd7070Spatrick
3455e5dd7070Spatrick static TryEmitResult
tryEmitARCRetainScalarExpr(CodeGenFunction & CGF,const Expr * e)3456e5dd7070Spatrick tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3457e5dd7070Spatrick return ARCRetainExprEmitter(CGF).visit(e);
3458e5dd7070Spatrick }
3459e5dd7070Spatrick
emitARCRetainLoadOfScalar(CodeGenFunction & CGF,LValue lvalue,QualType type)3460e5dd7070Spatrick static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3461e5dd7070Spatrick LValue lvalue,
3462e5dd7070Spatrick QualType type) {
3463e5dd7070Spatrick TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3464e5dd7070Spatrick llvm::Value *value = result.getPointer();
3465e5dd7070Spatrick if (!result.getInt())
3466e5dd7070Spatrick value = CGF.EmitARCRetain(type, value);
3467e5dd7070Spatrick return value;
3468e5dd7070Spatrick }
3469e5dd7070Spatrick
3470e5dd7070Spatrick /// EmitARCRetainScalarExpr - Semantically equivalent to
3471e5dd7070Spatrick /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3472e5dd7070Spatrick /// best-effort attempt to peephole expressions that naturally produce
3473e5dd7070Spatrick /// retained objects.
EmitARCRetainScalarExpr(const Expr * e)3474e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
3475e5dd7070Spatrick // The retain needs to happen within the full-expression.
3476e5dd7070Spatrick if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3477e5dd7070Spatrick RunCleanupsScope scope(*this);
3478e5dd7070Spatrick return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3479e5dd7070Spatrick }
3480e5dd7070Spatrick
3481e5dd7070Spatrick TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3482e5dd7070Spatrick llvm::Value *value = result.getPointer();
3483e5dd7070Spatrick if (!result.getInt())
3484e5dd7070Spatrick value = EmitARCRetain(e->getType(), value);
3485e5dd7070Spatrick return value;
3486e5dd7070Spatrick }
3487e5dd7070Spatrick
3488e5dd7070Spatrick llvm::Value *
EmitARCRetainAutoreleaseScalarExpr(const Expr * e)3489e5dd7070Spatrick CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
3490e5dd7070Spatrick // The retain needs to happen within the full-expression.
3491e5dd7070Spatrick if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3492e5dd7070Spatrick RunCleanupsScope scope(*this);
3493e5dd7070Spatrick return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3494e5dd7070Spatrick }
3495e5dd7070Spatrick
3496e5dd7070Spatrick TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3497e5dd7070Spatrick llvm::Value *value = result.getPointer();
3498e5dd7070Spatrick if (result.getInt())
3499e5dd7070Spatrick value = EmitARCAutorelease(value);
3500e5dd7070Spatrick else
3501e5dd7070Spatrick value = EmitARCRetainAutorelease(e->getType(), value);
3502e5dd7070Spatrick return value;
3503e5dd7070Spatrick }
3504e5dd7070Spatrick
EmitARCExtendBlockObject(const Expr * e)3505e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3506e5dd7070Spatrick llvm::Value *result;
3507e5dd7070Spatrick bool doRetain;
3508e5dd7070Spatrick
3509e5dd7070Spatrick if (shouldEmitSeparateBlockRetain(e)) {
3510e5dd7070Spatrick result = EmitScalarExpr(e);
3511e5dd7070Spatrick doRetain = true;
3512e5dd7070Spatrick } else {
3513e5dd7070Spatrick TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3514e5dd7070Spatrick result = subresult.getPointer();
3515e5dd7070Spatrick doRetain = !subresult.getInt();
3516e5dd7070Spatrick }
3517e5dd7070Spatrick
3518e5dd7070Spatrick if (doRetain)
3519e5dd7070Spatrick result = EmitARCRetainBlock(result, /*mandatory*/ true);
3520e5dd7070Spatrick return EmitObjCConsumeObject(e->getType(), result);
3521e5dd7070Spatrick }
3522e5dd7070Spatrick
EmitObjCThrowOperand(const Expr * expr)3523e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3524e5dd7070Spatrick // In ARC, retain and autorelease the expression.
3525e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount) {
3526e5dd7070Spatrick // Do so before running any cleanups for the full-expression.
3527e5dd7070Spatrick // EmitARCRetainAutoreleaseScalarExpr does this for us.
3528e5dd7070Spatrick return EmitARCRetainAutoreleaseScalarExpr(expr);
3529e5dd7070Spatrick }
3530e5dd7070Spatrick
3531e5dd7070Spatrick // Otherwise, use the normal scalar-expression emission. The
3532e5dd7070Spatrick // exception machinery doesn't do anything special with the
3533e5dd7070Spatrick // exception like retaining it, so there's no safety associated with
3534e5dd7070Spatrick // only running cleanups after the throw has started, and when it
3535e5dd7070Spatrick // matters it tends to be substantially inferior code.
3536e5dd7070Spatrick return EmitScalarExpr(expr);
3537e5dd7070Spatrick }
3538e5dd7070Spatrick
3539e5dd7070Spatrick namespace {
3540e5dd7070Spatrick
3541e5dd7070Spatrick /// An emitter for assigning into an __unsafe_unretained context.
3542e5dd7070Spatrick struct ARCUnsafeUnretainedExprEmitter :
3543e5dd7070Spatrick public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3544e5dd7070Spatrick
ARCUnsafeUnretainedExprEmitter__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3545e5dd7070Spatrick ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3546e5dd7070Spatrick
getValueOfResult__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3547e5dd7070Spatrick llvm::Value *getValueOfResult(llvm::Value *value) {
3548e5dd7070Spatrick return value;
3549e5dd7070Spatrick }
3550e5dd7070Spatrick
emitBitCast__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3551e5dd7070Spatrick llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3552e5dd7070Spatrick return CGF.Builder.CreateBitCast(value, resultType);
3553e5dd7070Spatrick }
3554e5dd7070Spatrick
visitLValueToRValue__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3555e5dd7070Spatrick llvm::Value *visitLValueToRValue(const Expr *e) {
3556e5dd7070Spatrick return CGF.EmitScalarExpr(e);
3557e5dd7070Spatrick }
3558e5dd7070Spatrick
3559e5dd7070Spatrick /// For consumptions, just emit the subexpression and perform the
3560e5dd7070Spatrick /// consumption like normal.
visitConsumeObject__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3561e5dd7070Spatrick llvm::Value *visitConsumeObject(const Expr *e) {
3562e5dd7070Spatrick llvm::Value *value = CGF.EmitScalarExpr(e);
3563e5dd7070Spatrick return CGF.EmitObjCConsumeObject(e->getType(), value);
3564e5dd7070Spatrick }
3565e5dd7070Spatrick
3566e5dd7070Spatrick /// No special logic for block extensions. (This probably can't
3567e5dd7070Spatrick /// actually happen in this emitter, though.)
visitExtendBlockObject__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3568e5dd7070Spatrick llvm::Value *visitExtendBlockObject(const Expr *e) {
3569e5dd7070Spatrick return CGF.EmitARCExtendBlockObject(e);
3570e5dd7070Spatrick }
3571e5dd7070Spatrick
3572e5dd7070Spatrick /// For reclaims, perform an unsafeClaim if that's enabled.
visitReclaimReturnedObject__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3573e5dd7070Spatrick llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3574e5dd7070Spatrick return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3575e5dd7070Spatrick }
3576e5dd7070Spatrick
3577e5dd7070Spatrick /// When we have an undecorated call, just emit it without adding
3578e5dd7070Spatrick /// the unsafeClaim.
visitCall__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3579e5dd7070Spatrick llvm::Value *visitCall(const Expr *e) {
3580e5dd7070Spatrick return CGF.EmitScalarExpr(e);
3581e5dd7070Spatrick }
3582e5dd7070Spatrick
3583e5dd7070Spatrick /// Just do normal scalar emission in the default case.
visitExpr__anonb505f9fd0c11::ARCUnsafeUnretainedExprEmitter3584e5dd7070Spatrick llvm::Value *visitExpr(const Expr *e) {
3585e5dd7070Spatrick return CGF.EmitScalarExpr(e);
3586e5dd7070Spatrick }
3587e5dd7070Spatrick };
3588e5dd7070Spatrick }
3589e5dd7070Spatrick
emitARCUnsafeUnretainedScalarExpr(CodeGenFunction & CGF,const Expr * e)3590e5dd7070Spatrick static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3591e5dd7070Spatrick const Expr *e) {
3592e5dd7070Spatrick return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3593e5dd7070Spatrick }
3594e5dd7070Spatrick
3595e5dd7070Spatrick /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3596e5dd7070Spatrick /// immediately releasing the resut of EmitARCRetainScalarExpr, but
3597e5dd7070Spatrick /// avoiding any spurious retains, including by performing reclaims
3598e5dd7070Spatrick /// with objc_unsafeClaimAutoreleasedReturnValue.
EmitARCUnsafeUnretainedScalarExpr(const Expr * e)3599e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3600e5dd7070Spatrick // Look through full-expressions.
3601e5dd7070Spatrick if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3602e5dd7070Spatrick RunCleanupsScope scope(*this);
3603e5dd7070Spatrick return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3604e5dd7070Spatrick }
3605e5dd7070Spatrick
3606e5dd7070Spatrick return emitARCUnsafeUnretainedScalarExpr(*this, e);
3607e5dd7070Spatrick }
3608e5dd7070Spatrick
3609e5dd7070Spatrick std::pair<LValue,llvm::Value*>
EmitARCStoreUnsafeUnretained(const BinaryOperator * e,bool ignored)3610e5dd7070Spatrick CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3611e5dd7070Spatrick bool ignored) {
3612e5dd7070Spatrick // Evaluate the RHS first. If we're ignoring the result, assume
3613e5dd7070Spatrick // that we can emit at an unsafe +0.
3614e5dd7070Spatrick llvm::Value *value;
3615e5dd7070Spatrick if (ignored) {
3616e5dd7070Spatrick value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3617e5dd7070Spatrick } else {
3618e5dd7070Spatrick value = EmitScalarExpr(e->getRHS());
3619e5dd7070Spatrick }
3620e5dd7070Spatrick
3621e5dd7070Spatrick // Emit the LHS and perform the store.
3622e5dd7070Spatrick LValue lvalue = EmitLValue(e->getLHS());
3623e5dd7070Spatrick EmitStoreOfScalar(value, lvalue);
3624e5dd7070Spatrick
3625e5dd7070Spatrick return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3626e5dd7070Spatrick }
3627e5dd7070Spatrick
3628e5dd7070Spatrick std::pair<LValue,llvm::Value*>
EmitARCStoreStrong(const BinaryOperator * e,bool ignored)3629e5dd7070Spatrick CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3630e5dd7070Spatrick bool ignored) {
3631e5dd7070Spatrick // Evaluate the RHS first.
3632e5dd7070Spatrick TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3633e5dd7070Spatrick llvm::Value *value = result.getPointer();
3634e5dd7070Spatrick
3635e5dd7070Spatrick bool hasImmediateRetain = result.getInt();
3636e5dd7070Spatrick
3637e5dd7070Spatrick // If we didn't emit a retained object, and the l-value is of block
3638e5dd7070Spatrick // type, then we need to emit the block-retain immediately in case
3639e5dd7070Spatrick // it invalidates the l-value.
3640e5dd7070Spatrick if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3641e5dd7070Spatrick value = EmitARCRetainBlock(value, /*mandatory*/ false);
3642e5dd7070Spatrick hasImmediateRetain = true;
3643e5dd7070Spatrick }
3644e5dd7070Spatrick
3645e5dd7070Spatrick LValue lvalue = EmitLValue(e->getLHS());
3646e5dd7070Spatrick
3647e5dd7070Spatrick // If the RHS was emitted retained, expand this.
3648e5dd7070Spatrick if (hasImmediateRetain) {
3649e5dd7070Spatrick llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3650e5dd7070Spatrick EmitStoreOfScalar(value, lvalue);
3651e5dd7070Spatrick EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3652e5dd7070Spatrick } else {
3653e5dd7070Spatrick value = EmitARCStoreStrong(lvalue, value, ignored);
3654e5dd7070Spatrick }
3655e5dd7070Spatrick
3656e5dd7070Spatrick return std::pair<LValue,llvm::Value*>(lvalue, value);
3657e5dd7070Spatrick }
3658e5dd7070Spatrick
3659e5dd7070Spatrick std::pair<LValue,llvm::Value*>
EmitARCStoreAutoreleasing(const BinaryOperator * e)3660e5dd7070Spatrick CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3661e5dd7070Spatrick llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3662e5dd7070Spatrick LValue lvalue = EmitLValue(e->getLHS());
3663e5dd7070Spatrick
3664e5dd7070Spatrick EmitStoreOfScalar(value, lvalue);
3665e5dd7070Spatrick
3666e5dd7070Spatrick return std::pair<LValue,llvm::Value*>(lvalue, value);
3667e5dd7070Spatrick }
3668e5dd7070Spatrick
EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt & ARPS)3669e5dd7070Spatrick void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
3670e5dd7070Spatrick const ObjCAutoreleasePoolStmt &ARPS) {
3671e5dd7070Spatrick const Stmt *subStmt = ARPS.getSubStmt();
3672e5dd7070Spatrick const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3673e5dd7070Spatrick
3674e5dd7070Spatrick CGDebugInfo *DI = getDebugInfo();
3675e5dd7070Spatrick if (DI)
3676e5dd7070Spatrick DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3677e5dd7070Spatrick
3678e5dd7070Spatrick // Keep track of the current cleanup stack depth.
3679e5dd7070Spatrick RunCleanupsScope Scope(*this);
3680e5dd7070Spatrick if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3681e5dd7070Spatrick llvm::Value *token = EmitObjCAutoreleasePoolPush();
3682e5dd7070Spatrick EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3683e5dd7070Spatrick } else {
3684e5dd7070Spatrick llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3685e5dd7070Spatrick EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3686e5dd7070Spatrick }
3687e5dd7070Spatrick
3688e5dd7070Spatrick for (const auto *I : S.body())
3689e5dd7070Spatrick EmitStmt(I);
3690e5dd7070Spatrick
3691e5dd7070Spatrick if (DI)
3692e5dd7070Spatrick DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3693e5dd7070Spatrick }
3694e5dd7070Spatrick
3695e5dd7070Spatrick /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3696e5dd7070Spatrick /// make sure it survives garbage collection until this point.
EmitExtendGCLifetime(llvm::Value * object)3697e5dd7070Spatrick void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3698e5dd7070Spatrick // We just use an inline assembly.
3699e5dd7070Spatrick llvm::FunctionType *extenderType
3700e5dd7070Spatrick = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3701e5dd7070Spatrick llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3702e5dd7070Spatrick /* assembly */ "",
3703e5dd7070Spatrick /* constraints */ "r",
3704e5dd7070Spatrick /* side effects */ true);
3705e5dd7070Spatrick
3706e5dd7070Spatrick object = Builder.CreateBitCast(object, VoidPtrTy);
3707e5dd7070Spatrick EmitNounwindRuntimeCall(extender, object);
3708e5dd7070Spatrick }
3709e5dd7070Spatrick
3710e5dd7070Spatrick /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3711e5dd7070Spatrick /// non-trivial copy assignment function, produce following helper function.
3712e5dd7070Spatrick /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3713e5dd7070Spatrick ///
3714e5dd7070Spatrick llvm::Constant *
GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl * PID)3715e5dd7070Spatrick CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3716e5dd7070Spatrick const ObjCPropertyImplDecl *PID) {
3717*12c85518Srobert const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3718*12c85518Srobert if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
3719*12c85518Srobert return nullptr;
3720*12c85518Srobert
3721*12c85518Srobert QualType Ty = PID->getPropertyIvarDecl()->getType();
3722*12c85518Srobert ASTContext &C = getContext();
3723*12c85518Srobert
3724*12c85518Srobert if (Ty.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
3725*12c85518Srobert // Call the move assignment operator instead of calling the copy assignment
3726*12c85518Srobert // operator and destructor.
3727*12c85518Srobert CharUnits Alignment = C.getTypeAlignInChars(Ty);
3728*12c85518Srobert llvm::Constant *Fn = getNonTrivialCStructMoveAssignmentOperator(
3729*12c85518Srobert CGM, Alignment, Alignment, Ty.isVolatileQualified(), Ty);
3730*12c85518Srobert return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3731*12c85518Srobert }
3732*12c85518Srobert
3733e5dd7070Spatrick if (!getLangOpts().CPlusPlus ||
3734e5dd7070Spatrick !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3735e5dd7070Spatrick return nullptr;
3736e5dd7070Spatrick if (!Ty->isRecordType())
3737e5dd7070Spatrick return nullptr;
3738e5dd7070Spatrick llvm::Constant *HelperFn = nullptr;
3739e5dd7070Spatrick if (hasTrivialSetExpr(PID))
3740e5dd7070Spatrick return nullptr;
3741e5dd7070Spatrick assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3742e5dd7070Spatrick if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3743e5dd7070Spatrick return HelperFn;
3744e5dd7070Spatrick
3745e5dd7070Spatrick IdentifierInfo *II
3746e5dd7070Spatrick = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3747e5dd7070Spatrick
3748e5dd7070Spatrick QualType ReturnTy = C.VoidTy;
3749e5dd7070Spatrick QualType DestTy = C.getPointerType(Ty);
3750e5dd7070Spatrick QualType SrcTy = Ty;
3751e5dd7070Spatrick SrcTy.addConst();
3752e5dd7070Spatrick SrcTy = C.getPointerType(SrcTy);
3753e5dd7070Spatrick
3754e5dd7070Spatrick SmallVector<QualType, 2> ArgTys;
3755e5dd7070Spatrick ArgTys.push_back(DestTy);
3756e5dd7070Spatrick ArgTys.push_back(SrcTy);
3757e5dd7070Spatrick QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3758e5dd7070Spatrick
3759e5dd7070Spatrick FunctionDecl *FD = FunctionDecl::Create(
3760e5dd7070Spatrick C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3761*12c85518Srobert FunctionTy, nullptr, SC_Static, false, false, false);
3762e5dd7070Spatrick
3763e5dd7070Spatrick FunctionArgList args;
3764a9ac8606Spatrick ParmVarDecl *Params[2];
3765a9ac8606Spatrick ParmVarDecl *DstDecl = ParmVarDecl::Create(
3766a9ac8606Spatrick C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
3767a9ac8606Spatrick C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
3768a9ac8606Spatrick /*DefArg=*/nullptr);
3769a9ac8606Spatrick args.push_back(Params[0] = DstDecl);
3770a9ac8606Spatrick ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3771a9ac8606Spatrick C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
3772a9ac8606Spatrick C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
3773a9ac8606Spatrick /*DefArg=*/nullptr);
3774a9ac8606Spatrick args.push_back(Params[1] = SrcDecl);
3775a9ac8606Spatrick FD->setParams(Params);
3776e5dd7070Spatrick
3777e5dd7070Spatrick const CGFunctionInfo &FI =
3778e5dd7070Spatrick CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3779e5dd7070Spatrick
3780e5dd7070Spatrick llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3781e5dd7070Spatrick
3782e5dd7070Spatrick llvm::Function *Fn =
3783e5dd7070Spatrick llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3784e5dd7070Spatrick "__assign_helper_atomic_property_",
3785e5dd7070Spatrick &CGM.getModule());
3786e5dd7070Spatrick
3787e5dd7070Spatrick CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3788e5dd7070Spatrick
3789e5dd7070Spatrick StartFunction(FD, ReturnTy, Fn, FI, args);
3790e5dd7070Spatrick
3791a9ac8606Spatrick DeclRefExpr DstExpr(C, DstDecl, false, DestTy, VK_PRValue, SourceLocation());
3792ec727ea7Spatrick UnaryOperator *DST = UnaryOperator::Create(
3793ec727ea7Spatrick C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
3794ec727ea7Spatrick SourceLocation(), false, FPOptionsOverride());
3795e5dd7070Spatrick
3796a9ac8606Spatrick DeclRefExpr SrcExpr(C, SrcDecl, false, SrcTy, VK_PRValue, SourceLocation());
3797ec727ea7Spatrick UnaryOperator *SRC = UnaryOperator::Create(
3798ec727ea7Spatrick C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3799ec727ea7Spatrick SourceLocation(), false, FPOptionsOverride());
3800e5dd7070Spatrick
3801ec727ea7Spatrick Expr *Args[2] = {DST, SRC};
3802e5dd7070Spatrick CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3803e5dd7070Spatrick CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3804e5dd7070Spatrick C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3805ec727ea7Spatrick VK_LValue, SourceLocation(), FPOptionsOverride());
3806e5dd7070Spatrick
3807e5dd7070Spatrick EmitStmt(TheCall);
3808e5dd7070Spatrick
3809e5dd7070Spatrick FinishFunction();
3810e5dd7070Spatrick HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3811e5dd7070Spatrick CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3812e5dd7070Spatrick return HelperFn;
3813e5dd7070Spatrick }
3814e5dd7070Spatrick
GenerateObjCAtomicGetterCopyHelperFunction(const ObjCPropertyImplDecl * PID)3815*12c85518Srobert llvm::Constant *CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3816e5dd7070Spatrick const ObjCPropertyImplDecl *PID) {
3817*12c85518Srobert const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3818*12c85518Srobert if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
3819*12c85518Srobert return nullptr;
3820*12c85518Srobert
3821*12c85518Srobert QualType Ty = PD->getType();
3822*12c85518Srobert ASTContext &C = getContext();
3823*12c85518Srobert
3824*12c85518Srobert if (Ty.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
3825*12c85518Srobert CharUnits Alignment = C.getTypeAlignInChars(Ty);
3826*12c85518Srobert llvm::Constant *Fn = getNonTrivialCStructCopyConstructor(
3827*12c85518Srobert CGM, Alignment, Alignment, Ty.isVolatileQualified(), Ty);
3828*12c85518Srobert return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3829*12c85518Srobert }
3830*12c85518Srobert
3831e5dd7070Spatrick if (!getLangOpts().CPlusPlus ||
3832e5dd7070Spatrick !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3833e5dd7070Spatrick return nullptr;
3834e5dd7070Spatrick if (!Ty->isRecordType())
3835e5dd7070Spatrick return nullptr;
3836e5dd7070Spatrick llvm::Constant *HelperFn = nullptr;
3837e5dd7070Spatrick if (hasTrivialGetExpr(PID))
3838e5dd7070Spatrick return nullptr;
3839e5dd7070Spatrick assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3840e5dd7070Spatrick if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3841e5dd7070Spatrick return HelperFn;
3842e5dd7070Spatrick
3843e5dd7070Spatrick IdentifierInfo *II =
3844e5dd7070Spatrick &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3845e5dd7070Spatrick
3846e5dd7070Spatrick QualType ReturnTy = C.VoidTy;
3847e5dd7070Spatrick QualType DestTy = C.getPointerType(Ty);
3848e5dd7070Spatrick QualType SrcTy = Ty;
3849e5dd7070Spatrick SrcTy.addConst();
3850e5dd7070Spatrick SrcTy = C.getPointerType(SrcTy);
3851e5dd7070Spatrick
3852e5dd7070Spatrick SmallVector<QualType, 2> ArgTys;
3853e5dd7070Spatrick ArgTys.push_back(DestTy);
3854e5dd7070Spatrick ArgTys.push_back(SrcTy);
3855e5dd7070Spatrick QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3856e5dd7070Spatrick
3857e5dd7070Spatrick FunctionDecl *FD = FunctionDecl::Create(
3858e5dd7070Spatrick C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3859*12c85518Srobert FunctionTy, nullptr, SC_Static, false, false, false);
3860e5dd7070Spatrick
3861e5dd7070Spatrick FunctionArgList args;
3862a9ac8606Spatrick ParmVarDecl *Params[2];
3863a9ac8606Spatrick ParmVarDecl *DstDecl = ParmVarDecl::Create(
3864a9ac8606Spatrick C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
3865a9ac8606Spatrick C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
3866a9ac8606Spatrick /*DefArg=*/nullptr);
3867a9ac8606Spatrick args.push_back(Params[0] = DstDecl);
3868a9ac8606Spatrick ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3869a9ac8606Spatrick C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
3870a9ac8606Spatrick C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
3871a9ac8606Spatrick /*DefArg=*/nullptr);
3872a9ac8606Spatrick args.push_back(Params[1] = SrcDecl);
3873a9ac8606Spatrick FD->setParams(Params);
3874e5dd7070Spatrick
3875e5dd7070Spatrick const CGFunctionInfo &FI =
3876e5dd7070Spatrick CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3877e5dd7070Spatrick
3878e5dd7070Spatrick llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3879e5dd7070Spatrick
3880e5dd7070Spatrick llvm::Function *Fn = llvm::Function::Create(
3881e5dd7070Spatrick LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3882e5dd7070Spatrick &CGM.getModule());
3883e5dd7070Spatrick
3884e5dd7070Spatrick CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3885e5dd7070Spatrick
3886e5dd7070Spatrick StartFunction(FD, ReturnTy, Fn, FI, args);
3887e5dd7070Spatrick
3888a9ac8606Spatrick DeclRefExpr SrcExpr(getContext(), SrcDecl, false, SrcTy, VK_PRValue,
3889e5dd7070Spatrick SourceLocation());
3890e5dd7070Spatrick
3891ec727ea7Spatrick UnaryOperator *SRC = UnaryOperator::Create(
3892ec727ea7Spatrick C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3893ec727ea7Spatrick SourceLocation(), false, FPOptionsOverride());
3894e5dd7070Spatrick
3895e5dd7070Spatrick CXXConstructExpr *CXXConstExpr =
3896e5dd7070Spatrick cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3897e5dd7070Spatrick
3898e5dd7070Spatrick SmallVector<Expr*, 4> ConstructorArgs;
3899ec727ea7Spatrick ConstructorArgs.push_back(SRC);
3900e5dd7070Spatrick ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3901e5dd7070Spatrick CXXConstExpr->arg_end());
3902e5dd7070Spatrick
3903e5dd7070Spatrick CXXConstructExpr *TheCXXConstructExpr =
3904e5dd7070Spatrick CXXConstructExpr::Create(C, Ty, SourceLocation(),
3905e5dd7070Spatrick CXXConstExpr->getConstructor(),
3906e5dd7070Spatrick CXXConstExpr->isElidable(),
3907e5dd7070Spatrick ConstructorArgs,
3908e5dd7070Spatrick CXXConstExpr->hadMultipleCandidates(),
3909e5dd7070Spatrick CXXConstExpr->isListInitialization(),
3910e5dd7070Spatrick CXXConstExpr->isStdInitListInitialization(),
3911e5dd7070Spatrick CXXConstExpr->requiresZeroInitialization(),
3912e5dd7070Spatrick CXXConstExpr->getConstructionKind(),
3913e5dd7070Spatrick SourceRange());
3914e5dd7070Spatrick
3915a9ac8606Spatrick DeclRefExpr DstExpr(getContext(), DstDecl, false, DestTy, VK_PRValue,
3916e5dd7070Spatrick SourceLocation());
3917e5dd7070Spatrick
3918e5dd7070Spatrick RValue DV = EmitAnyExpr(&DstExpr);
3919*12c85518Srobert CharUnits Alignment =
3920*12c85518Srobert getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3921e5dd7070Spatrick EmitAggExpr(TheCXXConstructExpr,
3922*12c85518Srobert AggValueSlot::forAddr(
3923*12c85518Srobert Address(DV.getScalarVal(), ConvertTypeForMem(Ty), Alignment),
3924*12c85518Srobert Qualifiers(), AggValueSlot::IsDestructed,
3925e5dd7070Spatrick AggValueSlot::DoesNotNeedGCBarriers,
3926*12c85518Srobert AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap));
3927e5dd7070Spatrick
3928e5dd7070Spatrick FinishFunction();
3929e5dd7070Spatrick HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3930e5dd7070Spatrick CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3931e5dd7070Spatrick return HelperFn;
3932e5dd7070Spatrick }
3933e5dd7070Spatrick
3934e5dd7070Spatrick llvm::Value *
EmitBlockCopyAndAutorelease(llvm::Value * Block,QualType Ty)3935e5dd7070Spatrick CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3936e5dd7070Spatrick // Get selectors for retain/autorelease.
3937e5dd7070Spatrick IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3938e5dd7070Spatrick Selector CopySelector =
3939e5dd7070Spatrick getContext().Selectors.getNullarySelector(CopyID);
3940e5dd7070Spatrick IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3941e5dd7070Spatrick Selector AutoreleaseSelector =
3942e5dd7070Spatrick getContext().Selectors.getNullarySelector(AutoreleaseID);
3943e5dd7070Spatrick
3944e5dd7070Spatrick // Emit calls to retain/autorelease.
3945e5dd7070Spatrick CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3946e5dd7070Spatrick llvm::Value *Val = Block;
3947e5dd7070Spatrick RValue Result;
3948e5dd7070Spatrick Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3949e5dd7070Spatrick Ty, CopySelector,
3950e5dd7070Spatrick Val, CallArgList(), nullptr, nullptr);
3951e5dd7070Spatrick Val = Result.getScalarVal();
3952e5dd7070Spatrick Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3953e5dd7070Spatrick Ty, AutoreleaseSelector,
3954e5dd7070Spatrick Val, CallArgList(), nullptr, nullptr);
3955e5dd7070Spatrick Val = Result.getScalarVal();
3956e5dd7070Spatrick return Val;
3957e5dd7070Spatrick }
3958e5dd7070Spatrick
getBaseMachOPlatformID(const llvm::Triple & TT)3959a9ac8606Spatrick static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
3960a9ac8606Spatrick switch (TT.getOS()) {
3961a9ac8606Spatrick case llvm::Triple::Darwin:
3962a9ac8606Spatrick case llvm::Triple::MacOSX:
3963a9ac8606Spatrick return llvm::MachO::PLATFORM_MACOS;
3964a9ac8606Spatrick case llvm::Triple::IOS:
3965a9ac8606Spatrick return llvm::MachO::PLATFORM_IOS;
3966a9ac8606Spatrick case llvm::Triple::TvOS:
3967a9ac8606Spatrick return llvm::MachO::PLATFORM_TVOS;
3968a9ac8606Spatrick case llvm::Triple::WatchOS:
3969a9ac8606Spatrick return llvm::MachO::PLATFORM_WATCHOS;
3970*12c85518Srobert case llvm::Triple::DriverKit:
3971*12c85518Srobert return llvm::MachO::PLATFORM_DRIVERKIT;
3972a9ac8606Spatrick default:
3973a9ac8606Spatrick return /*Unknown platform*/ 0;
3974a9ac8606Spatrick }
3975a9ac8606Spatrick }
3976a9ac8606Spatrick
emitIsPlatformVersionAtLeast(CodeGenFunction & CGF,const VersionTuple & Version)3977a9ac8606Spatrick static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
3978a9ac8606Spatrick const VersionTuple &Version) {
3979a9ac8606Spatrick CodeGenModule &CGM = CGF.CGM;
3980a9ac8606Spatrick // Note: we intend to support multi-platform version checks, so reserve
3981a9ac8606Spatrick // the room for a dual platform checking invocation that will be
3982a9ac8606Spatrick // implemented in the future.
3983a9ac8606Spatrick llvm::SmallVector<llvm::Value *, 8> Args;
3984a9ac8606Spatrick
3985a9ac8606Spatrick auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {
3986*12c85518Srobert std::optional<unsigned> Min = Version.getMinor(),
3987*12c85518Srobert SMin = Version.getSubminor();
3988a9ac8606Spatrick Args.push_back(
3989a9ac8606Spatrick llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));
3990a9ac8606Spatrick Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));
3991*12c85518Srobert Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)));
3992*12c85518Srobert Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0)));
3993a9ac8606Spatrick };
3994a9ac8606Spatrick
3995a9ac8606Spatrick assert(!Version.empty() && "unexpected empty version");
3996a9ac8606Spatrick EmitArgs(Version, CGM.getTarget().getTriple());
3997a9ac8606Spatrick
3998a9ac8606Spatrick if (!CGM.IsPlatformVersionAtLeastFn) {
3999a9ac8606Spatrick llvm::FunctionType *FTy = llvm::FunctionType::get(
4000a9ac8606Spatrick CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
4001a9ac8606Spatrick false);
4002a9ac8606Spatrick CGM.IsPlatformVersionAtLeastFn =
4003a9ac8606Spatrick CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
4004a9ac8606Spatrick }
4005a9ac8606Spatrick
4006a9ac8606Spatrick llvm::Value *Check =
4007a9ac8606Spatrick CGF.EmitNounwindRuntimeCall(CGM.IsPlatformVersionAtLeastFn, Args);
4008a9ac8606Spatrick return CGF.Builder.CreateICmpNE(Check,
4009a9ac8606Spatrick llvm::Constant::getNullValue(CGM.Int32Ty));
4010a9ac8606Spatrick }
4011a9ac8606Spatrick
4012e5dd7070Spatrick llvm::Value *
EmitBuiltinAvailable(const VersionTuple & Version)4013a9ac8606Spatrick CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
4014a9ac8606Spatrick // Darwin uses the new __isPlatformVersionAtLeast family of routines.
4015a9ac8606Spatrick if (CGM.getTarget().getTriple().isOSDarwin())
4016a9ac8606Spatrick return emitIsPlatformVersionAtLeast(*this, Version);
4017e5dd7070Spatrick
4018e5dd7070Spatrick if (!CGM.IsOSVersionAtLeastFn) {
4019e5dd7070Spatrick llvm::FunctionType *FTy =
4020e5dd7070Spatrick llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
4021e5dd7070Spatrick CGM.IsOSVersionAtLeastFn =
4022e5dd7070Spatrick CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
4023e5dd7070Spatrick }
4024e5dd7070Spatrick
4025*12c85518Srobert std::optional<unsigned> Min = Version.getMinor(),
4026*12c85518Srobert SMin = Version.getSubminor();
4027a9ac8606Spatrick llvm::Value *Args[] = {
4028a9ac8606Spatrick llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),
4029*12c85518Srobert llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)),
4030*12c85518Srobert llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0))};
4031a9ac8606Spatrick
4032e5dd7070Spatrick llvm::Value *CallRes =
4033e5dd7070Spatrick EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
4034e5dd7070Spatrick
4035e5dd7070Spatrick return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
4036e5dd7070Spatrick }
4037e5dd7070Spatrick
isFoundationNeededForDarwinAvailabilityCheck(const llvm::Triple & TT,const VersionTuple & TargetVersion)4038a9ac8606Spatrick static bool isFoundationNeededForDarwinAvailabilityCheck(
4039a9ac8606Spatrick const llvm::Triple &TT, const VersionTuple &TargetVersion) {
4040a9ac8606Spatrick VersionTuple FoundationDroppedInVersion;
4041a9ac8606Spatrick switch (TT.getOS()) {
4042a9ac8606Spatrick case llvm::Triple::IOS:
4043a9ac8606Spatrick case llvm::Triple::TvOS:
4044a9ac8606Spatrick FoundationDroppedInVersion = VersionTuple(/*Major=*/13);
4045a9ac8606Spatrick break;
4046a9ac8606Spatrick case llvm::Triple::WatchOS:
4047a9ac8606Spatrick FoundationDroppedInVersion = VersionTuple(/*Major=*/6);
4048a9ac8606Spatrick break;
4049a9ac8606Spatrick case llvm::Triple::Darwin:
4050a9ac8606Spatrick case llvm::Triple::MacOSX:
4051a9ac8606Spatrick FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);
4052a9ac8606Spatrick break;
4053*12c85518Srobert case llvm::Triple::DriverKit:
4054*12c85518Srobert // DriverKit doesn't need Foundation.
4055*12c85518Srobert return false;
4056a9ac8606Spatrick default:
4057a9ac8606Spatrick llvm_unreachable("Unexpected OS");
4058a9ac8606Spatrick }
4059a9ac8606Spatrick return TargetVersion < FoundationDroppedInVersion;
4060a9ac8606Spatrick }
4061a9ac8606Spatrick
emitAtAvailableLinkGuard()4062e5dd7070Spatrick void CodeGenModule::emitAtAvailableLinkGuard() {
4063a9ac8606Spatrick if (!IsPlatformVersionAtLeastFn)
4064e5dd7070Spatrick return;
4065e5dd7070Spatrick // @available requires CoreFoundation only on Darwin.
4066e5dd7070Spatrick if (!Target.getTriple().isOSDarwin())
4067e5dd7070Spatrick return;
4068a9ac8606Spatrick // @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or
4069a9ac8606Spatrick // watchOS 6+.
4070a9ac8606Spatrick if (!isFoundationNeededForDarwinAvailabilityCheck(
4071a9ac8606Spatrick Target.getTriple(), Target.getPlatformMinVersion()))
4072a9ac8606Spatrick return;
4073e5dd7070Spatrick // Add -framework CoreFoundation to the linker commands. We still want to
4074e5dd7070Spatrick // emit the core foundation reference down below because otherwise if
4075e5dd7070Spatrick // CoreFoundation is not used in the code, the linker won't link the
4076e5dd7070Spatrick // framework.
4077e5dd7070Spatrick auto &Context = getLLVMContext();
4078e5dd7070Spatrick llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
4079e5dd7070Spatrick llvm::MDString::get(Context, "CoreFoundation")};
4080e5dd7070Spatrick LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
4081e5dd7070Spatrick // Emit a reference to a symbol from CoreFoundation to ensure that
4082e5dd7070Spatrick // CoreFoundation is linked into the final binary.
4083e5dd7070Spatrick llvm::FunctionType *FTy =
4084e5dd7070Spatrick llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
4085e5dd7070Spatrick llvm::FunctionCallee CFFunc =
4086e5dd7070Spatrick CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
4087e5dd7070Spatrick
4088e5dd7070Spatrick llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
4089e5dd7070Spatrick llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
4090e5dd7070Spatrick CheckFTy, "__clang_at_available_requires_core_foundation_framework",
4091e5dd7070Spatrick llvm::AttributeList(), /*Local=*/true);
4092e5dd7070Spatrick llvm::Function *CFLinkCheckFunc =
4093e5dd7070Spatrick cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
4094e5dd7070Spatrick if (CFLinkCheckFunc->empty()) {
4095e5dd7070Spatrick CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
4096e5dd7070Spatrick CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
4097e5dd7070Spatrick CodeGenFunction CGF(*this);
4098e5dd7070Spatrick CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
4099e5dd7070Spatrick CGF.EmitNounwindRuntimeCall(CFFunc,
4100e5dd7070Spatrick llvm::Constant::getNullValue(VoidPtrTy));
4101e5dd7070Spatrick CGF.Builder.CreateUnreachable();
4102e5dd7070Spatrick addCompilerUsedGlobal(CFLinkCheckFunc);
4103e5dd7070Spatrick }
4104e5dd7070Spatrick }
4105e5dd7070Spatrick
~CGObjCRuntime()4106e5dd7070Spatrick CGObjCRuntime::~CGObjCRuntime() {}
4107