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