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