CGObjC.cpp revision 223017
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 "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/StmtObjC.h"
21#include "clang/Basic/Diagnostic.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Target/TargetData.h"
24using namespace clang;
25using namespace CodeGen;
26
27/// Emits an instance of NSConstantString representing the object.
28llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
29{
30  llvm::Constant *C =
31      CGM.getObjCRuntime().GenerateConstantString(E->getString());
32  // FIXME: This bitcast should just be made an invariant on the Runtime.
33  return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
34}
35
36/// Emit a selector.
37llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
38  // Untyped selector.
39  // Note that this implementation allows for non-constant strings to be passed
40  // as arguments to @selector().  Currently, the only thing preventing this
41  // behaviour is the type checking in the front end.
42  return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
43}
44
45llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
46  // FIXME: This should pass the Decl not the name.
47  return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
48}
49
50/// \brief Adjust the type of the result of an Objective-C message send
51/// expression when the method has a related result type.
52static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
53                                      const Expr *E,
54                                      const ObjCMethodDecl *Method,
55                                      RValue Result) {
56  if (!Method)
57    return Result;
58  if (!Method->hasRelatedResultType() ||
59      CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
60      !Result.isScalar())
61    return Result;
62
63  // We have applied a related result type. Cast the rvalue appropriately.
64  return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
65                                               CGF.ConvertType(E->getType())));
66}
67
68RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
69                                            ReturnValueSlot Return) {
70  // Only the lookup mechanism and first two arguments of the method
71  // implementation vary between runtimes.  We can get the receiver and
72  // arguments in generic code.
73
74  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
75  bool isSuperMessage = false;
76  bool isClassMessage = false;
77  ObjCInterfaceDecl *OID = 0;
78  // Find the receiver
79  QualType ReceiverType;
80  llvm::Value *Receiver = 0;
81  switch (E->getReceiverKind()) {
82  case ObjCMessageExpr::Instance:
83    Receiver = EmitScalarExpr(E->getInstanceReceiver());
84    ReceiverType = E->getInstanceReceiver()->getType();
85    break;
86
87  case ObjCMessageExpr::Class: {
88    ReceiverType = E->getClassReceiver();
89    const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
90    assert(ObjTy && "Invalid Objective-C class message send");
91    OID = ObjTy->getInterface();
92    assert(OID && "Invalid Objective-C class message send");
93    Receiver = Runtime.GetClass(Builder, OID);
94    isClassMessage = true;
95    break;
96  }
97
98  case ObjCMessageExpr::SuperInstance:
99    ReceiverType = E->getSuperType();
100    Receiver = LoadObjCSelf();
101    isSuperMessage = true;
102    break;
103
104  case ObjCMessageExpr::SuperClass:
105    ReceiverType = E->getSuperType();
106    Receiver = LoadObjCSelf();
107    isSuperMessage = true;
108    isClassMessage = true;
109    break;
110  }
111
112  CallArgList Args;
113  EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
114
115  QualType ResultType =
116    E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
117
118  RValue result;
119  if (isSuperMessage) {
120    // super is only valid in an Objective-C method
121    const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
122    bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
123    result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
124                                              E->getSelector(),
125                                              OMD->getClassInterface(),
126                                              isCategoryImpl,
127                                              Receiver,
128                                              isClassMessage,
129                                              Args,
130                                              E->getMethodDecl());
131  } else {
132    result = Runtime.GenerateMessageSend(*this, Return, ResultType,
133                                         E->getSelector(),
134                                         Receiver, Args, OID,
135                                         E->getMethodDecl());
136  }
137
138  return AdjustRelatedResultType(*this, E, E->getMethodDecl(), result);
139}
140
141/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
142/// the LLVM function and sets the other context used by
143/// CodeGenFunction.
144void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
145                                      const ObjCContainerDecl *CD,
146                                      SourceLocation StartLoc) {
147  FunctionArgList args;
148  // Check if we should generate debug info for this method.
149  if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
150    DebugInfo = CGM.getModuleDebugInfo();
151
152  llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
153
154  const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
155  CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
156
157  args.push_back(OMD->getSelfDecl());
158  args.push_back(OMD->getCmdDecl());
159
160  for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
161       E = OMD->param_end(); PI != E; ++PI)
162    args.push_back(*PI);
163
164  CurGD = OMD;
165
166  StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
167}
168
169void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
170                                             bool IsAtomic, bool IsStrong) {
171  LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
172                                Ivar, 0);
173  llvm::Value *GetCopyStructFn =
174  CGM.getObjCRuntime().GetGetStructFunction();
175  CodeGenTypes &Types = CGM.getTypes();
176  // objc_copyStruct (ReturnValue, &structIvar,
177  //                  sizeof (Type of Ivar), isAtomic, false);
178  CallArgList Args;
179  RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
180  Args.add(RV, getContext().VoidPtrTy);
181  RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
182  Args.add(RV, getContext().VoidPtrTy);
183  // sizeof (Type of Ivar)
184  CharUnits Size =  getContext().getTypeSizeInChars(Ivar->getType());
185  llvm::Value *SizeVal =
186  llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
187                         Size.getQuantity());
188  Args.add(RValue::get(SizeVal), getContext().LongTy);
189  llvm::Value *isAtomic =
190  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
191                         IsAtomic ? 1 : 0);
192  Args.add(RValue::get(isAtomic), getContext().BoolTy);
193  llvm::Value *hasStrong =
194  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
195                         IsStrong ? 1 : 0);
196  Args.add(RValue::get(hasStrong), getContext().BoolTy);
197  EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
198                                 FunctionType::ExtInfo()),
199           GetCopyStructFn, ReturnValueSlot(), Args);
200}
201
202/// Generate an Objective-C method.  An Objective-C method is a C function with
203/// its pointer, name, and types registered in the class struture.
204void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
205  StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
206  EmitStmt(OMD->getBody());
207  FinishFunction(OMD->getBodyRBrace());
208}
209
210// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
211// AST for the whole body we can just fall back to having a GenerateFunction
212// which takes the body Stmt.
213
214/// GenerateObjCGetter - Generate an Objective-C property getter
215/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
216/// is illegal within a category.
217void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
218                                         const ObjCPropertyImplDecl *PID) {
219  ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
220  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
221  bool IsAtomic =
222    !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
223  ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
224  assert(OMD && "Invalid call to generate getter (empty method)");
225  StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
226
227  // Determine if we should use an objc_getProperty call for
228  // this. Non-atomic properties are directly evaluated.
229  // atomic 'copy' and 'retain' properties are also directly
230  // evaluated in gc-only mode.
231  if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
232      IsAtomic &&
233      (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
234       PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
235    llvm::Value *GetPropertyFn =
236      CGM.getObjCRuntime().GetPropertyGetFunction();
237
238    if (!GetPropertyFn) {
239      CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
240      FinishFunction();
241      return;
242    }
243
244    // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
245    // FIXME: Can't this be simpler? This might even be worse than the
246    // corresponding gcc code.
247    CodeGenTypes &Types = CGM.getTypes();
248    ValueDecl *Cmd = OMD->getCmdDecl();
249    llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
250    QualType IdTy = getContext().getObjCIdType();
251    llvm::Value *SelfAsId =
252      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
253    llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
254    llvm::Value *True =
255      llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
256    CallArgList Args;
257    Args.add(RValue::get(SelfAsId), IdTy);
258    Args.add(RValue::get(CmdVal), Cmd->getType());
259    Args.add(RValue::get(Offset), getContext().getPointerDiffType());
260    Args.add(RValue::get(True), getContext().BoolTy);
261    // FIXME: We shouldn't need to get the function info here, the
262    // runtime already should have computed it to build the function.
263    RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
264                                               FunctionType::ExtInfo()),
265                         GetPropertyFn, ReturnValueSlot(), Args);
266    // We need to fix the type here. Ivars with copy & retain are
267    // always objects so we don't need to worry about complex or
268    // aggregates.
269    RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
270                                           Types.ConvertType(PD->getType())));
271    EmitReturnOfRValue(RV, PD->getType());
272  } else {
273    const llvm::Triple &Triple = getContext().Target.getTriple();
274    QualType IVART = Ivar->getType();
275    if (IsAtomic &&
276        IVART->isScalarType() &&
277        (Triple.getArch() == llvm::Triple::arm ||
278         Triple.getArch() == llvm::Triple::thumb) &&
279        (getContext().getTypeSizeInChars(IVART)
280         > CharUnits::fromQuantity(4)) &&
281        CGM.getObjCRuntime().GetGetStructFunction()) {
282      GenerateObjCGetterBody(Ivar, true, false);
283    }
284    else if (IsAtomic &&
285             (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
286             Triple.getArch() == llvm::Triple::x86 &&
287             (getContext().getTypeSizeInChars(IVART)
288              > CharUnits::fromQuantity(4)) &&
289             CGM.getObjCRuntime().GetGetStructFunction()) {
290      GenerateObjCGetterBody(Ivar, true, false);
291    }
292    else if (IsAtomic &&
293             (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
294             Triple.getArch() == llvm::Triple::x86_64 &&
295             (getContext().getTypeSizeInChars(IVART)
296              > CharUnits::fromQuantity(8)) &&
297             CGM.getObjCRuntime().GetGetStructFunction()) {
298      GenerateObjCGetterBody(Ivar, true, false);
299    }
300    else if (IVART->isAnyComplexType()) {
301      LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
302                                    Ivar, 0);
303      ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
304                                               LV.isVolatileQualified());
305      StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
306    }
307    else if (hasAggregateLLVMType(IVART)) {
308      bool IsStrong = false;
309      if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
310          && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
311          && CGM.getObjCRuntime().GetGetStructFunction()) {
312        GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
313      }
314      else {
315        const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
316
317        if (PID->getGetterCXXConstructor() &&
318            classDecl && !classDecl->hasTrivialDefaultConstructor()) {
319          ReturnStmt *Stmt =
320            new (getContext()) ReturnStmt(SourceLocation(),
321                                          PID->getGetterCXXConstructor(),
322                                          0);
323          EmitReturnStmt(*Stmt);
324        } else if (IsAtomic &&
325                   !IVART->isAnyComplexType() &&
326                   Triple.getArch() == llvm::Triple::x86 &&
327                   (getContext().getTypeSizeInChars(IVART)
328                    > CharUnits::fromQuantity(4)) &&
329                   CGM.getObjCRuntime().GetGetStructFunction()) {
330          GenerateObjCGetterBody(Ivar, true, false);
331        }
332        else if (IsAtomic &&
333                 !IVART->isAnyComplexType() &&
334                 Triple.getArch() == llvm::Triple::x86_64 &&
335                 (getContext().getTypeSizeInChars(IVART)
336                  > CharUnits::fromQuantity(8)) &&
337                 CGM.getObjCRuntime().GetGetStructFunction()) {
338          GenerateObjCGetterBody(Ivar, true, false);
339        }
340        else {
341          LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
342                                        Ivar, 0);
343          EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
344        }
345      }
346    }
347    else {
348        LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
349                                    Ivar, 0);
350        if (PD->getType()->isReferenceType()) {
351          RValue RV = RValue::get(LV.getAddress());
352          EmitReturnOfRValue(RV, PD->getType());
353        }
354        else {
355          CodeGenTypes &Types = CGM.getTypes();
356          RValue RV = EmitLoadOfLValue(LV, IVART);
357          RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
358                                               Types.ConvertType(PD->getType())));
359          EmitReturnOfRValue(RV, PD->getType());
360        }
361    }
362  }
363
364  FinishFunction();
365}
366
367void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
368                                                   ObjCIvarDecl *Ivar) {
369  // objc_copyStruct (&structIvar, &Arg,
370  //                  sizeof (struct something), true, false);
371  llvm::Value *GetCopyStructFn =
372  CGM.getObjCRuntime().GetSetStructFunction();
373  CodeGenTypes &Types = CGM.getTypes();
374  CallArgList Args;
375  LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
376  RValue RV =
377    RValue::get(Builder.CreateBitCast(LV.getAddress(),
378                Types.ConvertType(getContext().VoidPtrTy)));
379  Args.add(RV, getContext().VoidPtrTy);
380  llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
381  llvm::Value *ArgAsPtrTy =
382  Builder.CreateBitCast(Arg,
383                      Types.ConvertType(getContext().VoidPtrTy));
384  RV = RValue::get(ArgAsPtrTy);
385  Args.add(RV, getContext().VoidPtrTy);
386  // sizeof (Type of Ivar)
387  CharUnits Size =  getContext().getTypeSizeInChars(Ivar->getType());
388  llvm::Value *SizeVal =
389  llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
390                         Size.getQuantity());
391  Args.add(RValue::get(SizeVal), getContext().LongTy);
392  llvm::Value *True =
393  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
394  Args.add(RValue::get(True), getContext().BoolTy);
395  llvm::Value *False =
396  llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
397  Args.add(RValue::get(False), getContext().BoolTy);
398  EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
399                                 FunctionType::ExtInfo()),
400           GetCopyStructFn, ReturnValueSlot(), Args);
401}
402
403static bool
404IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID,
405                              QualType IvarT) {
406  bool HasTrvialAssignment = true;
407  if (PID->getSetterCXXAssignment()) {
408    const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl();
409    HasTrvialAssignment =
410      (!classDecl || classDecl->hasTrivialCopyAssignment());
411  }
412  return HasTrvialAssignment;
413}
414
415/// GenerateObjCSetter - Generate an Objective-C property setter
416/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
417/// is illegal within a category.
418void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
419                                         const ObjCPropertyImplDecl *PID) {
420  ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
421  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
422  ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
423  assert(OMD && "Invalid call to generate setter (empty method)");
424  StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
425  const llvm::Triple &Triple = getContext().Target.getTriple();
426  QualType IVART = Ivar->getType();
427  bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
428  bool IsAtomic =
429    !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
430
431  // Determine if we should use an objc_setProperty call for
432  // this. Properties with 'copy' semantics always use it, as do
433  // non-atomic properties with 'release' semantics as long as we are
434  // not in gc-only mode.
435  if (IsCopy ||
436      (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
437       PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
438    llvm::Value *SetPropertyFn =
439      CGM.getObjCRuntime().GetPropertySetFunction();
440
441    if (!SetPropertyFn) {
442      CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
443      FinishFunction();
444      return;
445    }
446
447    // Emit objc_setProperty((id) self, _cmd, offset, arg,
448    //                       <is-atomic>, <is-copy>).
449    // FIXME: Can't this be simpler? This might even be worse than the
450    // corresponding gcc code.
451    CodeGenTypes &Types = CGM.getTypes();
452    ValueDecl *Cmd = OMD->getCmdDecl();
453    llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
454    QualType IdTy = getContext().getObjCIdType();
455    llvm::Value *SelfAsId =
456      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
457    llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
458    llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
459    llvm::Value *ArgAsId =
460      Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
461                            Types.ConvertType(IdTy));
462    llvm::Value *True =
463      llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
464    llvm::Value *False =
465      llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
466    CallArgList Args;
467    Args.add(RValue::get(SelfAsId), IdTy);
468    Args.add(RValue::get(CmdVal), Cmd->getType());
469    Args.add(RValue::get(Offset), getContext().getPointerDiffType());
470    Args.add(RValue::get(ArgAsId), IdTy);
471    Args.add(RValue::get(IsAtomic ? True : False),  getContext().BoolTy);
472    Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy);
473    // FIXME: We shouldn't need to get the function info here, the runtime
474    // already should have computed it to build the function.
475    EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
476                                   FunctionType::ExtInfo()),
477             SetPropertyFn,
478             ReturnValueSlot(), Args);
479  } else if (IsAtomic && hasAggregateLLVMType(IVART) &&
480             !IVART->isAnyComplexType() &&
481             IvarAssignHasTrvialAssignment(PID, IVART) &&
482             ((Triple.getArch() == llvm::Triple::x86 &&
483              (getContext().getTypeSizeInChars(IVART)
484               > CharUnits::fromQuantity(4))) ||
485              (Triple.getArch() == llvm::Triple::x86_64 &&
486              (getContext().getTypeSizeInChars(IVART)
487               > CharUnits::fromQuantity(8))))
488             && CGM.getObjCRuntime().GetSetStructFunction()) {
489          // objc_copyStruct (&structIvar, &Arg,
490          //                  sizeof (struct something), true, false);
491    GenerateObjCAtomicSetterBody(OMD, Ivar);
492  } else if (PID->getSetterCXXAssignment()) {
493    EmitIgnoredExpr(PID->getSetterCXXAssignment());
494  } else {
495    if (IsAtomic &&
496        IVART->isScalarType() &&
497        (Triple.getArch() == llvm::Triple::arm ||
498         Triple.getArch() == llvm::Triple::thumb) &&
499        (getContext().getTypeSizeInChars(IVART)
500          > CharUnits::fromQuantity(4)) &&
501        CGM.getObjCRuntime().GetGetStructFunction()) {
502      GenerateObjCAtomicSetterBody(OMD, Ivar);
503    }
504    else if (IsAtomic &&
505             (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
506             Triple.getArch() == llvm::Triple::x86 &&
507             (getContext().getTypeSizeInChars(IVART)
508              > CharUnits::fromQuantity(4)) &&
509             CGM.getObjCRuntime().GetGetStructFunction()) {
510      GenerateObjCAtomicSetterBody(OMD, Ivar);
511    }
512    else if (IsAtomic &&
513             (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
514             Triple.getArch() == llvm::Triple::x86_64 &&
515             (getContext().getTypeSizeInChars(IVART)
516              > CharUnits::fromQuantity(8)) &&
517             CGM.getObjCRuntime().GetGetStructFunction()) {
518      GenerateObjCAtomicSetterBody(OMD, Ivar);
519    }
520    else {
521      // FIXME: Find a clean way to avoid AST node creation.
522      SourceLocation Loc = PID->getLocStart();
523      ValueDecl *Self = OMD->getSelfDecl();
524      ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
525      DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
526      ParmVarDecl *ArgDecl = *OMD->param_begin();
527      QualType T = ArgDecl->getType();
528      if (T->isReferenceType())
529        T = cast<ReferenceType>(T)->getPointeeType();
530      DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc);
531      ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
532
533      // The property type can differ from the ivar type in some situations with
534      // Objective-C pointer types, we can always bit cast the RHS in these cases.
535      if (getContext().getCanonicalType(Ivar->getType()) !=
536          getContext().getCanonicalType(ArgDecl->getType())) {
537        ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
538                                   Ivar->getType(), CK_BitCast, &Arg,
539                                   VK_RValue);
540        BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
541                              Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
542        EmitStmt(&Assign);
543      } else {
544        BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
545                              Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
546        EmitStmt(&Assign);
547      }
548    }
549  }
550
551  FinishFunction();
552}
553
554// FIXME: these are stolen from CGClass.cpp, which is lame.
555namespace {
556  struct CallArrayIvarDtor : EHScopeStack::Cleanup {
557    const ObjCIvarDecl *ivar;
558    llvm::Value *self;
559    CallArrayIvarDtor(const ObjCIvarDecl *ivar, llvm::Value *self)
560      : ivar(ivar), self(self) {}
561
562    void Emit(CodeGenFunction &CGF, bool IsForEH) {
563      LValue lvalue =
564        CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), self, ivar, 0);
565
566      QualType type = ivar->getType();
567      const ConstantArrayType *arrayType
568        = CGF.getContext().getAsConstantArrayType(type);
569      QualType baseType = CGF.getContext().getBaseElementType(arrayType);
570      const CXXRecordDecl *classDecl = baseType->getAsCXXRecordDecl();
571
572      llvm::Value *base
573        = CGF.Builder.CreateBitCast(lvalue.getAddress(),
574                                    CGF.ConvertType(baseType)->getPointerTo());
575      CGF.EmitCXXAggrDestructorCall(classDecl->getDestructor(),
576                                    arrayType, base);
577    }
578  };
579
580  struct CallIvarDtor : EHScopeStack::Cleanup {
581    const ObjCIvarDecl *ivar;
582    llvm::Value *self;
583    CallIvarDtor(const ObjCIvarDecl *ivar, llvm::Value *self)
584      : ivar(ivar), self(self) {}
585
586    void Emit(CodeGenFunction &CGF, bool IsForEH) {
587      LValue lvalue =
588        CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), self, ivar, 0);
589
590      QualType type = ivar->getType();
591      const CXXRecordDecl *classDecl = type->getAsCXXRecordDecl();
592
593      CGF.EmitCXXDestructorCall(classDecl->getDestructor(),
594                                Dtor_Complete, /*ForVirtualBase=*/false,
595                                lvalue.getAddress());
596    }
597  };
598}
599
600static void emitCXXDestructMethod(CodeGenFunction &CGF,
601                                  ObjCImplementationDecl *impl) {
602  CodeGenFunction::RunCleanupsScope scope(CGF);
603
604  llvm::Value *self = CGF.LoadObjCSelf();
605
606  ObjCInterfaceDecl *iface
607    = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
608  for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
609       ivar; ivar = ivar->getNextIvar()) {
610    QualType type = ivar->getType();
611
612    // Drill down to the base element type.
613    QualType baseType = type;
614    const ConstantArrayType *arrayType =
615      CGF.getContext().getAsConstantArrayType(baseType);
616    if (arrayType) baseType = CGF.getContext().getBaseElementType(arrayType);
617
618    // Check whether the ivar is a destructible type.
619    QualType::DestructionKind destructKind = baseType.isDestructedType();
620    assert(destructKind == type.isDestructedType());
621
622    switch (destructKind) {
623    case QualType::DK_none:
624      continue;
625
626    case QualType::DK_cxx_destructor:
627      if (arrayType)
628        CGF.EHStack.pushCleanup<CallArrayIvarDtor>(NormalAndEHCleanup,
629                                                   ivar, self);
630      else
631        CGF.EHStack.pushCleanup<CallIvarDtor>(NormalAndEHCleanup,
632                                              ivar, self);
633      break;
634    }
635  }
636
637  assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
638}
639
640void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
641                                                 ObjCMethodDecl *MD,
642                                                 bool ctor) {
643  MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
644  StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
645
646  // Emit .cxx_construct.
647  if (ctor) {
648    llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
649    for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
650           E = IMP->init_end(); B != E; ++B) {
651      CXXCtorInitializer *IvarInit = (*B);
652      FieldDecl *Field = IvarInit->getAnyMember();
653      ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
654      LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
655                                    LoadObjCSelf(), Ivar, 0);
656      EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
657    }
658    // constructor returns 'self'.
659    CodeGenTypes &Types = CGM.getTypes();
660    QualType IdTy(CGM.getContext().getObjCIdType());
661    llvm::Value *SelfAsId =
662      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
663    EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
664
665  // Emit .cxx_destruct.
666  } else {
667    emitCXXDestructMethod(*this, IMP);
668  }
669  FinishFunction();
670}
671
672bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
673  CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
674  it++; it++;
675  const ABIArgInfo &AI = it->info;
676  // FIXME. Is this sufficient check?
677  return (AI.getKind() == ABIArgInfo::Indirect);
678}
679
680bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
681  if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
682    return false;
683  if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
684    return FDTTy->getDecl()->hasObjectMember();
685  return false;
686}
687
688llvm::Value *CodeGenFunction::LoadObjCSelf() {
689  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
690  return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
691}
692
693QualType CodeGenFunction::TypeOfSelfObject() {
694  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
695  ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
696  const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
697    getContext().getCanonicalType(selfDecl->getType()));
698  return PTy->getPointeeType();
699}
700
701LValue
702CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
703  // This is a special l-value that just issues sends when we load or
704  // store through it.
705
706  // For certain base kinds, we need to emit the base immediately.
707  llvm::Value *Base;
708  if (E->isSuperReceiver())
709    Base = LoadObjCSelf();
710  else if (E->isClassReceiver())
711    Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
712  else
713    Base = EmitScalarExpr(E->getBase());
714  return LValue::MakePropertyRef(E, Base);
715}
716
717static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
718                                       ReturnValueSlot Return,
719                                       QualType ResultType,
720                                       Selector S,
721                                       llvm::Value *Receiver,
722                                       const CallArgList &CallArgs) {
723  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
724  bool isClassMessage = OMD->isClassMethod();
725  bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
726  return CGF.CGM.getObjCRuntime()
727                .GenerateMessageSendSuper(CGF, Return, ResultType,
728                                          S, OMD->getClassInterface(),
729                                          isCategoryImpl, Receiver,
730                                          isClassMessage, CallArgs);
731}
732
733RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
734                                                    ReturnValueSlot Return) {
735  const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
736  QualType ResultType = E->getGetterResultType();
737  Selector S;
738  const ObjCMethodDecl *method;
739  if (E->isExplicitProperty()) {
740    const ObjCPropertyDecl *Property = E->getExplicitProperty();
741    S = Property->getGetterName();
742    method = Property->getGetterMethodDecl();
743  } else {
744    method = E->getImplicitPropertyGetter();
745    S = method->getSelector();
746  }
747
748  llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
749
750  // Accesses to 'super' follow a different code path.
751  if (E->isSuperReceiver())
752    return AdjustRelatedResultType(*this, E, method,
753                                   GenerateMessageSendSuper(*this, Return,
754                                                            ResultType,
755                                                            S, Receiver,
756                                                            CallArgList()));
757  const ObjCInterfaceDecl *ReceiverClass
758    = (E->isClassReceiver() ? E->getClassReceiver() : 0);
759  return AdjustRelatedResultType(*this, E, method,
760                                 CGM.getObjCRuntime().
761                 GenerateMessageSend(*this, Return, ResultType, S,
762                                     Receiver, CallArgList(), ReceiverClass));
763}
764
765void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
766                                                        LValue Dst) {
767  const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
768  Selector S = E->getSetterSelector();
769  QualType ArgType = E->getSetterArgType();
770
771  // FIXME. Other than scalars, AST is not adequate for setter and
772  // getter type mismatches which require conversion.
773  if (Src.isScalar()) {
774    llvm::Value *SrcVal = Src.getScalarVal();
775    QualType DstType = getContext().getCanonicalType(ArgType);
776    const llvm::Type *DstTy = ConvertType(DstType);
777    if (SrcVal->getType() != DstTy)
778      Src =
779        RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
780  }
781
782  CallArgList Args;
783  Args.add(Src, ArgType);
784
785  llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
786  QualType ResultType = getContext().VoidTy;
787
788  if (E->isSuperReceiver()) {
789    GenerateMessageSendSuper(*this, ReturnValueSlot(),
790                             ResultType, S, Receiver, Args);
791    return;
792  }
793
794  const ObjCInterfaceDecl *ReceiverClass
795    = (E->isClassReceiver() ? E->getClassReceiver() : 0);
796
797  CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
798                                           ResultType, S, Receiver, Args,
799                                           ReceiverClass);
800}
801
802void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
803  llvm::Constant *EnumerationMutationFn =
804    CGM.getObjCRuntime().EnumerationMutationFunction();
805
806  if (!EnumerationMutationFn) {
807    CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
808    return;
809  }
810
811  // The local variable comes into scope immediately.
812  AutoVarEmission variable = AutoVarEmission::invalid();
813  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
814    variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
815
816  CGDebugInfo *DI = getDebugInfo();
817  if (DI) {
818    DI->setLocation(S.getSourceRange().getBegin());
819    DI->EmitRegionStart(Builder);
820  }
821
822  JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
823  JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
824
825  // Fast enumeration state.
826  QualType StateTy = getContext().getObjCFastEnumerationStateType();
827  llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
828  EmitNullInitialization(StatePtr, StateTy);
829
830  // Number of elements in the items array.
831  static const unsigned NumItems = 16;
832
833  // Fetch the countByEnumeratingWithState:objects:count: selector.
834  IdentifierInfo *II[] = {
835    &CGM.getContext().Idents.get("countByEnumeratingWithState"),
836    &CGM.getContext().Idents.get("objects"),
837    &CGM.getContext().Idents.get("count")
838  };
839  Selector FastEnumSel =
840    CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
841
842  QualType ItemsTy =
843    getContext().getConstantArrayType(getContext().getObjCIdType(),
844                                      llvm::APInt(32, NumItems),
845                                      ArrayType::Normal, 0);
846  llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
847
848  // Emit the collection pointer.
849  llvm::Value *Collection = EmitScalarExpr(S.getCollection());
850
851  // Send it our message:
852  CallArgList Args;
853
854  // The first argument is a temporary of the enumeration-state type.
855  Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
856
857  // The second argument is a temporary array with space for NumItems
858  // pointers.  We'll actually be loading elements from the array
859  // pointer written into the control state; this buffer is so that
860  // collections that *aren't* backed by arrays can still queue up
861  // batches of elements.
862  Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
863
864  // The third argument is the capacity of that temporary array.
865  const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
866  llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
867  Args.add(RValue::get(Count), getContext().UnsignedLongTy);
868
869  // Start the enumeration.
870  RValue CountRV =
871    CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
872                                             getContext().UnsignedLongTy,
873                                             FastEnumSel,
874                                             Collection, Args);
875
876  // The initial number of objects that were returned in the buffer.
877  llvm::Value *initialBufferLimit = CountRV.getScalarVal();
878
879  llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
880  llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
881
882  llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
883
884  // If the limit pointer was zero to begin with, the collection is
885  // empty; skip all this.
886  Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
887                       EmptyBB, LoopInitBB);
888
889  // Otherwise, initialize the loop.
890  EmitBlock(LoopInitBB);
891
892  // Save the initial mutations value.  This is the value at an
893  // address that was written into the state object by
894  // countByEnumeratingWithState:objects:count:.
895  llvm::Value *StateMutationsPtrPtr =
896    Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
897  llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
898                                                      "mutationsptr");
899
900  llvm::Value *initialMutations =
901    Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
902
903  // Start looping.  This is the point we return to whenever we have a
904  // fresh, non-empty batch of objects.
905  llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
906  EmitBlock(LoopBodyBB);
907
908  // The current index into the buffer.
909  llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
910  index->addIncoming(zero, LoopInitBB);
911
912  // The current buffer size.
913  llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
914  count->addIncoming(initialBufferLimit, LoopInitBB);
915
916  // Check whether the mutations value has changed from where it was
917  // at start.  StateMutationsPtr should actually be invariant between
918  // refreshes.
919  StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
920  llvm::Value *currentMutations
921    = Builder.CreateLoad(StateMutationsPtr, "statemutations");
922
923  llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
924  llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
925
926  Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
927                       WasNotMutatedBB, WasMutatedBB);
928
929  // If so, call the enumeration-mutation function.
930  EmitBlock(WasMutatedBB);
931  llvm::Value *V =
932    Builder.CreateBitCast(Collection,
933                          ConvertType(getContext().getObjCIdType()),
934                          "tmp");
935  CallArgList Args2;
936  Args2.add(RValue::get(V), getContext().getObjCIdType());
937  // FIXME: We shouldn't need to get the function info here, the runtime already
938  // should have computed it to build the function.
939  EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
940                                          FunctionType::ExtInfo()),
941           EnumerationMutationFn, ReturnValueSlot(), Args2);
942
943  // Otherwise, or if the mutation function returns, just continue.
944  EmitBlock(WasNotMutatedBB);
945
946  // Initialize the element variable.
947  RunCleanupsScope elementVariableScope(*this);
948  bool elementIsVariable;
949  LValue elementLValue;
950  QualType elementType;
951  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
952    // Initialize the variable, in case it's a __block variable or something.
953    EmitAutoVarInit(variable);
954
955    const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
956    DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
957                        VK_LValue, SourceLocation());
958    elementLValue = EmitLValue(&tempDRE);
959    elementType = D->getType();
960    elementIsVariable = true;
961  } else {
962    elementLValue = LValue(); // suppress warning
963    elementType = cast<Expr>(S.getElement())->getType();
964    elementIsVariable = false;
965  }
966  const llvm::Type *convertedElementType = ConvertType(elementType);
967
968  // Fetch the buffer out of the enumeration state.
969  // TODO: this pointer should actually be invariant between
970  // refreshes, which would help us do certain loop optimizations.
971  llvm::Value *StateItemsPtr =
972    Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
973  llvm::Value *EnumStateItems =
974    Builder.CreateLoad(StateItemsPtr, "stateitems");
975
976  // Fetch the value at the current index from the buffer.
977  llvm::Value *CurrentItemPtr =
978    Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
979  llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
980
981  // Cast that value to the right type.
982  CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
983                                      "currentitem");
984
985  // Make sure we have an l-value.  Yes, this gets evaluated every
986  // time through the loop.
987  if (!elementIsVariable)
988    elementLValue = EmitLValue(cast<Expr>(S.getElement()));
989
990  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
991
992  // If we do have an element variable, this assignment is the end of
993  // its initialization.
994  if (elementIsVariable)
995    EmitAutoVarCleanups(variable);
996
997  // Perform the loop body, setting up break and continue labels.
998  BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
999  {
1000    RunCleanupsScope Scope(*this);
1001    EmitStmt(S.getBody());
1002  }
1003  BreakContinueStack.pop_back();
1004
1005  // Destroy the element variable now.
1006  elementVariableScope.ForceCleanup();
1007
1008  // Check whether there are more elements.
1009  EmitBlock(AfterBody.getBlock());
1010
1011  llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1012
1013  // First we check in the local buffer.
1014  llvm::Value *indexPlusOne
1015    = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1016
1017  // If we haven't overrun the buffer yet, we can continue.
1018  Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1019                       LoopBodyBB, FetchMoreBB);
1020
1021  index->addIncoming(indexPlusOne, AfterBody.getBlock());
1022  count->addIncoming(count, AfterBody.getBlock());
1023
1024  // Otherwise, we have to fetch more elements.
1025  EmitBlock(FetchMoreBB);
1026
1027  CountRV =
1028    CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1029                                             getContext().UnsignedLongTy,
1030                                             FastEnumSel,
1031                                             Collection, Args);
1032
1033  // If we got a zero count, we're done.
1034  llvm::Value *refetchCount = CountRV.getScalarVal();
1035
1036  // (note that the message send might split FetchMoreBB)
1037  index->addIncoming(zero, Builder.GetInsertBlock());
1038  count->addIncoming(refetchCount, Builder.GetInsertBlock());
1039
1040  Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1041                       EmptyBB, LoopBodyBB);
1042
1043  // No more elements.
1044  EmitBlock(EmptyBB);
1045
1046  if (!elementIsVariable) {
1047    // If the element was not a declaration, set it to be null.
1048
1049    llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1050    elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1051    EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
1052  }
1053
1054  if (DI) {
1055    DI->setLocation(S.getSourceRange().getEnd());
1056    DI->EmitRegionEnd(Builder);
1057  }
1058
1059  EmitBlock(LoopEnd.getBlock());
1060}
1061
1062void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1063  CGM.getObjCRuntime().EmitTryStmt(*this, S);
1064}
1065
1066void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1067  CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1068}
1069
1070void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1071                                              const ObjCAtSynchronizedStmt &S) {
1072  CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1073}
1074
1075CGObjCRuntime::~CGObjCRuntime() {}
1076