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