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