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