]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGObjC.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / CodeGen / CGObjC.cpp
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
33 /// Given the address of a variable of pointer type, find the correct
34 /// null to store into it.
35 static llvm::Constant *getNullForVariable(llvm::Value *addr) {
36   const llvm::Type *type =
37     cast<llvm::PointerType>(addr->getType())->getElementType();
38   return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39 }
40
41 /// Emits an instance of NSConstantString representing the object.
42 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
43 {
44   llvm::Constant *C = 
45       CGM.getObjCRuntime().GenerateConstantString(E->getString());
46   // FIXME: This bitcast should just be made an invariant on the Runtime.
47   return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
48 }
49
50 /// Emit a selector.
51 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52   // Untyped selector.
53   // Note that this implementation allows for non-constant strings to be passed
54   // as arguments to @selector().  Currently, the only thing preventing this
55   // behaviour is the type checking in the front end.
56   return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
57 }
58
59 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60   // FIXME: This should pass the Decl not the name.
61   return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62 }
63
64 /// \brief Adjust the type of the result of an Objective-C message send 
65 /// expression when the method has a related result type.
66 static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67                                       const Expr *E,
68                                       const ObjCMethodDecl *Method,
69                                       RValue Result) {
70   if (!Method)
71     return Result;
72
73   if (!Method->hasRelatedResultType() ||
74       CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75       !Result.isScalar())
76     return Result;
77   
78   // We have applied a related result type. Cast the rvalue appropriately.
79   return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80                                                CGF.ConvertType(E->getType())));
81 }
82
83 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
84                                             ReturnValueSlot Return) {
85   // Only the lookup mechanism and first two arguments of the method
86   // implementation vary between runtimes.  We can get the receiver and
87   // arguments in generic code.
88
89   bool isDelegateInit = E->isDelegateInitCall();
90
91   // We don't retain the receiver in delegate init calls, and this is
92   // safe because the receiver value is always loaded from 'self',
93   // which we zero out.  We don't want to Block_copy block receivers,
94   // though.
95   bool retainSelf =
96     (!isDelegateInit &&
97      CGM.getLangOptions().ObjCAutoRefCount &&
98      E->getMethodDecl() &&
99      E->getMethodDecl()->hasAttr<NSConsumesSelfAttr>());
100
101   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
102   bool isSuperMessage = false;
103   bool isClassMessage = false;
104   ObjCInterfaceDecl *OID = 0;
105   // Find the receiver
106   QualType ReceiverType;
107   llvm::Value *Receiver = 0;
108   switch (E->getReceiverKind()) {
109   case ObjCMessageExpr::Instance:
110     ReceiverType = E->getInstanceReceiver()->getType();
111     if (retainSelf) {
112       TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
113                                                    E->getInstanceReceiver());
114       Receiver = ter.getPointer();
115       if (!ter.getInt())
116         Receiver = EmitARCRetainNonBlock(Receiver);
117     } else
118       Receiver = EmitScalarExpr(E->getInstanceReceiver());
119     break;
120
121   case ObjCMessageExpr::Class: {
122     ReceiverType = E->getClassReceiver();
123     const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
124     assert(ObjTy && "Invalid Objective-C class message send");
125     OID = ObjTy->getInterface();
126     assert(OID && "Invalid Objective-C class message send");
127     Receiver = Runtime.GetClass(Builder, OID);
128     isClassMessage = true;
129
130     if (retainSelf)
131       Receiver = EmitARCRetainNonBlock(Receiver);
132     break;
133   }
134
135   case ObjCMessageExpr::SuperInstance:
136     ReceiverType = E->getSuperType();
137     Receiver = LoadObjCSelf();
138     isSuperMessage = true;
139
140     if (retainSelf)
141       Receiver = EmitARCRetainNonBlock(Receiver);
142     break;
143
144   case ObjCMessageExpr::SuperClass:
145     ReceiverType = E->getSuperType();
146     Receiver = LoadObjCSelf();
147     isSuperMessage = true;
148     isClassMessage = true;
149
150     if (retainSelf)
151       Receiver = EmitARCRetainNonBlock(Receiver);
152     break;
153   }
154
155   QualType ResultType =
156     E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
157
158   CallArgList Args;
159   EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
160
161   // For delegate init calls in ARC, do an unsafe store of null into
162   // self.  This represents the call taking direct ownership of that
163   // value.  We have to do this after emitting the other call
164   // arguments because they might also reference self, but we don't
165   // have to worry about any of them modifying self because that would
166   // be an undefined read and write of an object in unordered
167   // expressions.
168   if (isDelegateInit) {
169     assert(getLangOptions().ObjCAutoRefCount &&
170            "delegate init calls should only be marked in ARC");
171
172     // Do an unsafe store of null into self.
173     llvm::Value *selfAddr =
174       LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
175     assert(selfAddr && "no self entry for a delegate init call?");
176
177     Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
178   }
179
180   RValue result;
181   if (isSuperMessage) {
182     // super is only valid in an Objective-C method
183     const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
184     bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
185     result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
186                                               E->getSelector(),
187                                               OMD->getClassInterface(),
188                                               isCategoryImpl,
189                                               Receiver,
190                                               isClassMessage,
191                                               Args,
192                                               E->getMethodDecl());
193   } else {
194     result = Runtime.GenerateMessageSend(*this, Return, ResultType,
195                                          E->getSelector(),
196                                          Receiver, Args, OID,
197                                          E->getMethodDecl());
198   }
199
200   // For delegate init calls in ARC, implicitly store the result of
201   // the call back into self.  This takes ownership of the value.
202   if (isDelegateInit) {
203     llvm::Value *selfAddr =
204       LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
205     llvm::Value *newSelf = result.getScalarVal();
206
207     // The delegate return type isn't necessarily a matching type; in
208     // fact, it's quite likely to be 'id'.
209     const llvm::Type *selfTy =
210       cast<llvm::PointerType>(selfAddr->getType())->getElementType();
211     newSelf = Builder.CreateBitCast(newSelf, selfTy);
212
213     Builder.CreateStore(newSelf, selfAddr);
214   }
215
216   return AdjustRelatedResultType(*this, E, E->getMethodDecl(), result);
217 }
218
219 namespace {
220 struct FinishARCDealloc : EHScopeStack::Cleanup {
221   void Emit(CodeGenFunction &CGF, Flags flags) {
222     const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
223
224     const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
225     const ObjCInterfaceDecl *iface = impl->getClassInterface();
226     if (!iface->getSuperClass()) return;
227
228     bool isCategory = isa<ObjCCategoryImplDecl>(impl);
229
230     // Call [super dealloc] if we have a superclass.
231     llvm::Value *self = CGF.LoadObjCSelf();
232
233     CallArgList args;
234     CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
235                                                       CGF.getContext().VoidTy,
236                                                       method->getSelector(),
237                                                       iface,
238                                                       isCategory,
239                                                       self,
240                                                       /*is class msg*/ false,
241                                                       args,
242                                                       method);
243   }
244 };
245 }
246
247 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
248 /// the LLVM function and sets the other context used by
249 /// CodeGenFunction.
250 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
251                                       const ObjCContainerDecl *CD,
252                                       SourceLocation StartLoc) {
253   FunctionArgList args;
254   // Check if we should generate debug info for this method.
255   if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
256     DebugInfo = CGM.getModuleDebugInfo();
257
258   llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
259
260   const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
261   CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
262
263   args.push_back(OMD->getSelfDecl());
264   args.push_back(OMD->getCmdDecl());
265
266   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
267        E = OMD->param_end(); PI != E; ++PI)
268     args.push_back(*PI);
269
270   CurGD = OMD;
271
272   StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
273
274   // In ARC, certain methods get an extra cleanup.
275   if (CGM.getLangOptions().ObjCAutoRefCount &&
276       OMD->isInstanceMethod() &&
277       OMD->getSelector().isUnarySelector()) {
278     const IdentifierInfo *ident = 
279       OMD->getSelector().getIdentifierInfoForSlot(0);
280     if (ident->isStr("dealloc"))
281       EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
282   }
283 }
284
285 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
286                                               LValue lvalue, QualType type);
287
288 void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar, 
289                                              bool IsAtomic, bool IsStrong) {
290   LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 
291                                 Ivar, 0);
292   llvm::Value *GetCopyStructFn =
293   CGM.getObjCRuntime().GetGetStructFunction();
294   CodeGenTypes &Types = CGM.getTypes();
295   // objc_copyStruct (ReturnValue, &structIvar, 
296   //                  sizeof (Type of Ivar), isAtomic, false);
297   CallArgList Args;
298   RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
299   Args.add(RV, getContext().VoidPtrTy);
300   RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
301   Args.add(RV, getContext().VoidPtrTy);
302   // sizeof (Type of Ivar)
303   CharUnits Size =  getContext().getTypeSizeInChars(Ivar->getType());
304   llvm::Value *SizeVal =
305   llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
306                          Size.getQuantity());
307   Args.add(RValue::get(SizeVal), getContext().LongTy);
308   llvm::Value *isAtomic =
309   llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 
310                          IsAtomic ? 1 : 0);
311   Args.add(RValue::get(isAtomic), getContext().BoolTy);
312   llvm::Value *hasStrong =
313   llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 
314                          IsStrong ? 1 : 0);
315   Args.add(RValue::get(hasStrong), getContext().BoolTy);
316   EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
317                                  FunctionType::ExtInfo()),
318            GetCopyStructFn, ReturnValueSlot(), Args);
319 }
320
321 /// Generate an Objective-C method.  An Objective-C method is a C function with
322 /// its pointer, name, and types registered in the class struture.
323 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
324   StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
325   EmitStmt(OMD->getBody());
326   FinishFunction(OMD->getBodyRBrace());
327 }
328
329 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an
330 // AST for the whole body we can just fall back to having a GenerateFunction
331 // which takes the body Stmt.
332
333 /// GenerateObjCGetter - Generate an Objective-C property getter
334 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
335 /// is illegal within a category.
336 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
337                                          const ObjCPropertyImplDecl *PID) {
338   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
339   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
340   bool IsAtomic =
341     !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
342   ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
343   assert(OMD && "Invalid call to generate getter (empty method)");
344   StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
345   
346   // Determine if we should use an objc_getProperty call for
347   // this. Non-atomic properties are directly evaluated.
348   // atomic 'copy' and 'retain' properties are also directly
349   // evaluated in gc-only mode.
350   if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
351       IsAtomic &&
352       (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
353        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
354     llvm::Value *GetPropertyFn =
355       CGM.getObjCRuntime().GetPropertyGetFunction();
356
357     if (!GetPropertyFn) {
358       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
359       FinishFunction();
360       return;
361     }
362
363     // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
364     // FIXME: Can't this be simpler? This might even be worse than the
365     // corresponding gcc code.
366     CodeGenTypes &Types = CGM.getTypes();
367     ValueDecl *Cmd = OMD->getCmdDecl();
368     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
369     QualType IdTy = getContext().getObjCIdType();
370     llvm::Value *SelfAsId =
371       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
372     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
373     llvm::Value *True =
374       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
375     CallArgList Args;
376     Args.add(RValue::get(SelfAsId), IdTy);
377     Args.add(RValue::get(CmdVal), Cmd->getType());
378     Args.add(RValue::get(Offset), getContext().getPointerDiffType());
379     Args.add(RValue::get(True), getContext().BoolTy);
380     // FIXME: We shouldn't need to get the function info here, the
381     // runtime already should have computed it to build the function.
382     RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
383                                                FunctionType::ExtInfo()),
384                          GetPropertyFn, ReturnValueSlot(), Args);
385     // We need to fix the type here. Ivars with copy & retain are
386     // always objects so we don't need to worry about complex or
387     // aggregates.
388     RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
389                                            Types.ConvertType(PD->getType())));
390     EmitReturnOfRValue(RV, PD->getType());
391
392     // objc_getProperty does an autorelease, so we should suppress ours.
393     AutoreleaseResult = false;
394   } else {
395     const llvm::Triple &Triple = getContext().Target.getTriple();
396     QualType IVART = Ivar->getType();
397     if (IsAtomic &&
398         IVART->isScalarType() &&
399         (Triple.getArch() == llvm::Triple::arm ||
400          Triple.getArch() == llvm::Triple::thumb) &&
401         (getContext().getTypeSizeInChars(IVART) 
402          > CharUnits::fromQuantity(4)) &&
403         CGM.getObjCRuntime().GetGetStructFunction()) {
404       GenerateObjCGetterBody(Ivar, true, false);
405     }
406     else if (IsAtomic &&
407              (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
408              Triple.getArch() == llvm::Triple::x86 &&
409              (getContext().getTypeSizeInChars(IVART) 
410               > CharUnits::fromQuantity(4)) &&
411              CGM.getObjCRuntime().GetGetStructFunction()) {
412       GenerateObjCGetterBody(Ivar, true, false);
413     }
414     else if (IsAtomic &&
415              (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
416              Triple.getArch() == llvm::Triple::x86_64 &&
417              (getContext().getTypeSizeInChars(IVART) 
418               > CharUnits::fromQuantity(8)) &&
419              CGM.getObjCRuntime().GetGetStructFunction()) {
420       GenerateObjCGetterBody(Ivar, true, false);
421     }
422     else if (IVART->isAnyComplexType()) {
423       LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 
424                                     Ivar, 0);
425       ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
426                                                LV.isVolatileQualified());
427       StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
428     }
429     else if (hasAggregateLLVMType(IVART)) {
430       bool IsStrong = false;
431       if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
432           && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
433           && CGM.getObjCRuntime().GetGetStructFunction()) {
434         GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
435       }
436       else {
437         const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
438         
439         if (PID->getGetterCXXConstructor() &&
440             classDecl && !classDecl->hasTrivialDefaultConstructor()) {
441           ReturnStmt *Stmt = 
442             new (getContext()) ReturnStmt(SourceLocation(), 
443                                           PID->getGetterCXXConstructor(),
444                                           0);
445           EmitReturnStmt(*Stmt);
446         } else if (IsAtomic &&
447                    !IVART->isAnyComplexType() &&
448                    Triple.getArch() == llvm::Triple::x86 &&
449                    (getContext().getTypeSizeInChars(IVART) 
450                     > CharUnits::fromQuantity(4)) &&
451                    CGM.getObjCRuntime().GetGetStructFunction()) {
452           GenerateObjCGetterBody(Ivar, true, false);
453         }
454         else if (IsAtomic &&
455                  !IVART->isAnyComplexType() &&
456                  Triple.getArch() == llvm::Triple::x86_64 &&
457                  (getContext().getTypeSizeInChars(IVART) 
458                   > CharUnits::fromQuantity(8)) &&
459                  CGM.getObjCRuntime().GetGetStructFunction()) {
460           GenerateObjCGetterBody(Ivar, true, false);
461         }
462         else {
463           LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 
464                                         Ivar, 0);
465           EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
466         }
467       }
468     } 
469     else {
470         LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 
471                                       Ivar, 0);
472         QualType propType = PD->getType();
473
474         llvm::Value *value;
475         if (propType->isReferenceType()) {
476           value = LV.getAddress();
477         } else {
478           // In ARC, we want to emit this retained.
479           if (getLangOptions().ObjCAutoRefCount &&
480               PD->getType()->isObjCRetainableType())
481             value = emitARCRetainLoadOfScalar(*this, LV, IVART);
482           else
483             value = EmitLoadOfLValue(LV).getScalarVal();
484
485           value = Builder.CreateBitCast(value, ConvertType(propType));
486         }
487
488         EmitReturnOfRValue(RValue::get(value), propType);
489     }
490   }
491
492   FinishFunction();
493 }
494
495 void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
496                                                    ObjCIvarDecl *Ivar) {
497   // objc_copyStruct (&structIvar, &Arg, 
498   //                  sizeof (struct something), true, false);
499   llvm::Value *GetCopyStructFn =
500   CGM.getObjCRuntime().GetSetStructFunction();
501   CodeGenTypes &Types = CGM.getTypes();
502   CallArgList Args;
503   LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
504   RValue RV =
505     RValue::get(Builder.CreateBitCast(LV.getAddress(),
506                 Types.ConvertType(getContext().VoidPtrTy)));
507   Args.add(RV, getContext().VoidPtrTy);
508   llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
509   llvm::Value *ArgAsPtrTy =
510   Builder.CreateBitCast(Arg,
511                       Types.ConvertType(getContext().VoidPtrTy));
512   RV = RValue::get(ArgAsPtrTy);
513   Args.add(RV, getContext().VoidPtrTy);
514   // sizeof (Type of Ivar)
515   CharUnits Size =  getContext().getTypeSizeInChars(Ivar->getType());
516   llvm::Value *SizeVal =
517   llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), 
518                          Size.getQuantity());
519   Args.add(RValue::get(SizeVal), getContext().LongTy);
520   llvm::Value *True =
521   llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
522   Args.add(RValue::get(True), getContext().BoolTy);
523   llvm::Value *False =
524   llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
525   Args.add(RValue::get(False), getContext().BoolTy);
526   EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
527                                  FunctionType::ExtInfo()),
528            GetCopyStructFn, ReturnValueSlot(), Args);
529 }
530
531 static bool
532 IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID,
533                               QualType IvarT) {
534   bool HasTrvialAssignment = true;
535   if (PID->getSetterCXXAssignment()) {
536     const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl();
537     HasTrvialAssignment = 
538       (!classDecl || classDecl->hasTrivialCopyAssignment());
539   }
540   return HasTrvialAssignment;
541 }
542
543 /// GenerateObjCSetter - Generate an Objective-C property setter
544 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
545 /// is illegal within a category.
546 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
547                                          const ObjCPropertyImplDecl *PID) {
548   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
549   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
550   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
551   assert(OMD && "Invalid call to generate setter (empty method)");
552   StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
553   const llvm::Triple &Triple = getContext().Target.getTriple();
554   QualType IVART = Ivar->getType();
555   bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
556   bool IsAtomic =
557     !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
558
559   // Determine if we should use an objc_setProperty call for
560   // this. Properties with 'copy' semantics always use it, as do
561   // non-atomic properties with 'release' semantics as long as we are
562   // not in gc-only mode.
563   if (IsCopy ||
564       (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
565        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
566     llvm::Value *SetPropertyFn =
567       CGM.getObjCRuntime().GetPropertySetFunction();
568
569     if (!SetPropertyFn) {
570       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
571       FinishFunction();
572       return;
573     }
574
575     // Emit objc_setProperty((id) self, _cmd, offset, arg,
576     //                       <is-atomic>, <is-copy>).
577     // FIXME: Can't this be simpler? This might even be worse than the
578     // corresponding gcc code.
579     CodeGenTypes &Types = CGM.getTypes();
580     ValueDecl *Cmd = OMD->getCmdDecl();
581     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
582     QualType IdTy = getContext().getObjCIdType();
583     llvm::Value *SelfAsId =
584       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
585     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
586     llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
587     llvm::Value *ArgAsId =
588       Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
589                             Types.ConvertType(IdTy));
590     llvm::Value *True =
591       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
592     llvm::Value *False =
593       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
594     CallArgList Args;
595     Args.add(RValue::get(SelfAsId), IdTy);
596     Args.add(RValue::get(CmdVal), Cmd->getType());
597     Args.add(RValue::get(Offset), getContext().getPointerDiffType());
598     Args.add(RValue::get(ArgAsId), IdTy);
599     Args.add(RValue::get(IsAtomic ? True : False),  getContext().BoolTy);
600     Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy);
601     // FIXME: We shouldn't need to get the function info here, the runtime
602     // already should have computed it to build the function.
603     EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
604                                    FunctionType::ExtInfo()),
605              SetPropertyFn,
606              ReturnValueSlot(), Args);
607   } else if (IsAtomic && hasAggregateLLVMType(IVART) &&
608              !IVART->isAnyComplexType() &&
609              IvarAssignHasTrvialAssignment(PID, IVART) &&
610              ((Triple.getArch() == llvm::Triple::x86 &&
611               (getContext().getTypeSizeInChars(IVART)
612                > CharUnits::fromQuantity(4))) ||
613               (Triple.getArch() == llvm::Triple::x86_64 &&
614               (getContext().getTypeSizeInChars(IVART)
615                > CharUnits::fromQuantity(8))))
616              && CGM.getObjCRuntime().GetSetStructFunction()) {
617           // objc_copyStruct (&structIvar, &Arg, 
618           //                  sizeof (struct something), true, false);
619     GenerateObjCAtomicSetterBody(OMD, Ivar);
620   } else if (PID->getSetterCXXAssignment()) {
621     EmitIgnoredExpr(PID->getSetterCXXAssignment());
622   } else {
623     if (IsAtomic &&
624         IVART->isScalarType() &&
625         (Triple.getArch() == llvm::Triple::arm ||
626          Triple.getArch() == llvm::Triple::thumb) &&
627         (getContext().getTypeSizeInChars(IVART)
628           > CharUnits::fromQuantity(4)) &&
629         CGM.getObjCRuntime().GetGetStructFunction()) {
630       GenerateObjCAtomicSetterBody(OMD, Ivar);
631     }
632     else if (IsAtomic &&
633              (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
634              Triple.getArch() == llvm::Triple::x86 &&
635              (getContext().getTypeSizeInChars(IVART)
636               > CharUnits::fromQuantity(4)) &&
637              CGM.getObjCRuntime().GetGetStructFunction()) {
638       GenerateObjCAtomicSetterBody(OMD, Ivar);
639     }
640     else if (IsAtomic &&
641              (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
642              Triple.getArch() == llvm::Triple::x86_64 &&
643              (getContext().getTypeSizeInChars(IVART)
644               > CharUnits::fromQuantity(8)) &&
645              CGM.getObjCRuntime().GetGetStructFunction()) {
646       GenerateObjCAtomicSetterBody(OMD, Ivar);
647     }
648     else {
649       // FIXME: Find a clean way to avoid AST node creation.
650       SourceLocation Loc = PID->getLocStart();
651       ValueDecl *Self = OMD->getSelfDecl();
652       ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
653       DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
654       ParmVarDecl *ArgDecl = *OMD->param_begin();
655       QualType T = ArgDecl->getType();
656       if (T->isReferenceType())
657         T = cast<ReferenceType>(T)->getPointeeType();
658       DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc);
659       ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
660     
661       // The property type can differ from the ivar type in some situations with
662       // Objective-C pointer types, we can always bit cast the RHS in these cases.
663       if (getContext().getCanonicalType(Ivar->getType()) !=
664           getContext().getCanonicalType(ArgDecl->getType())) {
665         ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
666                                    Ivar->getType(), CK_BitCast, &Arg,
667                                    VK_RValue);
668         BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
669                               Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
670         EmitStmt(&Assign);
671       } else {
672         BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
673                               Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
674         EmitStmt(&Assign);
675       }
676     }
677   }
678
679   FinishFunction();
680 }
681
682 namespace {
683   struct DestroyIvar : EHScopeStack::Cleanup {
684   private:
685     llvm::Value *addr;
686     const ObjCIvarDecl *ivar;
687     CodeGenFunction::Destroyer &destroyer;
688     bool useEHCleanupForArray;
689   public:
690     DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
691                 CodeGenFunction::Destroyer *destroyer,
692                 bool useEHCleanupForArray)
693       : addr(addr), ivar(ivar), destroyer(*destroyer),
694         useEHCleanupForArray(useEHCleanupForArray) {}
695
696     void Emit(CodeGenFunction &CGF, Flags flags) {
697       LValue lvalue
698         = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
699       CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
700                       flags.isForNormalCleanup() && useEHCleanupForArray);
701     }
702   };
703 }
704
705 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
706 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
707                                       llvm::Value *addr,
708                                       QualType type) {
709   llvm::Value *null = getNullForVariable(addr);
710   CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
711 }
712
713 static void emitCXXDestructMethod(CodeGenFunction &CGF,
714                                   ObjCImplementationDecl *impl) {
715   CodeGenFunction::RunCleanupsScope scope(CGF);
716
717   llvm::Value *self = CGF.LoadObjCSelf();
718
719   ObjCInterfaceDecl *iface
720     = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
721   for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
722        ivar; ivar = ivar->getNextIvar()) {
723     QualType type = ivar->getType();
724
725     // Check whether the ivar is a destructible type.
726     QualType::DestructionKind dtorKind = type.isDestructedType();
727     if (!dtorKind) continue;
728
729     CodeGenFunction::Destroyer *destroyer = 0;
730
731     // Use a call to objc_storeStrong to destroy strong ivars, for the
732     // general benefit of the tools.
733     if (dtorKind == QualType::DK_objc_strong_lifetime) {
734       destroyer = &destroyARCStrongWithStore;
735
736     // Otherwise use the default for the destruction kind.
737     } else {
738       destroyer = &CGF.getDestroyer(dtorKind);
739     }
740
741     CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
742
743     CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
744                                          cleanupKind & EHCleanup);
745   }
746
747   assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
748 }
749
750 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
751                                                  ObjCMethodDecl *MD,
752                                                  bool ctor) {
753   MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
754   StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
755
756   // Emit .cxx_construct.
757   if (ctor) {
758     // Suppress the final autorelease in ARC.
759     AutoreleaseResult = false;
760
761     llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
762     for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
763            E = IMP->init_end(); B != E; ++B) {
764       CXXCtorInitializer *IvarInit = (*B);
765       FieldDecl *Field = IvarInit->getAnyMember();
766       ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
767       LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 
768                                     LoadObjCSelf(), Ivar, 0);
769       EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
770     }
771     // constructor returns 'self'.
772     CodeGenTypes &Types = CGM.getTypes();
773     QualType IdTy(CGM.getContext().getObjCIdType());
774     llvm::Value *SelfAsId =
775       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
776     EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
777
778   // Emit .cxx_destruct.
779   } else {
780     emitCXXDestructMethod(*this, IMP);
781   }
782   FinishFunction();
783 }
784
785 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
786   CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
787   it++; it++;
788   const ABIArgInfo &AI = it->info;
789   // FIXME. Is this sufficient check?
790   return (AI.getKind() == ABIArgInfo::Indirect);
791 }
792
793 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
794   if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
795     return false;
796   if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
797     return FDTTy->getDecl()->hasObjectMember();
798   return false;
799 }
800
801 llvm::Value *CodeGenFunction::LoadObjCSelf() {
802   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
803   return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
804 }
805
806 QualType CodeGenFunction::TypeOfSelfObject() {
807   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
808   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
809   const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
810     getContext().getCanonicalType(selfDecl->getType()));
811   return PTy->getPointeeType();
812 }
813
814 LValue
815 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
816   // This is a special l-value that just issues sends when we load or
817   // store through it.
818
819   // For certain base kinds, we need to emit the base immediately.
820   llvm::Value *Base;
821   if (E->isSuperReceiver())
822     Base = LoadObjCSelf();
823   else if (E->isClassReceiver())
824     Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
825   else
826     Base = EmitScalarExpr(E->getBase());
827   return LValue::MakePropertyRef(E, Base);
828 }
829
830 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
831                                        ReturnValueSlot Return,
832                                        QualType ResultType,
833                                        Selector S,
834                                        llvm::Value *Receiver,
835                                        const CallArgList &CallArgs) {
836   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
837   bool isClassMessage = OMD->isClassMethod();
838   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
839   return CGF.CGM.getObjCRuntime()
840                 .GenerateMessageSendSuper(CGF, Return, ResultType,
841                                           S, OMD->getClassInterface(),
842                                           isCategoryImpl, Receiver,
843                                           isClassMessage, CallArgs);
844 }
845
846 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
847                                                     ReturnValueSlot Return) {
848   const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
849   QualType ResultType = E->getGetterResultType();
850   Selector S;
851   const ObjCMethodDecl *method;
852   if (E->isExplicitProperty()) {
853     const ObjCPropertyDecl *Property = E->getExplicitProperty();
854     S = Property->getGetterName();
855     method = Property->getGetterMethodDecl();
856   } else {
857     method = E->getImplicitPropertyGetter();
858     S = method->getSelector();
859   }
860
861   llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
862
863   if (CGM.getLangOptions().ObjCAutoRefCount) {
864     QualType receiverType;
865     if (E->isSuperReceiver())
866       receiverType = E->getSuperReceiverType();
867     else if (E->isClassReceiver())
868       receiverType = getContext().getObjCClassType();
869     else
870       receiverType = E->getBase()->getType();
871   }
872
873   // Accesses to 'super' follow a different code path.
874   if (E->isSuperReceiver())
875     return AdjustRelatedResultType(*this, E, method,
876                                    GenerateMessageSendSuper(*this, Return, 
877                                                             ResultType,
878                                                             S, Receiver, 
879                                                             CallArgList()));
880   const ObjCInterfaceDecl *ReceiverClass
881     = (E->isClassReceiver() ? E->getClassReceiver() : 0);
882   return AdjustRelatedResultType(*this, E, method,
883           CGM.getObjCRuntime().
884              GenerateMessageSend(*this, Return, ResultType, S,
885                                  Receiver, CallArgList(), ReceiverClass));
886 }
887
888 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
889                                                         LValue Dst) {
890   const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
891   Selector S = E->getSetterSelector();
892   QualType ArgType = E->getSetterArgType();
893   
894   // FIXME. Other than scalars, AST is not adequate for setter and
895   // getter type mismatches which require conversion.
896   if (Src.isScalar()) {
897     llvm::Value *SrcVal = Src.getScalarVal();
898     QualType DstType = getContext().getCanonicalType(ArgType);
899     const llvm::Type *DstTy = ConvertType(DstType);
900     if (SrcVal->getType() != DstTy)
901       Src = 
902         RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
903   }
904   
905   CallArgList Args;
906   Args.add(Src, ArgType);
907
908   llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
909   QualType ResultType = getContext().VoidTy;
910
911   if (E->isSuperReceiver()) {
912     GenerateMessageSendSuper(*this, ReturnValueSlot(),
913                              ResultType, S, Receiver, Args);
914     return;
915   }
916
917   const ObjCInterfaceDecl *ReceiverClass
918     = (E->isClassReceiver() ? E->getClassReceiver() : 0);
919
920   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
921                                            ResultType, S, Receiver, Args,
922                                            ReceiverClass);
923 }
924
925 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
926   llvm::Constant *EnumerationMutationFn =
927     CGM.getObjCRuntime().EnumerationMutationFunction();
928
929   if (!EnumerationMutationFn) {
930     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
931     return;
932   }
933
934   CGDebugInfo *DI = getDebugInfo();
935   if (DI) {
936     DI->setLocation(S.getSourceRange().getBegin());
937     DI->EmitRegionStart(Builder);
938   }
939
940   // The local variable comes into scope immediately.
941   AutoVarEmission variable = AutoVarEmission::invalid();
942   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
943     variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
944
945   JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
946   JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
947
948   // Fast enumeration state.
949   QualType StateTy = getContext().getObjCFastEnumerationStateType();
950   llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
951   EmitNullInitialization(StatePtr, StateTy);
952
953   // Number of elements in the items array.
954   static const unsigned NumItems = 16;
955
956   // Fetch the countByEnumeratingWithState:objects:count: selector.
957   IdentifierInfo *II[] = {
958     &CGM.getContext().Idents.get("countByEnumeratingWithState"),
959     &CGM.getContext().Idents.get("objects"),
960     &CGM.getContext().Idents.get("count")
961   };
962   Selector FastEnumSel =
963     CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
964
965   QualType ItemsTy =
966     getContext().getConstantArrayType(getContext().getObjCIdType(),
967                                       llvm::APInt(32, NumItems),
968                                       ArrayType::Normal, 0);
969   llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
970
971   // Emit the collection pointer.
972   llvm::Value *Collection = EmitScalarExpr(S.getCollection());
973
974   // Send it our message:
975   CallArgList Args;
976
977   // The first argument is a temporary of the enumeration-state type.
978   Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
979
980   // The second argument is a temporary array with space for NumItems
981   // pointers.  We'll actually be loading elements from the array
982   // pointer written into the control state; this buffer is so that
983   // collections that *aren't* backed by arrays can still queue up
984   // batches of elements.
985   Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
986
987   // The third argument is the capacity of that temporary array.
988   const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
989   llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
990   Args.add(RValue::get(Count), getContext().UnsignedLongTy);
991
992   // Start the enumeration.
993   RValue CountRV =
994     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
995                                              getContext().UnsignedLongTy,
996                                              FastEnumSel,
997                                              Collection, Args);
998
999   // The initial number of objects that were returned in the buffer.
1000   llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1001
1002   llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1003   llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1004
1005   llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
1006
1007   // If the limit pointer was zero to begin with, the collection is
1008   // empty; skip all this.
1009   Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1010                        EmptyBB, LoopInitBB);
1011
1012   // Otherwise, initialize the loop.
1013   EmitBlock(LoopInitBB);
1014
1015   // Save the initial mutations value.  This is the value at an
1016   // address that was written into the state object by
1017   // countByEnumeratingWithState:objects:count:.
1018   llvm::Value *StateMutationsPtrPtr =
1019     Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1020   llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
1021                                                       "mutationsptr");
1022
1023   llvm::Value *initialMutations =
1024     Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
1025
1026   // Start looping.  This is the point we return to whenever we have a
1027   // fresh, non-empty batch of objects.
1028   llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1029   EmitBlock(LoopBodyBB);
1030
1031   // The current index into the buffer.
1032   llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
1033   index->addIncoming(zero, LoopInitBB);
1034
1035   // The current buffer size.
1036   llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
1037   count->addIncoming(initialBufferLimit, LoopInitBB);
1038
1039   // Check whether the mutations value has changed from where it was
1040   // at start.  StateMutationsPtr should actually be invariant between
1041   // refreshes.
1042   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1043   llvm::Value *currentMutations
1044     = Builder.CreateLoad(StateMutationsPtr, "statemutations");
1045
1046   llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1047   llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1048
1049   Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1050                        WasNotMutatedBB, WasMutatedBB);
1051
1052   // If so, call the enumeration-mutation function.
1053   EmitBlock(WasMutatedBB);
1054   llvm::Value *V =
1055     Builder.CreateBitCast(Collection,
1056                           ConvertType(getContext().getObjCIdType()),
1057                           "tmp");
1058   CallArgList Args2;
1059   Args2.add(RValue::get(V), getContext().getObjCIdType());
1060   // FIXME: We shouldn't need to get the function info here, the runtime already
1061   // should have computed it to build the function.
1062   EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
1063                                           FunctionType::ExtInfo()),
1064            EnumerationMutationFn, ReturnValueSlot(), Args2);
1065
1066   // Otherwise, or if the mutation function returns, just continue.
1067   EmitBlock(WasNotMutatedBB);
1068
1069   // Initialize the element variable.
1070   RunCleanupsScope elementVariableScope(*this);
1071   bool elementIsVariable;
1072   LValue elementLValue;
1073   QualType elementType;
1074   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1075     // Initialize the variable, in case it's a __block variable or something.
1076     EmitAutoVarInit(variable);
1077
1078     const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1079     DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1080                         VK_LValue, SourceLocation());
1081     elementLValue = EmitLValue(&tempDRE);
1082     elementType = D->getType();
1083     elementIsVariable = true;
1084
1085     if (D->isARCPseudoStrong())
1086       elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1087   } else {
1088     elementLValue = LValue(); // suppress warning
1089     elementType = cast<Expr>(S.getElement())->getType();
1090     elementIsVariable = false;
1091   }
1092   const llvm::Type *convertedElementType = ConvertType(elementType);
1093
1094   // Fetch the buffer out of the enumeration state.
1095   // TODO: this pointer should actually be invariant between
1096   // refreshes, which would help us do certain loop optimizations.
1097   llvm::Value *StateItemsPtr =
1098     Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1099   llvm::Value *EnumStateItems =
1100     Builder.CreateLoad(StateItemsPtr, "stateitems");
1101
1102   // Fetch the value at the current index from the buffer.
1103   llvm::Value *CurrentItemPtr =
1104     Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1105   llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
1106
1107   // Cast that value to the right type.
1108   CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1109                                       "currentitem");
1110
1111   // Make sure we have an l-value.  Yes, this gets evaluated every
1112   // time through the loop.
1113   if (!elementIsVariable) {
1114     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1115     EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1116   } else {
1117     EmitScalarInit(CurrentItem, elementLValue);
1118   }
1119
1120   // If we do have an element variable, this assignment is the end of
1121   // its initialization.
1122   if (elementIsVariable)
1123     EmitAutoVarCleanups(variable);
1124
1125   // Perform the loop body, setting up break and continue labels.
1126   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1127   {
1128     RunCleanupsScope Scope(*this);
1129     EmitStmt(S.getBody());
1130   }
1131   BreakContinueStack.pop_back();
1132
1133   // Destroy the element variable now.
1134   elementVariableScope.ForceCleanup();
1135
1136   // Check whether there are more elements.
1137   EmitBlock(AfterBody.getBlock());
1138
1139   llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1140
1141   // First we check in the local buffer.
1142   llvm::Value *indexPlusOne
1143     = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1144
1145   // If we haven't overrun the buffer yet, we can continue.
1146   Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1147                        LoopBodyBB, FetchMoreBB);
1148
1149   index->addIncoming(indexPlusOne, AfterBody.getBlock());
1150   count->addIncoming(count, AfterBody.getBlock());
1151
1152   // Otherwise, we have to fetch more elements.
1153   EmitBlock(FetchMoreBB);
1154
1155   CountRV =
1156     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1157                                              getContext().UnsignedLongTy,
1158                                              FastEnumSel,
1159                                              Collection, Args);
1160
1161   // If we got a zero count, we're done.
1162   llvm::Value *refetchCount = CountRV.getScalarVal();
1163
1164   // (note that the message send might split FetchMoreBB)
1165   index->addIncoming(zero, Builder.GetInsertBlock());
1166   count->addIncoming(refetchCount, Builder.GetInsertBlock());
1167
1168   Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1169                        EmptyBB, LoopBodyBB);
1170
1171   // No more elements.
1172   EmitBlock(EmptyBB);
1173
1174   if (!elementIsVariable) {
1175     // If the element was not a declaration, set it to be null.
1176
1177     llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1178     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1179     EmitStoreThroughLValue(RValue::get(null), elementLValue);
1180   }
1181
1182   if (DI) {
1183     DI->setLocation(S.getSourceRange().getEnd());
1184     DI->EmitRegionEnd(Builder);
1185   }
1186
1187   EmitBlock(LoopEnd.getBlock());
1188 }
1189
1190 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1191   CGM.getObjCRuntime().EmitTryStmt(*this, S);
1192 }
1193
1194 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1195   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1196 }
1197
1198 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1199                                               const ObjCAtSynchronizedStmt &S) {
1200   CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1201 }
1202
1203 /// Produce the code for a CK_ObjCProduceObject.  Just does a
1204 /// primitive retain.
1205 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1206                                                     llvm::Value *value) {
1207   return EmitARCRetain(type, value);
1208 }
1209
1210 namespace {
1211   struct CallObjCRelease : EHScopeStack::Cleanup {
1212     CallObjCRelease(QualType type, llvm::Value *ptr, llvm::Value *condition)
1213       : type(type), ptr(ptr), condition(condition) {}
1214     QualType type;
1215     llvm::Value *ptr;
1216     llvm::Value *condition;
1217
1218     void Emit(CodeGenFunction &CGF, Flags flags) {
1219       llvm::Value *object;
1220
1221       // If we're in a conditional branch, we had to stash away in an
1222       // alloca the pointer to be released.
1223       llvm::BasicBlock *cont = 0;
1224       if (condition) {
1225         llvm::BasicBlock *release = CGF.createBasicBlock("release.yes");
1226         cont = CGF.createBasicBlock("release.cont");
1227
1228         llvm::Value *cond = CGF.Builder.CreateLoad(condition);
1229         CGF.Builder.CreateCondBr(cond, release, cont);
1230         CGF.EmitBlock(release);
1231         object = CGF.Builder.CreateLoad(ptr);
1232       } else {
1233         object = ptr;
1234       }
1235
1236       CGF.EmitARCRelease(object, /*precise*/ true);
1237
1238       if (cont) CGF.EmitBlock(cont);
1239     }
1240   };
1241 }
1242
1243 /// Produce the code for a CK_ObjCConsumeObject.  Does a primitive
1244 /// release at the end of the full-expression.
1245 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1246                                                     llvm::Value *object) {
1247   // If we're in a conditional branch, we need to make the cleanup
1248   // conditional.  FIXME: this really needs to be supported by the
1249   // environment.
1250   llvm::AllocaInst *cond;
1251   llvm::Value *ptr;
1252   if (isInConditionalBranch()) {
1253     cond = CreateTempAlloca(Builder.getInt1Ty(), "release.cond");
1254     ptr = CreateTempAlloca(object->getType(), "release.value");
1255
1256     // The alloca is false until we get here.
1257     // FIXME: er. doesn't this need to be set at the start of the condition?
1258     InitTempAlloca(cond, Builder.getFalse());
1259
1260     // Then it turns true.
1261     Builder.CreateStore(Builder.getTrue(), cond);
1262     Builder.CreateStore(object, ptr);
1263   } else {
1264     cond = 0;
1265     ptr = object;
1266   }
1267
1268   EHStack.pushCleanup<CallObjCRelease>(getARCCleanupKind(), type, ptr, cond);
1269   return object;
1270 }
1271
1272 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1273                                                            llvm::Value *value) {
1274   return EmitARCRetainAutorelease(type, value);
1275 }
1276
1277
1278 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1279                                                 const llvm::FunctionType *type,
1280                                                 llvm::StringRef fnName) {
1281   llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1282
1283   // In -fobjc-no-arc-runtime, emit weak references to the runtime
1284   // support library.
1285   if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
1286     if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1287       f->setLinkage(llvm::Function::ExternalWeakLinkage);
1288
1289   return fn;
1290 }
1291
1292 /// Perform an operation having the signature
1293 ///   i8* (i8*)
1294 /// where a null input causes a no-op and returns null.
1295 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1296                                           llvm::Value *value,
1297                                           llvm::Constant *&fn,
1298                                           llvm::StringRef fnName) {
1299   if (isa<llvm::ConstantPointerNull>(value)) return value;
1300
1301   if (!fn) {
1302     std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
1303     const llvm::FunctionType *fnType =
1304       llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1305     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1306   }
1307
1308   // Cast the argument to 'id'.
1309   const llvm::Type *origType = value->getType();
1310   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1311
1312   // Call the function.
1313   llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1314   call->setDoesNotThrow();
1315
1316   // Cast the result back to the original type.
1317   return CGF.Builder.CreateBitCast(call, origType);
1318 }
1319
1320 /// Perform an operation having the following signature:
1321 ///   i8* (i8**)
1322 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1323                                          llvm::Value *addr,
1324                                          llvm::Constant *&fn,
1325                                          llvm::StringRef fnName) {
1326   if (!fn) {
1327     std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
1328     const llvm::FunctionType *fnType =
1329       llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1330     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1331   }
1332
1333   // Cast the argument to 'id*'.
1334   const llvm::Type *origType = addr->getType();
1335   addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1336
1337   // Call the function.
1338   llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1339   call->setDoesNotThrow();
1340
1341   // Cast the result back to a dereference of the original type.
1342   llvm::Value *result = call;
1343   if (origType != CGF.Int8PtrPtrTy)
1344     result = CGF.Builder.CreateBitCast(result,
1345                         cast<llvm::PointerType>(origType)->getElementType());
1346
1347   return result;
1348 }
1349
1350 /// Perform an operation having the following signature:
1351 ///   i8* (i8**, i8*)
1352 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1353                                           llvm::Value *addr,
1354                                           llvm::Value *value,
1355                                           llvm::Constant *&fn,
1356                                           llvm::StringRef fnName,
1357                                           bool ignored) {
1358   assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1359            == value->getType());
1360
1361   if (!fn) {
1362     std::vector<llvm::Type*> argTypes(2);
1363     argTypes[0] = CGF.Int8PtrPtrTy;
1364     argTypes[1] = CGF.Int8PtrTy;
1365
1366     const llvm::FunctionType *fnType
1367       = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1368     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1369   }
1370
1371   const llvm::Type *origType = value->getType();
1372
1373   addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1374   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1375     
1376   llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1377   result->setDoesNotThrow();
1378
1379   if (ignored) return 0;
1380
1381   return CGF.Builder.CreateBitCast(result, origType);
1382 }
1383
1384 /// Perform an operation having the following signature:
1385 ///   void (i8**, i8**)
1386 static void emitARCCopyOperation(CodeGenFunction &CGF,
1387                                  llvm::Value *dst,
1388                                  llvm::Value *src,
1389                                  llvm::Constant *&fn,
1390                                  llvm::StringRef fnName) {
1391   assert(dst->getType() == src->getType());
1392
1393   if (!fn) {
1394     std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
1395     const llvm::FunctionType *fnType
1396       = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1397     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1398   }
1399
1400   dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1401   src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1402     
1403   llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1404   result->setDoesNotThrow();
1405 }
1406
1407 /// Produce the code to do a retain.  Based on the type, calls one of:
1408 ///   call i8* @objc_retain(i8* %value)
1409 ///   call i8* @objc_retainBlock(i8* %value)
1410 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1411   if (type->isBlockPointerType())
1412     return EmitARCRetainBlock(value);
1413   else
1414     return EmitARCRetainNonBlock(value);
1415 }
1416
1417 /// Retain the given object, with normal retain semantics.
1418 ///   call i8* @objc_retain(i8* %value)
1419 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1420   return emitARCValueOperation(*this, value,
1421                                CGM.getARCEntrypoints().objc_retain,
1422                                "objc_retain");
1423 }
1424
1425 /// Retain the given block, with _Block_copy semantics.
1426 ///   call i8* @objc_retainBlock(i8* %value)
1427 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1428   return emitARCValueOperation(*this, value,
1429                                CGM.getARCEntrypoints().objc_retainBlock,
1430                                "objc_retainBlock");
1431 }
1432
1433 /// Retain the given object which is the result of a function call.
1434 ///   call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1435 ///
1436 /// Yes, this function name is one character away from a different
1437 /// call with completely different semantics.
1438 llvm::Value *
1439 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1440   // Fetch the void(void) inline asm which marks that we're going to
1441   // retain the autoreleased return value.
1442   llvm::InlineAsm *&marker
1443     = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1444   if (!marker) {
1445     llvm::StringRef assembly
1446       = CGM.getTargetCodeGenInfo()
1447            .getARCRetainAutoreleasedReturnValueMarker();
1448
1449     // If we have an empty assembly string, there's nothing to do.
1450     if (assembly.empty()) {
1451
1452     // Otherwise, at -O0, build an inline asm that we're going to call
1453     // in a moment.
1454     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1455       llvm::FunctionType *type =
1456         llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1457                                 /*variadic*/ false);
1458       
1459       marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1460
1461     // If we're at -O1 and above, we don't want to litter the code
1462     // with this marker yet, so leave a breadcrumb for the ARC
1463     // optimizer to pick up.
1464     } else {
1465       llvm::NamedMDNode *metadata =
1466         CGM.getModule().getOrInsertNamedMetadata(
1467                             "clang.arc.retainAutoreleasedReturnValueMarker");
1468       assert(metadata->getNumOperands() <= 1);
1469       if (metadata->getNumOperands() == 0) {
1470         llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1471         llvm::Value *args[] = { string };
1472         metadata->addOperand(llvm::MDNode::get(getLLVMContext(), args));
1473       }
1474     }
1475   }
1476
1477   // Call the marker asm if we made one, which we do only at -O0.
1478   if (marker) Builder.CreateCall(marker);
1479
1480   return emitARCValueOperation(*this, value,
1481                      CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1482                                "objc_retainAutoreleasedReturnValue");
1483 }
1484
1485 /// Release the given object.
1486 ///   call void @objc_release(i8* %value)
1487 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1488   if (isa<llvm::ConstantPointerNull>(value)) return;
1489
1490   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1491   if (!fn) {
1492     std::vector<llvm::Type*> args(1, Int8PtrTy);
1493     const llvm::FunctionType *fnType =
1494       llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1495     fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1496   }
1497
1498   // Cast the argument to 'id'.
1499   value = Builder.CreateBitCast(value, Int8PtrTy);
1500
1501   // Call objc_release.
1502   llvm::CallInst *call = Builder.CreateCall(fn, value);
1503   call->setDoesNotThrow();
1504
1505   if (!precise) {
1506     llvm::SmallVector<llvm::Value*,1> args;
1507     call->setMetadata("clang.imprecise_release",
1508                       llvm::MDNode::get(Builder.getContext(), args));
1509   }
1510 }
1511
1512 /// Store into a strong object.  Always calls this:
1513 ///   call void @objc_storeStrong(i8** %addr, i8* %value)
1514 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1515                                                      llvm::Value *value,
1516                                                      bool ignored) {
1517   assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1518            == value->getType());
1519
1520   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1521   if (!fn) {
1522     llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
1523     const llvm::FunctionType *fnType
1524       = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1525     fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1526   }
1527
1528   addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1529   llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1530   
1531   Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1532
1533   if (ignored) return 0;
1534   return value;
1535 }
1536
1537 /// Store into a strong object.  Sometimes calls this:
1538 ///   call void @objc_storeStrong(i8** %addr, i8* %value)
1539 /// Other times, breaks it down into components.
1540 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
1541                                                  llvm::Value *newValue,
1542                                                  bool ignored) {
1543   QualType type = dst.getType();
1544   bool isBlock = type->isBlockPointerType();
1545
1546   // Use a store barrier at -O0 unless this is a block type or the
1547   // lvalue is inadequately aligned.
1548   if (shouldUseFusedARCCalls() &&
1549       !isBlock &&
1550       !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1551     return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1552   }
1553
1554   // Otherwise, split it out.
1555
1556   // Retain the new value.
1557   newValue = EmitARCRetain(type, newValue);
1558
1559   // Read the old value.
1560   llvm::Value *oldValue = EmitLoadOfScalar(dst);
1561
1562   // Store.  We do this before the release so that any deallocs won't
1563   // see the old value.
1564   EmitStoreOfScalar(newValue, dst);
1565
1566   // Finally, release the old value.
1567   EmitARCRelease(oldValue, /*precise*/ false);
1568
1569   return newValue;
1570 }
1571
1572 /// Autorelease the given object.
1573 ///   call i8* @objc_autorelease(i8* %value)
1574 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1575   return emitARCValueOperation(*this, value,
1576                                CGM.getARCEntrypoints().objc_autorelease,
1577                                "objc_autorelease");
1578 }
1579
1580 /// Autorelease the given object.
1581 ///   call i8* @objc_autoreleaseReturnValue(i8* %value)
1582 llvm::Value *
1583 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1584   return emitARCValueOperation(*this, value,
1585                             CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1586                                "objc_autoreleaseReturnValue");
1587 }
1588
1589 /// Do a fused retain/autorelease of the given object.
1590 ///   call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1591 llvm::Value *
1592 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1593   return emitARCValueOperation(*this, value,
1594                      CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1595                                "objc_retainAutoreleaseReturnValue");
1596 }
1597
1598 /// Do a fused retain/autorelease of the given object.
1599 ///   call i8* @objc_retainAutorelease(i8* %value)
1600 /// or
1601 ///   %retain = call i8* @objc_retainBlock(i8* %value)
1602 ///   call i8* @objc_autorelease(i8* %retain)
1603 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1604                                                        llvm::Value *value) {
1605   if (!type->isBlockPointerType())
1606     return EmitARCRetainAutoreleaseNonBlock(value);
1607
1608   if (isa<llvm::ConstantPointerNull>(value)) return value;
1609
1610   const llvm::Type *origType = value->getType();
1611   value = Builder.CreateBitCast(value, Int8PtrTy);
1612   value = EmitARCRetainBlock(value);
1613   value = EmitARCAutorelease(value);
1614   return Builder.CreateBitCast(value, origType);
1615 }
1616
1617 /// Do a fused retain/autorelease of the given object.
1618 ///   call i8* @objc_retainAutorelease(i8* %value)
1619 llvm::Value *
1620 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1621   return emitARCValueOperation(*this, value,
1622                                CGM.getARCEntrypoints().objc_retainAutorelease,
1623                                "objc_retainAutorelease");
1624 }
1625
1626 /// i8* @objc_loadWeak(i8** %addr)
1627 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1628 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1629   return emitARCLoadOperation(*this, addr,
1630                               CGM.getARCEntrypoints().objc_loadWeak,
1631                               "objc_loadWeak");
1632 }
1633
1634 /// i8* @objc_loadWeakRetained(i8** %addr)
1635 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1636   return emitARCLoadOperation(*this, addr,
1637                               CGM.getARCEntrypoints().objc_loadWeakRetained,
1638                               "objc_loadWeakRetained");
1639 }
1640
1641 /// i8* @objc_storeWeak(i8** %addr, i8* %value)
1642 /// Returns %value.
1643 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1644                                                llvm::Value *value,
1645                                                bool ignored) {
1646   return emitARCStoreOperation(*this, addr, value,
1647                                CGM.getARCEntrypoints().objc_storeWeak,
1648                                "objc_storeWeak", ignored);
1649 }
1650
1651 /// i8* @objc_initWeak(i8** %addr, i8* %value)
1652 /// Returns %value.  %addr is known to not have a current weak entry.
1653 /// Essentially equivalent to:
1654 ///   *addr = nil; objc_storeWeak(addr, value);
1655 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1656   // If we're initializing to null, just write null to memory; no need
1657   // to get the runtime involved.  But don't do this if optimization
1658   // is enabled, because accounting for this would make the optimizer
1659   // much more complicated.
1660   if (isa<llvm::ConstantPointerNull>(value) &&
1661       CGM.getCodeGenOpts().OptimizationLevel == 0) {
1662     Builder.CreateStore(value, addr);
1663     return;
1664   }
1665
1666   emitARCStoreOperation(*this, addr, value,
1667                         CGM.getARCEntrypoints().objc_initWeak,
1668                         "objc_initWeak", /*ignored*/ true);
1669 }
1670
1671 /// void @objc_destroyWeak(i8** %addr)
1672 /// Essentially objc_storeWeak(addr, nil).
1673 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1674   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1675   if (!fn) {
1676     std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
1677     const llvm::FunctionType *fnType =
1678       llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1679     fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1680   }
1681
1682   // Cast the argument to 'id*'.
1683   addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1684
1685   llvm::CallInst *call = Builder.CreateCall(fn, addr);
1686   call->setDoesNotThrow();
1687 }
1688
1689 /// void @objc_moveWeak(i8** %dest, i8** %src)
1690 /// Disregards the current value in %dest.  Leaves %src pointing to nothing.
1691 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1692 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1693   emitARCCopyOperation(*this, dst, src,
1694                        CGM.getARCEntrypoints().objc_moveWeak,
1695                        "objc_moveWeak");
1696 }
1697
1698 /// void @objc_copyWeak(i8** %dest, i8** %src)
1699 /// Disregards the current value in %dest.  Essentially
1700 ///   objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1701 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1702   emitARCCopyOperation(*this, dst, src,
1703                        CGM.getARCEntrypoints().objc_copyWeak,
1704                        "objc_copyWeak");
1705 }
1706
1707 /// Produce the code to do a objc_autoreleasepool_push.
1708 ///   call i8* @objc_autoreleasePoolPush(void)
1709 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1710   llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1711   if (!fn) {
1712     const llvm::FunctionType *fnType =
1713       llvm::FunctionType::get(Int8PtrTy, false);
1714     fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1715   }
1716
1717   llvm::CallInst *call = Builder.CreateCall(fn);
1718   call->setDoesNotThrow();
1719
1720   return call;
1721 }
1722
1723 /// Produce the code to do a primitive release.
1724 ///   call void @objc_autoreleasePoolPop(i8* %ptr)
1725 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1726   assert(value->getType() == Int8PtrTy);
1727
1728   llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1729   if (!fn) {
1730     std::vector<llvm::Type*> args(1, Int8PtrTy);
1731     const llvm::FunctionType *fnType =
1732       llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1733
1734     // We don't want to use a weak import here; instead we should not
1735     // fall into this path.
1736     fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1737   }
1738
1739   llvm::CallInst *call = Builder.CreateCall(fn, value);
1740   call->setDoesNotThrow();
1741 }
1742
1743 /// Produce the code to do an MRR version objc_autoreleasepool_push.
1744 /// Which is: [[NSAutoreleasePool alloc] init];
1745 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1746 /// init is declared as: - (id) init; in its NSObject super class.
1747 ///
1748 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1749   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1750   llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1751   // [NSAutoreleasePool alloc]
1752   IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1753   Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1754   CallArgList Args;
1755   RValue AllocRV =  
1756     Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 
1757                                 getContext().getObjCIdType(),
1758                                 AllocSel, Receiver, Args); 
1759
1760   // [Receiver init]
1761   Receiver = AllocRV.getScalarVal();
1762   II = &CGM.getContext().Idents.get("init");
1763   Selector InitSel = getContext().Selectors.getSelector(0, &II);
1764   RValue InitRV =
1765     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1766                                 getContext().getObjCIdType(),
1767                                 InitSel, Receiver, Args); 
1768   return InitRV.getScalarVal();
1769 }
1770
1771 /// Produce the code to do a primitive release.
1772 /// [tmp drain];
1773 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1774   IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1775   Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1776   CallArgList Args;
1777   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1778                               getContext().VoidTy, DrainSel, Arg, Args); 
1779 }
1780
1781 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1782                                               llvm::Value *addr,
1783                                               QualType type) {
1784   llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1785   CGF.EmitARCRelease(ptr, /*precise*/ true);
1786 }
1787
1788 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1789                                                 llvm::Value *addr,
1790                                                 QualType type) {
1791   llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1792   CGF.EmitARCRelease(ptr, /*precise*/ false);  
1793 }
1794
1795 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1796                                      llvm::Value *addr,
1797                                      QualType type) {
1798   CGF.EmitARCDestroyWeak(addr);
1799 }
1800
1801 namespace {
1802   struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1803     llvm::Value *Token;
1804
1805     CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1806
1807     void Emit(CodeGenFunction &CGF, Flags flags) {
1808       CGF.EmitObjCAutoreleasePoolPop(Token);
1809     }
1810   };
1811   struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1812     llvm::Value *Token;
1813
1814     CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1815
1816     void Emit(CodeGenFunction &CGF, Flags flags) {
1817       CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1818     }
1819   };
1820 }
1821
1822 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1823   if (CGM.getLangOptions().ObjCAutoRefCount)
1824     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1825   else
1826     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1827 }
1828
1829 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1830                                                   LValue lvalue,
1831                                                   QualType type) {
1832   switch (type.getObjCLifetime()) {
1833   case Qualifiers::OCL_None:
1834   case Qualifiers::OCL_ExplicitNone:
1835   case Qualifiers::OCL_Strong:
1836   case Qualifiers::OCL_Autoreleasing:
1837     return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
1838                          false);
1839
1840   case Qualifiers::OCL_Weak:
1841     return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1842                          true);
1843   }
1844
1845   llvm_unreachable("impossible lifetime!");
1846   return TryEmitResult();
1847 }
1848
1849 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1850                                                   const Expr *e) {
1851   e = e->IgnoreParens();
1852   QualType type = e->getType();
1853
1854   // As a very special optimization, in ARC++, if the l-value is the
1855   // result of a non-volatile assignment, do a simple retain of the
1856   // result of the call to objc_storeWeak instead of reloading.
1857   if (CGF.getLangOptions().CPlusPlus &&
1858       !type.isVolatileQualified() &&
1859       type.getObjCLifetime() == Qualifiers::OCL_Weak &&
1860       isa<BinaryOperator>(e) &&
1861       cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
1862     return TryEmitResult(CGF.EmitScalarExpr(e), false);
1863
1864   return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
1865 }
1866
1867 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1868                                            llvm::Value *value);
1869
1870 /// Given that the given expression is some sort of call (which does
1871 /// not return retained), emit a retain following it.
1872 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
1873   llvm::Value *value = CGF.EmitScalarExpr(e);
1874   return emitARCRetainAfterCall(CGF, value);
1875 }
1876
1877 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1878                                            llvm::Value *value) {
1879   if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
1880     CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1881
1882     // Place the retain immediately following the call.
1883     CGF.Builder.SetInsertPoint(call->getParent(),
1884                                ++llvm::BasicBlock::iterator(call));
1885     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1886
1887     CGF.Builder.restoreIP(ip);
1888     return value;
1889   } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
1890     CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1891
1892     // Place the retain at the beginning of the normal destination block.
1893     llvm::BasicBlock *BB = invoke->getNormalDest();
1894     CGF.Builder.SetInsertPoint(BB, BB->begin());
1895     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1896
1897     CGF.Builder.restoreIP(ip);
1898     return value;
1899
1900   // Bitcasts can arise because of related-result returns.  Rewrite
1901   // the operand.
1902   } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
1903     llvm::Value *operand = bitcast->getOperand(0);
1904     operand = emitARCRetainAfterCall(CGF, operand);
1905     bitcast->setOperand(0, operand);
1906     return bitcast;
1907
1908   // Generic fall-back case.
1909   } else {
1910     // Retain using the non-block variant: we never need to do a copy
1911     // of a block that's been returned to us.
1912     return CGF.EmitARCRetainNonBlock(value);
1913   }
1914 }
1915
1916 static TryEmitResult
1917 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
1918   // The desired result type, if it differs from the type of the
1919   // ultimate opaque expression.
1920   const llvm::Type *resultType = 0;
1921
1922   // If we're loading retained from a __strong xvalue, we can avoid 
1923   // an extra retain/release pair by zeroing out the source of this
1924   // "move" operation.
1925   if (e->isXValue() && !e->getType().isConstQualified() &&
1926       e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
1927     // Emit the lvalue
1928     LValue lv = CGF.EmitLValue(e);
1929     
1930     // Load the object pointer and cast it to the appropriate type.
1931     QualType exprType = e->getType();
1932     llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
1933     
1934     if (resultType)
1935       result = CGF.Builder.CreateBitCast(result, resultType);
1936     
1937     // Set the source pointer to NULL.
1938     llvm::Value *null 
1939       = llvm::ConstantPointerNull::get(
1940                             cast<llvm::PointerType>(CGF.ConvertType(exprType)));
1941     CGF.EmitStoreOfScalar(null, lv);
1942     
1943     return TryEmitResult(result, true);
1944   }
1945
1946   while (true) {
1947     e = e->IgnoreParens();
1948
1949     // There's a break at the end of this if-chain;  anything
1950     // that wants to keep looping has to explicitly continue.
1951     if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
1952       switch (ce->getCastKind()) {
1953       // No-op casts don't change the type, so we just ignore them.
1954       case CK_NoOp:
1955         e = ce->getSubExpr();
1956         continue;
1957
1958       case CK_LValueToRValue: {
1959         TryEmitResult loadResult
1960           = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
1961         if (resultType) {
1962           llvm::Value *value = loadResult.getPointer();
1963           value = CGF.Builder.CreateBitCast(value, resultType);
1964           loadResult.setPointer(value);
1965         }
1966         return loadResult;
1967       }
1968
1969       // These casts can change the type, so remember that and
1970       // soldier on.  We only need to remember the outermost such
1971       // cast, though.
1972       case CK_AnyPointerToObjCPointerCast:
1973       case CK_AnyPointerToBlockPointerCast:
1974       case CK_BitCast:
1975         if (!resultType)
1976           resultType = CGF.ConvertType(ce->getType());
1977         e = ce->getSubExpr();
1978         assert(e->getType()->hasPointerRepresentation());
1979         continue;
1980
1981       // For consumptions, just emit the subexpression and thus elide
1982       // the retain/release pair.
1983       case CK_ObjCConsumeObject: {
1984         llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
1985         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1986         return TryEmitResult(result, true);
1987       }
1988
1989       // For reclaims, emit the subexpression as a retained call and
1990       // skip the consumption.
1991       case CK_ObjCReclaimReturnedObject: {
1992         llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
1993         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1994         return TryEmitResult(result, true);
1995       }
1996
1997       case CK_GetObjCProperty: {
1998         llvm::Value *result = emitARCRetainCall(CGF, ce);
1999         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2000         return TryEmitResult(result, true);
2001       }
2002
2003       default:
2004         break;
2005       }
2006
2007     // Skip __extension__.
2008     } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2009       if (op->getOpcode() == UO_Extension) {
2010         e = op->getSubExpr();
2011         continue;
2012       }
2013
2014     // For calls and message sends, use the retained-call logic.
2015     // Delegate inits are a special case in that they're the only
2016     // returns-retained expression that *isn't* surrounded by
2017     // a consume.
2018     } else if (isa<CallExpr>(e) ||
2019                (isa<ObjCMessageExpr>(e) &&
2020                 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2021       llvm::Value *result = emitARCRetainCall(CGF, e);
2022       if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2023       return TryEmitResult(result, true);
2024     }
2025
2026     // Conservatively halt the search at any other expression kind.
2027     break;
2028   }
2029
2030   // We didn't find an obvious production, so emit what we've got and
2031   // tell the caller that we didn't manage to retain.
2032   llvm::Value *result = CGF.EmitScalarExpr(e);
2033   if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2034   return TryEmitResult(result, false);
2035 }
2036
2037 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2038                                                 LValue lvalue,
2039                                                 QualType type) {
2040   TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2041   llvm::Value *value = result.getPointer();
2042   if (!result.getInt())
2043     value = CGF.EmitARCRetain(type, value);
2044   return value;
2045 }
2046
2047 /// EmitARCRetainScalarExpr - Semantically equivalent to
2048 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2049 /// best-effort attempt to peephole expressions that naturally produce
2050 /// retained objects.
2051 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2052   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2053   llvm::Value *value = result.getPointer();
2054   if (!result.getInt())
2055     value = EmitARCRetain(e->getType(), value);
2056   return value;
2057 }
2058
2059 llvm::Value *
2060 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2061   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2062   llvm::Value *value = result.getPointer();
2063   if (result.getInt())
2064     value = EmitARCAutorelease(value);
2065   else
2066     value = EmitARCRetainAutorelease(e->getType(), value);
2067   return value;
2068 }
2069
2070 std::pair<LValue,llvm::Value*>
2071 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2072                                     bool ignored) {
2073   // Evaluate the RHS first.
2074   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2075   llvm::Value *value = result.getPointer();
2076
2077   LValue lvalue = EmitLValue(e->getLHS());
2078
2079   // If the RHS was emitted retained, expand this.
2080   if (result.getInt()) {
2081     llvm::Value *oldValue =
2082       EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2083                        lvalue.getAlignment(), e->getType(),
2084                        lvalue.getTBAAInfo());
2085     EmitStoreOfScalar(value, lvalue.getAddress(),
2086                       lvalue.isVolatileQualified(), lvalue.getAlignment(),
2087                       e->getType(), lvalue.getTBAAInfo());
2088     EmitARCRelease(oldValue, /*precise*/ false);
2089   } else {
2090     value = EmitARCStoreStrong(lvalue, value, ignored);
2091   }
2092
2093   return std::pair<LValue,llvm::Value*>(lvalue, value);
2094 }
2095
2096 std::pair<LValue,llvm::Value*>
2097 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2098   llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2099   LValue lvalue = EmitLValue(e->getLHS());
2100
2101   EmitStoreOfScalar(value, lvalue.getAddress(),
2102                     lvalue.isVolatileQualified(), lvalue.getAlignment(),
2103                     e->getType(), lvalue.getTBAAInfo());
2104
2105   return std::pair<LValue,llvm::Value*>(lvalue, value);
2106 }
2107
2108 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2109                                              const ObjCAutoreleasePoolStmt &ARPS) {
2110   const Stmt *subStmt = ARPS.getSubStmt();
2111   const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2112
2113   CGDebugInfo *DI = getDebugInfo();
2114   if (DI) {
2115     DI->setLocation(S.getLBracLoc());
2116     DI->EmitRegionStart(Builder);
2117   }
2118
2119   // Keep track of the current cleanup stack depth.
2120   RunCleanupsScope Scope(*this);
2121   if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
2122     llvm::Value *token = EmitObjCAutoreleasePoolPush();
2123     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2124   } else {
2125     llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2126     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2127   }
2128
2129   for (CompoundStmt::const_body_iterator I = S.body_begin(),
2130        E = S.body_end(); I != E; ++I)
2131     EmitStmt(*I);
2132
2133   if (DI) {
2134     DI->setLocation(S.getRBracLoc());
2135     DI->EmitRegionEnd(Builder);
2136   }
2137 }
2138
2139 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2140 /// make sure it survives garbage collection until this point.
2141 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2142   // We just use an inline assembly.
2143   llvm::Type *paramTypes[] = { VoidPtrTy };
2144   llvm::FunctionType *extenderType
2145     = llvm::FunctionType::get(VoidTy, paramTypes, /*variadic*/ false);
2146   llvm::Value *extender
2147     = llvm::InlineAsm::get(extenderType,
2148                            /* assembly */ "",
2149                            /* constraints */ "r",
2150                            /* side effects */ true);
2151
2152   object = Builder.CreateBitCast(object, VoidPtrTy);
2153   Builder.CreateCall(extender, object)->setDoesNotThrow();
2154 }
2155
2156 CGObjCRuntime::~CGObjCRuntime() {}