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