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