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