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