xref: /minix3/external/bsd/llvm/dist/clang/lib/CodeGen/CGObjC.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This contains code to emit Objective-C code as LLVM code.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "CGDebugInfo.h"
15f4a2713aSLionel Sambuc #include "CGObjCRuntime.h"
16f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
17f4a2713aSLionel Sambuc #include "CodeGenModule.h"
18f4a2713aSLionel Sambuc #include "TargetInfo.h"
19f4a2713aSLionel Sambuc #include "clang/AST/ASTContext.h"
20f4a2713aSLionel Sambuc #include "clang/AST/DeclObjC.h"
21f4a2713aSLionel Sambuc #include "clang/AST/StmtObjC.h"
22f4a2713aSLionel Sambuc #include "clang/Basic/Diagnostic.h"
23f4a2713aSLionel Sambuc #include "clang/CodeGen/CGFunctionInfo.h"
24f4a2713aSLionel Sambuc #include "llvm/ADT/STLExtras.h"
25*0a6a1f1dSLionel Sambuc #include "llvm/IR/CallSite.h"
26f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
27f4a2713aSLionel Sambuc #include "llvm/IR/InlineAsm.h"
28f4a2713aSLionel Sambuc using namespace clang;
29f4a2713aSLionel Sambuc using namespace CodeGen;
30f4a2713aSLionel Sambuc 
31f4a2713aSLionel Sambuc typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32f4a2713aSLionel Sambuc static TryEmitResult
33f4a2713aSLionel Sambuc tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
34f4a2713aSLionel Sambuc static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
35f4a2713aSLionel Sambuc                                       QualType ET,
36f4a2713aSLionel Sambuc                                       const ObjCMethodDecl *Method,
37f4a2713aSLionel Sambuc                                       RValue Result);
38f4a2713aSLionel Sambuc 
39f4a2713aSLionel Sambuc /// Given the address of a variable of pointer type, find the correct
40f4a2713aSLionel Sambuc /// null to store into it.
getNullForVariable(llvm::Value * addr)41f4a2713aSLionel Sambuc static llvm::Constant *getNullForVariable(llvm::Value *addr) {
42f4a2713aSLionel Sambuc   llvm::Type *type =
43f4a2713aSLionel Sambuc     cast<llvm::PointerType>(addr->getType())->getElementType();
44f4a2713aSLionel Sambuc   return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45f4a2713aSLionel Sambuc }
46f4a2713aSLionel Sambuc 
47f4a2713aSLionel Sambuc /// Emits an instance of NSConstantString representing the object.
EmitObjCStringLiteral(const ObjCStringLiteral * E)48f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
49f4a2713aSLionel Sambuc {
50f4a2713aSLionel Sambuc   llvm::Constant *C =
51f4a2713aSLionel Sambuc       CGM.getObjCRuntime().GenerateConstantString(E->getString());
52f4a2713aSLionel Sambuc   // FIXME: This bitcast should just be made an invariant on the Runtime.
53f4a2713aSLionel Sambuc   return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
54f4a2713aSLionel Sambuc }
55f4a2713aSLionel Sambuc 
56f4a2713aSLionel Sambuc /// EmitObjCBoxedExpr - This routine generates code to call
57f4a2713aSLionel Sambuc /// the appropriate expression boxing method. This will either be
58f4a2713aSLionel Sambuc /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
59f4a2713aSLionel Sambuc ///
60f4a2713aSLionel Sambuc llvm::Value *
EmitObjCBoxedExpr(const ObjCBoxedExpr * E)61f4a2713aSLionel Sambuc CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
62f4a2713aSLionel Sambuc   // Generate the correct selector for this literal's concrete type.
63f4a2713aSLionel Sambuc   // Get the method.
64f4a2713aSLionel Sambuc   const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
65f4a2713aSLionel Sambuc   assert(BoxingMethod && "BoxingMethod is null");
66f4a2713aSLionel Sambuc   assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67f4a2713aSLionel Sambuc   Selector Sel = BoxingMethod->getSelector();
68f4a2713aSLionel Sambuc 
69f4a2713aSLionel Sambuc   // Generate a reference to the class pointer, which will be the receiver.
70f4a2713aSLionel Sambuc   // Assumes that the method was introduced in the class that should be
71f4a2713aSLionel Sambuc   // messaged (avoids pulling it out of the result type).
72f4a2713aSLionel Sambuc   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
73f4a2713aSLionel Sambuc   const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
74f4a2713aSLionel Sambuc   llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
75f4a2713aSLionel Sambuc 
76f4a2713aSLionel Sambuc   CallArgList Args;
77*0a6a1f1dSLionel Sambuc   EmitCallArgs(Args, BoxingMethod, E->arg_begin(), E->arg_end());
78f4a2713aSLionel Sambuc 
79*0a6a1f1dSLionel Sambuc   RValue result = Runtime.GenerateMessageSend(
80*0a6a1f1dSLionel Sambuc       *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
81*0a6a1f1dSLionel Sambuc       Args, ClassDecl, BoxingMethod);
82f4a2713aSLionel Sambuc   return Builder.CreateBitCast(result.getScalarVal(),
83f4a2713aSLionel Sambuc                                ConvertType(E->getType()));
84f4a2713aSLionel Sambuc }
85f4a2713aSLionel Sambuc 
EmitObjCCollectionLiteral(const Expr * E,const ObjCMethodDecl * MethodWithObjects)86f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
87f4a2713aSLionel Sambuc                                     const ObjCMethodDecl *MethodWithObjects) {
88f4a2713aSLionel Sambuc   ASTContext &Context = CGM.getContext();
89*0a6a1f1dSLionel Sambuc   const ObjCDictionaryLiteral *DLE = nullptr;
90f4a2713aSLionel Sambuc   const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
91f4a2713aSLionel Sambuc   if (!ALE)
92f4a2713aSLionel Sambuc     DLE = cast<ObjCDictionaryLiteral>(E);
93f4a2713aSLionel Sambuc 
94f4a2713aSLionel Sambuc   // Compute the type of the array we're initializing.
95f4a2713aSLionel Sambuc   uint64_t NumElements =
96f4a2713aSLionel Sambuc     ALE ? ALE->getNumElements() : DLE->getNumElements();
97f4a2713aSLionel Sambuc   llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
98f4a2713aSLionel Sambuc                             NumElements);
99f4a2713aSLionel Sambuc   QualType ElementType = Context.getObjCIdType().withConst();
100f4a2713aSLionel Sambuc   QualType ElementArrayType
101f4a2713aSLionel Sambuc     = Context.getConstantArrayType(ElementType, APNumElements,
102f4a2713aSLionel Sambuc                                    ArrayType::Normal, /*IndexTypeQuals=*/0);
103f4a2713aSLionel Sambuc 
104f4a2713aSLionel Sambuc   // Allocate the temporary array(s).
105f4a2713aSLionel Sambuc   llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
106*0a6a1f1dSLionel Sambuc   llvm::Value *Keys = nullptr;
107f4a2713aSLionel Sambuc   if (DLE)
108f4a2713aSLionel Sambuc     Keys = CreateMemTemp(ElementArrayType, "keys");
109f4a2713aSLionel Sambuc 
110f4a2713aSLionel Sambuc   // In ARC, we may need to do extra work to keep all the keys and
111f4a2713aSLionel Sambuc   // values alive until after the call.
112f4a2713aSLionel Sambuc   SmallVector<llvm::Value *, 16> NeededObjects;
113f4a2713aSLionel Sambuc   bool TrackNeededObjects =
114f4a2713aSLionel Sambuc     (getLangOpts().ObjCAutoRefCount &&
115f4a2713aSLionel Sambuc     CGM.getCodeGenOpts().OptimizationLevel != 0);
116f4a2713aSLionel Sambuc 
117f4a2713aSLionel Sambuc   // Perform the actual initialialization of the array(s).
118f4a2713aSLionel Sambuc   for (uint64_t i = 0; i < NumElements; i++) {
119f4a2713aSLionel Sambuc     if (ALE) {
120f4a2713aSLionel Sambuc       // Emit the element and store it to the appropriate array slot.
121f4a2713aSLionel Sambuc       const Expr *Rhs = ALE->getElement(i);
122f4a2713aSLionel Sambuc       LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
123f4a2713aSLionel Sambuc                                    ElementType,
124f4a2713aSLionel Sambuc                                    Context.getTypeAlignInChars(Rhs->getType()),
125f4a2713aSLionel Sambuc                                    Context);
126f4a2713aSLionel Sambuc 
127f4a2713aSLionel Sambuc       llvm::Value *value = EmitScalarExpr(Rhs);
128f4a2713aSLionel Sambuc       EmitStoreThroughLValue(RValue::get(value), LV, true);
129f4a2713aSLionel Sambuc       if (TrackNeededObjects) {
130f4a2713aSLionel Sambuc         NeededObjects.push_back(value);
131f4a2713aSLionel Sambuc       }
132f4a2713aSLionel Sambuc     } else {
133f4a2713aSLionel Sambuc       // Emit the key and store it to the appropriate array slot.
134f4a2713aSLionel Sambuc       const Expr *Key = DLE->getKeyValueElement(i).Key;
135f4a2713aSLionel Sambuc       LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
136f4a2713aSLionel Sambuc                                       ElementType,
137f4a2713aSLionel Sambuc                                     Context.getTypeAlignInChars(Key->getType()),
138f4a2713aSLionel Sambuc                                       Context);
139f4a2713aSLionel Sambuc       llvm::Value *keyValue = EmitScalarExpr(Key);
140f4a2713aSLionel Sambuc       EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
141f4a2713aSLionel Sambuc 
142f4a2713aSLionel Sambuc       // Emit the value and store it to the appropriate array slot.
143f4a2713aSLionel Sambuc       const Expr *Value = DLE->getKeyValueElement(i).Value;
144f4a2713aSLionel Sambuc       LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
145f4a2713aSLionel Sambuc                                         ElementType,
146f4a2713aSLionel Sambuc                                   Context.getTypeAlignInChars(Value->getType()),
147f4a2713aSLionel Sambuc                                         Context);
148f4a2713aSLionel Sambuc       llvm::Value *valueValue = EmitScalarExpr(Value);
149f4a2713aSLionel Sambuc       EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
150f4a2713aSLionel Sambuc       if (TrackNeededObjects) {
151f4a2713aSLionel Sambuc         NeededObjects.push_back(keyValue);
152f4a2713aSLionel Sambuc         NeededObjects.push_back(valueValue);
153f4a2713aSLionel Sambuc       }
154f4a2713aSLionel Sambuc     }
155f4a2713aSLionel Sambuc   }
156f4a2713aSLionel Sambuc 
157f4a2713aSLionel Sambuc   // Generate the argument list.
158f4a2713aSLionel Sambuc   CallArgList Args;
159f4a2713aSLionel Sambuc   ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
160f4a2713aSLionel Sambuc   const ParmVarDecl *argDecl = *PI++;
161f4a2713aSLionel Sambuc   QualType ArgQT = argDecl->getType().getUnqualifiedType();
162f4a2713aSLionel Sambuc   Args.add(RValue::get(Objects), ArgQT);
163f4a2713aSLionel Sambuc   if (DLE) {
164f4a2713aSLionel Sambuc     argDecl = *PI++;
165f4a2713aSLionel Sambuc     ArgQT = argDecl->getType().getUnqualifiedType();
166f4a2713aSLionel Sambuc     Args.add(RValue::get(Keys), ArgQT);
167f4a2713aSLionel Sambuc   }
168f4a2713aSLionel Sambuc   argDecl = *PI;
169f4a2713aSLionel Sambuc   ArgQT = argDecl->getType().getUnqualifiedType();
170f4a2713aSLionel Sambuc   llvm::Value *Count =
171f4a2713aSLionel Sambuc     llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
172f4a2713aSLionel Sambuc   Args.add(RValue::get(Count), ArgQT);
173f4a2713aSLionel Sambuc 
174f4a2713aSLionel Sambuc   // Generate a reference to the class pointer, which will be the receiver.
175f4a2713aSLionel Sambuc   Selector Sel = MethodWithObjects->getSelector();
176f4a2713aSLionel Sambuc   QualType ResultType = E->getType();
177f4a2713aSLionel Sambuc   const ObjCObjectPointerType *InterfacePointerType
178f4a2713aSLionel Sambuc     = ResultType->getAsObjCInterfacePointerType();
179f4a2713aSLionel Sambuc   ObjCInterfaceDecl *Class
180f4a2713aSLionel Sambuc     = InterfacePointerType->getObjectType()->getInterface();
181f4a2713aSLionel Sambuc   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
182f4a2713aSLionel Sambuc   llvm::Value *Receiver = Runtime.GetClass(*this, Class);
183f4a2713aSLionel Sambuc 
184f4a2713aSLionel Sambuc   // Generate the message send.
185*0a6a1f1dSLionel Sambuc   RValue result = Runtime.GenerateMessageSend(
186*0a6a1f1dSLionel Sambuc       *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
187*0a6a1f1dSLionel Sambuc       Receiver, Args, Class, MethodWithObjects);
188f4a2713aSLionel Sambuc 
189f4a2713aSLionel Sambuc   // The above message send needs these objects, but in ARC they are
190f4a2713aSLionel Sambuc   // passed in a buffer that is essentially __unsafe_unretained.
191f4a2713aSLionel Sambuc   // Therefore we must prevent the optimizer from releasing them until
192f4a2713aSLionel Sambuc   // after the call.
193f4a2713aSLionel Sambuc   if (TrackNeededObjects) {
194f4a2713aSLionel Sambuc     EmitARCIntrinsicUse(NeededObjects);
195f4a2713aSLionel Sambuc   }
196f4a2713aSLionel Sambuc 
197f4a2713aSLionel Sambuc   return Builder.CreateBitCast(result.getScalarVal(),
198f4a2713aSLionel Sambuc                                ConvertType(E->getType()));
199f4a2713aSLionel Sambuc }
200f4a2713aSLionel Sambuc 
EmitObjCArrayLiteral(const ObjCArrayLiteral * E)201f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
202f4a2713aSLionel Sambuc   return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
203f4a2713aSLionel Sambuc }
204f4a2713aSLionel Sambuc 
EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral * E)205f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
206f4a2713aSLionel Sambuc                                             const ObjCDictionaryLiteral *E) {
207f4a2713aSLionel Sambuc   return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
208f4a2713aSLionel Sambuc }
209f4a2713aSLionel Sambuc 
210f4a2713aSLionel Sambuc /// Emit a selector.
EmitObjCSelectorExpr(const ObjCSelectorExpr * E)211f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
212f4a2713aSLionel Sambuc   // Untyped selector.
213f4a2713aSLionel Sambuc   // Note that this implementation allows for non-constant strings to be passed
214f4a2713aSLionel Sambuc   // as arguments to @selector().  Currently, the only thing preventing this
215f4a2713aSLionel Sambuc   // behaviour is the type checking in the front end.
216f4a2713aSLionel Sambuc   return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
217f4a2713aSLionel Sambuc }
218f4a2713aSLionel Sambuc 
EmitObjCProtocolExpr(const ObjCProtocolExpr * E)219f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
220f4a2713aSLionel Sambuc   // FIXME: This should pass the Decl not the name.
221f4a2713aSLionel Sambuc   return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
222f4a2713aSLionel Sambuc }
223f4a2713aSLionel Sambuc 
224f4a2713aSLionel Sambuc /// \brief Adjust the type of the result of an Objective-C message send
225f4a2713aSLionel Sambuc /// expression when the method has a related result type.
AdjustRelatedResultType(CodeGenFunction & CGF,QualType ExpT,const ObjCMethodDecl * Method,RValue Result)226f4a2713aSLionel Sambuc static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
227f4a2713aSLionel Sambuc                                       QualType ExpT,
228f4a2713aSLionel Sambuc                                       const ObjCMethodDecl *Method,
229f4a2713aSLionel Sambuc                                       RValue Result) {
230f4a2713aSLionel Sambuc   if (!Method)
231f4a2713aSLionel Sambuc     return Result;
232f4a2713aSLionel Sambuc 
233f4a2713aSLionel Sambuc   if (!Method->hasRelatedResultType() ||
234*0a6a1f1dSLionel Sambuc       CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
235f4a2713aSLionel Sambuc       !Result.isScalar())
236f4a2713aSLionel Sambuc     return Result;
237f4a2713aSLionel Sambuc 
238f4a2713aSLionel Sambuc   // We have applied a related result type. Cast the rvalue appropriately.
239f4a2713aSLionel Sambuc   return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
240f4a2713aSLionel Sambuc                                                CGF.ConvertType(ExpT)));
241f4a2713aSLionel Sambuc }
242f4a2713aSLionel Sambuc 
243f4a2713aSLionel Sambuc /// Decide whether to extend the lifetime of the receiver of a
244f4a2713aSLionel Sambuc /// returns-inner-pointer message.
245f4a2713aSLionel Sambuc static bool
shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr * message)246f4a2713aSLionel Sambuc shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
247f4a2713aSLionel Sambuc   switch (message->getReceiverKind()) {
248f4a2713aSLionel Sambuc 
249f4a2713aSLionel Sambuc   // For a normal instance message, we should extend unless the
250f4a2713aSLionel Sambuc   // receiver is loaded from a variable with precise lifetime.
251f4a2713aSLionel Sambuc   case ObjCMessageExpr::Instance: {
252f4a2713aSLionel Sambuc     const Expr *receiver = message->getInstanceReceiver();
253f4a2713aSLionel Sambuc     const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
254f4a2713aSLionel Sambuc     if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
255f4a2713aSLionel Sambuc     receiver = ice->getSubExpr()->IgnoreParens();
256f4a2713aSLionel Sambuc 
257f4a2713aSLionel Sambuc     // Only __strong variables.
258f4a2713aSLionel Sambuc     if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
259f4a2713aSLionel Sambuc       return true;
260f4a2713aSLionel Sambuc 
261f4a2713aSLionel Sambuc     // All ivars and fields have precise lifetime.
262f4a2713aSLionel Sambuc     if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
263f4a2713aSLionel Sambuc       return false;
264f4a2713aSLionel Sambuc 
265f4a2713aSLionel Sambuc     // Otherwise, check for variables.
266f4a2713aSLionel Sambuc     const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
267f4a2713aSLionel Sambuc     if (!declRef) return true;
268f4a2713aSLionel Sambuc     const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
269f4a2713aSLionel Sambuc     if (!var) return true;
270f4a2713aSLionel Sambuc 
271f4a2713aSLionel Sambuc     // All variables have precise lifetime except local variables with
272f4a2713aSLionel Sambuc     // automatic storage duration that aren't specially marked.
273f4a2713aSLionel Sambuc     return (var->hasLocalStorage() &&
274f4a2713aSLionel Sambuc             !var->hasAttr<ObjCPreciseLifetimeAttr>());
275f4a2713aSLionel Sambuc   }
276f4a2713aSLionel Sambuc 
277f4a2713aSLionel Sambuc   case ObjCMessageExpr::Class:
278f4a2713aSLionel Sambuc   case ObjCMessageExpr::SuperClass:
279f4a2713aSLionel Sambuc     // It's never necessary for class objects.
280f4a2713aSLionel Sambuc     return false;
281f4a2713aSLionel Sambuc 
282f4a2713aSLionel Sambuc   case ObjCMessageExpr::SuperInstance:
283f4a2713aSLionel Sambuc     // We generally assume that 'self' lives throughout a method call.
284f4a2713aSLionel Sambuc     return false;
285f4a2713aSLionel Sambuc   }
286f4a2713aSLionel Sambuc 
287f4a2713aSLionel Sambuc   llvm_unreachable("invalid receiver kind");
288f4a2713aSLionel Sambuc }
289f4a2713aSLionel Sambuc 
EmitObjCMessageExpr(const ObjCMessageExpr * E,ReturnValueSlot Return)290f4a2713aSLionel Sambuc RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
291f4a2713aSLionel Sambuc                                             ReturnValueSlot Return) {
292f4a2713aSLionel Sambuc   // Only the lookup mechanism and first two arguments of the method
293f4a2713aSLionel Sambuc   // implementation vary between runtimes.  We can get the receiver and
294f4a2713aSLionel Sambuc   // arguments in generic code.
295f4a2713aSLionel Sambuc 
296f4a2713aSLionel Sambuc   bool isDelegateInit = E->isDelegateInitCall();
297f4a2713aSLionel Sambuc 
298f4a2713aSLionel Sambuc   const ObjCMethodDecl *method = E->getMethodDecl();
299f4a2713aSLionel Sambuc 
300f4a2713aSLionel Sambuc   // We don't retain the receiver in delegate init calls, and this is
301f4a2713aSLionel Sambuc   // safe because the receiver value is always loaded from 'self',
302f4a2713aSLionel Sambuc   // which we zero out.  We don't want to Block_copy block receivers,
303f4a2713aSLionel Sambuc   // though.
304f4a2713aSLionel Sambuc   bool retainSelf =
305f4a2713aSLionel Sambuc     (!isDelegateInit &&
306f4a2713aSLionel Sambuc      CGM.getLangOpts().ObjCAutoRefCount &&
307f4a2713aSLionel Sambuc      method &&
308f4a2713aSLionel Sambuc      method->hasAttr<NSConsumesSelfAttr>());
309f4a2713aSLionel Sambuc 
310f4a2713aSLionel Sambuc   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
311f4a2713aSLionel Sambuc   bool isSuperMessage = false;
312f4a2713aSLionel Sambuc   bool isClassMessage = false;
313*0a6a1f1dSLionel Sambuc   ObjCInterfaceDecl *OID = nullptr;
314f4a2713aSLionel Sambuc   // Find the receiver
315f4a2713aSLionel Sambuc   QualType ReceiverType;
316*0a6a1f1dSLionel Sambuc   llvm::Value *Receiver = nullptr;
317f4a2713aSLionel Sambuc   switch (E->getReceiverKind()) {
318f4a2713aSLionel Sambuc   case ObjCMessageExpr::Instance:
319f4a2713aSLionel Sambuc     ReceiverType = E->getInstanceReceiver()->getType();
320f4a2713aSLionel Sambuc     if (retainSelf) {
321f4a2713aSLionel Sambuc       TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
322f4a2713aSLionel Sambuc                                                    E->getInstanceReceiver());
323f4a2713aSLionel Sambuc       Receiver = ter.getPointer();
324f4a2713aSLionel Sambuc       if (ter.getInt()) retainSelf = false;
325f4a2713aSLionel Sambuc     } else
326f4a2713aSLionel Sambuc       Receiver = EmitScalarExpr(E->getInstanceReceiver());
327f4a2713aSLionel Sambuc     break;
328f4a2713aSLionel Sambuc 
329f4a2713aSLionel Sambuc   case ObjCMessageExpr::Class: {
330f4a2713aSLionel Sambuc     ReceiverType = E->getClassReceiver();
331f4a2713aSLionel Sambuc     const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
332f4a2713aSLionel Sambuc     assert(ObjTy && "Invalid Objective-C class message send");
333f4a2713aSLionel Sambuc     OID = ObjTy->getInterface();
334f4a2713aSLionel Sambuc     assert(OID && "Invalid Objective-C class message send");
335f4a2713aSLionel Sambuc     Receiver = Runtime.GetClass(*this, OID);
336f4a2713aSLionel Sambuc     isClassMessage = true;
337f4a2713aSLionel Sambuc     break;
338f4a2713aSLionel Sambuc   }
339f4a2713aSLionel Sambuc 
340f4a2713aSLionel Sambuc   case ObjCMessageExpr::SuperInstance:
341f4a2713aSLionel Sambuc     ReceiverType = E->getSuperType();
342f4a2713aSLionel Sambuc     Receiver = LoadObjCSelf();
343f4a2713aSLionel Sambuc     isSuperMessage = true;
344f4a2713aSLionel Sambuc     break;
345f4a2713aSLionel Sambuc 
346f4a2713aSLionel Sambuc   case ObjCMessageExpr::SuperClass:
347f4a2713aSLionel Sambuc     ReceiverType = E->getSuperType();
348f4a2713aSLionel Sambuc     Receiver = LoadObjCSelf();
349f4a2713aSLionel Sambuc     isSuperMessage = true;
350f4a2713aSLionel Sambuc     isClassMessage = true;
351f4a2713aSLionel Sambuc     break;
352f4a2713aSLionel Sambuc   }
353f4a2713aSLionel Sambuc 
354f4a2713aSLionel Sambuc   if (retainSelf)
355f4a2713aSLionel Sambuc     Receiver = EmitARCRetainNonBlock(Receiver);
356f4a2713aSLionel Sambuc 
357f4a2713aSLionel Sambuc   // In ARC, we sometimes want to "extend the lifetime"
358f4a2713aSLionel Sambuc   // (i.e. retain+autorelease) of receivers of returns-inner-pointer
359f4a2713aSLionel Sambuc   // messages.
360f4a2713aSLionel Sambuc   if (getLangOpts().ObjCAutoRefCount && method &&
361f4a2713aSLionel Sambuc       method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
362f4a2713aSLionel Sambuc       shouldExtendReceiverForInnerPointerMessage(E))
363f4a2713aSLionel Sambuc     Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
364f4a2713aSLionel Sambuc 
365*0a6a1f1dSLionel Sambuc   QualType ResultType = method ? method->getReturnType() : E->getType();
366f4a2713aSLionel Sambuc 
367f4a2713aSLionel Sambuc   CallArgList Args;
368f4a2713aSLionel Sambuc   EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
369f4a2713aSLionel Sambuc 
370f4a2713aSLionel Sambuc   // For delegate init calls in ARC, do an unsafe store of null into
371f4a2713aSLionel Sambuc   // self.  This represents the call taking direct ownership of that
372f4a2713aSLionel Sambuc   // value.  We have to do this after emitting the other call
373f4a2713aSLionel Sambuc   // arguments because they might also reference self, but we don't
374f4a2713aSLionel Sambuc   // have to worry about any of them modifying self because that would
375f4a2713aSLionel Sambuc   // be an undefined read and write of an object in unordered
376f4a2713aSLionel Sambuc   // expressions.
377f4a2713aSLionel Sambuc   if (isDelegateInit) {
378f4a2713aSLionel Sambuc     assert(getLangOpts().ObjCAutoRefCount &&
379f4a2713aSLionel Sambuc            "delegate init calls should only be marked in ARC");
380f4a2713aSLionel Sambuc 
381f4a2713aSLionel Sambuc     // Do an unsafe store of null into self.
382f4a2713aSLionel Sambuc     llvm::Value *selfAddr =
383f4a2713aSLionel Sambuc       LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
384f4a2713aSLionel Sambuc     assert(selfAddr && "no self entry for a delegate init call?");
385f4a2713aSLionel Sambuc 
386f4a2713aSLionel Sambuc     Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
387f4a2713aSLionel Sambuc   }
388f4a2713aSLionel Sambuc 
389f4a2713aSLionel Sambuc   RValue result;
390f4a2713aSLionel Sambuc   if (isSuperMessage) {
391f4a2713aSLionel Sambuc     // super is only valid in an Objective-C method
392f4a2713aSLionel Sambuc     const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
393f4a2713aSLionel Sambuc     bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
394f4a2713aSLionel Sambuc     result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
395f4a2713aSLionel Sambuc                                               E->getSelector(),
396f4a2713aSLionel Sambuc                                               OMD->getClassInterface(),
397f4a2713aSLionel Sambuc                                               isCategoryImpl,
398f4a2713aSLionel Sambuc                                               Receiver,
399f4a2713aSLionel Sambuc                                               isClassMessage,
400f4a2713aSLionel Sambuc                                               Args,
401f4a2713aSLionel Sambuc                                               method);
402f4a2713aSLionel Sambuc   } else {
403f4a2713aSLionel Sambuc     result = Runtime.GenerateMessageSend(*this, Return, ResultType,
404f4a2713aSLionel Sambuc                                          E->getSelector(),
405f4a2713aSLionel Sambuc                                          Receiver, Args, OID,
406f4a2713aSLionel Sambuc                                          method);
407f4a2713aSLionel Sambuc   }
408f4a2713aSLionel Sambuc 
409f4a2713aSLionel Sambuc   // For delegate init calls in ARC, implicitly store the result of
410f4a2713aSLionel Sambuc   // the call back into self.  This takes ownership of the value.
411f4a2713aSLionel Sambuc   if (isDelegateInit) {
412f4a2713aSLionel Sambuc     llvm::Value *selfAddr =
413f4a2713aSLionel Sambuc       LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
414f4a2713aSLionel Sambuc     llvm::Value *newSelf = result.getScalarVal();
415f4a2713aSLionel Sambuc 
416f4a2713aSLionel Sambuc     // The delegate return type isn't necessarily a matching type; in
417f4a2713aSLionel Sambuc     // fact, it's quite likely to be 'id'.
418f4a2713aSLionel Sambuc     llvm::Type *selfTy =
419f4a2713aSLionel Sambuc       cast<llvm::PointerType>(selfAddr->getType())->getElementType();
420f4a2713aSLionel Sambuc     newSelf = Builder.CreateBitCast(newSelf, selfTy);
421f4a2713aSLionel Sambuc 
422f4a2713aSLionel Sambuc     Builder.CreateStore(newSelf, selfAddr);
423f4a2713aSLionel Sambuc   }
424f4a2713aSLionel Sambuc 
425f4a2713aSLionel Sambuc   return AdjustRelatedResultType(*this, E->getType(), method, result);
426f4a2713aSLionel Sambuc }
427f4a2713aSLionel Sambuc 
428f4a2713aSLionel Sambuc namespace {
429f4a2713aSLionel Sambuc struct FinishARCDealloc : EHScopeStack::Cleanup {
Emit__anon86dbc8190111::FinishARCDealloc430*0a6a1f1dSLionel Sambuc   void Emit(CodeGenFunction &CGF, Flags flags) override {
431f4a2713aSLionel Sambuc     const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
432f4a2713aSLionel Sambuc 
433f4a2713aSLionel Sambuc     const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
434f4a2713aSLionel Sambuc     const ObjCInterfaceDecl *iface = impl->getClassInterface();
435f4a2713aSLionel Sambuc     if (!iface->getSuperClass()) return;
436f4a2713aSLionel Sambuc 
437f4a2713aSLionel Sambuc     bool isCategory = isa<ObjCCategoryImplDecl>(impl);
438f4a2713aSLionel Sambuc 
439f4a2713aSLionel Sambuc     // Call [super dealloc] if we have a superclass.
440f4a2713aSLionel Sambuc     llvm::Value *self = CGF.LoadObjCSelf();
441f4a2713aSLionel Sambuc 
442f4a2713aSLionel Sambuc     CallArgList args;
443f4a2713aSLionel Sambuc     CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
444f4a2713aSLionel Sambuc                                                       CGF.getContext().VoidTy,
445f4a2713aSLionel Sambuc                                                       method->getSelector(),
446f4a2713aSLionel Sambuc                                                       iface,
447f4a2713aSLionel Sambuc                                                       isCategory,
448f4a2713aSLionel Sambuc                                                       self,
449f4a2713aSLionel Sambuc                                                       /*is class msg*/ false,
450f4a2713aSLionel Sambuc                                                       args,
451f4a2713aSLionel Sambuc                                                       method);
452f4a2713aSLionel Sambuc   }
453f4a2713aSLionel Sambuc };
454f4a2713aSLionel Sambuc }
455f4a2713aSLionel Sambuc 
456f4a2713aSLionel Sambuc /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
457f4a2713aSLionel Sambuc /// the LLVM function and sets the other context used by
458f4a2713aSLionel Sambuc /// CodeGenFunction.
StartObjCMethod(const ObjCMethodDecl * OMD,const ObjCContainerDecl * CD)459f4a2713aSLionel Sambuc void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
460*0a6a1f1dSLionel Sambuc                                       const ObjCContainerDecl *CD) {
461*0a6a1f1dSLionel Sambuc   SourceLocation StartLoc = OMD->getLocStart();
462f4a2713aSLionel Sambuc   FunctionArgList args;
463f4a2713aSLionel Sambuc   // Check if we should generate debug info for this method.
464f4a2713aSLionel Sambuc   if (OMD->hasAttr<NoDebugAttr>())
465*0a6a1f1dSLionel Sambuc     DebugInfo = nullptr; // disable debug info indefinitely for this function
466f4a2713aSLionel Sambuc 
467f4a2713aSLionel Sambuc   llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
468f4a2713aSLionel Sambuc 
469f4a2713aSLionel Sambuc   const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
470f4a2713aSLionel Sambuc   CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
471f4a2713aSLionel Sambuc 
472f4a2713aSLionel Sambuc   args.push_back(OMD->getSelfDecl());
473f4a2713aSLionel Sambuc   args.push_back(OMD->getCmdDecl());
474f4a2713aSLionel Sambuc 
475*0a6a1f1dSLionel Sambuc   for (const auto *PI : OMD->params())
476*0a6a1f1dSLionel Sambuc     args.push_back(PI);
477f4a2713aSLionel Sambuc 
478f4a2713aSLionel Sambuc   CurGD = OMD;
479*0a6a1f1dSLionel Sambuc   CurEHLocation = OMD->getLocEnd();
480f4a2713aSLionel Sambuc 
481*0a6a1f1dSLionel Sambuc   StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
482*0a6a1f1dSLionel Sambuc                 OMD->getLocation(), StartLoc);
483f4a2713aSLionel Sambuc 
484f4a2713aSLionel Sambuc   // In ARC, certain methods get an extra cleanup.
485f4a2713aSLionel Sambuc   if (CGM.getLangOpts().ObjCAutoRefCount &&
486f4a2713aSLionel Sambuc       OMD->isInstanceMethod() &&
487f4a2713aSLionel Sambuc       OMD->getSelector().isUnarySelector()) {
488f4a2713aSLionel Sambuc     const IdentifierInfo *ident =
489f4a2713aSLionel Sambuc       OMD->getSelector().getIdentifierInfoForSlot(0);
490f4a2713aSLionel Sambuc     if (ident->isStr("dealloc"))
491f4a2713aSLionel Sambuc       EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
492f4a2713aSLionel Sambuc   }
493f4a2713aSLionel Sambuc }
494f4a2713aSLionel Sambuc 
495f4a2713aSLionel Sambuc static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
496f4a2713aSLionel Sambuc                                               LValue lvalue, QualType type);
497f4a2713aSLionel Sambuc 
498f4a2713aSLionel Sambuc /// Generate an Objective-C method.  An Objective-C method is a C function with
499f4a2713aSLionel Sambuc /// its pointer, name, and types registered in the class struture.
GenerateObjCMethod(const ObjCMethodDecl * OMD)500f4a2713aSLionel Sambuc void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
501*0a6a1f1dSLionel Sambuc   StartObjCMethod(OMD, OMD->getClassInterface());
502*0a6a1f1dSLionel Sambuc   PGO.assignRegionCounters(OMD, CurFn);
503*0a6a1f1dSLionel Sambuc   assert(isa<CompoundStmt>(OMD->getBody()));
504*0a6a1f1dSLionel Sambuc   RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
505*0a6a1f1dSLionel Sambuc   Cnt.beginRegion(Builder);
506*0a6a1f1dSLionel Sambuc   EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
507f4a2713aSLionel Sambuc   FinishFunction(OMD->getBodyRBrace());
508f4a2713aSLionel Sambuc }
509f4a2713aSLionel Sambuc 
510f4a2713aSLionel Sambuc /// emitStructGetterCall - Call the runtime function to load a property
511f4a2713aSLionel Sambuc /// into the return value slot.
emitStructGetterCall(CodeGenFunction & CGF,ObjCIvarDecl * ivar,bool isAtomic,bool hasStrong)512f4a2713aSLionel Sambuc static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
513f4a2713aSLionel Sambuc                                  bool isAtomic, bool hasStrong) {
514f4a2713aSLionel Sambuc   ASTContext &Context = CGF.getContext();
515f4a2713aSLionel Sambuc 
516f4a2713aSLionel Sambuc   llvm::Value *src =
517f4a2713aSLionel Sambuc     CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
518f4a2713aSLionel Sambuc                           ivar, 0).getAddress();
519f4a2713aSLionel Sambuc 
520f4a2713aSLionel Sambuc   // objc_copyStruct (ReturnValue, &structIvar,
521f4a2713aSLionel Sambuc   //                  sizeof (Type of Ivar), isAtomic, false);
522f4a2713aSLionel Sambuc   CallArgList args;
523f4a2713aSLionel Sambuc 
524f4a2713aSLionel Sambuc   llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
525f4a2713aSLionel Sambuc   args.add(RValue::get(dest), Context.VoidPtrTy);
526f4a2713aSLionel Sambuc 
527f4a2713aSLionel Sambuc   src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
528f4a2713aSLionel Sambuc   args.add(RValue::get(src), Context.VoidPtrTy);
529f4a2713aSLionel Sambuc 
530f4a2713aSLionel Sambuc   CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
531f4a2713aSLionel Sambuc   args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
532f4a2713aSLionel Sambuc   args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
533f4a2713aSLionel Sambuc   args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
534f4a2713aSLionel Sambuc 
535f4a2713aSLionel Sambuc   llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
536f4a2713aSLionel Sambuc   CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
537f4a2713aSLionel Sambuc                                                       FunctionType::ExtInfo(),
538f4a2713aSLionel Sambuc                                                       RequiredArgs::All),
539f4a2713aSLionel Sambuc                fn, ReturnValueSlot(), args);
540f4a2713aSLionel Sambuc }
541f4a2713aSLionel Sambuc 
542f4a2713aSLionel Sambuc /// Determine whether the given architecture supports unaligned atomic
543f4a2713aSLionel Sambuc /// accesses.  They don't have to be fast, just faster than a function
544f4a2713aSLionel Sambuc /// call and a mutex.
hasUnalignedAtomics(llvm::Triple::ArchType arch)545f4a2713aSLionel Sambuc static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
546f4a2713aSLionel Sambuc   // FIXME: Allow unaligned atomic load/store on x86.  (It is not
547f4a2713aSLionel Sambuc   // currently supported by the backend.)
548f4a2713aSLionel Sambuc   return 0;
549f4a2713aSLionel Sambuc }
550f4a2713aSLionel Sambuc 
551f4a2713aSLionel Sambuc /// Return the maximum size that permits atomic accesses for the given
552f4a2713aSLionel Sambuc /// architecture.
getMaxAtomicAccessSize(CodeGenModule & CGM,llvm::Triple::ArchType arch)553f4a2713aSLionel Sambuc static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
554f4a2713aSLionel Sambuc                                         llvm::Triple::ArchType arch) {
555f4a2713aSLionel Sambuc   // ARM has 8-byte atomic accesses, but it's not clear whether we
556f4a2713aSLionel Sambuc   // want to rely on them here.
557f4a2713aSLionel Sambuc 
558f4a2713aSLionel Sambuc   // In the default case, just assume that any size up to a pointer is
559f4a2713aSLionel Sambuc   // fine given adequate alignment.
560f4a2713aSLionel Sambuc   return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
561f4a2713aSLionel Sambuc }
562f4a2713aSLionel Sambuc 
563f4a2713aSLionel Sambuc namespace {
564f4a2713aSLionel Sambuc   class PropertyImplStrategy {
565f4a2713aSLionel Sambuc   public:
566f4a2713aSLionel Sambuc     enum StrategyKind {
567f4a2713aSLionel Sambuc       /// The 'native' strategy is to use the architecture's provided
568f4a2713aSLionel Sambuc       /// reads and writes.
569f4a2713aSLionel Sambuc       Native,
570f4a2713aSLionel Sambuc 
571f4a2713aSLionel Sambuc       /// Use objc_setProperty and objc_getProperty.
572f4a2713aSLionel Sambuc       GetSetProperty,
573f4a2713aSLionel Sambuc 
574f4a2713aSLionel Sambuc       /// Use objc_setProperty for the setter, but use expression
575f4a2713aSLionel Sambuc       /// evaluation for the getter.
576f4a2713aSLionel Sambuc       SetPropertyAndExpressionGet,
577f4a2713aSLionel Sambuc 
578f4a2713aSLionel Sambuc       /// Use objc_copyStruct.
579f4a2713aSLionel Sambuc       CopyStruct,
580f4a2713aSLionel Sambuc 
581f4a2713aSLionel Sambuc       /// The 'expression' strategy is to emit normal assignment or
582f4a2713aSLionel Sambuc       /// lvalue-to-rvalue expressions.
583f4a2713aSLionel Sambuc       Expression
584f4a2713aSLionel Sambuc     };
585f4a2713aSLionel Sambuc 
getKind() const586f4a2713aSLionel Sambuc     StrategyKind getKind() const { return StrategyKind(Kind); }
587f4a2713aSLionel Sambuc 
hasStrongMember() const588f4a2713aSLionel Sambuc     bool hasStrongMember() const { return HasStrong; }
isAtomic() const589f4a2713aSLionel Sambuc     bool isAtomic() const { return IsAtomic; }
isCopy() const590f4a2713aSLionel Sambuc     bool isCopy() const { return IsCopy; }
591f4a2713aSLionel Sambuc 
getIvarSize() const592f4a2713aSLionel Sambuc     CharUnits getIvarSize() const { return IvarSize; }
getIvarAlignment() const593f4a2713aSLionel Sambuc     CharUnits getIvarAlignment() const { return IvarAlignment; }
594f4a2713aSLionel Sambuc 
595f4a2713aSLionel Sambuc     PropertyImplStrategy(CodeGenModule &CGM,
596f4a2713aSLionel Sambuc                          const ObjCPropertyImplDecl *propImpl);
597f4a2713aSLionel Sambuc 
598f4a2713aSLionel Sambuc   private:
599f4a2713aSLionel Sambuc     unsigned Kind : 8;
600f4a2713aSLionel Sambuc     unsigned IsAtomic : 1;
601f4a2713aSLionel Sambuc     unsigned IsCopy : 1;
602f4a2713aSLionel Sambuc     unsigned HasStrong : 1;
603f4a2713aSLionel Sambuc 
604f4a2713aSLionel Sambuc     CharUnits IvarSize;
605f4a2713aSLionel Sambuc     CharUnits IvarAlignment;
606f4a2713aSLionel Sambuc   };
607f4a2713aSLionel Sambuc }
608f4a2713aSLionel Sambuc 
609f4a2713aSLionel Sambuc /// Pick an implementation strategy for the given property synthesis.
PropertyImplStrategy(CodeGenModule & CGM,const ObjCPropertyImplDecl * propImpl)610f4a2713aSLionel Sambuc PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
611f4a2713aSLionel Sambuc                                      const ObjCPropertyImplDecl *propImpl) {
612f4a2713aSLionel Sambuc   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
613f4a2713aSLionel Sambuc   ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
614f4a2713aSLionel Sambuc 
615f4a2713aSLionel Sambuc   IsCopy = (setterKind == ObjCPropertyDecl::Copy);
616f4a2713aSLionel Sambuc   IsAtomic = prop->isAtomic();
617f4a2713aSLionel Sambuc   HasStrong = false; // doesn't matter here.
618f4a2713aSLionel Sambuc 
619f4a2713aSLionel Sambuc   // Evaluate the ivar's size and alignment.
620f4a2713aSLionel Sambuc   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
621f4a2713aSLionel Sambuc   QualType ivarType = ivar->getType();
622*0a6a1f1dSLionel Sambuc   std::tie(IvarSize, IvarAlignment) =
623*0a6a1f1dSLionel Sambuc       CGM.getContext().getTypeInfoInChars(ivarType);
624f4a2713aSLionel Sambuc 
625f4a2713aSLionel Sambuc   // If we have a copy property, we always have to use getProperty/setProperty.
626f4a2713aSLionel Sambuc   // TODO: we could actually use setProperty and an expression for non-atomics.
627f4a2713aSLionel Sambuc   if (IsCopy) {
628f4a2713aSLionel Sambuc     Kind = GetSetProperty;
629f4a2713aSLionel Sambuc     return;
630f4a2713aSLionel Sambuc   }
631f4a2713aSLionel Sambuc 
632f4a2713aSLionel Sambuc   // Handle retain.
633f4a2713aSLionel Sambuc   if (setterKind == ObjCPropertyDecl::Retain) {
634f4a2713aSLionel Sambuc     // In GC-only, there's nothing special that needs to be done.
635f4a2713aSLionel Sambuc     if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
636f4a2713aSLionel Sambuc       // fallthrough
637f4a2713aSLionel Sambuc 
638f4a2713aSLionel Sambuc     // In ARC, if the property is non-atomic, use expression emission,
639f4a2713aSLionel Sambuc     // which translates to objc_storeStrong.  This isn't required, but
640f4a2713aSLionel Sambuc     // it's slightly nicer.
641f4a2713aSLionel Sambuc     } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
642f4a2713aSLionel Sambuc       // Using standard expression emission for the setter is only
643f4a2713aSLionel Sambuc       // acceptable if the ivar is __strong, which won't be true if
644f4a2713aSLionel Sambuc       // the property is annotated with __attribute__((NSObject)).
645f4a2713aSLionel Sambuc       // TODO: falling all the way back to objc_setProperty here is
646f4a2713aSLionel Sambuc       // just laziness, though;  we could still use objc_storeStrong
647f4a2713aSLionel Sambuc       // if we hacked it right.
648f4a2713aSLionel Sambuc       if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
649f4a2713aSLionel Sambuc         Kind = Expression;
650f4a2713aSLionel Sambuc       else
651f4a2713aSLionel Sambuc         Kind = SetPropertyAndExpressionGet;
652f4a2713aSLionel Sambuc       return;
653f4a2713aSLionel Sambuc 
654f4a2713aSLionel Sambuc     // Otherwise, we need to at least use setProperty.  However, if
655f4a2713aSLionel Sambuc     // the property isn't atomic, we can use normal expression
656f4a2713aSLionel Sambuc     // emission for the getter.
657f4a2713aSLionel Sambuc     } else if (!IsAtomic) {
658f4a2713aSLionel Sambuc       Kind = SetPropertyAndExpressionGet;
659f4a2713aSLionel Sambuc       return;
660f4a2713aSLionel Sambuc 
661f4a2713aSLionel Sambuc     // Otherwise, we have to use both setProperty and getProperty.
662f4a2713aSLionel Sambuc     } else {
663f4a2713aSLionel Sambuc       Kind = GetSetProperty;
664f4a2713aSLionel Sambuc       return;
665f4a2713aSLionel Sambuc     }
666f4a2713aSLionel Sambuc   }
667f4a2713aSLionel Sambuc 
668f4a2713aSLionel Sambuc   // If we're not atomic, just use expression accesses.
669f4a2713aSLionel Sambuc   if (!IsAtomic) {
670f4a2713aSLionel Sambuc     Kind = Expression;
671f4a2713aSLionel Sambuc     return;
672f4a2713aSLionel Sambuc   }
673f4a2713aSLionel Sambuc 
674f4a2713aSLionel Sambuc   // Properties on bitfield ivars need to be emitted using expression
675f4a2713aSLionel Sambuc   // accesses even if they're nominally atomic.
676f4a2713aSLionel Sambuc   if (ivar->isBitField()) {
677f4a2713aSLionel Sambuc     Kind = Expression;
678f4a2713aSLionel Sambuc     return;
679f4a2713aSLionel Sambuc   }
680f4a2713aSLionel Sambuc 
681f4a2713aSLionel Sambuc   // GC-qualified or ARC-qualified ivars need to be emitted as
682f4a2713aSLionel Sambuc   // expressions.  This actually works out to being atomic anyway,
683f4a2713aSLionel Sambuc   // except for ARC __strong, but that should trigger the above code.
684f4a2713aSLionel Sambuc   if (ivarType.hasNonTrivialObjCLifetime() ||
685f4a2713aSLionel Sambuc       (CGM.getLangOpts().getGC() &&
686f4a2713aSLionel Sambuc        CGM.getContext().getObjCGCAttrKind(ivarType))) {
687f4a2713aSLionel Sambuc     Kind = Expression;
688f4a2713aSLionel Sambuc     return;
689f4a2713aSLionel Sambuc   }
690f4a2713aSLionel Sambuc 
691f4a2713aSLionel Sambuc   // Compute whether the ivar has strong members.
692f4a2713aSLionel Sambuc   if (CGM.getLangOpts().getGC())
693f4a2713aSLionel Sambuc     if (const RecordType *recordType = ivarType->getAs<RecordType>())
694f4a2713aSLionel Sambuc       HasStrong = recordType->getDecl()->hasObjectMember();
695f4a2713aSLionel Sambuc 
696f4a2713aSLionel Sambuc   // We can never access structs with object members with a native
697f4a2713aSLionel Sambuc   // access, because we need to use write barriers.  This is what
698f4a2713aSLionel Sambuc   // objc_copyStruct is for.
699f4a2713aSLionel Sambuc   if (HasStrong) {
700f4a2713aSLionel Sambuc     Kind = CopyStruct;
701f4a2713aSLionel Sambuc     return;
702f4a2713aSLionel Sambuc   }
703f4a2713aSLionel Sambuc 
704f4a2713aSLionel Sambuc   // Otherwise, this is target-dependent and based on the size and
705f4a2713aSLionel Sambuc   // alignment of the ivar.
706f4a2713aSLionel Sambuc 
707f4a2713aSLionel Sambuc   // If the size of the ivar is not a power of two, give up.  We don't
708f4a2713aSLionel Sambuc   // want to get into the business of doing compare-and-swaps.
709f4a2713aSLionel Sambuc   if (!IvarSize.isPowerOfTwo()) {
710f4a2713aSLionel Sambuc     Kind = CopyStruct;
711f4a2713aSLionel Sambuc     return;
712f4a2713aSLionel Sambuc   }
713f4a2713aSLionel Sambuc 
714f4a2713aSLionel Sambuc   llvm::Triple::ArchType arch =
715f4a2713aSLionel Sambuc     CGM.getTarget().getTriple().getArch();
716f4a2713aSLionel Sambuc 
717f4a2713aSLionel Sambuc   // Most architectures require memory to fit within a single cache
718f4a2713aSLionel Sambuc   // line, so the alignment has to be at least the size of the access.
719f4a2713aSLionel Sambuc   // Otherwise we have to grab a lock.
720f4a2713aSLionel Sambuc   if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
721f4a2713aSLionel Sambuc     Kind = CopyStruct;
722f4a2713aSLionel Sambuc     return;
723f4a2713aSLionel Sambuc   }
724f4a2713aSLionel Sambuc 
725f4a2713aSLionel Sambuc   // If the ivar's size exceeds the architecture's maximum atomic
726f4a2713aSLionel Sambuc   // access size, we have to use CopyStruct.
727f4a2713aSLionel Sambuc   if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
728f4a2713aSLionel Sambuc     Kind = CopyStruct;
729f4a2713aSLionel Sambuc     return;
730f4a2713aSLionel Sambuc   }
731f4a2713aSLionel Sambuc 
732f4a2713aSLionel Sambuc   // Otherwise, we can use native loads and stores.
733f4a2713aSLionel Sambuc   Kind = Native;
734f4a2713aSLionel Sambuc }
735f4a2713aSLionel Sambuc 
736f4a2713aSLionel Sambuc /// \brief Generate an Objective-C property getter function.
737f4a2713aSLionel Sambuc ///
738f4a2713aSLionel Sambuc /// The given Decl must be an ObjCImplementationDecl. \@synthesize
739f4a2713aSLionel Sambuc /// is illegal within a category.
GenerateObjCGetter(ObjCImplementationDecl * IMP,const ObjCPropertyImplDecl * PID)740f4a2713aSLionel Sambuc void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
741f4a2713aSLionel Sambuc                                          const ObjCPropertyImplDecl *PID) {
742f4a2713aSLionel Sambuc   llvm::Constant *AtomicHelperFn =
743*0a6a1f1dSLionel Sambuc       CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
744f4a2713aSLionel Sambuc   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
745f4a2713aSLionel Sambuc   ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
746f4a2713aSLionel Sambuc   assert(OMD && "Invalid call to generate getter (empty method)");
747*0a6a1f1dSLionel Sambuc   StartObjCMethod(OMD, IMP->getClassInterface());
748f4a2713aSLionel Sambuc 
749f4a2713aSLionel Sambuc   generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
750f4a2713aSLionel Sambuc 
751f4a2713aSLionel Sambuc   FinishFunction();
752f4a2713aSLionel Sambuc }
753f4a2713aSLionel Sambuc 
hasTrivialGetExpr(const ObjCPropertyImplDecl * propImpl)754f4a2713aSLionel Sambuc static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
755f4a2713aSLionel Sambuc   const Expr *getter = propImpl->getGetterCXXConstructor();
756f4a2713aSLionel Sambuc   if (!getter) return true;
757f4a2713aSLionel Sambuc 
758f4a2713aSLionel Sambuc   // Sema only makes only of these when the ivar has a C++ class type,
759f4a2713aSLionel Sambuc   // so the form is pretty constrained.
760f4a2713aSLionel Sambuc 
761f4a2713aSLionel Sambuc   // If the property has a reference type, we might just be binding a
762f4a2713aSLionel Sambuc   // reference, in which case the result will be a gl-value.  We should
763f4a2713aSLionel Sambuc   // treat this as a non-trivial operation.
764f4a2713aSLionel Sambuc   if (getter->isGLValue())
765f4a2713aSLionel Sambuc     return false;
766f4a2713aSLionel Sambuc 
767f4a2713aSLionel Sambuc   // If we selected a trivial copy-constructor, we're okay.
768f4a2713aSLionel Sambuc   if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
769f4a2713aSLionel Sambuc     return (construct->getConstructor()->isTrivial());
770f4a2713aSLionel Sambuc 
771f4a2713aSLionel Sambuc   // The constructor might require cleanups (in which case it's never
772f4a2713aSLionel Sambuc   // trivial).
773f4a2713aSLionel Sambuc   assert(isa<ExprWithCleanups>(getter));
774f4a2713aSLionel Sambuc   return false;
775f4a2713aSLionel Sambuc }
776f4a2713aSLionel Sambuc 
777f4a2713aSLionel Sambuc /// emitCPPObjectAtomicGetterCall - Call the runtime function to
778f4a2713aSLionel Sambuc /// copy the ivar into the resturn slot.
emitCPPObjectAtomicGetterCall(CodeGenFunction & CGF,llvm::Value * returnAddr,ObjCIvarDecl * ivar,llvm::Constant * AtomicHelperFn)779f4a2713aSLionel Sambuc static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
780f4a2713aSLionel Sambuc                                           llvm::Value *returnAddr,
781f4a2713aSLionel Sambuc                                           ObjCIvarDecl *ivar,
782f4a2713aSLionel Sambuc                                           llvm::Constant *AtomicHelperFn) {
783f4a2713aSLionel Sambuc   // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
784f4a2713aSLionel Sambuc   //                           AtomicHelperFn);
785f4a2713aSLionel Sambuc   CallArgList args;
786f4a2713aSLionel Sambuc 
787f4a2713aSLionel Sambuc   // The 1st argument is the return Slot.
788f4a2713aSLionel Sambuc   args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
789f4a2713aSLionel Sambuc 
790f4a2713aSLionel Sambuc   // The 2nd argument is the address of the ivar.
791f4a2713aSLionel Sambuc   llvm::Value *ivarAddr =
792f4a2713aSLionel Sambuc   CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
793f4a2713aSLionel Sambuc                         CGF.LoadObjCSelf(), ivar, 0).getAddress();
794f4a2713aSLionel Sambuc   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
795f4a2713aSLionel Sambuc   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
796f4a2713aSLionel Sambuc 
797f4a2713aSLionel Sambuc   // Third argument is the helper function.
798f4a2713aSLionel Sambuc   args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
799f4a2713aSLionel Sambuc 
800f4a2713aSLionel Sambuc   llvm::Value *copyCppAtomicObjectFn =
801f4a2713aSLionel Sambuc     CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
802f4a2713aSLionel Sambuc   CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
803f4a2713aSLionel Sambuc                                                       args,
804f4a2713aSLionel Sambuc                                                       FunctionType::ExtInfo(),
805f4a2713aSLionel Sambuc                                                       RequiredArgs::All),
806f4a2713aSLionel Sambuc                copyCppAtomicObjectFn, ReturnValueSlot(), args);
807f4a2713aSLionel Sambuc }
808f4a2713aSLionel Sambuc 
809f4a2713aSLionel Sambuc void
generateObjCGetterBody(const ObjCImplementationDecl * classImpl,const ObjCPropertyImplDecl * propImpl,const ObjCMethodDecl * GetterMethodDecl,llvm::Constant * AtomicHelperFn)810f4a2713aSLionel Sambuc CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
811f4a2713aSLionel Sambuc                                         const ObjCPropertyImplDecl *propImpl,
812f4a2713aSLionel Sambuc                                         const ObjCMethodDecl *GetterMethodDecl,
813f4a2713aSLionel Sambuc                                         llvm::Constant *AtomicHelperFn) {
814f4a2713aSLionel Sambuc   // If there's a non-trivial 'get' expression, we just have to emit that.
815f4a2713aSLionel Sambuc   if (!hasTrivialGetExpr(propImpl)) {
816f4a2713aSLionel Sambuc     if (!AtomicHelperFn) {
817f4a2713aSLionel Sambuc       ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
818*0a6a1f1dSLionel Sambuc                      /*nrvo*/ nullptr);
819f4a2713aSLionel Sambuc       EmitReturnStmt(ret);
820f4a2713aSLionel Sambuc     }
821f4a2713aSLionel Sambuc     else {
822f4a2713aSLionel Sambuc       ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
823f4a2713aSLionel Sambuc       emitCPPObjectAtomicGetterCall(*this, ReturnValue,
824f4a2713aSLionel Sambuc                                     ivar, AtomicHelperFn);
825f4a2713aSLionel Sambuc     }
826f4a2713aSLionel Sambuc     return;
827f4a2713aSLionel Sambuc   }
828f4a2713aSLionel Sambuc 
829f4a2713aSLionel Sambuc   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
830f4a2713aSLionel Sambuc   QualType propType = prop->getType();
831f4a2713aSLionel Sambuc   ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
832f4a2713aSLionel Sambuc 
833f4a2713aSLionel Sambuc   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
834f4a2713aSLionel Sambuc 
835f4a2713aSLionel Sambuc   // Pick an implementation strategy.
836f4a2713aSLionel Sambuc   PropertyImplStrategy strategy(CGM, propImpl);
837f4a2713aSLionel Sambuc   switch (strategy.getKind()) {
838f4a2713aSLionel Sambuc   case PropertyImplStrategy::Native: {
839f4a2713aSLionel Sambuc     // We don't need to do anything for a zero-size struct.
840f4a2713aSLionel Sambuc     if (strategy.getIvarSize().isZero())
841f4a2713aSLionel Sambuc       return;
842f4a2713aSLionel Sambuc 
843f4a2713aSLionel Sambuc     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
844f4a2713aSLionel Sambuc 
845f4a2713aSLionel Sambuc     // Currently, all atomic accesses have to be through integer
846f4a2713aSLionel Sambuc     // types, so there's no point in trying to pick a prettier type.
847f4a2713aSLionel Sambuc     llvm::Type *bitcastType =
848f4a2713aSLionel Sambuc       llvm::Type::getIntNTy(getLLVMContext(),
849f4a2713aSLionel Sambuc                             getContext().toBits(strategy.getIvarSize()));
850f4a2713aSLionel Sambuc     bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
851f4a2713aSLionel Sambuc 
852f4a2713aSLionel Sambuc     // Perform an atomic load.  This does not impose ordering constraints.
853f4a2713aSLionel Sambuc     llvm::Value *ivarAddr = LV.getAddress();
854f4a2713aSLionel Sambuc     ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
855f4a2713aSLionel Sambuc     llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
856f4a2713aSLionel Sambuc     load->setAlignment(strategy.getIvarAlignment().getQuantity());
857f4a2713aSLionel Sambuc     load->setAtomic(llvm::Unordered);
858f4a2713aSLionel Sambuc 
859f4a2713aSLionel Sambuc     // Store that value into the return address.  Doing this with a
860f4a2713aSLionel Sambuc     // bitcast is likely to produce some pretty ugly IR, but it's not
861f4a2713aSLionel Sambuc     // the *most* terrible thing in the world.
862f4a2713aSLionel Sambuc     Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
863f4a2713aSLionel Sambuc 
864f4a2713aSLionel Sambuc     // Make sure we don't do an autorelease.
865f4a2713aSLionel Sambuc     AutoreleaseResult = false;
866f4a2713aSLionel Sambuc     return;
867f4a2713aSLionel Sambuc   }
868f4a2713aSLionel Sambuc 
869f4a2713aSLionel Sambuc   case PropertyImplStrategy::GetSetProperty: {
870f4a2713aSLionel Sambuc     llvm::Value *getPropertyFn =
871f4a2713aSLionel Sambuc       CGM.getObjCRuntime().GetPropertyGetFunction();
872f4a2713aSLionel Sambuc     if (!getPropertyFn) {
873f4a2713aSLionel Sambuc       CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
874f4a2713aSLionel Sambuc       return;
875f4a2713aSLionel Sambuc     }
876f4a2713aSLionel Sambuc 
877f4a2713aSLionel Sambuc     // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
878f4a2713aSLionel Sambuc     // FIXME: Can't this be simpler? This might even be worse than the
879f4a2713aSLionel Sambuc     // corresponding gcc code.
880f4a2713aSLionel Sambuc     llvm::Value *cmd =
881f4a2713aSLionel Sambuc       Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
882f4a2713aSLionel Sambuc     llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
883f4a2713aSLionel Sambuc     llvm::Value *ivarOffset =
884f4a2713aSLionel Sambuc       EmitIvarOffset(classImpl->getClassInterface(), ivar);
885f4a2713aSLionel Sambuc 
886f4a2713aSLionel Sambuc     CallArgList args;
887f4a2713aSLionel Sambuc     args.add(RValue::get(self), getContext().getObjCIdType());
888f4a2713aSLionel Sambuc     args.add(RValue::get(cmd), getContext().getObjCSelType());
889f4a2713aSLionel Sambuc     args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
890f4a2713aSLionel Sambuc     args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
891f4a2713aSLionel Sambuc              getContext().BoolTy);
892f4a2713aSLionel Sambuc 
893f4a2713aSLionel Sambuc     // FIXME: We shouldn't need to get the function info here, the
894f4a2713aSLionel Sambuc     // runtime already should have computed it to build the function.
895*0a6a1f1dSLionel Sambuc     llvm::Instruction *CallInstruction;
896f4a2713aSLionel Sambuc     RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
897f4a2713aSLionel Sambuc                                                        FunctionType::ExtInfo(),
898f4a2713aSLionel Sambuc                                                             RequiredArgs::All),
899*0a6a1f1dSLionel Sambuc                          getPropertyFn, ReturnValueSlot(), args, nullptr,
900*0a6a1f1dSLionel Sambuc                          &CallInstruction);
901*0a6a1f1dSLionel Sambuc     if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
902*0a6a1f1dSLionel Sambuc       call->setTailCall();
903f4a2713aSLionel Sambuc 
904f4a2713aSLionel Sambuc     // We need to fix the type here. Ivars with copy & retain are
905f4a2713aSLionel Sambuc     // always objects so we don't need to worry about complex or
906f4a2713aSLionel Sambuc     // aggregates.
907*0a6a1f1dSLionel Sambuc     RV = RValue::get(Builder.CreateBitCast(
908*0a6a1f1dSLionel Sambuc         RV.getScalarVal(),
909*0a6a1f1dSLionel Sambuc         getTypes().ConvertType(getterMethod->getReturnType())));
910f4a2713aSLionel Sambuc 
911f4a2713aSLionel Sambuc     EmitReturnOfRValue(RV, propType);
912f4a2713aSLionel Sambuc 
913f4a2713aSLionel Sambuc     // objc_getProperty does an autorelease, so we should suppress ours.
914f4a2713aSLionel Sambuc     AutoreleaseResult = false;
915f4a2713aSLionel Sambuc 
916f4a2713aSLionel Sambuc     return;
917f4a2713aSLionel Sambuc   }
918f4a2713aSLionel Sambuc 
919f4a2713aSLionel Sambuc   case PropertyImplStrategy::CopyStruct:
920f4a2713aSLionel Sambuc     emitStructGetterCall(*this, ivar, strategy.isAtomic(),
921f4a2713aSLionel Sambuc                          strategy.hasStrongMember());
922f4a2713aSLionel Sambuc     return;
923f4a2713aSLionel Sambuc 
924f4a2713aSLionel Sambuc   case PropertyImplStrategy::Expression:
925f4a2713aSLionel Sambuc   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
926f4a2713aSLionel Sambuc     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
927f4a2713aSLionel Sambuc 
928f4a2713aSLionel Sambuc     QualType ivarType = ivar->getType();
929f4a2713aSLionel Sambuc     switch (getEvaluationKind(ivarType)) {
930f4a2713aSLionel Sambuc     case TEK_Complex: {
931f4a2713aSLionel Sambuc       ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
932f4a2713aSLionel Sambuc       EmitStoreOfComplex(pair,
933f4a2713aSLionel Sambuc                          MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
934f4a2713aSLionel Sambuc                          /*init*/ true);
935f4a2713aSLionel Sambuc       return;
936f4a2713aSLionel Sambuc     }
937f4a2713aSLionel Sambuc     case TEK_Aggregate:
938f4a2713aSLionel Sambuc       // The return value slot is guaranteed to not be aliased, but
939f4a2713aSLionel Sambuc       // that's not necessarily the same as "on the stack", so
940f4a2713aSLionel Sambuc       // we still potentially need objc_memmove_collectable.
941f4a2713aSLionel Sambuc       EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
942f4a2713aSLionel Sambuc       return;
943f4a2713aSLionel Sambuc     case TEK_Scalar: {
944f4a2713aSLionel Sambuc       llvm::Value *value;
945f4a2713aSLionel Sambuc       if (propType->isReferenceType()) {
946f4a2713aSLionel Sambuc         value = LV.getAddress();
947f4a2713aSLionel Sambuc       } else {
948f4a2713aSLionel Sambuc         // We want to load and autoreleaseReturnValue ARC __weak ivars.
949f4a2713aSLionel Sambuc         if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
950f4a2713aSLionel Sambuc           value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
951f4a2713aSLionel Sambuc 
952f4a2713aSLionel Sambuc         // Otherwise we want to do a simple load, suppressing the
953f4a2713aSLionel Sambuc         // final autorelease.
954f4a2713aSLionel Sambuc         } else {
955f4a2713aSLionel Sambuc           value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
956f4a2713aSLionel Sambuc           AutoreleaseResult = false;
957f4a2713aSLionel Sambuc         }
958f4a2713aSLionel Sambuc 
959f4a2713aSLionel Sambuc         value = Builder.CreateBitCast(value, ConvertType(propType));
960*0a6a1f1dSLionel Sambuc         value = Builder.CreateBitCast(
961*0a6a1f1dSLionel Sambuc             value, ConvertType(GetterMethodDecl->getReturnType()));
962f4a2713aSLionel Sambuc       }
963f4a2713aSLionel Sambuc 
964f4a2713aSLionel Sambuc       EmitReturnOfRValue(RValue::get(value), propType);
965f4a2713aSLionel Sambuc       return;
966f4a2713aSLionel Sambuc     }
967f4a2713aSLionel Sambuc     }
968f4a2713aSLionel Sambuc     llvm_unreachable("bad evaluation kind");
969f4a2713aSLionel Sambuc   }
970f4a2713aSLionel Sambuc 
971f4a2713aSLionel Sambuc   }
972f4a2713aSLionel Sambuc   llvm_unreachable("bad @property implementation strategy!");
973f4a2713aSLionel Sambuc }
974f4a2713aSLionel Sambuc 
975f4a2713aSLionel Sambuc /// emitStructSetterCall - Call the runtime function to store the value
976f4a2713aSLionel Sambuc /// from the first formal parameter into the given ivar.
emitStructSetterCall(CodeGenFunction & CGF,ObjCMethodDecl * OMD,ObjCIvarDecl * ivar)977f4a2713aSLionel Sambuc static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
978f4a2713aSLionel Sambuc                                  ObjCIvarDecl *ivar) {
979f4a2713aSLionel Sambuc   // objc_copyStruct (&structIvar, &Arg,
980f4a2713aSLionel Sambuc   //                  sizeof (struct something), true, false);
981f4a2713aSLionel Sambuc   CallArgList args;
982f4a2713aSLionel Sambuc 
983f4a2713aSLionel Sambuc   // The first argument is the address of the ivar.
984f4a2713aSLionel Sambuc   llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
985f4a2713aSLionel Sambuc                                                 CGF.LoadObjCSelf(), ivar, 0)
986f4a2713aSLionel Sambuc     .getAddress();
987f4a2713aSLionel Sambuc   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
988f4a2713aSLionel Sambuc   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
989f4a2713aSLionel Sambuc 
990f4a2713aSLionel Sambuc   // The second argument is the address of the parameter variable.
991f4a2713aSLionel Sambuc   ParmVarDecl *argVar = *OMD->param_begin();
992f4a2713aSLionel Sambuc   DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
993f4a2713aSLionel Sambuc                      VK_LValue, SourceLocation());
994f4a2713aSLionel Sambuc   llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
995f4a2713aSLionel Sambuc   argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
996f4a2713aSLionel Sambuc   args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
997f4a2713aSLionel Sambuc 
998f4a2713aSLionel Sambuc   // The third argument is the sizeof the type.
999f4a2713aSLionel Sambuc   llvm::Value *size =
1000f4a2713aSLionel Sambuc     CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1001f4a2713aSLionel Sambuc   args.add(RValue::get(size), CGF.getContext().getSizeType());
1002f4a2713aSLionel Sambuc 
1003f4a2713aSLionel Sambuc   // The fourth argument is the 'isAtomic' flag.
1004f4a2713aSLionel Sambuc   args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1005f4a2713aSLionel Sambuc 
1006f4a2713aSLionel Sambuc   // The fifth argument is the 'hasStrong' flag.
1007f4a2713aSLionel Sambuc   // FIXME: should this really always be false?
1008f4a2713aSLionel Sambuc   args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1009f4a2713aSLionel Sambuc 
1010f4a2713aSLionel Sambuc   llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1011f4a2713aSLionel Sambuc   CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1012f4a2713aSLionel Sambuc                                                       args,
1013f4a2713aSLionel Sambuc                                                       FunctionType::ExtInfo(),
1014f4a2713aSLionel Sambuc                                                       RequiredArgs::All),
1015f4a2713aSLionel Sambuc                copyStructFn, ReturnValueSlot(), args);
1016f4a2713aSLionel Sambuc }
1017f4a2713aSLionel Sambuc 
1018f4a2713aSLionel Sambuc /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1019f4a2713aSLionel Sambuc /// the value from the first formal parameter into the given ivar, using
1020f4a2713aSLionel Sambuc /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
emitCPPObjectAtomicSetterCall(CodeGenFunction & CGF,ObjCMethodDecl * OMD,ObjCIvarDecl * ivar,llvm::Constant * AtomicHelperFn)1021f4a2713aSLionel Sambuc static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1022f4a2713aSLionel Sambuc                                           ObjCMethodDecl *OMD,
1023f4a2713aSLionel Sambuc                                           ObjCIvarDecl *ivar,
1024f4a2713aSLionel Sambuc                                           llvm::Constant *AtomicHelperFn) {
1025f4a2713aSLionel Sambuc   // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1026f4a2713aSLionel Sambuc   //                           AtomicHelperFn);
1027f4a2713aSLionel Sambuc   CallArgList args;
1028f4a2713aSLionel Sambuc 
1029f4a2713aSLionel Sambuc   // The first argument is the address of the ivar.
1030f4a2713aSLionel Sambuc   llvm::Value *ivarAddr =
1031f4a2713aSLionel Sambuc     CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1032f4a2713aSLionel Sambuc                           CGF.LoadObjCSelf(), ivar, 0).getAddress();
1033f4a2713aSLionel Sambuc   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1034f4a2713aSLionel Sambuc   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1035f4a2713aSLionel Sambuc 
1036f4a2713aSLionel Sambuc   // The second argument is the address of the parameter variable.
1037f4a2713aSLionel Sambuc   ParmVarDecl *argVar = *OMD->param_begin();
1038f4a2713aSLionel Sambuc   DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
1039f4a2713aSLionel Sambuc                      VK_LValue, SourceLocation());
1040f4a2713aSLionel Sambuc   llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1041f4a2713aSLionel Sambuc   argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1042f4a2713aSLionel Sambuc   args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1043f4a2713aSLionel Sambuc 
1044f4a2713aSLionel Sambuc   // Third argument is the helper function.
1045f4a2713aSLionel Sambuc   args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1046f4a2713aSLionel Sambuc 
1047f4a2713aSLionel Sambuc   llvm::Value *copyCppAtomicObjectFn =
1048f4a2713aSLionel Sambuc     CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1049f4a2713aSLionel Sambuc   CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1050f4a2713aSLionel Sambuc                                                       args,
1051f4a2713aSLionel Sambuc                                                       FunctionType::ExtInfo(),
1052f4a2713aSLionel Sambuc                                                       RequiredArgs::All),
1053f4a2713aSLionel Sambuc                copyCppAtomicObjectFn, ReturnValueSlot(), args);
1054f4a2713aSLionel Sambuc }
1055f4a2713aSLionel Sambuc 
1056f4a2713aSLionel Sambuc 
hasTrivialSetExpr(const ObjCPropertyImplDecl * PID)1057f4a2713aSLionel Sambuc static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1058f4a2713aSLionel Sambuc   Expr *setter = PID->getSetterCXXAssignment();
1059f4a2713aSLionel Sambuc   if (!setter) return true;
1060f4a2713aSLionel Sambuc 
1061f4a2713aSLionel Sambuc   // Sema only makes only of these when the ivar has a C++ class type,
1062f4a2713aSLionel Sambuc   // so the form is pretty constrained.
1063f4a2713aSLionel Sambuc 
1064f4a2713aSLionel Sambuc   // An operator call is trivial if the function it calls is trivial.
1065f4a2713aSLionel Sambuc   // This also implies that there's nothing non-trivial going on with
1066f4a2713aSLionel Sambuc   // the arguments, because operator= can only be trivial if it's a
1067f4a2713aSLionel Sambuc   // synthesized assignment operator and therefore both parameters are
1068f4a2713aSLionel Sambuc   // references.
1069f4a2713aSLionel Sambuc   if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1070f4a2713aSLionel Sambuc     if (const FunctionDecl *callee
1071f4a2713aSLionel Sambuc           = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1072f4a2713aSLionel Sambuc       if (callee->isTrivial())
1073f4a2713aSLionel Sambuc         return true;
1074f4a2713aSLionel Sambuc     return false;
1075f4a2713aSLionel Sambuc   }
1076f4a2713aSLionel Sambuc 
1077f4a2713aSLionel Sambuc   assert(isa<ExprWithCleanups>(setter));
1078f4a2713aSLionel Sambuc   return false;
1079f4a2713aSLionel Sambuc }
1080f4a2713aSLionel Sambuc 
UseOptimizedSetter(CodeGenModule & CGM)1081f4a2713aSLionel Sambuc static bool UseOptimizedSetter(CodeGenModule &CGM) {
1082f4a2713aSLionel Sambuc   if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1083f4a2713aSLionel Sambuc     return false;
1084f4a2713aSLionel Sambuc   return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1085f4a2713aSLionel Sambuc }
1086f4a2713aSLionel Sambuc 
1087f4a2713aSLionel Sambuc void
generateObjCSetterBody(const ObjCImplementationDecl * classImpl,const ObjCPropertyImplDecl * propImpl,llvm::Constant * AtomicHelperFn)1088f4a2713aSLionel Sambuc CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1089f4a2713aSLionel Sambuc                                         const ObjCPropertyImplDecl *propImpl,
1090f4a2713aSLionel Sambuc                                         llvm::Constant *AtomicHelperFn) {
1091f4a2713aSLionel Sambuc   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1092f4a2713aSLionel Sambuc   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1093f4a2713aSLionel Sambuc   ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
1094f4a2713aSLionel Sambuc 
1095f4a2713aSLionel Sambuc   // Just use the setter expression if Sema gave us one and it's
1096f4a2713aSLionel Sambuc   // non-trivial.
1097f4a2713aSLionel Sambuc   if (!hasTrivialSetExpr(propImpl)) {
1098f4a2713aSLionel Sambuc     if (!AtomicHelperFn)
1099f4a2713aSLionel Sambuc       // If non-atomic, assignment is called directly.
1100f4a2713aSLionel Sambuc       EmitStmt(propImpl->getSetterCXXAssignment());
1101f4a2713aSLionel Sambuc     else
1102f4a2713aSLionel Sambuc       // If atomic, assignment is called via a locking api.
1103f4a2713aSLionel Sambuc       emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1104f4a2713aSLionel Sambuc                                     AtomicHelperFn);
1105f4a2713aSLionel Sambuc     return;
1106f4a2713aSLionel Sambuc   }
1107f4a2713aSLionel Sambuc 
1108f4a2713aSLionel Sambuc   PropertyImplStrategy strategy(CGM, propImpl);
1109f4a2713aSLionel Sambuc   switch (strategy.getKind()) {
1110f4a2713aSLionel Sambuc   case PropertyImplStrategy::Native: {
1111f4a2713aSLionel Sambuc     // We don't need to do anything for a zero-size struct.
1112f4a2713aSLionel Sambuc     if (strategy.getIvarSize().isZero())
1113f4a2713aSLionel Sambuc       return;
1114f4a2713aSLionel Sambuc 
1115f4a2713aSLionel Sambuc     llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
1116f4a2713aSLionel Sambuc 
1117f4a2713aSLionel Sambuc     LValue ivarLValue =
1118f4a2713aSLionel Sambuc       EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1119f4a2713aSLionel Sambuc     llvm::Value *ivarAddr = ivarLValue.getAddress();
1120f4a2713aSLionel Sambuc 
1121f4a2713aSLionel Sambuc     // Currently, all atomic accesses have to be through integer
1122f4a2713aSLionel Sambuc     // types, so there's no point in trying to pick a prettier type.
1123f4a2713aSLionel Sambuc     llvm::Type *bitcastType =
1124f4a2713aSLionel Sambuc       llvm::Type::getIntNTy(getLLVMContext(),
1125f4a2713aSLionel Sambuc                             getContext().toBits(strategy.getIvarSize()));
1126f4a2713aSLionel Sambuc     bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1127f4a2713aSLionel Sambuc 
1128f4a2713aSLionel Sambuc     // Cast both arguments to the chosen operation type.
1129f4a2713aSLionel Sambuc     argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1130f4a2713aSLionel Sambuc     ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1131f4a2713aSLionel Sambuc 
1132f4a2713aSLionel Sambuc     // This bitcast load is likely to cause some nasty IR.
1133f4a2713aSLionel Sambuc     llvm::Value *load = Builder.CreateLoad(argAddr);
1134f4a2713aSLionel Sambuc 
1135f4a2713aSLionel Sambuc     // Perform an atomic store.  There are no memory ordering requirements.
1136f4a2713aSLionel Sambuc     llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1137f4a2713aSLionel Sambuc     store->setAlignment(strategy.getIvarAlignment().getQuantity());
1138f4a2713aSLionel Sambuc     store->setAtomic(llvm::Unordered);
1139f4a2713aSLionel Sambuc     return;
1140f4a2713aSLionel Sambuc   }
1141f4a2713aSLionel Sambuc 
1142f4a2713aSLionel Sambuc   case PropertyImplStrategy::GetSetProperty:
1143f4a2713aSLionel Sambuc   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1144f4a2713aSLionel Sambuc 
1145*0a6a1f1dSLionel Sambuc     llvm::Value *setOptimizedPropertyFn = nullptr;
1146*0a6a1f1dSLionel Sambuc     llvm::Value *setPropertyFn = nullptr;
1147f4a2713aSLionel Sambuc     if (UseOptimizedSetter(CGM)) {
1148f4a2713aSLionel Sambuc       // 10.8 and iOS 6.0 code and GC is off
1149f4a2713aSLionel Sambuc       setOptimizedPropertyFn =
1150f4a2713aSLionel Sambuc         CGM.getObjCRuntime()
1151f4a2713aSLionel Sambuc            .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1152f4a2713aSLionel Sambuc                                             strategy.isCopy());
1153f4a2713aSLionel Sambuc       if (!setOptimizedPropertyFn) {
1154f4a2713aSLionel Sambuc         CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1155f4a2713aSLionel Sambuc         return;
1156f4a2713aSLionel Sambuc       }
1157f4a2713aSLionel Sambuc     }
1158f4a2713aSLionel Sambuc     else {
1159f4a2713aSLionel Sambuc       setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1160f4a2713aSLionel Sambuc       if (!setPropertyFn) {
1161f4a2713aSLionel Sambuc         CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1162f4a2713aSLionel Sambuc         return;
1163f4a2713aSLionel Sambuc       }
1164f4a2713aSLionel Sambuc     }
1165f4a2713aSLionel Sambuc 
1166f4a2713aSLionel Sambuc     // Emit objc_setProperty((id) self, _cmd, offset, arg,
1167f4a2713aSLionel Sambuc     //                       <is-atomic>, <is-copy>).
1168f4a2713aSLionel Sambuc     llvm::Value *cmd =
1169f4a2713aSLionel Sambuc       Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1170f4a2713aSLionel Sambuc     llvm::Value *self =
1171f4a2713aSLionel Sambuc       Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1172f4a2713aSLionel Sambuc     llvm::Value *ivarOffset =
1173f4a2713aSLionel Sambuc       EmitIvarOffset(classImpl->getClassInterface(), ivar);
1174f4a2713aSLionel Sambuc     llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1175f4a2713aSLionel Sambuc     arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1176f4a2713aSLionel Sambuc 
1177f4a2713aSLionel Sambuc     CallArgList args;
1178f4a2713aSLionel Sambuc     args.add(RValue::get(self), getContext().getObjCIdType());
1179f4a2713aSLionel Sambuc     args.add(RValue::get(cmd), getContext().getObjCSelType());
1180f4a2713aSLionel Sambuc     if (setOptimizedPropertyFn) {
1181f4a2713aSLionel Sambuc       args.add(RValue::get(arg), getContext().getObjCIdType());
1182f4a2713aSLionel Sambuc       args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1183f4a2713aSLionel Sambuc       EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1184f4a2713aSLionel Sambuc                                                   FunctionType::ExtInfo(),
1185f4a2713aSLionel Sambuc                                                   RequiredArgs::All),
1186f4a2713aSLionel Sambuc                setOptimizedPropertyFn, ReturnValueSlot(), args);
1187f4a2713aSLionel Sambuc     } else {
1188f4a2713aSLionel Sambuc       args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1189f4a2713aSLionel Sambuc       args.add(RValue::get(arg), getContext().getObjCIdType());
1190f4a2713aSLionel Sambuc       args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1191f4a2713aSLionel Sambuc                getContext().BoolTy);
1192f4a2713aSLionel Sambuc       args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1193f4a2713aSLionel Sambuc                getContext().BoolTy);
1194f4a2713aSLionel Sambuc       // FIXME: We shouldn't need to get the function info here, the runtime
1195f4a2713aSLionel Sambuc       // already should have computed it to build the function.
1196f4a2713aSLionel Sambuc       EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1197f4a2713aSLionel Sambuc                                                   FunctionType::ExtInfo(),
1198f4a2713aSLionel Sambuc                                                   RequiredArgs::All),
1199f4a2713aSLionel Sambuc                setPropertyFn, ReturnValueSlot(), args);
1200f4a2713aSLionel Sambuc     }
1201f4a2713aSLionel Sambuc 
1202f4a2713aSLionel Sambuc     return;
1203f4a2713aSLionel Sambuc   }
1204f4a2713aSLionel Sambuc 
1205f4a2713aSLionel Sambuc   case PropertyImplStrategy::CopyStruct:
1206f4a2713aSLionel Sambuc     emitStructSetterCall(*this, setterMethod, ivar);
1207f4a2713aSLionel Sambuc     return;
1208f4a2713aSLionel Sambuc 
1209f4a2713aSLionel Sambuc   case PropertyImplStrategy::Expression:
1210f4a2713aSLionel Sambuc     break;
1211f4a2713aSLionel Sambuc   }
1212f4a2713aSLionel Sambuc 
1213f4a2713aSLionel Sambuc   // Otherwise, fake up some ASTs and emit a normal assignment.
1214f4a2713aSLionel Sambuc   ValueDecl *selfDecl = setterMethod->getSelfDecl();
1215f4a2713aSLionel Sambuc   DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1216f4a2713aSLionel Sambuc                    VK_LValue, SourceLocation());
1217f4a2713aSLionel Sambuc   ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1218f4a2713aSLionel Sambuc                             selfDecl->getType(), CK_LValueToRValue, &self,
1219f4a2713aSLionel Sambuc                             VK_RValue);
1220f4a2713aSLionel Sambuc   ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1221f4a2713aSLionel Sambuc                           SourceLocation(), SourceLocation(),
1222f4a2713aSLionel Sambuc                           &selfLoad, true, true);
1223f4a2713aSLionel Sambuc 
1224f4a2713aSLionel Sambuc   ParmVarDecl *argDecl = *setterMethod->param_begin();
1225f4a2713aSLionel Sambuc   QualType argType = argDecl->getType().getNonReferenceType();
1226f4a2713aSLionel Sambuc   DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
1227f4a2713aSLionel Sambuc   ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1228f4a2713aSLionel Sambuc                            argType.getUnqualifiedType(), CK_LValueToRValue,
1229f4a2713aSLionel Sambuc                            &arg, VK_RValue);
1230f4a2713aSLionel Sambuc 
1231f4a2713aSLionel Sambuc   // The property type can differ from the ivar type in some situations with
1232f4a2713aSLionel Sambuc   // Objective-C pointer types, we can always bit cast the RHS in these cases.
1233f4a2713aSLionel Sambuc   // The following absurdity is just to ensure well-formed IR.
1234f4a2713aSLionel Sambuc   CastKind argCK = CK_NoOp;
1235f4a2713aSLionel Sambuc   if (ivarRef.getType()->isObjCObjectPointerType()) {
1236f4a2713aSLionel Sambuc     if (argLoad.getType()->isObjCObjectPointerType())
1237f4a2713aSLionel Sambuc       argCK = CK_BitCast;
1238f4a2713aSLionel Sambuc     else if (argLoad.getType()->isBlockPointerType())
1239f4a2713aSLionel Sambuc       argCK = CK_BlockPointerToObjCPointerCast;
1240f4a2713aSLionel Sambuc     else
1241f4a2713aSLionel Sambuc       argCK = CK_CPointerToObjCPointerCast;
1242f4a2713aSLionel Sambuc   } else if (ivarRef.getType()->isBlockPointerType()) {
1243f4a2713aSLionel Sambuc      if (argLoad.getType()->isBlockPointerType())
1244f4a2713aSLionel Sambuc       argCK = CK_BitCast;
1245f4a2713aSLionel Sambuc     else
1246f4a2713aSLionel Sambuc       argCK = CK_AnyPointerToBlockPointerCast;
1247f4a2713aSLionel Sambuc   } else if (ivarRef.getType()->isPointerType()) {
1248f4a2713aSLionel Sambuc     argCK = CK_BitCast;
1249f4a2713aSLionel Sambuc   }
1250f4a2713aSLionel Sambuc   ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1251f4a2713aSLionel Sambuc                            ivarRef.getType(), argCK, &argLoad,
1252f4a2713aSLionel Sambuc                            VK_RValue);
1253f4a2713aSLionel Sambuc   Expr *finalArg = &argLoad;
1254f4a2713aSLionel Sambuc   if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1255f4a2713aSLionel Sambuc                                            argLoad.getType()))
1256f4a2713aSLionel Sambuc     finalArg = &argCast;
1257f4a2713aSLionel Sambuc 
1258f4a2713aSLionel Sambuc 
1259f4a2713aSLionel Sambuc   BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1260f4a2713aSLionel Sambuc                         ivarRef.getType(), VK_RValue, OK_Ordinary,
1261f4a2713aSLionel Sambuc                         SourceLocation(), false);
1262f4a2713aSLionel Sambuc   EmitStmt(&assign);
1263f4a2713aSLionel Sambuc }
1264f4a2713aSLionel Sambuc 
1265f4a2713aSLionel Sambuc /// \brief Generate an Objective-C property setter function.
1266f4a2713aSLionel Sambuc ///
1267f4a2713aSLionel Sambuc /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1268f4a2713aSLionel Sambuc /// is illegal within a category.
GenerateObjCSetter(ObjCImplementationDecl * IMP,const ObjCPropertyImplDecl * PID)1269f4a2713aSLionel Sambuc void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1270f4a2713aSLionel Sambuc                                          const ObjCPropertyImplDecl *PID) {
1271f4a2713aSLionel Sambuc   llvm::Constant *AtomicHelperFn =
1272*0a6a1f1dSLionel Sambuc       CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1273f4a2713aSLionel Sambuc   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1274f4a2713aSLionel Sambuc   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1275f4a2713aSLionel Sambuc   assert(OMD && "Invalid call to generate setter (empty method)");
1276*0a6a1f1dSLionel Sambuc   StartObjCMethod(OMD, IMP->getClassInterface());
1277f4a2713aSLionel Sambuc 
1278f4a2713aSLionel Sambuc   generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1279f4a2713aSLionel Sambuc 
1280f4a2713aSLionel Sambuc   FinishFunction();
1281f4a2713aSLionel Sambuc }
1282f4a2713aSLionel Sambuc 
1283f4a2713aSLionel Sambuc namespace {
1284f4a2713aSLionel Sambuc   struct DestroyIvar : EHScopeStack::Cleanup {
1285f4a2713aSLionel Sambuc   private:
1286f4a2713aSLionel Sambuc     llvm::Value *addr;
1287f4a2713aSLionel Sambuc     const ObjCIvarDecl *ivar;
1288f4a2713aSLionel Sambuc     CodeGenFunction::Destroyer *destroyer;
1289f4a2713aSLionel Sambuc     bool useEHCleanupForArray;
1290f4a2713aSLionel Sambuc   public:
DestroyIvar__anon86dbc8190311::DestroyIvar1291f4a2713aSLionel Sambuc     DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1292f4a2713aSLionel Sambuc                 CodeGenFunction::Destroyer *destroyer,
1293f4a2713aSLionel Sambuc                 bool useEHCleanupForArray)
1294f4a2713aSLionel Sambuc       : addr(addr), ivar(ivar), destroyer(destroyer),
1295f4a2713aSLionel Sambuc         useEHCleanupForArray(useEHCleanupForArray) {}
1296f4a2713aSLionel Sambuc 
Emit__anon86dbc8190311::DestroyIvar1297*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1298f4a2713aSLionel Sambuc       LValue lvalue
1299f4a2713aSLionel Sambuc         = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1300f4a2713aSLionel Sambuc       CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
1301f4a2713aSLionel Sambuc                       flags.isForNormalCleanup() && useEHCleanupForArray);
1302f4a2713aSLionel Sambuc     }
1303f4a2713aSLionel Sambuc   };
1304f4a2713aSLionel Sambuc }
1305f4a2713aSLionel Sambuc 
1306f4a2713aSLionel Sambuc /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
destroyARCStrongWithStore(CodeGenFunction & CGF,llvm::Value * addr,QualType type)1307f4a2713aSLionel Sambuc static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1308f4a2713aSLionel Sambuc                                       llvm::Value *addr,
1309f4a2713aSLionel Sambuc                                       QualType type) {
1310f4a2713aSLionel Sambuc   llvm::Value *null = getNullForVariable(addr);
1311f4a2713aSLionel Sambuc   CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1312f4a2713aSLionel Sambuc }
1313f4a2713aSLionel Sambuc 
emitCXXDestructMethod(CodeGenFunction & CGF,ObjCImplementationDecl * impl)1314f4a2713aSLionel Sambuc static void emitCXXDestructMethod(CodeGenFunction &CGF,
1315f4a2713aSLionel Sambuc                                   ObjCImplementationDecl *impl) {
1316f4a2713aSLionel Sambuc   CodeGenFunction::RunCleanupsScope scope(CGF);
1317f4a2713aSLionel Sambuc 
1318f4a2713aSLionel Sambuc   llvm::Value *self = CGF.LoadObjCSelf();
1319f4a2713aSLionel Sambuc 
1320f4a2713aSLionel Sambuc   const ObjCInterfaceDecl *iface = impl->getClassInterface();
1321f4a2713aSLionel Sambuc   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1322f4a2713aSLionel Sambuc        ivar; ivar = ivar->getNextIvar()) {
1323f4a2713aSLionel Sambuc     QualType type = ivar->getType();
1324f4a2713aSLionel Sambuc 
1325f4a2713aSLionel Sambuc     // Check whether the ivar is a destructible type.
1326f4a2713aSLionel Sambuc     QualType::DestructionKind dtorKind = type.isDestructedType();
1327f4a2713aSLionel Sambuc     if (!dtorKind) continue;
1328f4a2713aSLionel Sambuc 
1329*0a6a1f1dSLionel Sambuc     CodeGenFunction::Destroyer *destroyer = nullptr;
1330f4a2713aSLionel Sambuc 
1331f4a2713aSLionel Sambuc     // Use a call to objc_storeStrong to destroy strong ivars, for the
1332f4a2713aSLionel Sambuc     // general benefit of the tools.
1333f4a2713aSLionel Sambuc     if (dtorKind == QualType::DK_objc_strong_lifetime) {
1334f4a2713aSLionel Sambuc       destroyer = destroyARCStrongWithStore;
1335f4a2713aSLionel Sambuc 
1336f4a2713aSLionel Sambuc     // Otherwise use the default for the destruction kind.
1337f4a2713aSLionel Sambuc     } else {
1338f4a2713aSLionel Sambuc       destroyer = CGF.getDestroyer(dtorKind);
1339f4a2713aSLionel Sambuc     }
1340f4a2713aSLionel Sambuc 
1341f4a2713aSLionel Sambuc     CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1342f4a2713aSLionel Sambuc 
1343f4a2713aSLionel Sambuc     CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1344f4a2713aSLionel Sambuc                                          cleanupKind & EHCleanup);
1345f4a2713aSLionel Sambuc   }
1346f4a2713aSLionel Sambuc 
1347f4a2713aSLionel Sambuc   assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1348f4a2713aSLionel Sambuc }
1349f4a2713aSLionel Sambuc 
GenerateObjCCtorDtorMethod(ObjCImplementationDecl * IMP,ObjCMethodDecl * MD,bool ctor)1350f4a2713aSLionel Sambuc void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1351f4a2713aSLionel Sambuc                                                  ObjCMethodDecl *MD,
1352f4a2713aSLionel Sambuc                                                  bool ctor) {
1353f4a2713aSLionel Sambuc   MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1354*0a6a1f1dSLionel Sambuc   StartObjCMethod(MD, IMP->getClassInterface());
1355f4a2713aSLionel Sambuc 
1356f4a2713aSLionel Sambuc   // Emit .cxx_construct.
1357f4a2713aSLionel Sambuc   if (ctor) {
1358f4a2713aSLionel Sambuc     // Suppress the final autorelease in ARC.
1359f4a2713aSLionel Sambuc     AutoreleaseResult = false;
1360f4a2713aSLionel Sambuc 
1361*0a6a1f1dSLionel Sambuc     for (const auto *IvarInit : IMP->inits()) {
1362f4a2713aSLionel Sambuc       FieldDecl *Field = IvarInit->getAnyMember();
1363f4a2713aSLionel Sambuc       ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1364f4a2713aSLionel Sambuc       LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1365f4a2713aSLionel Sambuc                                     LoadObjCSelf(), Ivar, 0);
1366f4a2713aSLionel Sambuc       EmitAggExpr(IvarInit->getInit(),
1367f4a2713aSLionel Sambuc                   AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
1368f4a2713aSLionel Sambuc                                           AggValueSlot::DoesNotNeedGCBarriers,
1369f4a2713aSLionel Sambuc                                           AggValueSlot::IsNotAliased));
1370f4a2713aSLionel Sambuc     }
1371f4a2713aSLionel Sambuc     // constructor returns 'self'.
1372f4a2713aSLionel Sambuc     CodeGenTypes &Types = CGM.getTypes();
1373f4a2713aSLionel Sambuc     QualType IdTy(CGM.getContext().getObjCIdType());
1374f4a2713aSLionel Sambuc     llvm::Value *SelfAsId =
1375f4a2713aSLionel Sambuc       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1376f4a2713aSLionel Sambuc     EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1377f4a2713aSLionel Sambuc 
1378f4a2713aSLionel Sambuc   // Emit .cxx_destruct.
1379f4a2713aSLionel Sambuc   } else {
1380f4a2713aSLionel Sambuc     emitCXXDestructMethod(*this, IMP);
1381f4a2713aSLionel Sambuc   }
1382f4a2713aSLionel Sambuc   FinishFunction();
1383f4a2713aSLionel Sambuc }
1384f4a2713aSLionel Sambuc 
IndirectObjCSetterArg(const CGFunctionInfo & FI)1385f4a2713aSLionel Sambuc bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1386f4a2713aSLionel Sambuc   CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1387f4a2713aSLionel Sambuc   it++; it++;
1388f4a2713aSLionel Sambuc   const ABIArgInfo &AI = it->info;
1389f4a2713aSLionel Sambuc   // FIXME. Is this sufficient check?
1390f4a2713aSLionel Sambuc   return (AI.getKind() == ABIArgInfo::Indirect);
1391f4a2713aSLionel Sambuc }
1392f4a2713aSLionel Sambuc 
IvarTypeWithAggrGCObjects(QualType Ty)1393f4a2713aSLionel Sambuc bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1394f4a2713aSLionel Sambuc   if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
1395f4a2713aSLionel Sambuc     return false;
1396f4a2713aSLionel Sambuc   if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1397f4a2713aSLionel Sambuc     return FDTTy->getDecl()->hasObjectMember();
1398f4a2713aSLionel Sambuc   return false;
1399f4a2713aSLionel Sambuc }
1400f4a2713aSLionel Sambuc 
LoadObjCSelf()1401f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::LoadObjCSelf() {
1402f4a2713aSLionel Sambuc   VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1403f4a2713aSLionel Sambuc   DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1404f4a2713aSLionel Sambuc                   Self->getType(), VK_LValue, SourceLocation());
1405f4a2713aSLionel Sambuc   return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1406f4a2713aSLionel Sambuc }
1407f4a2713aSLionel Sambuc 
TypeOfSelfObject()1408f4a2713aSLionel Sambuc QualType CodeGenFunction::TypeOfSelfObject() {
1409f4a2713aSLionel Sambuc   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1410f4a2713aSLionel Sambuc   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1411f4a2713aSLionel Sambuc   const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1412f4a2713aSLionel Sambuc     getContext().getCanonicalType(selfDecl->getType()));
1413f4a2713aSLionel Sambuc   return PTy->getPointeeType();
1414f4a2713aSLionel Sambuc }
1415f4a2713aSLionel Sambuc 
EmitObjCForCollectionStmt(const ObjCForCollectionStmt & S)1416f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1417f4a2713aSLionel Sambuc   llvm::Constant *EnumerationMutationFn =
1418f4a2713aSLionel Sambuc     CGM.getObjCRuntime().EnumerationMutationFunction();
1419f4a2713aSLionel Sambuc 
1420f4a2713aSLionel Sambuc   if (!EnumerationMutationFn) {
1421f4a2713aSLionel Sambuc     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1422f4a2713aSLionel Sambuc     return;
1423f4a2713aSLionel Sambuc   }
1424f4a2713aSLionel Sambuc 
1425f4a2713aSLionel Sambuc   CGDebugInfo *DI = getDebugInfo();
1426f4a2713aSLionel Sambuc   if (DI)
1427f4a2713aSLionel Sambuc     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1428f4a2713aSLionel Sambuc 
1429f4a2713aSLionel Sambuc   // The local variable comes into scope immediately.
1430f4a2713aSLionel Sambuc   AutoVarEmission variable = AutoVarEmission::invalid();
1431f4a2713aSLionel Sambuc   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1432f4a2713aSLionel Sambuc     variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1433f4a2713aSLionel Sambuc 
1434f4a2713aSLionel Sambuc   JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1435f4a2713aSLionel Sambuc 
1436f4a2713aSLionel Sambuc   // Fast enumeration state.
1437f4a2713aSLionel Sambuc   QualType StateTy = CGM.getObjCFastEnumerationStateType();
1438f4a2713aSLionel Sambuc   llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
1439f4a2713aSLionel Sambuc   EmitNullInitialization(StatePtr, StateTy);
1440f4a2713aSLionel Sambuc 
1441f4a2713aSLionel Sambuc   // Number of elements in the items array.
1442f4a2713aSLionel Sambuc   static const unsigned NumItems = 16;
1443f4a2713aSLionel Sambuc 
1444f4a2713aSLionel Sambuc   // Fetch the countByEnumeratingWithState:objects:count: selector.
1445f4a2713aSLionel Sambuc   IdentifierInfo *II[] = {
1446f4a2713aSLionel Sambuc     &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1447f4a2713aSLionel Sambuc     &CGM.getContext().Idents.get("objects"),
1448f4a2713aSLionel Sambuc     &CGM.getContext().Idents.get("count")
1449f4a2713aSLionel Sambuc   };
1450f4a2713aSLionel Sambuc   Selector FastEnumSel =
1451f4a2713aSLionel Sambuc     CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1452f4a2713aSLionel Sambuc 
1453f4a2713aSLionel Sambuc   QualType ItemsTy =
1454f4a2713aSLionel Sambuc     getContext().getConstantArrayType(getContext().getObjCIdType(),
1455f4a2713aSLionel Sambuc                                       llvm::APInt(32, NumItems),
1456f4a2713aSLionel Sambuc                                       ArrayType::Normal, 0);
1457f4a2713aSLionel Sambuc   llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1458f4a2713aSLionel Sambuc 
1459f4a2713aSLionel Sambuc   // Emit the collection pointer.  In ARC, we do a retain.
1460f4a2713aSLionel Sambuc   llvm::Value *Collection;
1461f4a2713aSLionel Sambuc   if (getLangOpts().ObjCAutoRefCount) {
1462f4a2713aSLionel Sambuc     Collection = EmitARCRetainScalarExpr(S.getCollection());
1463f4a2713aSLionel Sambuc 
1464f4a2713aSLionel Sambuc     // Enter a cleanup to do the release.
1465f4a2713aSLionel Sambuc     EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1466f4a2713aSLionel Sambuc   } else {
1467f4a2713aSLionel Sambuc     Collection = EmitScalarExpr(S.getCollection());
1468f4a2713aSLionel Sambuc   }
1469f4a2713aSLionel Sambuc 
1470f4a2713aSLionel Sambuc   // The 'continue' label needs to appear within the cleanup for the
1471f4a2713aSLionel Sambuc   // collection object.
1472f4a2713aSLionel Sambuc   JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1473f4a2713aSLionel Sambuc 
1474f4a2713aSLionel Sambuc   // Send it our message:
1475f4a2713aSLionel Sambuc   CallArgList Args;
1476f4a2713aSLionel Sambuc 
1477f4a2713aSLionel Sambuc   // The first argument is a temporary of the enumeration-state type.
1478f4a2713aSLionel Sambuc   Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
1479f4a2713aSLionel Sambuc 
1480f4a2713aSLionel Sambuc   // The second argument is a temporary array with space for NumItems
1481f4a2713aSLionel Sambuc   // pointers.  We'll actually be loading elements from the array
1482f4a2713aSLionel Sambuc   // pointer written into the control state; this buffer is so that
1483f4a2713aSLionel Sambuc   // collections that *aren't* backed by arrays can still queue up
1484f4a2713aSLionel Sambuc   // batches of elements.
1485f4a2713aSLionel Sambuc   Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
1486f4a2713aSLionel Sambuc 
1487f4a2713aSLionel Sambuc   // The third argument is the capacity of that temporary array.
1488f4a2713aSLionel Sambuc   llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
1489f4a2713aSLionel Sambuc   llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
1490f4a2713aSLionel Sambuc   Args.add(RValue::get(Count), getContext().UnsignedLongTy);
1491f4a2713aSLionel Sambuc 
1492f4a2713aSLionel Sambuc   // Start the enumeration.
1493f4a2713aSLionel Sambuc   RValue CountRV =
1494f4a2713aSLionel Sambuc     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1495f4a2713aSLionel Sambuc                                              getContext().UnsignedLongTy,
1496f4a2713aSLionel Sambuc                                              FastEnumSel,
1497f4a2713aSLionel Sambuc                                              Collection, Args);
1498f4a2713aSLionel Sambuc 
1499f4a2713aSLionel Sambuc   // The initial number of objects that were returned in the buffer.
1500f4a2713aSLionel Sambuc   llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1501f4a2713aSLionel Sambuc 
1502f4a2713aSLionel Sambuc   llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1503f4a2713aSLionel Sambuc   llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1504f4a2713aSLionel Sambuc 
1505f4a2713aSLionel Sambuc   llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
1506f4a2713aSLionel Sambuc 
1507f4a2713aSLionel Sambuc   // If the limit pointer was zero to begin with, the collection is
1508*0a6a1f1dSLionel Sambuc   // empty; skip all this. Set the branch weight assuming this has the same
1509*0a6a1f1dSLionel Sambuc   // probability of exiting the loop as any other loop exit.
1510*0a6a1f1dSLionel Sambuc   uint64_t EntryCount = PGO.getCurrentRegionCount();
1511*0a6a1f1dSLionel Sambuc   RegionCounter Cnt = getPGORegionCounter(&S);
1512f4a2713aSLionel Sambuc   Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1513*0a6a1f1dSLionel Sambuc                        EmptyBB, LoopInitBB,
1514*0a6a1f1dSLionel Sambuc                        PGO.createBranchWeights(EntryCount, Cnt.getCount()));
1515f4a2713aSLionel Sambuc 
1516f4a2713aSLionel Sambuc   // Otherwise, initialize the loop.
1517f4a2713aSLionel Sambuc   EmitBlock(LoopInitBB);
1518f4a2713aSLionel Sambuc 
1519f4a2713aSLionel Sambuc   // Save the initial mutations value.  This is the value at an
1520f4a2713aSLionel Sambuc   // address that was written into the state object by
1521f4a2713aSLionel Sambuc   // countByEnumeratingWithState:objects:count:.
1522f4a2713aSLionel Sambuc   llvm::Value *StateMutationsPtrPtr =
1523f4a2713aSLionel Sambuc     Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1524f4a2713aSLionel Sambuc   llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
1525f4a2713aSLionel Sambuc                                                       "mutationsptr");
1526f4a2713aSLionel Sambuc 
1527f4a2713aSLionel Sambuc   llvm::Value *initialMutations =
1528f4a2713aSLionel Sambuc     Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
1529f4a2713aSLionel Sambuc 
1530f4a2713aSLionel Sambuc   // Start looping.  This is the point we return to whenever we have a
1531f4a2713aSLionel Sambuc   // fresh, non-empty batch of objects.
1532f4a2713aSLionel Sambuc   llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1533f4a2713aSLionel Sambuc   EmitBlock(LoopBodyBB);
1534f4a2713aSLionel Sambuc 
1535f4a2713aSLionel Sambuc   // The current index into the buffer.
1536f4a2713aSLionel Sambuc   llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
1537f4a2713aSLionel Sambuc   index->addIncoming(zero, LoopInitBB);
1538f4a2713aSLionel Sambuc 
1539f4a2713aSLionel Sambuc   // The current buffer size.
1540f4a2713aSLionel Sambuc   llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
1541f4a2713aSLionel Sambuc   count->addIncoming(initialBufferLimit, LoopInitBB);
1542f4a2713aSLionel Sambuc 
1543*0a6a1f1dSLionel Sambuc   Cnt.beginRegion(Builder);
1544*0a6a1f1dSLionel Sambuc 
1545f4a2713aSLionel Sambuc   // Check whether the mutations value has changed from where it was
1546f4a2713aSLionel Sambuc   // at start.  StateMutationsPtr should actually be invariant between
1547f4a2713aSLionel Sambuc   // refreshes.
1548f4a2713aSLionel Sambuc   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1549f4a2713aSLionel Sambuc   llvm::Value *currentMutations
1550f4a2713aSLionel Sambuc     = Builder.CreateLoad(StateMutationsPtr, "statemutations");
1551f4a2713aSLionel Sambuc 
1552f4a2713aSLionel Sambuc   llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1553f4a2713aSLionel Sambuc   llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1554f4a2713aSLionel Sambuc 
1555f4a2713aSLionel Sambuc   Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1556f4a2713aSLionel Sambuc                        WasNotMutatedBB, WasMutatedBB);
1557f4a2713aSLionel Sambuc 
1558f4a2713aSLionel Sambuc   // If so, call the enumeration-mutation function.
1559f4a2713aSLionel Sambuc   EmitBlock(WasMutatedBB);
1560f4a2713aSLionel Sambuc   llvm::Value *V =
1561f4a2713aSLionel Sambuc     Builder.CreateBitCast(Collection,
1562f4a2713aSLionel Sambuc                           ConvertType(getContext().getObjCIdType()));
1563f4a2713aSLionel Sambuc   CallArgList Args2;
1564f4a2713aSLionel Sambuc   Args2.add(RValue::get(V), getContext().getObjCIdType());
1565f4a2713aSLionel Sambuc   // FIXME: We shouldn't need to get the function info here, the runtime already
1566f4a2713aSLionel Sambuc   // should have computed it to build the function.
1567f4a2713aSLionel Sambuc   EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1568f4a2713aSLionel Sambuc                                                   FunctionType::ExtInfo(),
1569f4a2713aSLionel Sambuc                                                   RequiredArgs::All),
1570f4a2713aSLionel Sambuc            EnumerationMutationFn, ReturnValueSlot(), Args2);
1571f4a2713aSLionel Sambuc 
1572f4a2713aSLionel Sambuc   // Otherwise, or if the mutation function returns, just continue.
1573f4a2713aSLionel Sambuc   EmitBlock(WasNotMutatedBB);
1574f4a2713aSLionel Sambuc 
1575f4a2713aSLionel Sambuc   // Initialize the element variable.
1576f4a2713aSLionel Sambuc   RunCleanupsScope elementVariableScope(*this);
1577f4a2713aSLionel Sambuc   bool elementIsVariable;
1578f4a2713aSLionel Sambuc   LValue elementLValue;
1579f4a2713aSLionel Sambuc   QualType elementType;
1580f4a2713aSLionel Sambuc   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1581f4a2713aSLionel Sambuc     // Initialize the variable, in case it's a __block variable or something.
1582f4a2713aSLionel Sambuc     EmitAutoVarInit(variable);
1583f4a2713aSLionel Sambuc 
1584f4a2713aSLionel Sambuc     const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1585f4a2713aSLionel Sambuc     DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
1586f4a2713aSLionel Sambuc                         VK_LValue, SourceLocation());
1587f4a2713aSLionel Sambuc     elementLValue = EmitLValue(&tempDRE);
1588f4a2713aSLionel Sambuc     elementType = D->getType();
1589f4a2713aSLionel Sambuc     elementIsVariable = true;
1590f4a2713aSLionel Sambuc 
1591f4a2713aSLionel Sambuc     if (D->isARCPseudoStrong())
1592f4a2713aSLionel Sambuc       elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1593f4a2713aSLionel Sambuc   } else {
1594f4a2713aSLionel Sambuc     elementLValue = LValue(); // suppress warning
1595f4a2713aSLionel Sambuc     elementType = cast<Expr>(S.getElement())->getType();
1596f4a2713aSLionel Sambuc     elementIsVariable = false;
1597f4a2713aSLionel Sambuc   }
1598f4a2713aSLionel Sambuc   llvm::Type *convertedElementType = ConvertType(elementType);
1599f4a2713aSLionel Sambuc 
1600f4a2713aSLionel Sambuc   // Fetch the buffer out of the enumeration state.
1601f4a2713aSLionel Sambuc   // TODO: this pointer should actually be invariant between
1602f4a2713aSLionel Sambuc   // refreshes, which would help us do certain loop optimizations.
1603f4a2713aSLionel Sambuc   llvm::Value *StateItemsPtr =
1604f4a2713aSLionel Sambuc     Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1605f4a2713aSLionel Sambuc   llvm::Value *EnumStateItems =
1606f4a2713aSLionel Sambuc     Builder.CreateLoad(StateItemsPtr, "stateitems");
1607f4a2713aSLionel Sambuc 
1608f4a2713aSLionel Sambuc   // Fetch the value at the current index from the buffer.
1609f4a2713aSLionel Sambuc   llvm::Value *CurrentItemPtr =
1610f4a2713aSLionel Sambuc     Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1611f4a2713aSLionel Sambuc   llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
1612f4a2713aSLionel Sambuc 
1613f4a2713aSLionel Sambuc   // Cast that value to the right type.
1614f4a2713aSLionel Sambuc   CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1615f4a2713aSLionel Sambuc                                       "currentitem");
1616f4a2713aSLionel Sambuc 
1617f4a2713aSLionel Sambuc   // Make sure we have an l-value.  Yes, this gets evaluated every
1618f4a2713aSLionel Sambuc   // time through the loop.
1619f4a2713aSLionel Sambuc   if (!elementIsVariable) {
1620f4a2713aSLionel Sambuc     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1621f4a2713aSLionel Sambuc     EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1622f4a2713aSLionel Sambuc   } else {
1623f4a2713aSLionel Sambuc     EmitScalarInit(CurrentItem, elementLValue);
1624f4a2713aSLionel Sambuc   }
1625f4a2713aSLionel Sambuc 
1626f4a2713aSLionel Sambuc   // If we do have an element variable, this assignment is the end of
1627f4a2713aSLionel Sambuc   // its initialization.
1628f4a2713aSLionel Sambuc   if (elementIsVariable)
1629f4a2713aSLionel Sambuc     EmitAutoVarCleanups(variable);
1630f4a2713aSLionel Sambuc 
1631f4a2713aSLionel Sambuc   // Perform the loop body, setting up break and continue labels.
1632f4a2713aSLionel Sambuc   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1633f4a2713aSLionel Sambuc   {
1634f4a2713aSLionel Sambuc     RunCleanupsScope Scope(*this);
1635f4a2713aSLionel Sambuc     EmitStmt(S.getBody());
1636f4a2713aSLionel Sambuc   }
1637f4a2713aSLionel Sambuc   BreakContinueStack.pop_back();
1638f4a2713aSLionel Sambuc 
1639f4a2713aSLionel Sambuc   // Destroy the element variable now.
1640f4a2713aSLionel Sambuc   elementVariableScope.ForceCleanup();
1641f4a2713aSLionel Sambuc 
1642f4a2713aSLionel Sambuc   // Check whether there are more elements.
1643f4a2713aSLionel Sambuc   EmitBlock(AfterBody.getBlock());
1644f4a2713aSLionel Sambuc 
1645f4a2713aSLionel Sambuc   llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1646f4a2713aSLionel Sambuc 
1647f4a2713aSLionel Sambuc   // First we check in the local buffer.
1648f4a2713aSLionel Sambuc   llvm::Value *indexPlusOne
1649f4a2713aSLionel Sambuc     = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1650f4a2713aSLionel Sambuc 
1651f4a2713aSLionel Sambuc   // If we haven't overrun the buffer yet, we can continue.
1652*0a6a1f1dSLionel Sambuc   // Set the branch weights based on the simplifying assumption that this is
1653*0a6a1f1dSLionel Sambuc   // like a while-loop, i.e., ignoring that the false branch fetches more
1654*0a6a1f1dSLionel Sambuc   // elements and then returns to the loop.
1655f4a2713aSLionel Sambuc   Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1656*0a6a1f1dSLionel Sambuc                        LoopBodyBB, FetchMoreBB,
1657*0a6a1f1dSLionel Sambuc                        PGO.createBranchWeights(Cnt.getCount(), EntryCount));
1658f4a2713aSLionel Sambuc 
1659f4a2713aSLionel Sambuc   index->addIncoming(indexPlusOne, AfterBody.getBlock());
1660f4a2713aSLionel Sambuc   count->addIncoming(count, AfterBody.getBlock());
1661f4a2713aSLionel Sambuc 
1662f4a2713aSLionel Sambuc   // Otherwise, we have to fetch more elements.
1663f4a2713aSLionel Sambuc   EmitBlock(FetchMoreBB);
1664f4a2713aSLionel Sambuc 
1665f4a2713aSLionel Sambuc   CountRV =
1666f4a2713aSLionel Sambuc     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1667f4a2713aSLionel Sambuc                                              getContext().UnsignedLongTy,
1668f4a2713aSLionel Sambuc                                              FastEnumSel,
1669f4a2713aSLionel Sambuc                                              Collection, Args);
1670f4a2713aSLionel Sambuc 
1671f4a2713aSLionel Sambuc   // If we got a zero count, we're done.
1672f4a2713aSLionel Sambuc   llvm::Value *refetchCount = CountRV.getScalarVal();
1673f4a2713aSLionel Sambuc 
1674f4a2713aSLionel Sambuc   // (note that the message send might split FetchMoreBB)
1675f4a2713aSLionel Sambuc   index->addIncoming(zero, Builder.GetInsertBlock());
1676f4a2713aSLionel Sambuc   count->addIncoming(refetchCount, Builder.GetInsertBlock());
1677f4a2713aSLionel Sambuc 
1678f4a2713aSLionel Sambuc   Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1679f4a2713aSLionel Sambuc                        EmptyBB, LoopBodyBB);
1680f4a2713aSLionel Sambuc 
1681f4a2713aSLionel Sambuc   // No more elements.
1682f4a2713aSLionel Sambuc   EmitBlock(EmptyBB);
1683f4a2713aSLionel Sambuc 
1684f4a2713aSLionel Sambuc   if (!elementIsVariable) {
1685f4a2713aSLionel Sambuc     // If the element was not a declaration, set it to be null.
1686f4a2713aSLionel Sambuc 
1687f4a2713aSLionel Sambuc     llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1688f4a2713aSLionel Sambuc     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1689f4a2713aSLionel Sambuc     EmitStoreThroughLValue(RValue::get(null), elementLValue);
1690f4a2713aSLionel Sambuc   }
1691f4a2713aSLionel Sambuc 
1692f4a2713aSLionel Sambuc   if (DI)
1693f4a2713aSLionel Sambuc     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
1694f4a2713aSLionel Sambuc 
1695f4a2713aSLionel Sambuc   // Leave the cleanup we entered in ARC.
1696f4a2713aSLionel Sambuc   if (getLangOpts().ObjCAutoRefCount)
1697f4a2713aSLionel Sambuc     PopCleanupBlock();
1698f4a2713aSLionel Sambuc 
1699f4a2713aSLionel Sambuc   EmitBlock(LoopEnd.getBlock());
1700f4a2713aSLionel Sambuc }
1701f4a2713aSLionel Sambuc 
EmitObjCAtTryStmt(const ObjCAtTryStmt & S)1702f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1703f4a2713aSLionel Sambuc   CGM.getObjCRuntime().EmitTryStmt(*this, S);
1704f4a2713aSLionel Sambuc }
1705f4a2713aSLionel Sambuc 
EmitObjCAtThrowStmt(const ObjCAtThrowStmt & S)1706f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1707f4a2713aSLionel Sambuc   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1708f4a2713aSLionel Sambuc }
1709f4a2713aSLionel Sambuc 
EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt & S)1710f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1711f4a2713aSLionel Sambuc                                               const ObjCAtSynchronizedStmt &S) {
1712f4a2713aSLionel Sambuc   CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1713f4a2713aSLionel Sambuc }
1714f4a2713aSLionel Sambuc 
1715f4a2713aSLionel Sambuc /// Produce the code for a CK_ARCProduceObject.  Just does a
1716f4a2713aSLionel Sambuc /// primitive retain.
EmitObjCProduceObject(QualType type,llvm::Value * value)1717f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1718f4a2713aSLionel Sambuc                                                     llvm::Value *value) {
1719f4a2713aSLionel Sambuc   return EmitARCRetain(type, value);
1720f4a2713aSLionel Sambuc }
1721f4a2713aSLionel Sambuc 
1722f4a2713aSLionel Sambuc namespace {
1723f4a2713aSLionel Sambuc   struct CallObjCRelease : EHScopeStack::Cleanup {
CallObjCRelease__anon86dbc8190411::CallObjCRelease1724f4a2713aSLionel Sambuc     CallObjCRelease(llvm::Value *object) : object(object) {}
1725f4a2713aSLionel Sambuc     llvm::Value *object;
1726f4a2713aSLionel Sambuc 
Emit__anon86dbc8190411::CallObjCRelease1727*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
1728f4a2713aSLionel Sambuc       // Releases at the end of the full-expression are imprecise.
1729f4a2713aSLionel Sambuc       CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1730f4a2713aSLionel Sambuc     }
1731f4a2713aSLionel Sambuc   };
1732f4a2713aSLionel Sambuc }
1733f4a2713aSLionel Sambuc 
1734f4a2713aSLionel Sambuc /// Produce the code for a CK_ARCConsumeObject.  Does a primitive
1735f4a2713aSLionel Sambuc /// release at the end of the full-expression.
EmitObjCConsumeObject(QualType type,llvm::Value * object)1736f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1737f4a2713aSLionel Sambuc                                                     llvm::Value *object) {
1738f4a2713aSLionel Sambuc   // If we're in a conditional branch, we need to make the cleanup
1739f4a2713aSLionel Sambuc   // conditional.
1740f4a2713aSLionel Sambuc   pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1741f4a2713aSLionel Sambuc   return object;
1742f4a2713aSLionel Sambuc }
1743f4a2713aSLionel Sambuc 
EmitObjCExtendObjectLifetime(QualType type,llvm::Value * value)1744f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1745f4a2713aSLionel Sambuc                                                            llvm::Value *value) {
1746f4a2713aSLionel Sambuc   return EmitARCRetainAutorelease(type, value);
1747f4a2713aSLionel Sambuc }
1748f4a2713aSLionel Sambuc 
1749f4a2713aSLionel Sambuc /// Given a number of pointers, inform the optimizer that they're
1750f4a2713aSLionel Sambuc /// being intrinsically used up until this point in the program.
EmitARCIntrinsicUse(ArrayRef<llvm::Value * > values)1751f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1752f4a2713aSLionel Sambuc   llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1753f4a2713aSLionel Sambuc   if (!fn) {
1754f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
1755*0a6a1f1dSLionel Sambuc       llvm::FunctionType::get(CGM.VoidTy, None, true);
1756f4a2713aSLionel Sambuc     fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1757f4a2713aSLionel Sambuc   }
1758f4a2713aSLionel Sambuc 
1759f4a2713aSLionel Sambuc   // This isn't really a "runtime" function, but as an intrinsic it
1760f4a2713aSLionel Sambuc   // doesn't really matter as long as we align things up.
1761f4a2713aSLionel Sambuc   EmitNounwindRuntimeCall(fn, values);
1762f4a2713aSLionel Sambuc }
1763f4a2713aSLionel Sambuc 
1764f4a2713aSLionel Sambuc 
createARCRuntimeFunction(CodeGenModule & CGM,llvm::FunctionType * type,StringRef fnName)1765f4a2713aSLionel Sambuc static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1766f4a2713aSLionel Sambuc                                                 llvm::FunctionType *type,
1767f4a2713aSLionel Sambuc                                                 StringRef fnName) {
1768f4a2713aSLionel Sambuc   llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1769f4a2713aSLionel Sambuc 
1770f4a2713aSLionel Sambuc   if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
1771f4a2713aSLionel Sambuc     // If the target runtime doesn't naturally support ARC, emit weak
1772f4a2713aSLionel Sambuc     // references to the runtime support library.  We don't really
1773f4a2713aSLionel Sambuc     // permit this to fail, but we need a particular relocation style.
1774f4a2713aSLionel Sambuc     if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
1775f4a2713aSLionel Sambuc       f->setLinkage(llvm::Function::ExternalWeakLinkage);
1776f4a2713aSLionel Sambuc     } else if (fnName == "objc_retain" || fnName  == "objc_release") {
1777f4a2713aSLionel Sambuc       // If we have Native ARC, set nonlazybind attribute for these APIs for
1778f4a2713aSLionel Sambuc       // performance.
1779f4a2713aSLionel Sambuc       f->addFnAttr(llvm::Attribute::NonLazyBind);
1780f4a2713aSLionel Sambuc     }
1781f4a2713aSLionel Sambuc   }
1782f4a2713aSLionel Sambuc 
1783f4a2713aSLionel Sambuc   return fn;
1784f4a2713aSLionel Sambuc }
1785f4a2713aSLionel Sambuc 
1786f4a2713aSLionel Sambuc /// Perform an operation having the signature
1787f4a2713aSLionel Sambuc ///   i8* (i8*)
1788f4a2713aSLionel Sambuc /// where a null input causes a no-op and returns null.
emitARCValueOperation(CodeGenFunction & CGF,llvm::Value * value,llvm::Constant * & fn,StringRef fnName,bool isTailCall=false)1789f4a2713aSLionel Sambuc static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1790f4a2713aSLionel Sambuc                                           llvm::Value *value,
1791f4a2713aSLionel Sambuc                                           llvm::Constant *&fn,
1792f4a2713aSLionel Sambuc                                           StringRef fnName,
1793f4a2713aSLionel Sambuc                                           bool isTailCall = false) {
1794f4a2713aSLionel Sambuc   if (isa<llvm::ConstantPointerNull>(value)) return value;
1795f4a2713aSLionel Sambuc 
1796f4a2713aSLionel Sambuc   if (!fn) {
1797f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
1798f4a2713aSLionel Sambuc       llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
1799f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1800f4a2713aSLionel Sambuc   }
1801f4a2713aSLionel Sambuc 
1802f4a2713aSLionel Sambuc   // Cast the argument to 'id'.
1803f4a2713aSLionel Sambuc   llvm::Type *origType = value->getType();
1804f4a2713aSLionel Sambuc   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1805f4a2713aSLionel Sambuc 
1806f4a2713aSLionel Sambuc   // Call the function.
1807f4a2713aSLionel Sambuc   llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
1808f4a2713aSLionel Sambuc   if (isTailCall)
1809f4a2713aSLionel Sambuc     call->setTailCall();
1810f4a2713aSLionel Sambuc 
1811f4a2713aSLionel Sambuc   // Cast the result back to the original type.
1812f4a2713aSLionel Sambuc   return CGF.Builder.CreateBitCast(call, origType);
1813f4a2713aSLionel Sambuc }
1814f4a2713aSLionel Sambuc 
1815f4a2713aSLionel Sambuc /// Perform an operation having the following signature:
1816f4a2713aSLionel Sambuc ///   i8* (i8**)
emitARCLoadOperation(CodeGenFunction & CGF,llvm::Value * addr,llvm::Constant * & fn,StringRef fnName)1817f4a2713aSLionel Sambuc static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1818f4a2713aSLionel Sambuc                                          llvm::Value *addr,
1819f4a2713aSLionel Sambuc                                          llvm::Constant *&fn,
1820f4a2713aSLionel Sambuc                                          StringRef fnName) {
1821f4a2713aSLionel Sambuc   if (!fn) {
1822f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
1823f4a2713aSLionel Sambuc       llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
1824f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1825f4a2713aSLionel Sambuc   }
1826f4a2713aSLionel Sambuc 
1827f4a2713aSLionel Sambuc   // Cast the argument to 'id*'.
1828f4a2713aSLionel Sambuc   llvm::Type *origType = addr->getType();
1829f4a2713aSLionel Sambuc   addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1830f4a2713aSLionel Sambuc 
1831f4a2713aSLionel Sambuc   // Call the function.
1832f4a2713aSLionel Sambuc   llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
1833f4a2713aSLionel Sambuc 
1834f4a2713aSLionel Sambuc   // Cast the result back to a dereference of the original type.
1835f4a2713aSLionel Sambuc   if (origType != CGF.Int8PtrPtrTy)
1836f4a2713aSLionel Sambuc     result = CGF.Builder.CreateBitCast(result,
1837f4a2713aSLionel Sambuc                         cast<llvm::PointerType>(origType)->getElementType());
1838f4a2713aSLionel Sambuc 
1839f4a2713aSLionel Sambuc   return result;
1840f4a2713aSLionel Sambuc }
1841f4a2713aSLionel Sambuc 
1842f4a2713aSLionel Sambuc /// Perform an operation having the following signature:
1843f4a2713aSLionel Sambuc ///   i8* (i8**, i8*)
emitARCStoreOperation(CodeGenFunction & CGF,llvm::Value * addr,llvm::Value * value,llvm::Constant * & fn,StringRef fnName,bool ignored)1844f4a2713aSLionel Sambuc static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1845f4a2713aSLionel Sambuc                                           llvm::Value *addr,
1846f4a2713aSLionel Sambuc                                           llvm::Value *value,
1847f4a2713aSLionel Sambuc                                           llvm::Constant *&fn,
1848f4a2713aSLionel Sambuc                                           StringRef fnName,
1849f4a2713aSLionel Sambuc                                           bool ignored) {
1850f4a2713aSLionel Sambuc   assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1851f4a2713aSLionel Sambuc            == value->getType());
1852f4a2713aSLionel Sambuc 
1853f4a2713aSLionel Sambuc   if (!fn) {
1854f4a2713aSLionel Sambuc     llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
1855f4a2713aSLionel Sambuc 
1856f4a2713aSLionel Sambuc     llvm::FunctionType *fnType
1857f4a2713aSLionel Sambuc       = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1858f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1859f4a2713aSLionel Sambuc   }
1860f4a2713aSLionel Sambuc 
1861f4a2713aSLionel Sambuc   llvm::Type *origType = value->getType();
1862f4a2713aSLionel Sambuc 
1863f4a2713aSLionel Sambuc   llvm::Value *args[] = {
1864f4a2713aSLionel Sambuc     CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1865f4a2713aSLionel Sambuc     CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1866f4a2713aSLionel Sambuc   };
1867f4a2713aSLionel Sambuc   llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
1868f4a2713aSLionel Sambuc 
1869*0a6a1f1dSLionel Sambuc   if (ignored) return nullptr;
1870f4a2713aSLionel Sambuc 
1871f4a2713aSLionel Sambuc   return CGF.Builder.CreateBitCast(result, origType);
1872f4a2713aSLionel Sambuc }
1873f4a2713aSLionel Sambuc 
1874f4a2713aSLionel Sambuc /// Perform an operation having the following signature:
1875f4a2713aSLionel Sambuc ///   void (i8**, i8**)
emitARCCopyOperation(CodeGenFunction & CGF,llvm::Value * dst,llvm::Value * src,llvm::Constant * & fn,StringRef fnName)1876f4a2713aSLionel Sambuc static void emitARCCopyOperation(CodeGenFunction &CGF,
1877f4a2713aSLionel Sambuc                                  llvm::Value *dst,
1878f4a2713aSLionel Sambuc                                  llvm::Value *src,
1879f4a2713aSLionel Sambuc                                  llvm::Constant *&fn,
1880f4a2713aSLionel Sambuc                                  StringRef fnName) {
1881f4a2713aSLionel Sambuc   assert(dst->getType() == src->getType());
1882f4a2713aSLionel Sambuc 
1883f4a2713aSLionel Sambuc   if (!fn) {
1884f4a2713aSLionel Sambuc     llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1885f4a2713aSLionel Sambuc 
1886f4a2713aSLionel Sambuc     llvm::FunctionType *fnType
1887f4a2713aSLionel Sambuc       = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1888f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1889f4a2713aSLionel Sambuc   }
1890f4a2713aSLionel Sambuc 
1891f4a2713aSLionel Sambuc   llvm::Value *args[] = {
1892f4a2713aSLionel Sambuc     CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1893f4a2713aSLionel Sambuc     CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1894f4a2713aSLionel Sambuc   };
1895f4a2713aSLionel Sambuc   CGF.EmitNounwindRuntimeCall(fn, args);
1896f4a2713aSLionel Sambuc }
1897f4a2713aSLionel Sambuc 
1898f4a2713aSLionel Sambuc /// Produce the code to do a retain.  Based on the type, calls one of:
1899f4a2713aSLionel Sambuc ///   call i8* \@objc_retain(i8* %value)
1900f4a2713aSLionel Sambuc ///   call i8* \@objc_retainBlock(i8* %value)
EmitARCRetain(QualType type,llvm::Value * value)1901f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1902f4a2713aSLionel Sambuc   if (type->isBlockPointerType())
1903f4a2713aSLionel Sambuc     return EmitARCRetainBlock(value, /*mandatory*/ false);
1904f4a2713aSLionel Sambuc   else
1905f4a2713aSLionel Sambuc     return EmitARCRetainNonBlock(value);
1906f4a2713aSLionel Sambuc }
1907f4a2713aSLionel Sambuc 
1908f4a2713aSLionel Sambuc /// Retain the given object, with normal retain semantics.
1909f4a2713aSLionel Sambuc ///   call i8* \@objc_retain(i8* %value)
EmitARCRetainNonBlock(llvm::Value * value)1910f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1911f4a2713aSLionel Sambuc   return emitARCValueOperation(*this, value,
1912f4a2713aSLionel Sambuc                                CGM.getARCEntrypoints().objc_retain,
1913f4a2713aSLionel Sambuc                                "objc_retain");
1914f4a2713aSLionel Sambuc }
1915f4a2713aSLionel Sambuc 
1916f4a2713aSLionel Sambuc /// Retain the given block, with _Block_copy semantics.
1917f4a2713aSLionel Sambuc ///   call i8* \@objc_retainBlock(i8* %value)
1918f4a2713aSLionel Sambuc ///
1919f4a2713aSLionel Sambuc /// \param mandatory - If false, emit the call with metadata
1920f4a2713aSLionel Sambuc /// indicating that it's okay for the optimizer to eliminate this call
1921f4a2713aSLionel Sambuc /// if it can prove that the block never escapes except down the stack.
EmitARCRetainBlock(llvm::Value * value,bool mandatory)1922f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1923f4a2713aSLionel Sambuc                                                  bool mandatory) {
1924f4a2713aSLionel Sambuc   llvm::Value *result
1925f4a2713aSLionel Sambuc     = emitARCValueOperation(*this, value,
1926f4a2713aSLionel Sambuc                             CGM.getARCEntrypoints().objc_retainBlock,
1927f4a2713aSLionel Sambuc                             "objc_retainBlock");
1928f4a2713aSLionel Sambuc 
1929f4a2713aSLionel Sambuc   // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1930f4a2713aSLionel Sambuc   // tell the optimizer that it doesn't need to do this copy if the
1931f4a2713aSLionel Sambuc   // block doesn't escape, where being passed as an argument doesn't
1932f4a2713aSLionel Sambuc   // count as escaping.
1933f4a2713aSLionel Sambuc   if (!mandatory && isa<llvm::Instruction>(result)) {
1934f4a2713aSLionel Sambuc     llvm::CallInst *call
1935f4a2713aSLionel Sambuc       = cast<llvm::CallInst>(result->stripPointerCasts());
1936f4a2713aSLionel Sambuc     assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1937f4a2713aSLionel Sambuc 
1938f4a2713aSLionel Sambuc     call->setMetadata("clang.arc.copy_on_escape",
1939*0a6a1f1dSLionel Sambuc                       llvm::MDNode::get(Builder.getContext(), None));
1940f4a2713aSLionel Sambuc   }
1941f4a2713aSLionel Sambuc 
1942f4a2713aSLionel Sambuc   return result;
1943f4a2713aSLionel Sambuc }
1944f4a2713aSLionel Sambuc 
1945f4a2713aSLionel Sambuc /// Retain the given object which is the result of a function call.
1946f4a2713aSLionel Sambuc ///   call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
1947f4a2713aSLionel Sambuc ///
1948f4a2713aSLionel Sambuc /// Yes, this function name is one character away from a different
1949f4a2713aSLionel Sambuc /// call with completely different semantics.
1950f4a2713aSLionel Sambuc llvm::Value *
EmitARCRetainAutoreleasedReturnValue(llvm::Value * value)1951f4a2713aSLionel Sambuc CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1952f4a2713aSLionel Sambuc   // Fetch the void(void) inline asm which marks that we're going to
1953f4a2713aSLionel Sambuc   // retain the autoreleased return value.
1954f4a2713aSLionel Sambuc   llvm::InlineAsm *&marker
1955f4a2713aSLionel Sambuc     = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1956f4a2713aSLionel Sambuc   if (!marker) {
1957f4a2713aSLionel Sambuc     StringRef assembly
1958f4a2713aSLionel Sambuc       = CGM.getTargetCodeGenInfo()
1959f4a2713aSLionel Sambuc            .getARCRetainAutoreleasedReturnValueMarker();
1960f4a2713aSLionel Sambuc 
1961f4a2713aSLionel Sambuc     // If we have an empty assembly string, there's nothing to do.
1962f4a2713aSLionel Sambuc     if (assembly.empty()) {
1963f4a2713aSLionel Sambuc 
1964f4a2713aSLionel Sambuc     // Otherwise, at -O0, build an inline asm that we're going to call
1965f4a2713aSLionel Sambuc     // in a moment.
1966f4a2713aSLionel Sambuc     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1967f4a2713aSLionel Sambuc       llvm::FunctionType *type =
1968f4a2713aSLionel Sambuc         llvm::FunctionType::get(VoidTy, /*variadic*/false);
1969f4a2713aSLionel Sambuc 
1970f4a2713aSLionel Sambuc       marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1971f4a2713aSLionel Sambuc 
1972f4a2713aSLionel Sambuc     // If we're at -O1 and above, we don't want to litter the code
1973f4a2713aSLionel Sambuc     // with this marker yet, so leave a breadcrumb for the ARC
1974f4a2713aSLionel Sambuc     // optimizer to pick up.
1975f4a2713aSLionel Sambuc     } else {
1976f4a2713aSLionel Sambuc       llvm::NamedMDNode *metadata =
1977f4a2713aSLionel Sambuc         CGM.getModule().getOrInsertNamedMetadata(
1978f4a2713aSLionel Sambuc                             "clang.arc.retainAutoreleasedReturnValueMarker");
1979f4a2713aSLionel Sambuc       assert(metadata->getNumOperands() <= 1);
1980f4a2713aSLionel Sambuc       if (metadata->getNumOperands() == 0) {
1981*0a6a1f1dSLionel Sambuc         metadata->addOperand(llvm::MDNode::get(
1982*0a6a1f1dSLionel Sambuc             getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
1983f4a2713aSLionel Sambuc       }
1984f4a2713aSLionel Sambuc     }
1985f4a2713aSLionel Sambuc   }
1986f4a2713aSLionel Sambuc 
1987f4a2713aSLionel Sambuc   // Call the marker asm if we made one, which we do only at -O0.
1988f4a2713aSLionel Sambuc   if (marker) Builder.CreateCall(marker);
1989f4a2713aSLionel Sambuc 
1990f4a2713aSLionel Sambuc   return emitARCValueOperation(*this, value,
1991f4a2713aSLionel Sambuc                      CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1992f4a2713aSLionel Sambuc                                "objc_retainAutoreleasedReturnValue");
1993f4a2713aSLionel Sambuc }
1994f4a2713aSLionel Sambuc 
1995f4a2713aSLionel Sambuc /// Release the given object.
1996f4a2713aSLionel Sambuc ///   call void \@objc_release(i8* %value)
EmitARCRelease(llvm::Value * value,ARCPreciseLifetime_t precise)1997f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1998f4a2713aSLionel Sambuc                                      ARCPreciseLifetime_t precise) {
1999f4a2713aSLionel Sambuc   if (isa<llvm::ConstantPointerNull>(value)) return;
2000f4a2713aSLionel Sambuc 
2001f4a2713aSLionel Sambuc   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2002f4a2713aSLionel Sambuc   if (!fn) {
2003f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
2004f4a2713aSLionel Sambuc       llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2005f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2006f4a2713aSLionel Sambuc   }
2007f4a2713aSLionel Sambuc 
2008f4a2713aSLionel Sambuc   // Cast the argument to 'id'.
2009f4a2713aSLionel Sambuc   value = Builder.CreateBitCast(value, Int8PtrTy);
2010f4a2713aSLionel Sambuc 
2011f4a2713aSLionel Sambuc   // Call objc_release.
2012f4a2713aSLionel Sambuc   llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2013f4a2713aSLionel Sambuc 
2014f4a2713aSLionel Sambuc   if (precise == ARCImpreciseLifetime) {
2015f4a2713aSLionel Sambuc     call->setMetadata("clang.imprecise_release",
2016*0a6a1f1dSLionel Sambuc                       llvm::MDNode::get(Builder.getContext(), None));
2017f4a2713aSLionel Sambuc   }
2018f4a2713aSLionel Sambuc }
2019f4a2713aSLionel Sambuc 
2020f4a2713aSLionel Sambuc /// Destroy a __strong variable.
2021f4a2713aSLionel Sambuc ///
2022f4a2713aSLionel Sambuc /// At -O0, emit a call to store 'null' into the address;
2023f4a2713aSLionel Sambuc /// instrumenting tools prefer this because the address is exposed,
2024f4a2713aSLionel Sambuc /// but it's relatively cumbersome to optimize.
2025f4a2713aSLionel Sambuc ///
2026f4a2713aSLionel Sambuc /// At -O1 and above, just load and call objc_release.
2027f4a2713aSLionel Sambuc ///
2028f4a2713aSLionel Sambuc ///   call void \@objc_storeStrong(i8** %addr, i8* null)
EmitARCDestroyStrong(llvm::Value * addr,ARCPreciseLifetime_t precise)2029f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2030f4a2713aSLionel Sambuc                                            ARCPreciseLifetime_t precise) {
2031f4a2713aSLionel Sambuc   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2032f4a2713aSLionel Sambuc     llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2033f4a2713aSLionel Sambuc     llvm::Value *null = llvm::ConstantPointerNull::get(
2034f4a2713aSLionel Sambuc                           cast<llvm::PointerType>(addrTy->getElementType()));
2035f4a2713aSLionel Sambuc     EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2036f4a2713aSLionel Sambuc     return;
2037f4a2713aSLionel Sambuc   }
2038f4a2713aSLionel Sambuc 
2039f4a2713aSLionel Sambuc   llvm::Value *value = Builder.CreateLoad(addr);
2040f4a2713aSLionel Sambuc   EmitARCRelease(value, precise);
2041f4a2713aSLionel Sambuc }
2042f4a2713aSLionel Sambuc 
2043f4a2713aSLionel Sambuc /// Store into a strong object.  Always calls this:
2044f4a2713aSLionel Sambuc ///   call void \@objc_storeStrong(i8** %addr, i8* %value)
EmitARCStoreStrongCall(llvm::Value * addr,llvm::Value * value,bool ignored)2045f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2046f4a2713aSLionel Sambuc                                                      llvm::Value *value,
2047f4a2713aSLionel Sambuc                                                      bool ignored) {
2048f4a2713aSLionel Sambuc   assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2049f4a2713aSLionel Sambuc            == value->getType());
2050f4a2713aSLionel Sambuc 
2051f4a2713aSLionel Sambuc   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2052f4a2713aSLionel Sambuc   if (!fn) {
2053f4a2713aSLionel Sambuc     llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
2054f4a2713aSLionel Sambuc     llvm::FunctionType *fnType
2055f4a2713aSLionel Sambuc       = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2056f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2057f4a2713aSLionel Sambuc   }
2058f4a2713aSLionel Sambuc 
2059f4a2713aSLionel Sambuc   llvm::Value *args[] = {
2060f4a2713aSLionel Sambuc     Builder.CreateBitCast(addr, Int8PtrPtrTy),
2061f4a2713aSLionel Sambuc     Builder.CreateBitCast(value, Int8PtrTy)
2062f4a2713aSLionel Sambuc   };
2063f4a2713aSLionel Sambuc   EmitNounwindRuntimeCall(fn, args);
2064f4a2713aSLionel Sambuc 
2065*0a6a1f1dSLionel Sambuc   if (ignored) return nullptr;
2066f4a2713aSLionel Sambuc   return value;
2067f4a2713aSLionel Sambuc }
2068f4a2713aSLionel Sambuc 
2069f4a2713aSLionel Sambuc /// Store into a strong object.  Sometimes calls this:
2070f4a2713aSLionel Sambuc ///   call void \@objc_storeStrong(i8** %addr, i8* %value)
2071f4a2713aSLionel Sambuc /// Other times, breaks it down into components.
EmitARCStoreStrong(LValue dst,llvm::Value * newValue,bool ignored)2072f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2073f4a2713aSLionel Sambuc                                                  llvm::Value *newValue,
2074f4a2713aSLionel Sambuc                                                  bool ignored) {
2075f4a2713aSLionel Sambuc   QualType type = dst.getType();
2076f4a2713aSLionel Sambuc   bool isBlock = type->isBlockPointerType();
2077f4a2713aSLionel Sambuc 
2078f4a2713aSLionel Sambuc   // Use a store barrier at -O0 unless this is a block type or the
2079f4a2713aSLionel Sambuc   // lvalue is inadequately aligned.
2080f4a2713aSLionel Sambuc   if (shouldUseFusedARCCalls() &&
2081f4a2713aSLionel Sambuc       !isBlock &&
2082f4a2713aSLionel Sambuc       (dst.getAlignment().isZero() ||
2083f4a2713aSLionel Sambuc        dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2084f4a2713aSLionel Sambuc     return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2085f4a2713aSLionel Sambuc   }
2086f4a2713aSLionel Sambuc 
2087f4a2713aSLionel Sambuc   // Otherwise, split it out.
2088f4a2713aSLionel Sambuc 
2089f4a2713aSLionel Sambuc   // Retain the new value.
2090f4a2713aSLionel Sambuc   newValue = EmitARCRetain(type, newValue);
2091f4a2713aSLionel Sambuc 
2092f4a2713aSLionel Sambuc   // Read the old value.
2093f4a2713aSLionel Sambuc   llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2094f4a2713aSLionel Sambuc 
2095f4a2713aSLionel Sambuc   // Store.  We do this before the release so that any deallocs won't
2096f4a2713aSLionel Sambuc   // see the old value.
2097f4a2713aSLionel Sambuc   EmitStoreOfScalar(newValue, dst);
2098f4a2713aSLionel Sambuc 
2099f4a2713aSLionel Sambuc   // Finally, release the old value.
2100f4a2713aSLionel Sambuc   EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2101f4a2713aSLionel Sambuc 
2102f4a2713aSLionel Sambuc   return newValue;
2103f4a2713aSLionel Sambuc }
2104f4a2713aSLionel Sambuc 
2105f4a2713aSLionel Sambuc /// Autorelease the given object.
2106f4a2713aSLionel Sambuc ///   call i8* \@objc_autorelease(i8* %value)
EmitARCAutorelease(llvm::Value * value)2107f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2108f4a2713aSLionel Sambuc   return emitARCValueOperation(*this, value,
2109f4a2713aSLionel Sambuc                                CGM.getARCEntrypoints().objc_autorelease,
2110f4a2713aSLionel Sambuc                                "objc_autorelease");
2111f4a2713aSLionel Sambuc }
2112f4a2713aSLionel Sambuc 
2113f4a2713aSLionel Sambuc /// Autorelease the given object.
2114f4a2713aSLionel Sambuc ///   call i8* \@objc_autoreleaseReturnValue(i8* %value)
2115f4a2713aSLionel Sambuc llvm::Value *
EmitARCAutoreleaseReturnValue(llvm::Value * value)2116f4a2713aSLionel Sambuc CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2117f4a2713aSLionel Sambuc   return emitARCValueOperation(*this, value,
2118f4a2713aSLionel Sambuc                             CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2119f4a2713aSLionel Sambuc                                "objc_autoreleaseReturnValue",
2120f4a2713aSLionel Sambuc                                /*isTailCall*/ true);
2121f4a2713aSLionel Sambuc }
2122f4a2713aSLionel Sambuc 
2123f4a2713aSLionel Sambuc /// Do a fused retain/autorelease of the given object.
2124f4a2713aSLionel Sambuc ///   call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2125f4a2713aSLionel Sambuc llvm::Value *
EmitARCRetainAutoreleaseReturnValue(llvm::Value * value)2126f4a2713aSLionel Sambuc CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2127f4a2713aSLionel Sambuc   return emitARCValueOperation(*this, value,
2128f4a2713aSLionel Sambuc                      CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2129f4a2713aSLionel Sambuc                                "objc_retainAutoreleaseReturnValue",
2130f4a2713aSLionel Sambuc                                /*isTailCall*/ true);
2131f4a2713aSLionel Sambuc }
2132f4a2713aSLionel Sambuc 
2133f4a2713aSLionel Sambuc /// Do a fused retain/autorelease of the given object.
2134f4a2713aSLionel Sambuc ///   call i8* \@objc_retainAutorelease(i8* %value)
2135f4a2713aSLionel Sambuc /// or
2136f4a2713aSLionel Sambuc ///   %retain = call i8* \@objc_retainBlock(i8* %value)
2137f4a2713aSLionel Sambuc ///   call i8* \@objc_autorelease(i8* %retain)
EmitARCRetainAutorelease(QualType type,llvm::Value * value)2138f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2139f4a2713aSLionel Sambuc                                                        llvm::Value *value) {
2140f4a2713aSLionel Sambuc   if (!type->isBlockPointerType())
2141f4a2713aSLionel Sambuc     return EmitARCRetainAutoreleaseNonBlock(value);
2142f4a2713aSLionel Sambuc 
2143f4a2713aSLionel Sambuc   if (isa<llvm::ConstantPointerNull>(value)) return value;
2144f4a2713aSLionel Sambuc 
2145f4a2713aSLionel Sambuc   llvm::Type *origType = value->getType();
2146f4a2713aSLionel Sambuc   value = Builder.CreateBitCast(value, Int8PtrTy);
2147f4a2713aSLionel Sambuc   value = EmitARCRetainBlock(value, /*mandatory*/ true);
2148f4a2713aSLionel Sambuc   value = EmitARCAutorelease(value);
2149f4a2713aSLionel Sambuc   return Builder.CreateBitCast(value, origType);
2150f4a2713aSLionel Sambuc }
2151f4a2713aSLionel Sambuc 
2152f4a2713aSLionel Sambuc /// Do a fused retain/autorelease of the given object.
2153f4a2713aSLionel Sambuc ///   call i8* \@objc_retainAutorelease(i8* %value)
2154f4a2713aSLionel Sambuc llvm::Value *
EmitARCRetainAutoreleaseNonBlock(llvm::Value * value)2155f4a2713aSLionel Sambuc CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2156f4a2713aSLionel Sambuc   return emitARCValueOperation(*this, value,
2157f4a2713aSLionel Sambuc                                CGM.getARCEntrypoints().objc_retainAutorelease,
2158f4a2713aSLionel Sambuc                                "objc_retainAutorelease");
2159f4a2713aSLionel Sambuc }
2160f4a2713aSLionel Sambuc 
2161f4a2713aSLionel Sambuc /// i8* \@objc_loadWeak(i8** %addr)
2162f4a2713aSLionel Sambuc /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
EmitARCLoadWeak(llvm::Value * addr)2163f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2164f4a2713aSLionel Sambuc   return emitARCLoadOperation(*this, addr,
2165f4a2713aSLionel Sambuc                               CGM.getARCEntrypoints().objc_loadWeak,
2166f4a2713aSLionel Sambuc                               "objc_loadWeak");
2167f4a2713aSLionel Sambuc }
2168f4a2713aSLionel Sambuc 
2169f4a2713aSLionel Sambuc /// i8* \@objc_loadWeakRetained(i8** %addr)
EmitARCLoadWeakRetained(llvm::Value * addr)2170f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2171f4a2713aSLionel Sambuc   return emitARCLoadOperation(*this, addr,
2172f4a2713aSLionel Sambuc                               CGM.getARCEntrypoints().objc_loadWeakRetained,
2173f4a2713aSLionel Sambuc                               "objc_loadWeakRetained");
2174f4a2713aSLionel Sambuc }
2175f4a2713aSLionel Sambuc 
2176f4a2713aSLionel Sambuc /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2177f4a2713aSLionel Sambuc /// Returns %value.
EmitARCStoreWeak(llvm::Value * addr,llvm::Value * value,bool ignored)2178f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2179f4a2713aSLionel Sambuc                                                llvm::Value *value,
2180f4a2713aSLionel Sambuc                                                bool ignored) {
2181f4a2713aSLionel Sambuc   return emitARCStoreOperation(*this, addr, value,
2182f4a2713aSLionel Sambuc                                CGM.getARCEntrypoints().objc_storeWeak,
2183f4a2713aSLionel Sambuc                                "objc_storeWeak", ignored);
2184f4a2713aSLionel Sambuc }
2185f4a2713aSLionel Sambuc 
2186f4a2713aSLionel Sambuc /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2187f4a2713aSLionel Sambuc /// Returns %value.  %addr is known to not have a current weak entry.
2188f4a2713aSLionel Sambuc /// Essentially equivalent to:
2189f4a2713aSLionel Sambuc ///   *addr = nil; objc_storeWeak(addr, value);
EmitARCInitWeak(llvm::Value * addr,llvm::Value * value)2190f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2191f4a2713aSLionel Sambuc   // If we're initializing to null, just write null to memory; no need
2192f4a2713aSLionel Sambuc   // to get the runtime involved.  But don't do this if optimization
2193f4a2713aSLionel Sambuc   // is enabled, because accounting for this would make the optimizer
2194f4a2713aSLionel Sambuc   // much more complicated.
2195f4a2713aSLionel Sambuc   if (isa<llvm::ConstantPointerNull>(value) &&
2196f4a2713aSLionel Sambuc       CGM.getCodeGenOpts().OptimizationLevel == 0) {
2197f4a2713aSLionel Sambuc     Builder.CreateStore(value, addr);
2198f4a2713aSLionel Sambuc     return;
2199f4a2713aSLionel Sambuc   }
2200f4a2713aSLionel Sambuc 
2201f4a2713aSLionel Sambuc   emitARCStoreOperation(*this, addr, value,
2202f4a2713aSLionel Sambuc                         CGM.getARCEntrypoints().objc_initWeak,
2203f4a2713aSLionel Sambuc                         "objc_initWeak", /*ignored*/ true);
2204f4a2713aSLionel Sambuc }
2205f4a2713aSLionel Sambuc 
2206f4a2713aSLionel Sambuc /// void \@objc_destroyWeak(i8** %addr)
2207f4a2713aSLionel Sambuc /// Essentially objc_storeWeak(addr, nil).
EmitARCDestroyWeak(llvm::Value * addr)2208f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2209f4a2713aSLionel Sambuc   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2210f4a2713aSLionel Sambuc   if (!fn) {
2211f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
2212f4a2713aSLionel Sambuc       llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
2213f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2214f4a2713aSLionel Sambuc   }
2215f4a2713aSLionel Sambuc 
2216f4a2713aSLionel Sambuc   // Cast the argument to 'id*'.
2217f4a2713aSLionel Sambuc   addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2218f4a2713aSLionel Sambuc 
2219f4a2713aSLionel Sambuc   EmitNounwindRuntimeCall(fn, addr);
2220f4a2713aSLionel Sambuc }
2221f4a2713aSLionel Sambuc 
2222f4a2713aSLionel Sambuc /// void \@objc_moveWeak(i8** %dest, i8** %src)
2223f4a2713aSLionel Sambuc /// Disregards the current value in %dest.  Leaves %src pointing to nothing.
2224f4a2713aSLionel Sambuc /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
EmitARCMoveWeak(llvm::Value * dst,llvm::Value * src)2225f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2226f4a2713aSLionel Sambuc   emitARCCopyOperation(*this, dst, src,
2227f4a2713aSLionel Sambuc                        CGM.getARCEntrypoints().objc_moveWeak,
2228f4a2713aSLionel Sambuc                        "objc_moveWeak");
2229f4a2713aSLionel Sambuc }
2230f4a2713aSLionel Sambuc 
2231f4a2713aSLionel Sambuc /// void \@objc_copyWeak(i8** %dest, i8** %src)
2232f4a2713aSLionel Sambuc /// Disregards the current value in %dest.  Essentially
2233f4a2713aSLionel Sambuc ///   objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
EmitARCCopyWeak(llvm::Value * dst,llvm::Value * src)2234f4a2713aSLionel Sambuc void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2235f4a2713aSLionel Sambuc   emitARCCopyOperation(*this, dst, src,
2236f4a2713aSLionel Sambuc                        CGM.getARCEntrypoints().objc_copyWeak,
2237f4a2713aSLionel Sambuc                        "objc_copyWeak");
2238f4a2713aSLionel Sambuc }
2239f4a2713aSLionel Sambuc 
2240f4a2713aSLionel Sambuc /// Produce the code to do a objc_autoreleasepool_push.
2241f4a2713aSLionel Sambuc ///   call i8* \@objc_autoreleasePoolPush(void)
EmitObjCAutoreleasePoolPush()2242f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2243f4a2713aSLionel Sambuc   llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2244f4a2713aSLionel Sambuc   if (!fn) {
2245f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
2246f4a2713aSLionel Sambuc       llvm::FunctionType::get(Int8PtrTy, false);
2247f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2248f4a2713aSLionel Sambuc   }
2249f4a2713aSLionel Sambuc 
2250f4a2713aSLionel Sambuc   return EmitNounwindRuntimeCall(fn);
2251f4a2713aSLionel Sambuc }
2252f4a2713aSLionel Sambuc 
2253f4a2713aSLionel Sambuc /// Produce the code to do a primitive release.
2254f4a2713aSLionel Sambuc ///   call void \@objc_autoreleasePoolPop(i8* %ptr)
EmitObjCAutoreleasePoolPop(llvm::Value * value)2255f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2256f4a2713aSLionel Sambuc   assert(value->getType() == Int8PtrTy);
2257f4a2713aSLionel Sambuc 
2258f4a2713aSLionel Sambuc   llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2259f4a2713aSLionel Sambuc   if (!fn) {
2260f4a2713aSLionel Sambuc     llvm::FunctionType *fnType =
2261f4a2713aSLionel Sambuc       llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2262f4a2713aSLionel Sambuc 
2263f4a2713aSLionel Sambuc     // We don't want to use a weak import here; instead we should not
2264f4a2713aSLionel Sambuc     // fall into this path.
2265f4a2713aSLionel Sambuc     fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2266f4a2713aSLionel Sambuc   }
2267f4a2713aSLionel Sambuc 
2268f4a2713aSLionel Sambuc   // objc_autoreleasePoolPop can throw.
2269f4a2713aSLionel Sambuc   EmitRuntimeCallOrInvoke(fn, value);
2270f4a2713aSLionel Sambuc }
2271f4a2713aSLionel Sambuc 
2272f4a2713aSLionel Sambuc /// Produce the code to do an MRR version objc_autoreleasepool_push.
2273f4a2713aSLionel Sambuc /// Which is: [[NSAutoreleasePool alloc] init];
2274f4a2713aSLionel Sambuc /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2275f4a2713aSLionel Sambuc /// init is declared as: - (id) init; in its NSObject super class.
2276f4a2713aSLionel Sambuc ///
EmitObjCMRRAutoreleasePoolPush()2277f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2278f4a2713aSLionel Sambuc   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2279f4a2713aSLionel Sambuc   llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2280f4a2713aSLionel Sambuc   // [NSAutoreleasePool alloc]
2281f4a2713aSLionel Sambuc   IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2282f4a2713aSLionel Sambuc   Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2283f4a2713aSLionel Sambuc   CallArgList Args;
2284f4a2713aSLionel Sambuc   RValue AllocRV =
2285f4a2713aSLionel Sambuc     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2286f4a2713aSLionel Sambuc                                 getContext().getObjCIdType(),
2287f4a2713aSLionel Sambuc                                 AllocSel, Receiver, Args);
2288f4a2713aSLionel Sambuc 
2289f4a2713aSLionel Sambuc   // [Receiver init]
2290f4a2713aSLionel Sambuc   Receiver = AllocRV.getScalarVal();
2291f4a2713aSLionel Sambuc   II = &CGM.getContext().Idents.get("init");
2292f4a2713aSLionel Sambuc   Selector InitSel = getContext().Selectors.getSelector(0, &II);
2293f4a2713aSLionel Sambuc   RValue InitRV =
2294f4a2713aSLionel Sambuc     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2295f4a2713aSLionel Sambuc                                 getContext().getObjCIdType(),
2296f4a2713aSLionel Sambuc                                 InitSel, Receiver, Args);
2297f4a2713aSLionel Sambuc   return InitRV.getScalarVal();
2298f4a2713aSLionel Sambuc }
2299f4a2713aSLionel Sambuc 
2300f4a2713aSLionel Sambuc /// Produce the code to do a primitive release.
2301f4a2713aSLionel Sambuc /// [tmp drain];
EmitObjCMRRAutoreleasePoolPop(llvm::Value * Arg)2302f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2303f4a2713aSLionel Sambuc   IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2304f4a2713aSLionel Sambuc   Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2305f4a2713aSLionel Sambuc   CallArgList Args;
2306f4a2713aSLionel Sambuc   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2307f4a2713aSLionel Sambuc                               getContext().VoidTy, DrainSel, Arg, Args);
2308f4a2713aSLionel Sambuc }
2309f4a2713aSLionel Sambuc 
destroyARCStrongPrecise(CodeGenFunction & CGF,llvm::Value * addr,QualType type)2310f4a2713aSLionel Sambuc void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2311f4a2713aSLionel Sambuc                                               llvm::Value *addr,
2312f4a2713aSLionel Sambuc                                               QualType type) {
2313f4a2713aSLionel Sambuc   CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2314f4a2713aSLionel Sambuc }
2315f4a2713aSLionel Sambuc 
destroyARCStrongImprecise(CodeGenFunction & CGF,llvm::Value * addr,QualType type)2316f4a2713aSLionel Sambuc void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2317f4a2713aSLionel Sambuc                                                 llvm::Value *addr,
2318f4a2713aSLionel Sambuc                                                 QualType type) {
2319f4a2713aSLionel Sambuc   CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2320f4a2713aSLionel Sambuc }
2321f4a2713aSLionel Sambuc 
destroyARCWeak(CodeGenFunction & CGF,llvm::Value * addr,QualType type)2322f4a2713aSLionel Sambuc void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2323f4a2713aSLionel Sambuc                                      llvm::Value *addr,
2324f4a2713aSLionel Sambuc                                      QualType type) {
2325f4a2713aSLionel Sambuc   CGF.EmitARCDestroyWeak(addr);
2326f4a2713aSLionel Sambuc }
2327f4a2713aSLionel Sambuc 
2328f4a2713aSLionel Sambuc namespace {
2329f4a2713aSLionel Sambuc   struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2330f4a2713aSLionel Sambuc     llvm::Value *Token;
2331f4a2713aSLionel Sambuc 
CallObjCAutoreleasePoolObject__anon86dbc8190511::CallObjCAutoreleasePoolObject2332f4a2713aSLionel Sambuc     CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2333f4a2713aSLionel Sambuc 
Emit__anon86dbc8190511::CallObjCAutoreleasePoolObject2334*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
2335f4a2713aSLionel Sambuc       CGF.EmitObjCAutoreleasePoolPop(Token);
2336f4a2713aSLionel Sambuc     }
2337f4a2713aSLionel Sambuc   };
2338f4a2713aSLionel Sambuc   struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2339f4a2713aSLionel Sambuc     llvm::Value *Token;
2340f4a2713aSLionel Sambuc 
CallObjCMRRAutoreleasePoolObject__anon86dbc8190511::CallObjCMRRAutoreleasePoolObject2341f4a2713aSLionel Sambuc     CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2342f4a2713aSLionel Sambuc 
Emit__anon86dbc8190511::CallObjCMRRAutoreleasePoolObject2343*0a6a1f1dSLionel Sambuc     void Emit(CodeGenFunction &CGF, Flags flags) override {
2344f4a2713aSLionel Sambuc       CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2345f4a2713aSLionel Sambuc     }
2346f4a2713aSLionel Sambuc   };
2347f4a2713aSLionel Sambuc }
2348f4a2713aSLionel Sambuc 
EmitObjCAutoreleasePoolCleanup(llvm::Value * Ptr)2349f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2350f4a2713aSLionel Sambuc   if (CGM.getLangOpts().ObjCAutoRefCount)
2351f4a2713aSLionel Sambuc     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2352f4a2713aSLionel Sambuc   else
2353f4a2713aSLionel Sambuc     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2354f4a2713aSLionel Sambuc }
2355f4a2713aSLionel Sambuc 
tryEmitARCRetainLoadOfScalar(CodeGenFunction & CGF,LValue lvalue,QualType type)2356f4a2713aSLionel Sambuc static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2357f4a2713aSLionel Sambuc                                                   LValue lvalue,
2358f4a2713aSLionel Sambuc                                                   QualType type) {
2359f4a2713aSLionel Sambuc   switch (type.getObjCLifetime()) {
2360f4a2713aSLionel Sambuc   case Qualifiers::OCL_None:
2361f4a2713aSLionel Sambuc   case Qualifiers::OCL_ExplicitNone:
2362f4a2713aSLionel Sambuc   case Qualifiers::OCL_Strong:
2363f4a2713aSLionel Sambuc   case Qualifiers::OCL_Autoreleasing:
2364f4a2713aSLionel Sambuc     return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2365f4a2713aSLionel Sambuc                                               SourceLocation()).getScalarVal(),
2366f4a2713aSLionel Sambuc                          false);
2367f4a2713aSLionel Sambuc 
2368f4a2713aSLionel Sambuc   case Qualifiers::OCL_Weak:
2369f4a2713aSLionel Sambuc     return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2370f4a2713aSLionel Sambuc                          true);
2371f4a2713aSLionel Sambuc   }
2372f4a2713aSLionel Sambuc 
2373f4a2713aSLionel Sambuc   llvm_unreachable("impossible lifetime!");
2374f4a2713aSLionel Sambuc }
2375f4a2713aSLionel Sambuc 
tryEmitARCRetainLoadOfScalar(CodeGenFunction & CGF,const Expr * e)2376f4a2713aSLionel Sambuc static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2377f4a2713aSLionel Sambuc                                                   const Expr *e) {
2378f4a2713aSLionel Sambuc   e = e->IgnoreParens();
2379f4a2713aSLionel Sambuc   QualType type = e->getType();
2380f4a2713aSLionel Sambuc 
2381f4a2713aSLionel Sambuc   // If we're loading retained from a __strong xvalue, we can avoid
2382f4a2713aSLionel Sambuc   // an extra retain/release pair by zeroing out the source of this
2383f4a2713aSLionel Sambuc   // "move" operation.
2384f4a2713aSLionel Sambuc   if (e->isXValue() &&
2385f4a2713aSLionel Sambuc       !type.isConstQualified() &&
2386f4a2713aSLionel Sambuc       type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2387f4a2713aSLionel Sambuc     // Emit the lvalue.
2388f4a2713aSLionel Sambuc     LValue lv = CGF.EmitLValue(e);
2389f4a2713aSLionel Sambuc 
2390f4a2713aSLionel Sambuc     // Load the object pointer.
2391f4a2713aSLionel Sambuc     llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2392f4a2713aSLionel Sambuc                                                SourceLocation()).getScalarVal();
2393f4a2713aSLionel Sambuc 
2394f4a2713aSLionel Sambuc     // Set the source pointer to NULL.
2395f4a2713aSLionel Sambuc     CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2396f4a2713aSLionel Sambuc 
2397f4a2713aSLionel Sambuc     return TryEmitResult(result, true);
2398f4a2713aSLionel Sambuc   }
2399f4a2713aSLionel Sambuc 
2400f4a2713aSLionel Sambuc   // As a very special optimization, in ARC++, if the l-value is the
2401f4a2713aSLionel Sambuc   // result of a non-volatile assignment, do a simple retain of the
2402f4a2713aSLionel Sambuc   // result of the call to objc_storeWeak instead of reloading.
2403f4a2713aSLionel Sambuc   if (CGF.getLangOpts().CPlusPlus &&
2404f4a2713aSLionel Sambuc       !type.isVolatileQualified() &&
2405f4a2713aSLionel Sambuc       type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2406f4a2713aSLionel Sambuc       isa<BinaryOperator>(e) &&
2407f4a2713aSLionel Sambuc       cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2408f4a2713aSLionel Sambuc     return TryEmitResult(CGF.EmitScalarExpr(e), false);
2409f4a2713aSLionel Sambuc 
2410f4a2713aSLionel Sambuc   return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2411f4a2713aSLionel Sambuc }
2412f4a2713aSLionel Sambuc 
2413f4a2713aSLionel Sambuc static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2414f4a2713aSLionel Sambuc                                            llvm::Value *value);
2415f4a2713aSLionel Sambuc 
2416f4a2713aSLionel Sambuc /// Given that the given expression is some sort of call (which does
2417f4a2713aSLionel Sambuc /// not return retained), emit a retain following it.
emitARCRetainCall(CodeGenFunction & CGF,const Expr * e)2418f4a2713aSLionel Sambuc static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2419f4a2713aSLionel Sambuc   llvm::Value *value = CGF.EmitScalarExpr(e);
2420f4a2713aSLionel Sambuc   return emitARCRetainAfterCall(CGF, value);
2421f4a2713aSLionel Sambuc }
2422f4a2713aSLionel Sambuc 
emitARCRetainAfterCall(CodeGenFunction & CGF,llvm::Value * value)2423f4a2713aSLionel Sambuc static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2424f4a2713aSLionel Sambuc                                            llvm::Value *value) {
2425f4a2713aSLionel Sambuc   if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2426f4a2713aSLionel Sambuc     CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2427f4a2713aSLionel Sambuc 
2428f4a2713aSLionel Sambuc     // Place the retain immediately following the call.
2429f4a2713aSLionel Sambuc     CGF.Builder.SetInsertPoint(call->getParent(),
2430f4a2713aSLionel Sambuc                                ++llvm::BasicBlock::iterator(call));
2431f4a2713aSLionel Sambuc     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2432f4a2713aSLionel Sambuc 
2433f4a2713aSLionel Sambuc     CGF.Builder.restoreIP(ip);
2434f4a2713aSLionel Sambuc     return value;
2435f4a2713aSLionel Sambuc   } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2436f4a2713aSLionel Sambuc     CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2437f4a2713aSLionel Sambuc 
2438f4a2713aSLionel Sambuc     // Place the retain at the beginning of the normal destination block.
2439f4a2713aSLionel Sambuc     llvm::BasicBlock *BB = invoke->getNormalDest();
2440f4a2713aSLionel Sambuc     CGF.Builder.SetInsertPoint(BB, BB->begin());
2441f4a2713aSLionel Sambuc     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2442f4a2713aSLionel Sambuc 
2443f4a2713aSLionel Sambuc     CGF.Builder.restoreIP(ip);
2444f4a2713aSLionel Sambuc     return value;
2445f4a2713aSLionel Sambuc 
2446f4a2713aSLionel Sambuc   // Bitcasts can arise because of related-result returns.  Rewrite
2447f4a2713aSLionel Sambuc   // the operand.
2448f4a2713aSLionel Sambuc   } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2449f4a2713aSLionel Sambuc     llvm::Value *operand = bitcast->getOperand(0);
2450f4a2713aSLionel Sambuc     operand = emitARCRetainAfterCall(CGF, operand);
2451f4a2713aSLionel Sambuc     bitcast->setOperand(0, operand);
2452f4a2713aSLionel Sambuc     return bitcast;
2453f4a2713aSLionel Sambuc 
2454f4a2713aSLionel Sambuc   // Generic fall-back case.
2455f4a2713aSLionel Sambuc   } else {
2456f4a2713aSLionel Sambuc     // Retain using the non-block variant: we never need to do a copy
2457f4a2713aSLionel Sambuc     // of a block that's been returned to us.
2458f4a2713aSLionel Sambuc     return CGF.EmitARCRetainNonBlock(value);
2459f4a2713aSLionel Sambuc   }
2460f4a2713aSLionel Sambuc }
2461f4a2713aSLionel Sambuc 
2462f4a2713aSLionel Sambuc /// Determine whether it might be important to emit a separate
2463f4a2713aSLionel Sambuc /// objc_retain_block on the result of the given expression, or
2464f4a2713aSLionel Sambuc /// whether it's okay to just emit it in a +1 context.
shouldEmitSeparateBlockRetain(const Expr * e)2465f4a2713aSLionel Sambuc static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2466f4a2713aSLionel Sambuc   assert(e->getType()->isBlockPointerType());
2467f4a2713aSLionel Sambuc   e = e->IgnoreParens();
2468f4a2713aSLionel Sambuc 
2469f4a2713aSLionel Sambuc   // For future goodness, emit block expressions directly in +1
2470f4a2713aSLionel Sambuc   // contexts if we can.
2471f4a2713aSLionel Sambuc   if (isa<BlockExpr>(e))
2472f4a2713aSLionel Sambuc     return false;
2473f4a2713aSLionel Sambuc 
2474f4a2713aSLionel Sambuc   if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2475f4a2713aSLionel Sambuc     switch (cast->getCastKind()) {
2476f4a2713aSLionel Sambuc     // Emitting these operations in +1 contexts is goodness.
2477f4a2713aSLionel Sambuc     case CK_LValueToRValue:
2478f4a2713aSLionel Sambuc     case CK_ARCReclaimReturnedObject:
2479f4a2713aSLionel Sambuc     case CK_ARCConsumeObject:
2480f4a2713aSLionel Sambuc     case CK_ARCProduceObject:
2481f4a2713aSLionel Sambuc       return false;
2482f4a2713aSLionel Sambuc 
2483f4a2713aSLionel Sambuc     // These operations preserve a block type.
2484f4a2713aSLionel Sambuc     case CK_NoOp:
2485f4a2713aSLionel Sambuc     case CK_BitCast:
2486f4a2713aSLionel Sambuc       return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2487f4a2713aSLionel Sambuc 
2488f4a2713aSLionel Sambuc     // These operations are known to be bad (or haven't been considered).
2489f4a2713aSLionel Sambuc     case CK_AnyPointerToBlockPointerCast:
2490f4a2713aSLionel Sambuc     default:
2491f4a2713aSLionel Sambuc       return true;
2492f4a2713aSLionel Sambuc     }
2493f4a2713aSLionel Sambuc   }
2494f4a2713aSLionel Sambuc 
2495f4a2713aSLionel Sambuc   return true;
2496f4a2713aSLionel Sambuc }
2497f4a2713aSLionel Sambuc 
2498f4a2713aSLionel Sambuc /// Try to emit a PseudoObjectExpr at +1.
2499f4a2713aSLionel Sambuc ///
2500f4a2713aSLionel Sambuc /// This massively duplicates emitPseudoObjectRValue.
tryEmitARCRetainPseudoObject(CodeGenFunction & CGF,const PseudoObjectExpr * E)2501f4a2713aSLionel Sambuc static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2502f4a2713aSLionel Sambuc                                                   const PseudoObjectExpr *E) {
2503f4a2713aSLionel Sambuc   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2504f4a2713aSLionel Sambuc 
2505f4a2713aSLionel Sambuc   // Find the result expression.
2506f4a2713aSLionel Sambuc   const Expr *resultExpr = E->getResultExpr();
2507f4a2713aSLionel Sambuc   assert(resultExpr);
2508f4a2713aSLionel Sambuc   TryEmitResult result;
2509f4a2713aSLionel Sambuc 
2510f4a2713aSLionel Sambuc   for (PseudoObjectExpr::const_semantics_iterator
2511f4a2713aSLionel Sambuc          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2512f4a2713aSLionel Sambuc     const Expr *semantic = *i;
2513f4a2713aSLionel Sambuc 
2514f4a2713aSLionel Sambuc     // If this semantic expression is an opaque value, bind it
2515f4a2713aSLionel Sambuc     // to the result of its source expression.
2516f4a2713aSLionel Sambuc     if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2517f4a2713aSLionel Sambuc       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2518f4a2713aSLionel Sambuc       OVMA opaqueData;
2519f4a2713aSLionel Sambuc 
2520f4a2713aSLionel Sambuc       // If this semantic is the result of the pseudo-object
2521f4a2713aSLionel Sambuc       // expression, try to evaluate the source as +1.
2522f4a2713aSLionel Sambuc       if (ov == resultExpr) {
2523f4a2713aSLionel Sambuc         assert(!OVMA::shouldBindAsLValue(ov));
2524f4a2713aSLionel Sambuc         result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2525f4a2713aSLionel Sambuc         opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2526f4a2713aSLionel Sambuc 
2527f4a2713aSLionel Sambuc       // Otherwise, just bind it.
2528f4a2713aSLionel Sambuc       } else {
2529f4a2713aSLionel Sambuc         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2530f4a2713aSLionel Sambuc       }
2531f4a2713aSLionel Sambuc       opaques.push_back(opaqueData);
2532f4a2713aSLionel Sambuc 
2533f4a2713aSLionel Sambuc     // Otherwise, if the expression is the result, evaluate it
2534f4a2713aSLionel Sambuc     // and remember the result.
2535f4a2713aSLionel Sambuc     } else if (semantic == resultExpr) {
2536f4a2713aSLionel Sambuc       result = tryEmitARCRetainScalarExpr(CGF, semantic);
2537f4a2713aSLionel Sambuc 
2538f4a2713aSLionel Sambuc     // Otherwise, evaluate the expression in an ignored context.
2539f4a2713aSLionel Sambuc     } else {
2540f4a2713aSLionel Sambuc       CGF.EmitIgnoredExpr(semantic);
2541f4a2713aSLionel Sambuc     }
2542f4a2713aSLionel Sambuc   }
2543f4a2713aSLionel Sambuc 
2544f4a2713aSLionel Sambuc   // Unbind all the opaques now.
2545f4a2713aSLionel Sambuc   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2546f4a2713aSLionel Sambuc     opaques[i].unbind(CGF);
2547f4a2713aSLionel Sambuc 
2548f4a2713aSLionel Sambuc   return result;
2549f4a2713aSLionel Sambuc }
2550f4a2713aSLionel Sambuc 
2551f4a2713aSLionel Sambuc static TryEmitResult
tryEmitARCRetainScalarExpr(CodeGenFunction & CGF,const Expr * e)2552f4a2713aSLionel Sambuc tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2553f4a2713aSLionel Sambuc   // We should *never* see a nested full-expression here, because if
2554f4a2713aSLionel Sambuc   // we fail to emit at +1, our caller must not retain after we close
2555f4a2713aSLionel Sambuc   // out the full-expression.
2556f4a2713aSLionel Sambuc   assert(!isa<ExprWithCleanups>(e));
2557f4a2713aSLionel Sambuc 
2558f4a2713aSLionel Sambuc   // The desired result type, if it differs from the type of the
2559f4a2713aSLionel Sambuc   // ultimate opaque expression.
2560*0a6a1f1dSLionel Sambuc   llvm::Type *resultType = nullptr;
2561f4a2713aSLionel Sambuc 
2562f4a2713aSLionel Sambuc   while (true) {
2563f4a2713aSLionel Sambuc     e = e->IgnoreParens();
2564f4a2713aSLionel Sambuc 
2565f4a2713aSLionel Sambuc     // There's a break at the end of this if-chain;  anything
2566f4a2713aSLionel Sambuc     // that wants to keep looping has to explicitly continue.
2567f4a2713aSLionel Sambuc     if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2568f4a2713aSLionel Sambuc       switch (ce->getCastKind()) {
2569f4a2713aSLionel Sambuc       // No-op casts don't change the type, so we just ignore them.
2570f4a2713aSLionel Sambuc       case CK_NoOp:
2571f4a2713aSLionel Sambuc         e = ce->getSubExpr();
2572f4a2713aSLionel Sambuc         continue;
2573f4a2713aSLionel Sambuc 
2574f4a2713aSLionel Sambuc       case CK_LValueToRValue: {
2575f4a2713aSLionel Sambuc         TryEmitResult loadResult
2576f4a2713aSLionel Sambuc           = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2577f4a2713aSLionel Sambuc         if (resultType) {
2578f4a2713aSLionel Sambuc           llvm::Value *value = loadResult.getPointer();
2579f4a2713aSLionel Sambuc           value = CGF.Builder.CreateBitCast(value, resultType);
2580f4a2713aSLionel Sambuc           loadResult.setPointer(value);
2581f4a2713aSLionel Sambuc         }
2582f4a2713aSLionel Sambuc         return loadResult;
2583f4a2713aSLionel Sambuc       }
2584f4a2713aSLionel Sambuc 
2585f4a2713aSLionel Sambuc       // These casts can change the type, so remember that and
2586f4a2713aSLionel Sambuc       // soldier on.  We only need to remember the outermost such
2587f4a2713aSLionel Sambuc       // cast, though.
2588f4a2713aSLionel Sambuc       case CK_CPointerToObjCPointerCast:
2589f4a2713aSLionel Sambuc       case CK_BlockPointerToObjCPointerCast:
2590f4a2713aSLionel Sambuc       case CK_AnyPointerToBlockPointerCast:
2591f4a2713aSLionel Sambuc       case CK_BitCast:
2592f4a2713aSLionel Sambuc         if (!resultType)
2593f4a2713aSLionel Sambuc           resultType = CGF.ConvertType(ce->getType());
2594f4a2713aSLionel Sambuc         e = ce->getSubExpr();
2595f4a2713aSLionel Sambuc         assert(e->getType()->hasPointerRepresentation());
2596f4a2713aSLionel Sambuc         continue;
2597f4a2713aSLionel Sambuc 
2598f4a2713aSLionel Sambuc       // For consumptions, just emit the subexpression and thus elide
2599f4a2713aSLionel Sambuc       // the retain/release pair.
2600f4a2713aSLionel Sambuc       case CK_ARCConsumeObject: {
2601f4a2713aSLionel Sambuc         llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2602f4a2713aSLionel Sambuc         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2603f4a2713aSLionel Sambuc         return TryEmitResult(result, true);
2604f4a2713aSLionel Sambuc       }
2605f4a2713aSLionel Sambuc 
2606f4a2713aSLionel Sambuc       // Block extends are net +0.  Naively, we could just recurse on
2607f4a2713aSLionel Sambuc       // the subexpression, but actually we need to ensure that the
2608f4a2713aSLionel Sambuc       // value is copied as a block, so there's a little filter here.
2609f4a2713aSLionel Sambuc       case CK_ARCExtendBlockObject: {
2610f4a2713aSLionel Sambuc         llvm::Value *result; // will be a +0 value
2611f4a2713aSLionel Sambuc 
2612f4a2713aSLionel Sambuc         // If we can't safely assume the sub-expression will produce a
2613f4a2713aSLionel Sambuc         // block-copied value, emit the sub-expression at +0.
2614f4a2713aSLionel Sambuc         if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2615f4a2713aSLionel Sambuc           result = CGF.EmitScalarExpr(ce->getSubExpr());
2616f4a2713aSLionel Sambuc 
2617f4a2713aSLionel Sambuc         // Otherwise, try to emit the sub-expression at +1 recursively.
2618f4a2713aSLionel Sambuc         } else {
2619f4a2713aSLionel Sambuc           TryEmitResult subresult
2620f4a2713aSLionel Sambuc             = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2621f4a2713aSLionel Sambuc           result = subresult.getPointer();
2622f4a2713aSLionel Sambuc 
2623f4a2713aSLionel Sambuc           // If that produced a retained value, just use that,
2624f4a2713aSLionel Sambuc           // possibly casting down.
2625f4a2713aSLionel Sambuc           if (subresult.getInt()) {
2626f4a2713aSLionel Sambuc             if (resultType)
2627f4a2713aSLionel Sambuc               result = CGF.Builder.CreateBitCast(result, resultType);
2628f4a2713aSLionel Sambuc             return TryEmitResult(result, true);
2629f4a2713aSLionel Sambuc           }
2630f4a2713aSLionel Sambuc 
2631f4a2713aSLionel Sambuc           // Otherwise it's +0.
2632f4a2713aSLionel Sambuc         }
2633f4a2713aSLionel Sambuc 
2634f4a2713aSLionel Sambuc         // Retain the object as a block, then cast down.
2635f4a2713aSLionel Sambuc         result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2636f4a2713aSLionel Sambuc         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2637f4a2713aSLionel Sambuc         return TryEmitResult(result, true);
2638f4a2713aSLionel Sambuc       }
2639f4a2713aSLionel Sambuc 
2640f4a2713aSLionel Sambuc       // For reclaims, emit the subexpression as a retained call and
2641f4a2713aSLionel Sambuc       // skip the consumption.
2642f4a2713aSLionel Sambuc       case CK_ARCReclaimReturnedObject: {
2643f4a2713aSLionel Sambuc         llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2644f4a2713aSLionel Sambuc         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2645f4a2713aSLionel Sambuc         return TryEmitResult(result, true);
2646f4a2713aSLionel Sambuc       }
2647f4a2713aSLionel Sambuc 
2648f4a2713aSLionel Sambuc       default:
2649f4a2713aSLionel Sambuc         break;
2650f4a2713aSLionel Sambuc       }
2651f4a2713aSLionel Sambuc 
2652f4a2713aSLionel Sambuc     // Skip __extension__.
2653f4a2713aSLionel Sambuc     } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2654f4a2713aSLionel Sambuc       if (op->getOpcode() == UO_Extension) {
2655f4a2713aSLionel Sambuc         e = op->getSubExpr();
2656f4a2713aSLionel Sambuc         continue;
2657f4a2713aSLionel Sambuc       }
2658f4a2713aSLionel Sambuc 
2659f4a2713aSLionel Sambuc     // For calls and message sends, use the retained-call logic.
2660f4a2713aSLionel Sambuc     // Delegate inits are a special case in that they're the only
2661f4a2713aSLionel Sambuc     // returns-retained expression that *isn't* surrounded by
2662f4a2713aSLionel Sambuc     // a consume.
2663f4a2713aSLionel Sambuc     } else if (isa<CallExpr>(e) ||
2664f4a2713aSLionel Sambuc                (isa<ObjCMessageExpr>(e) &&
2665f4a2713aSLionel Sambuc                 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2666f4a2713aSLionel Sambuc       llvm::Value *result = emitARCRetainCall(CGF, e);
2667f4a2713aSLionel Sambuc       if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2668f4a2713aSLionel Sambuc       return TryEmitResult(result, true);
2669f4a2713aSLionel Sambuc 
2670f4a2713aSLionel Sambuc     // Look through pseudo-object expressions.
2671f4a2713aSLionel Sambuc     } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2672f4a2713aSLionel Sambuc       TryEmitResult result
2673f4a2713aSLionel Sambuc         = tryEmitARCRetainPseudoObject(CGF, pseudo);
2674f4a2713aSLionel Sambuc       if (resultType) {
2675f4a2713aSLionel Sambuc         llvm::Value *value = result.getPointer();
2676f4a2713aSLionel Sambuc         value = CGF.Builder.CreateBitCast(value, resultType);
2677f4a2713aSLionel Sambuc         result.setPointer(value);
2678f4a2713aSLionel Sambuc       }
2679f4a2713aSLionel Sambuc       return result;
2680f4a2713aSLionel Sambuc     }
2681f4a2713aSLionel Sambuc 
2682f4a2713aSLionel Sambuc     // Conservatively halt the search at any other expression kind.
2683f4a2713aSLionel Sambuc     break;
2684f4a2713aSLionel Sambuc   }
2685f4a2713aSLionel Sambuc 
2686f4a2713aSLionel Sambuc   // We didn't find an obvious production, so emit what we've got and
2687f4a2713aSLionel Sambuc   // tell the caller that we didn't manage to retain.
2688f4a2713aSLionel Sambuc   llvm::Value *result = CGF.EmitScalarExpr(e);
2689f4a2713aSLionel Sambuc   if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2690f4a2713aSLionel Sambuc   return TryEmitResult(result, false);
2691f4a2713aSLionel Sambuc }
2692f4a2713aSLionel Sambuc 
emitARCRetainLoadOfScalar(CodeGenFunction & CGF,LValue lvalue,QualType type)2693f4a2713aSLionel Sambuc static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2694f4a2713aSLionel Sambuc                                                 LValue lvalue,
2695f4a2713aSLionel Sambuc                                                 QualType type) {
2696f4a2713aSLionel Sambuc   TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2697f4a2713aSLionel Sambuc   llvm::Value *value = result.getPointer();
2698f4a2713aSLionel Sambuc   if (!result.getInt())
2699f4a2713aSLionel Sambuc     value = CGF.EmitARCRetain(type, value);
2700f4a2713aSLionel Sambuc   return value;
2701f4a2713aSLionel Sambuc }
2702f4a2713aSLionel Sambuc 
2703f4a2713aSLionel Sambuc /// EmitARCRetainScalarExpr - Semantically equivalent to
2704f4a2713aSLionel Sambuc /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2705f4a2713aSLionel Sambuc /// best-effort attempt to peephole expressions that naturally produce
2706f4a2713aSLionel Sambuc /// retained objects.
EmitARCRetainScalarExpr(const Expr * e)2707f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2708f4a2713aSLionel Sambuc   // The retain needs to happen within the full-expression.
2709f4a2713aSLionel Sambuc   if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2710f4a2713aSLionel Sambuc     enterFullExpression(cleanups);
2711f4a2713aSLionel Sambuc     RunCleanupsScope scope(*this);
2712f4a2713aSLionel Sambuc     return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2713f4a2713aSLionel Sambuc   }
2714f4a2713aSLionel Sambuc 
2715f4a2713aSLionel Sambuc   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2716f4a2713aSLionel Sambuc   llvm::Value *value = result.getPointer();
2717f4a2713aSLionel Sambuc   if (!result.getInt())
2718f4a2713aSLionel Sambuc     value = EmitARCRetain(e->getType(), value);
2719f4a2713aSLionel Sambuc   return value;
2720f4a2713aSLionel Sambuc }
2721f4a2713aSLionel Sambuc 
2722f4a2713aSLionel Sambuc llvm::Value *
EmitARCRetainAutoreleaseScalarExpr(const Expr * e)2723f4a2713aSLionel Sambuc CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2724f4a2713aSLionel Sambuc   // The retain needs to happen within the full-expression.
2725f4a2713aSLionel Sambuc   if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2726f4a2713aSLionel Sambuc     enterFullExpression(cleanups);
2727f4a2713aSLionel Sambuc     RunCleanupsScope scope(*this);
2728f4a2713aSLionel Sambuc     return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2729f4a2713aSLionel Sambuc   }
2730f4a2713aSLionel Sambuc 
2731f4a2713aSLionel Sambuc   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2732f4a2713aSLionel Sambuc   llvm::Value *value = result.getPointer();
2733f4a2713aSLionel Sambuc   if (result.getInt())
2734f4a2713aSLionel Sambuc     value = EmitARCAutorelease(value);
2735f4a2713aSLionel Sambuc   else
2736f4a2713aSLionel Sambuc     value = EmitARCRetainAutorelease(e->getType(), value);
2737f4a2713aSLionel Sambuc   return value;
2738f4a2713aSLionel Sambuc }
2739f4a2713aSLionel Sambuc 
EmitARCExtendBlockObject(const Expr * e)2740f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2741f4a2713aSLionel Sambuc   llvm::Value *result;
2742f4a2713aSLionel Sambuc   bool doRetain;
2743f4a2713aSLionel Sambuc 
2744f4a2713aSLionel Sambuc   if (shouldEmitSeparateBlockRetain(e)) {
2745f4a2713aSLionel Sambuc     result = EmitScalarExpr(e);
2746f4a2713aSLionel Sambuc     doRetain = true;
2747f4a2713aSLionel Sambuc   } else {
2748f4a2713aSLionel Sambuc     TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2749f4a2713aSLionel Sambuc     result = subresult.getPointer();
2750f4a2713aSLionel Sambuc     doRetain = !subresult.getInt();
2751f4a2713aSLionel Sambuc   }
2752f4a2713aSLionel Sambuc 
2753f4a2713aSLionel Sambuc   if (doRetain)
2754f4a2713aSLionel Sambuc     result = EmitARCRetainBlock(result, /*mandatory*/ true);
2755f4a2713aSLionel Sambuc   return EmitObjCConsumeObject(e->getType(), result);
2756f4a2713aSLionel Sambuc }
2757f4a2713aSLionel Sambuc 
EmitObjCThrowOperand(const Expr * expr)2758f4a2713aSLionel Sambuc llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2759f4a2713aSLionel Sambuc   // In ARC, retain and autorelease the expression.
2760f4a2713aSLionel Sambuc   if (getLangOpts().ObjCAutoRefCount) {
2761f4a2713aSLionel Sambuc     // Do so before running any cleanups for the full-expression.
2762f4a2713aSLionel Sambuc     // EmitARCRetainAutoreleaseScalarExpr does this for us.
2763f4a2713aSLionel Sambuc     return EmitARCRetainAutoreleaseScalarExpr(expr);
2764f4a2713aSLionel Sambuc   }
2765f4a2713aSLionel Sambuc 
2766f4a2713aSLionel Sambuc   // Otherwise, use the normal scalar-expression emission.  The
2767f4a2713aSLionel Sambuc   // exception machinery doesn't do anything special with the
2768f4a2713aSLionel Sambuc   // exception like retaining it, so there's no safety associated with
2769f4a2713aSLionel Sambuc   // only running cleanups after the throw has started, and when it
2770f4a2713aSLionel Sambuc   // matters it tends to be substantially inferior code.
2771f4a2713aSLionel Sambuc   return EmitScalarExpr(expr);
2772f4a2713aSLionel Sambuc }
2773f4a2713aSLionel Sambuc 
2774f4a2713aSLionel Sambuc std::pair<LValue,llvm::Value*>
EmitARCStoreStrong(const BinaryOperator * e,bool ignored)2775f4a2713aSLionel Sambuc CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2776f4a2713aSLionel Sambuc                                     bool ignored) {
2777f4a2713aSLionel Sambuc   // Evaluate the RHS first.
2778f4a2713aSLionel Sambuc   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2779f4a2713aSLionel Sambuc   llvm::Value *value = result.getPointer();
2780f4a2713aSLionel Sambuc 
2781f4a2713aSLionel Sambuc   bool hasImmediateRetain = result.getInt();
2782f4a2713aSLionel Sambuc 
2783f4a2713aSLionel Sambuc   // If we didn't emit a retained object, and the l-value is of block
2784f4a2713aSLionel Sambuc   // type, then we need to emit the block-retain immediately in case
2785f4a2713aSLionel Sambuc   // it invalidates the l-value.
2786f4a2713aSLionel Sambuc   if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2787f4a2713aSLionel Sambuc     value = EmitARCRetainBlock(value, /*mandatory*/ false);
2788f4a2713aSLionel Sambuc     hasImmediateRetain = true;
2789f4a2713aSLionel Sambuc   }
2790f4a2713aSLionel Sambuc 
2791f4a2713aSLionel Sambuc   LValue lvalue = EmitLValue(e->getLHS());
2792f4a2713aSLionel Sambuc 
2793f4a2713aSLionel Sambuc   // If the RHS was emitted retained, expand this.
2794f4a2713aSLionel Sambuc   if (hasImmediateRetain) {
2795f4a2713aSLionel Sambuc     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
2796f4a2713aSLionel Sambuc     EmitStoreOfScalar(value, lvalue);
2797f4a2713aSLionel Sambuc     EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
2798f4a2713aSLionel Sambuc   } else {
2799f4a2713aSLionel Sambuc     value = EmitARCStoreStrong(lvalue, value, ignored);
2800f4a2713aSLionel Sambuc   }
2801f4a2713aSLionel Sambuc 
2802f4a2713aSLionel Sambuc   return std::pair<LValue,llvm::Value*>(lvalue, value);
2803f4a2713aSLionel Sambuc }
2804f4a2713aSLionel Sambuc 
2805f4a2713aSLionel Sambuc std::pair<LValue,llvm::Value*>
EmitARCStoreAutoreleasing(const BinaryOperator * e)2806f4a2713aSLionel Sambuc CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2807f4a2713aSLionel Sambuc   llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2808f4a2713aSLionel Sambuc   LValue lvalue = EmitLValue(e->getLHS());
2809f4a2713aSLionel Sambuc 
2810f4a2713aSLionel Sambuc   EmitStoreOfScalar(value, lvalue);
2811f4a2713aSLionel Sambuc 
2812f4a2713aSLionel Sambuc   return std::pair<LValue,llvm::Value*>(lvalue, value);
2813f4a2713aSLionel Sambuc }
2814f4a2713aSLionel Sambuc 
EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt & ARPS)2815f4a2713aSLionel Sambuc void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2816f4a2713aSLionel Sambuc                                           const ObjCAutoreleasePoolStmt &ARPS) {
2817f4a2713aSLionel Sambuc   const Stmt *subStmt = ARPS.getSubStmt();
2818f4a2713aSLionel Sambuc   const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2819f4a2713aSLionel Sambuc 
2820f4a2713aSLionel Sambuc   CGDebugInfo *DI = getDebugInfo();
2821f4a2713aSLionel Sambuc   if (DI)
2822f4a2713aSLionel Sambuc     DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
2823f4a2713aSLionel Sambuc 
2824f4a2713aSLionel Sambuc   // Keep track of the current cleanup stack depth.
2825f4a2713aSLionel Sambuc   RunCleanupsScope Scope(*this);
2826f4a2713aSLionel Sambuc   if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
2827f4a2713aSLionel Sambuc     llvm::Value *token = EmitObjCAutoreleasePoolPush();
2828f4a2713aSLionel Sambuc     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2829f4a2713aSLionel Sambuc   } else {
2830f4a2713aSLionel Sambuc     llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2831f4a2713aSLionel Sambuc     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2832f4a2713aSLionel Sambuc   }
2833f4a2713aSLionel Sambuc 
2834*0a6a1f1dSLionel Sambuc   for (const auto *I : S.body())
2835*0a6a1f1dSLionel Sambuc     EmitStmt(I);
2836f4a2713aSLionel Sambuc 
2837f4a2713aSLionel Sambuc   if (DI)
2838f4a2713aSLionel Sambuc     DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
2839f4a2713aSLionel Sambuc }
2840f4a2713aSLionel Sambuc 
2841f4a2713aSLionel Sambuc /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2842f4a2713aSLionel Sambuc /// make sure it survives garbage collection until this point.
EmitExtendGCLifetime(llvm::Value * object)2843f4a2713aSLionel Sambuc void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2844f4a2713aSLionel Sambuc   // We just use an inline assembly.
2845f4a2713aSLionel Sambuc   llvm::FunctionType *extenderType
2846f4a2713aSLionel Sambuc     = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
2847f4a2713aSLionel Sambuc   llvm::Value *extender
2848f4a2713aSLionel Sambuc     = llvm::InlineAsm::get(extenderType,
2849f4a2713aSLionel Sambuc                            /* assembly */ "",
2850f4a2713aSLionel Sambuc                            /* constraints */ "r",
2851f4a2713aSLionel Sambuc                            /* side effects */ true);
2852f4a2713aSLionel Sambuc 
2853f4a2713aSLionel Sambuc   object = Builder.CreateBitCast(object, VoidPtrTy);
2854f4a2713aSLionel Sambuc   EmitNounwindRuntimeCall(extender, object);
2855f4a2713aSLionel Sambuc }
2856f4a2713aSLionel Sambuc 
2857f4a2713aSLionel Sambuc /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
2858f4a2713aSLionel Sambuc /// non-trivial copy assignment function, produce following helper function.
2859f4a2713aSLionel Sambuc /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2860f4a2713aSLionel Sambuc ///
2861f4a2713aSLionel Sambuc llvm::Constant *
GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl * PID)2862f4a2713aSLionel Sambuc CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2863f4a2713aSLionel Sambuc                                         const ObjCPropertyImplDecl *PID) {
2864f4a2713aSLionel Sambuc   if (!getLangOpts().CPlusPlus ||
2865f4a2713aSLionel Sambuc       !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
2866*0a6a1f1dSLionel Sambuc     return nullptr;
2867f4a2713aSLionel Sambuc   QualType Ty = PID->getPropertyIvarDecl()->getType();
2868f4a2713aSLionel Sambuc   if (!Ty->isRecordType())
2869*0a6a1f1dSLionel Sambuc     return nullptr;
2870f4a2713aSLionel Sambuc   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2871f4a2713aSLionel Sambuc   if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2872*0a6a1f1dSLionel Sambuc     return nullptr;
2873*0a6a1f1dSLionel Sambuc   llvm::Constant *HelperFn = nullptr;
2874f4a2713aSLionel Sambuc   if (hasTrivialSetExpr(PID))
2875*0a6a1f1dSLionel Sambuc     return nullptr;
2876f4a2713aSLionel Sambuc   assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2877f4a2713aSLionel Sambuc   if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2878f4a2713aSLionel Sambuc     return HelperFn;
2879f4a2713aSLionel Sambuc 
2880f4a2713aSLionel Sambuc   ASTContext &C = getContext();
2881f4a2713aSLionel Sambuc   IdentifierInfo *II
2882f4a2713aSLionel Sambuc     = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
2883f4a2713aSLionel Sambuc   FunctionDecl *FD = FunctionDecl::Create(C,
2884f4a2713aSLionel Sambuc                                           C.getTranslationUnitDecl(),
2885f4a2713aSLionel Sambuc                                           SourceLocation(),
2886*0a6a1f1dSLionel Sambuc                                           SourceLocation(), II, C.VoidTy,
2887*0a6a1f1dSLionel Sambuc                                           nullptr, SC_Static,
2888f4a2713aSLionel Sambuc                                           false,
2889f4a2713aSLionel Sambuc                                           false);
2890f4a2713aSLionel Sambuc 
2891f4a2713aSLionel Sambuc   QualType DestTy = C.getPointerType(Ty);
2892f4a2713aSLionel Sambuc   QualType SrcTy = Ty;
2893f4a2713aSLionel Sambuc   SrcTy.addConst();
2894f4a2713aSLionel Sambuc   SrcTy = C.getPointerType(SrcTy);
2895f4a2713aSLionel Sambuc 
2896f4a2713aSLionel Sambuc   FunctionArgList args;
2897*0a6a1f1dSLionel Sambuc   ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
2898f4a2713aSLionel Sambuc   args.push_back(&dstDecl);
2899*0a6a1f1dSLionel Sambuc   ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
2900f4a2713aSLionel Sambuc   args.push_back(&srcDecl);
2901f4a2713aSLionel Sambuc 
2902*0a6a1f1dSLionel Sambuc   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2903*0a6a1f1dSLionel Sambuc       C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2904f4a2713aSLionel Sambuc 
2905f4a2713aSLionel Sambuc   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2906f4a2713aSLionel Sambuc 
2907f4a2713aSLionel Sambuc   llvm::Function *Fn =
2908f4a2713aSLionel Sambuc     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2909f4a2713aSLionel Sambuc                            "__assign_helper_atomic_property_",
2910f4a2713aSLionel Sambuc                            &CGM.getModule());
2911f4a2713aSLionel Sambuc 
2912*0a6a1f1dSLionel Sambuc   StartFunction(FD, C.VoidTy, Fn, FI, args);
2913f4a2713aSLionel Sambuc 
2914f4a2713aSLionel Sambuc   DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2915f4a2713aSLionel Sambuc                       VK_RValue, SourceLocation());
2916f4a2713aSLionel Sambuc   UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2917f4a2713aSLionel Sambuc                     VK_LValue, OK_Ordinary, SourceLocation());
2918f4a2713aSLionel Sambuc 
2919f4a2713aSLionel Sambuc   DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2920f4a2713aSLionel Sambuc                       VK_RValue, SourceLocation());
2921f4a2713aSLionel Sambuc   UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2922f4a2713aSLionel Sambuc                     VK_LValue, OK_Ordinary, SourceLocation());
2923f4a2713aSLionel Sambuc 
2924f4a2713aSLionel Sambuc   Expr *Args[2] = { &DST, &SRC };
2925f4a2713aSLionel Sambuc   CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
2926f4a2713aSLionel Sambuc   CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2927f4a2713aSLionel Sambuc                               Args, DestTy->getPointeeType(),
2928f4a2713aSLionel Sambuc                               VK_LValue, SourceLocation(), false);
2929f4a2713aSLionel Sambuc 
2930f4a2713aSLionel Sambuc   EmitStmt(&TheCall);
2931f4a2713aSLionel Sambuc 
2932f4a2713aSLionel Sambuc   FinishFunction();
2933f4a2713aSLionel Sambuc   HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2934f4a2713aSLionel Sambuc   CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
2935f4a2713aSLionel Sambuc   return HelperFn;
2936f4a2713aSLionel Sambuc }
2937f4a2713aSLionel Sambuc 
2938f4a2713aSLionel Sambuc llvm::Constant *
GenerateObjCAtomicGetterCopyHelperFunction(const ObjCPropertyImplDecl * PID)2939f4a2713aSLionel Sambuc CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2940f4a2713aSLionel Sambuc                                             const ObjCPropertyImplDecl *PID) {
2941f4a2713aSLionel Sambuc   if (!getLangOpts().CPlusPlus ||
2942f4a2713aSLionel Sambuc       !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
2943*0a6a1f1dSLionel Sambuc     return nullptr;
2944f4a2713aSLionel Sambuc   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2945f4a2713aSLionel Sambuc   QualType Ty = PD->getType();
2946f4a2713aSLionel Sambuc   if (!Ty->isRecordType())
2947*0a6a1f1dSLionel Sambuc     return nullptr;
2948f4a2713aSLionel Sambuc   if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2949*0a6a1f1dSLionel Sambuc     return nullptr;
2950*0a6a1f1dSLionel Sambuc   llvm::Constant *HelperFn = nullptr;
2951f4a2713aSLionel Sambuc 
2952f4a2713aSLionel Sambuc   if (hasTrivialGetExpr(PID))
2953*0a6a1f1dSLionel Sambuc     return nullptr;
2954f4a2713aSLionel Sambuc   assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2955f4a2713aSLionel Sambuc   if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2956f4a2713aSLionel Sambuc     return HelperFn;
2957f4a2713aSLionel Sambuc 
2958f4a2713aSLionel Sambuc 
2959f4a2713aSLionel Sambuc   ASTContext &C = getContext();
2960f4a2713aSLionel Sambuc   IdentifierInfo *II
2961f4a2713aSLionel Sambuc   = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2962f4a2713aSLionel Sambuc   FunctionDecl *FD = FunctionDecl::Create(C,
2963f4a2713aSLionel Sambuc                                           C.getTranslationUnitDecl(),
2964f4a2713aSLionel Sambuc                                           SourceLocation(),
2965*0a6a1f1dSLionel Sambuc                                           SourceLocation(), II, C.VoidTy,
2966*0a6a1f1dSLionel Sambuc                                           nullptr, SC_Static,
2967f4a2713aSLionel Sambuc                                           false,
2968f4a2713aSLionel Sambuc                                           false);
2969f4a2713aSLionel Sambuc 
2970f4a2713aSLionel Sambuc   QualType DestTy = C.getPointerType(Ty);
2971f4a2713aSLionel Sambuc   QualType SrcTy = Ty;
2972f4a2713aSLionel Sambuc   SrcTy.addConst();
2973f4a2713aSLionel Sambuc   SrcTy = C.getPointerType(SrcTy);
2974f4a2713aSLionel Sambuc 
2975f4a2713aSLionel Sambuc   FunctionArgList args;
2976*0a6a1f1dSLionel Sambuc   ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
2977f4a2713aSLionel Sambuc   args.push_back(&dstDecl);
2978*0a6a1f1dSLionel Sambuc   ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
2979f4a2713aSLionel Sambuc   args.push_back(&srcDecl);
2980f4a2713aSLionel Sambuc 
2981*0a6a1f1dSLionel Sambuc   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2982*0a6a1f1dSLionel Sambuc       C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2983f4a2713aSLionel Sambuc 
2984f4a2713aSLionel Sambuc   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2985f4a2713aSLionel Sambuc 
2986f4a2713aSLionel Sambuc   llvm::Function *Fn =
2987f4a2713aSLionel Sambuc   llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2988f4a2713aSLionel Sambuc                          "__copy_helper_atomic_property_", &CGM.getModule());
2989f4a2713aSLionel Sambuc 
2990*0a6a1f1dSLionel Sambuc   StartFunction(FD, C.VoidTy, Fn, FI, args);
2991f4a2713aSLionel Sambuc 
2992f4a2713aSLionel Sambuc   DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2993f4a2713aSLionel Sambuc                       VK_RValue, SourceLocation());
2994f4a2713aSLionel Sambuc 
2995f4a2713aSLionel Sambuc   UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2996f4a2713aSLionel Sambuc                     VK_LValue, OK_Ordinary, SourceLocation());
2997f4a2713aSLionel Sambuc 
2998f4a2713aSLionel Sambuc   CXXConstructExpr *CXXConstExpr =
2999f4a2713aSLionel Sambuc     cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3000f4a2713aSLionel Sambuc 
3001f4a2713aSLionel Sambuc   SmallVector<Expr*, 4> ConstructorArgs;
3002f4a2713aSLionel Sambuc   ConstructorArgs.push_back(&SRC);
3003f4a2713aSLionel Sambuc   CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3004f4a2713aSLionel Sambuc   ++A;
3005f4a2713aSLionel Sambuc 
3006f4a2713aSLionel Sambuc   for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3007f4a2713aSLionel Sambuc        A != AEnd; ++A)
3008f4a2713aSLionel Sambuc     ConstructorArgs.push_back(*A);
3009f4a2713aSLionel Sambuc 
3010f4a2713aSLionel Sambuc   CXXConstructExpr *TheCXXConstructExpr =
3011f4a2713aSLionel Sambuc     CXXConstructExpr::Create(C, Ty, SourceLocation(),
3012f4a2713aSLionel Sambuc                              CXXConstExpr->getConstructor(),
3013f4a2713aSLionel Sambuc                              CXXConstExpr->isElidable(),
3014f4a2713aSLionel Sambuc                              ConstructorArgs,
3015f4a2713aSLionel Sambuc                              CXXConstExpr->hadMultipleCandidates(),
3016f4a2713aSLionel Sambuc                              CXXConstExpr->isListInitialization(),
3017*0a6a1f1dSLionel Sambuc                              CXXConstExpr->isStdInitListInitialization(),
3018f4a2713aSLionel Sambuc                              CXXConstExpr->requiresZeroInitialization(),
3019f4a2713aSLionel Sambuc                              CXXConstExpr->getConstructionKind(),
3020f4a2713aSLionel Sambuc                              SourceRange());
3021f4a2713aSLionel Sambuc 
3022f4a2713aSLionel Sambuc   DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3023f4a2713aSLionel Sambuc                       VK_RValue, SourceLocation());
3024f4a2713aSLionel Sambuc 
3025f4a2713aSLionel Sambuc   RValue DV = EmitAnyExpr(&DstExpr);
3026f4a2713aSLionel Sambuc   CharUnits Alignment
3027f4a2713aSLionel Sambuc     = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3028f4a2713aSLionel Sambuc   EmitAggExpr(TheCXXConstructExpr,
3029f4a2713aSLionel Sambuc               AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3030f4a2713aSLionel Sambuc                                     AggValueSlot::IsDestructed,
3031f4a2713aSLionel Sambuc                                     AggValueSlot::DoesNotNeedGCBarriers,
3032f4a2713aSLionel Sambuc                                     AggValueSlot::IsNotAliased));
3033f4a2713aSLionel Sambuc 
3034f4a2713aSLionel Sambuc   FinishFunction();
3035f4a2713aSLionel Sambuc   HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3036f4a2713aSLionel Sambuc   CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3037f4a2713aSLionel Sambuc   return HelperFn;
3038f4a2713aSLionel Sambuc }
3039f4a2713aSLionel Sambuc 
3040f4a2713aSLionel Sambuc llvm::Value *
EmitBlockCopyAndAutorelease(llvm::Value * Block,QualType Ty)3041f4a2713aSLionel Sambuc CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3042f4a2713aSLionel Sambuc   // Get selectors for retain/autorelease.
3043f4a2713aSLionel Sambuc   IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3044f4a2713aSLionel Sambuc   Selector CopySelector =
3045f4a2713aSLionel Sambuc       getContext().Selectors.getNullarySelector(CopyID);
3046f4a2713aSLionel Sambuc   IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3047f4a2713aSLionel Sambuc   Selector AutoreleaseSelector =
3048f4a2713aSLionel Sambuc       getContext().Selectors.getNullarySelector(AutoreleaseID);
3049f4a2713aSLionel Sambuc 
3050f4a2713aSLionel Sambuc   // Emit calls to retain/autorelease.
3051f4a2713aSLionel Sambuc   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3052f4a2713aSLionel Sambuc   llvm::Value *Val = Block;
3053f4a2713aSLionel Sambuc   RValue Result;
3054f4a2713aSLionel Sambuc   Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3055f4a2713aSLionel Sambuc                                        Ty, CopySelector,
3056*0a6a1f1dSLionel Sambuc                                        Val, CallArgList(), nullptr, nullptr);
3057f4a2713aSLionel Sambuc   Val = Result.getScalarVal();
3058f4a2713aSLionel Sambuc   Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3059f4a2713aSLionel Sambuc                                        Ty, AutoreleaseSelector,
3060*0a6a1f1dSLionel Sambuc                                        Val, CallArgList(), nullptr, nullptr);
3061f4a2713aSLionel Sambuc   Val = Result.getScalarVal();
3062f4a2713aSLionel Sambuc   return Val;
3063f4a2713aSLionel Sambuc }
3064f4a2713aSLionel Sambuc 
3065f4a2713aSLionel Sambuc 
~CGObjCRuntime()3066f4a2713aSLionel Sambuc CGObjCRuntime::~CGObjCRuntime() {}
3067