1//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
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 file defines ObjC ARC optimizations. ARC stands for
11// Automatic Reference Counting and is a system for managing reference counts
12// for objects in Objective C.
13//
14// The optimizations performed include elimination of redundant, partially
15// redundant, and inconsequential reference count operations, elimination of
16// redundant weak pointer operations, pattern-matching and replacement of
17// low-level operations into higher-level operations, and numerous minor
18// simplifications.
19//
20// This file also defines a simple ARC-aware AliasAnalysis.
21//
22// WARNING: This file knows about certain library functions. It recognizes them
23// by name, and hardwires knowledge of their semantics.
24//
25// WARNING: This file knows about how certain Objective-C library functions are
26// used. Naive LLVM IR transformations which would otherwise be
27// behavior-preserving may break these assumptions.
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/ADT/DenseMap.h"
34using namespace llvm;
35
36// A handy option to enable/disable all optimizations in this file.
37static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
38
39//===----------------------------------------------------------------------===//
40// Misc. Utilities
41//===----------------------------------------------------------------------===//
42
43namespace {
44  /// MapVector - An associative container with fast insertion-order
45  /// (deterministic) iteration over its elements. Plus the special
46  /// blot operation.
47  template<class KeyT, class ValueT>
48  class MapVector {
49    /// Map - Map keys to indices in Vector.
50    typedef DenseMap<KeyT, size_t> MapTy;
51    MapTy Map;
52
53    /// Vector - Keys and values.
54    typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
55    VectorTy Vector;
56
57  public:
58    typedef typename VectorTy::iterator iterator;
59    typedef typename VectorTy::const_iterator const_iterator;
60    iterator begin() { return Vector.begin(); }
61    iterator end() { return Vector.end(); }
62    const_iterator begin() const { return Vector.begin(); }
63    const_iterator end() const { return Vector.end(); }
64
65#ifdef XDEBUG
66    ~MapVector() {
67      assert(Vector.size() >= Map.size()); // May differ due to blotting.
68      for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
69           I != E; ++I) {
70        assert(I->second < Vector.size());
71        assert(Vector[I->second].first == I->first);
72      }
73      for (typename VectorTy::const_iterator I = Vector.begin(),
74           E = Vector.end(); I != E; ++I)
75        assert(!I->first ||
76               (Map.count(I->first) &&
77                Map[I->first] == size_t(I - Vector.begin())));
78    }
79#endif
80
81    ValueT &operator[](const KeyT &Arg) {
82      std::pair<typename MapTy::iterator, bool> Pair =
83        Map.insert(std::make_pair(Arg, size_t(0)));
84      if (Pair.second) {
85        size_t Num = Vector.size();
86        Pair.first->second = Num;
87        Vector.push_back(std::make_pair(Arg, ValueT()));
88        return Vector[Num].second;
89      }
90      return Vector[Pair.first->second].second;
91    }
92
93    std::pair<iterator, bool>
94    insert(const std::pair<KeyT, ValueT> &InsertPair) {
95      std::pair<typename MapTy::iterator, bool> Pair =
96        Map.insert(std::make_pair(InsertPair.first, size_t(0)));
97      if (Pair.second) {
98        size_t Num = Vector.size();
99        Pair.first->second = Num;
100        Vector.push_back(InsertPair);
101        return std::make_pair(Vector.begin() + Num, true);
102      }
103      return std::make_pair(Vector.begin() + Pair.first->second, false);
104    }
105
106    const_iterator find(const KeyT &Key) const {
107      typename MapTy::const_iterator It = Map.find(Key);
108      if (It == Map.end()) return Vector.end();
109      return Vector.begin() + It->second;
110    }
111
112    /// blot - This is similar to erase, but instead of removing the element
113    /// from the vector, it just zeros out the key in the vector. This leaves
114    /// iterators intact, but clients must be prepared for zeroed-out keys when
115    /// iterating.
116    void blot(const KeyT &Key) {
117      typename MapTy::iterator It = Map.find(Key);
118      if (It == Map.end()) return;
119      Vector[It->second].first = KeyT();
120      Map.erase(It);
121    }
122
123    void clear() {
124      Map.clear();
125      Vector.clear();
126    }
127  };
128}
129
130//===----------------------------------------------------------------------===//
131// ARC Utilities.
132//===----------------------------------------------------------------------===//
133
134#include "llvm/Intrinsics.h"
135#include "llvm/Module.h"
136#include "llvm/Analysis/ValueTracking.h"
137#include "llvm/Transforms/Utils/Local.h"
138#include "llvm/Support/CallSite.h"
139#include "llvm/ADT/StringSwitch.h"
140
141namespace {
142  /// InstructionClass - A simple classification for instructions.
143  enum InstructionClass {
144    IC_Retain,              ///< objc_retain
145    IC_RetainRV,            ///< objc_retainAutoreleasedReturnValue
146    IC_RetainBlock,         ///< objc_retainBlock
147    IC_Release,             ///< objc_release
148    IC_Autorelease,         ///< objc_autorelease
149    IC_AutoreleaseRV,       ///< objc_autoreleaseReturnValue
150    IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
151    IC_AutoreleasepoolPop,  ///< objc_autoreleasePoolPop
152    IC_NoopCast,            ///< objc_retainedObject, etc.
153    IC_FusedRetainAutorelease, ///< objc_retainAutorelease
154    IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
155    IC_LoadWeakRetained,    ///< objc_loadWeakRetained (primitive)
156    IC_StoreWeak,           ///< objc_storeWeak (primitive)
157    IC_InitWeak,            ///< objc_initWeak (derived)
158    IC_LoadWeak,            ///< objc_loadWeak (derived)
159    IC_MoveWeak,            ///< objc_moveWeak (derived)
160    IC_CopyWeak,            ///< objc_copyWeak (derived)
161    IC_DestroyWeak,         ///< objc_destroyWeak (derived)
162    IC_StoreStrong,         ///< objc_storeStrong (derived)
163    IC_CallOrUser,          ///< could call objc_release and/or "use" pointers
164    IC_Call,                ///< could call objc_release
165    IC_User,                ///< could "use" a pointer
166    IC_None                 ///< anything else
167  };
168}
169
170/// IsPotentialUse - Test whether the given value is possible a
171/// reference-counted pointer.
172static bool IsPotentialUse(const Value *Op) {
173  // Pointers to static or stack storage are not reference-counted pointers.
174  if (isa<Constant>(Op) || isa<AllocaInst>(Op))
175    return false;
176  // Special arguments are not reference-counted.
177  if (const Argument *Arg = dyn_cast<Argument>(Op))
178    if (Arg->hasByValAttr() ||
179        Arg->hasNestAttr() ||
180        Arg->hasStructRetAttr())
181      return false;
182  // Only consider values with pointer types.
183  // It seemes intuitive to exclude function pointer types as well, since
184  // functions are never reference-counted, however clang occasionally
185  // bitcasts reference-counted pointers to function-pointer type
186  // temporarily.
187  PointerType *Ty = dyn_cast<PointerType>(Op->getType());
188  if (!Ty)
189    return false;
190  // Conservatively assume anything else is a potential use.
191  return true;
192}
193
194/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
195/// of construct CS is.
196static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
197  for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
198       I != E; ++I)
199    if (IsPotentialUse(*I))
200      return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
201
202  return CS.onlyReadsMemory() ? IC_None : IC_Call;
203}
204
205/// GetFunctionClass - Determine if F is one of the special known Functions.
206/// If it isn't, return IC_CallOrUser.
207static InstructionClass GetFunctionClass(const Function *F) {
208  Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
209
210  // No arguments.
211  if (AI == AE)
212    return StringSwitch<InstructionClass>(F->getName())
213      .Case("objc_autoreleasePoolPush",  IC_AutoreleasepoolPush)
214      .Default(IC_CallOrUser);
215
216  // One argument.
217  const Argument *A0 = AI++;
218  if (AI == AE)
219    // Argument is a pointer.
220    if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
221      Type *ETy = PTy->getElementType();
222      // Argument is i8*.
223      if (ETy->isIntegerTy(8))
224        return StringSwitch<InstructionClass>(F->getName())
225          .Case("objc_retain",                IC_Retain)
226          .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
227          .Case("objc_retainBlock",           IC_RetainBlock)
228          .Case("objc_release",               IC_Release)
229          .Case("objc_autorelease",           IC_Autorelease)
230          .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
231          .Case("objc_autoreleasePoolPop",    IC_AutoreleasepoolPop)
232          .Case("objc_retainedObject",        IC_NoopCast)
233          .Case("objc_unretainedObject",      IC_NoopCast)
234          .Case("objc_unretainedPointer",     IC_NoopCast)
235          .Case("objc_retain_autorelease",    IC_FusedRetainAutorelease)
236          .Case("objc_retainAutorelease",     IC_FusedRetainAutorelease)
237          .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
238          .Default(IC_CallOrUser);
239
240      // Argument is i8**
241      if (PointerType *Pte = dyn_cast<PointerType>(ETy))
242        if (Pte->getElementType()->isIntegerTy(8))
243          return StringSwitch<InstructionClass>(F->getName())
244            .Case("objc_loadWeakRetained",      IC_LoadWeakRetained)
245            .Case("objc_loadWeak",              IC_LoadWeak)
246            .Case("objc_destroyWeak",           IC_DestroyWeak)
247            .Default(IC_CallOrUser);
248    }
249
250  // Two arguments, first is i8**.
251  const Argument *A1 = AI++;
252  if (AI == AE)
253    if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
254      if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
255        if (Pte->getElementType()->isIntegerTy(8))
256          if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
257            Type *ETy1 = PTy1->getElementType();
258            // Second argument is i8*
259            if (ETy1->isIntegerTy(8))
260              return StringSwitch<InstructionClass>(F->getName())
261                     .Case("objc_storeWeak",             IC_StoreWeak)
262                     .Case("objc_initWeak",              IC_InitWeak)
263                     .Case("objc_storeStrong",           IC_StoreStrong)
264                     .Default(IC_CallOrUser);
265            // Second argument is i8**.
266            if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
267              if (Pte1->getElementType()->isIntegerTy(8))
268                return StringSwitch<InstructionClass>(F->getName())
269                       .Case("objc_moveWeak",              IC_MoveWeak)
270                       .Case("objc_copyWeak",              IC_CopyWeak)
271                       .Default(IC_CallOrUser);
272          }
273
274  // Anything else.
275  return IC_CallOrUser;
276}
277
278/// GetInstructionClass - Determine what kind of construct V is.
279static InstructionClass GetInstructionClass(const Value *V) {
280  if (const Instruction *I = dyn_cast<Instruction>(V)) {
281    // Any instruction other than bitcast and gep with a pointer operand have a
282    // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
283    // to a subsequent use, rather than using it themselves, in this sense.
284    // As a short cut, several other opcodes are known to have no pointer
285    // operands of interest. And ret is never followed by a release, so it's
286    // not interesting to examine.
287    switch (I->getOpcode()) {
288    case Instruction::Call: {
289      const CallInst *CI = cast<CallInst>(I);
290      // Check for calls to special functions.
291      if (const Function *F = CI->getCalledFunction()) {
292        InstructionClass Class = GetFunctionClass(F);
293        if (Class != IC_CallOrUser)
294          return Class;
295
296        // None of the intrinsic functions do objc_release. For intrinsics, the
297        // only question is whether or not they may be users.
298        switch (F->getIntrinsicID()) {
299        case Intrinsic::returnaddress: case Intrinsic::frameaddress:
300        case Intrinsic::stacksave: case Intrinsic::stackrestore:
301        case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
302        case Intrinsic::objectsize: case Intrinsic::prefetch:
303        case Intrinsic::stackprotector:
304        case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
305        case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
306        case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
307        case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
308        case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
309        case Intrinsic::invariant_start: case Intrinsic::invariant_end:
310        // Don't let dbg info affect our results.
311        case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
312          // Short cut: Some intrinsics obviously don't use ObjC pointers.
313          return IC_None;
314        default:
315          break;
316        }
317      }
318      return GetCallSiteClass(CI);
319    }
320    case Instruction::Invoke:
321      return GetCallSiteClass(cast<InvokeInst>(I));
322    case Instruction::BitCast:
323    case Instruction::GetElementPtr:
324    case Instruction::Select: case Instruction::PHI:
325    case Instruction::Ret: case Instruction::Br:
326    case Instruction::Switch: case Instruction::IndirectBr:
327    case Instruction::Alloca: case Instruction::VAArg:
328    case Instruction::Add: case Instruction::FAdd:
329    case Instruction::Sub: case Instruction::FSub:
330    case Instruction::Mul: case Instruction::FMul:
331    case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
332    case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
333    case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
334    case Instruction::And: case Instruction::Or: case Instruction::Xor:
335    case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
336    case Instruction::IntToPtr: case Instruction::FCmp:
337    case Instruction::FPTrunc: case Instruction::FPExt:
338    case Instruction::FPToUI: case Instruction::FPToSI:
339    case Instruction::UIToFP: case Instruction::SIToFP:
340    case Instruction::InsertElement: case Instruction::ExtractElement:
341    case Instruction::ShuffleVector:
342    case Instruction::ExtractValue:
343      break;
344    case Instruction::ICmp:
345      // Comparing a pointer with null, or any other constant, isn't an
346      // interesting use, because we don't care what the pointer points to, or
347      // about the values of any other dynamic reference-counted pointers.
348      if (IsPotentialUse(I->getOperand(1)))
349        return IC_User;
350      break;
351    default:
352      // For anything else, check all the operands.
353      // Note that this includes both operands of a Store: while the first
354      // operand isn't actually being dereferenced, it is being stored to
355      // memory where we can no longer track who might read it and dereference
356      // it, so we have to consider it potentially used.
357      for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
358           OI != OE; ++OI)
359        if (IsPotentialUse(*OI))
360          return IC_User;
361    }
362  }
363
364  // Otherwise, it's totally inert for ARC purposes.
365  return IC_None;
366}
367
368/// GetBasicInstructionClass - Determine what kind of construct V is. This is
369/// similar to GetInstructionClass except that it only detects objc runtine
370/// calls. This allows it to be faster.
371static InstructionClass GetBasicInstructionClass(const Value *V) {
372  if (const CallInst *CI = dyn_cast<CallInst>(V)) {
373    if (const Function *F = CI->getCalledFunction())
374      return GetFunctionClass(F);
375    // Otherwise, be conservative.
376    return IC_CallOrUser;
377  }
378
379  // Otherwise, be conservative.
380  return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
381}
382
383/// IsRetain - Test if the given class is objc_retain or
384/// equivalent.
385static bool IsRetain(InstructionClass Class) {
386  return Class == IC_Retain ||
387         Class == IC_RetainRV;
388}
389
390/// IsAutorelease - Test if the given class is objc_autorelease or
391/// equivalent.
392static bool IsAutorelease(InstructionClass Class) {
393  return Class == IC_Autorelease ||
394         Class == IC_AutoreleaseRV;
395}
396
397/// IsForwarding - Test if the given class represents instructions which return
398/// their argument verbatim.
399static bool IsForwarding(InstructionClass Class) {
400  // objc_retainBlock technically doesn't always return its argument
401  // verbatim, but it doesn't matter for our purposes here.
402  return Class == IC_Retain ||
403         Class == IC_RetainRV ||
404         Class == IC_Autorelease ||
405         Class == IC_AutoreleaseRV ||
406         Class == IC_RetainBlock ||
407         Class == IC_NoopCast;
408}
409
410/// IsNoopOnNull - Test if the given class represents instructions which do
411/// nothing if passed a null pointer.
412static bool IsNoopOnNull(InstructionClass Class) {
413  return Class == IC_Retain ||
414         Class == IC_RetainRV ||
415         Class == IC_Release ||
416         Class == IC_Autorelease ||
417         Class == IC_AutoreleaseRV ||
418         Class == IC_RetainBlock;
419}
420
421/// IsAlwaysTail - Test if the given class represents instructions which are
422/// always safe to mark with the "tail" keyword.
423static bool IsAlwaysTail(InstructionClass Class) {
424  // IC_RetainBlock may be given a stack argument.
425  return Class == IC_Retain ||
426         Class == IC_RetainRV ||
427         Class == IC_Autorelease ||
428         Class == IC_AutoreleaseRV;
429}
430
431/// IsNoThrow - Test if the given class represents instructions which are always
432/// safe to mark with the nounwind attribute..
433static bool IsNoThrow(InstructionClass Class) {
434  // objc_retainBlock is not nounwind because it calls user copy constructors
435  // which could theoretically throw.
436  return Class == IC_Retain ||
437         Class == IC_RetainRV ||
438         Class == IC_Release ||
439         Class == IC_Autorelease ||
440         Class == IC_AutoreleaseRV ||
441         Class == IC_AutoreleasepoolPush ||
442         Class == IC_AutoreleasepoolPop;
443}
444
445/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
446/// argument verbatim, so if it's such a call and the return value has users,
447/// replace them with the argument value.
448static void EraseInstruction(Instruction *CI) {
449  Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
450
451  bool Unused = CI->use_empty();
452
453  if (!Unused) {
454    // Replace the return value with the argument.
455    assert(IsForwarding(GetBasicInstructionClass(CI)) &&
456           "Can't delete non-forwarding instruction with users!");
457    CI->replaceAllUsesWith(OldArg);
458  }
459
460  CI->eraseFromParent();
461
462  if (Unused)
463    RecursivelyDeleteTriviallyDeadInstructions(OldArg);
464}
465
466/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
467/// also knows how to look through objc_retain and objc_autorelease calls, which
468/// we know to return their argument verbatim.
469static const Value *GetUnderlyingObjCPtr(const Value *V) {
470  for (;;) {
471    V = GetUnderlyingObject(V);
472    if (!IsForwarding(GetBasicInstructionClass(V)))
473      break;
474    V = cast<CallInst>(V)->getArgOperand(0);
475  }
476
477  return V;
478}
479
480/// StripPointerCastsAndObjCCalls - This is a wrapper around
481/// Value::stripPointerCasts which also knows how to look through objc_retain
482/// and objc_autorelease calls, which we know to return their argument verbatim.
483static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
484  for (;;) {
485    V = V->stripPointerCasts();
486    if (!IsForwarding(GetBasicInstructionClass(V)))
487      break;
488    V = cast<CallInst>(V)->getArgOperand(0);
489  }
490  return V;
491}
492
493/// StripPointerCastsAndObjCCalls - This is a wrapper around
494/// Value::stripPointerCasts which also knows how to look through objc_retain
495/// and objc_autorelease calls, which we know to return their argument verbatim.
496static Value *StripPointerCastsAndObjCCalls(Value *V) {
497  for (;;) {
498    V = V->stripPointerCasts();
499    if (!IsForwarding(GetBasicInstructionClass(V)))
500      break;
501    V = cast<CallInst>(V)->getArgOperand(0);
502  }
503  return V;
504}
505
506/// GetObjCArg - Assuming the given instruction is one of the special calls such
507/// as objc_retain or objc_release, return the argument value, stripped of no-op
508/// casts and forwarding calls.
509static Value *GetObjCArg(Value *Inst) {
510  return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
511}
512
513/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
514/// isObjCIdentifiedObject, except that it uses special knowledge of
515/// ObjC conventions...
516static bool IsObjCIdentifiedObject(const Value *V) {
517  // Assume that call results and arguments have their own "provenance".
518  // Constants (including GlobalVariables) and Allocas are never
519  // reference-counted.
520  if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
521      isa<Argument>(V) || isa<Constant>(V) ||
522      isa<AllocaInst>(V))
523    return true;
524
525  if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
526    const Value *Pointer =
527      StripPointerCastsAndObjCCalls(LI->getPointerOperand());
528    if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
529      // A constant pointer can't be pointing to an object on the heap. It may
530      // be reference-counted, but it won't be deleted.
531      if (GV->isConstant())
532        return true;
533      StringRef Name = GV->getName();
534      // These special variables are known to hold values which are not
535      // reference-counted pointers.
536      if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
537          Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
538          Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
539          Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
540          Name.startswith("\01l_objc_msgSend_fixup_"))
541        return true;
542    }
543  }
544
545  return false;
546}
547
548/// FindSingleUseIdentifiedObject - This is similar to
549/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
550/// with multiple uses.
551static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
552  if (Arg->hasOneUse()) {
553    if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
554      return FindSingleUseIdentifiedObject(BC->getOperand(0));
555    if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
556      if (GEP->hasAllZeroIndices())
557        return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
558    if (IsForwarding(GetBasicInstructionClass(Arg)))
559      return FindSingleUseIdentifiedObject(
560               cast<CallInst>(Arg)->getArgOperand(0));
561    if (!IsObjCIdentifiedObject(Arg))
562      return 0;
563    return Arg;
564  }
565
566  // If we found an identifiable object but it has multiple uses, but they are
567  // trivial uses, we can still consider this to be a single-use value.
568  if (IsObjCIdentifiedObject(Arg)) {
569    for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
570         UI != UE; ++UI) {
571      const User *U = *UI;
572      if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
573         return 0;
574    }
575
576    return Arg;
577  }
578
579  return 0;
580}
581
582/// ModuleHasARC - Test if the given module looks interesting to run ARC
583/// optimization on.
584static bool ModuleHasARC(const Module &M) {
585  return
586    M.getNamedValue("objc_retain") ||
587    M.getNamedValue("objc_release") ||
588    M.getNamedValue("objc_autorelease") ||
589    M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
590    M.getNamedValue("objc_retainBlock") ||
591    M.getNamedValue("objc_autoreleaseReturnValue") ||
592    M.getNamedValue("objc_autoreleasePoolPush") ||
593    M.getNamedValue("objc_loadWeakRetained") ||
594    M.getNamedValue("objc_loadWeak") ||
595    M.getNamedValue("objc_destroyWeak") ||
596    M.getNamedValue("objc_storeWeak") ||
597    M.getNamedValue("objc_initWeak") ||
598    M.getNamedValue("objc_moveWeak") ||
599    M.getNamedValue("objc_copyWeak") ||
600    M.getNamedValue("objc_retainedObject") ||
601    M.getNamedValue("objc_unretainedObject") ||
602    M.getNamedValue("objc_unretainedPointer");
603}
604
605/// DoesObjCBlockEscape - Test whether the given pointer, which is an
606/// Objective C block pointer, does not "escape". This differs from regular
607/// escape analysis in that a use as an argument to a call is not considered
608/// an escape.
609static bool DoesObjCBlockEscape(const Value *BlockPtr) {
610  // Walk the def-use chains.
611  SmallVector<const Value *, 4> Worklist;
612  Worklist.push_back(BlockPtr);
613  do {
614    const Value *V = Worklist.pop_back_val();
615    for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
616         UI != UE; ++UI) {
617      const User *UUser = *UI;
618      // Special - Use by a call (callee or argument) is not considered
619      // to be an escape.
620      switch (GetBasicInstructionClass(UUser)) {
621      case IC_StoreWeak:
622      case IC_InitWeak:
623      case IC_StoreStrong:
624      case IC_Autorelease:
625      case IC_AutoreleaseRV:
626        // These special functions make copies of their pointer arguments.
627        return true;
628      case IC_User:
629      case IC_None:
630        // Use by an instruction which copies the value is an escape if the
631        // result is an escape.
632        if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
633            isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
634          Worklist.push_back(UUser);
635          continue;
636        }
637        // Use by a load is not an escape.
638        if (isa<LoadInst>(UUser))
639          continue;
640        // Use by a store is not an escape if the use is the address.
641        if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
642          if (V != SI->getValueOperand())
643            continue;
644        break;
645      default:
646        // Regular calls and other stuff are not considered escapes.
647        continue;
648      }
649      // Otherwise, conservatively assume an escape.
650      return true;
651    }
652  } while (!Worklist.empty());
653
654  // No escapes found.
655  return false;
656}
657
658//===----------------------------------------------------------------------===//
659// ARC AliasAnalysis.
660//===----------------------------------------------------------------------===//
661
662#include "llvm/Pass.h"
663#include "llvm/Analysis/AliasAnalysis.h"
664#include "llvm/Analysis/Passes.h"
665
666namespace {
667  /// ObjCARCAliasAnalysis - This is a simple alias analysis
668  /// implementation that uses knowledge of ARC constructs to answer queries.
669  ///
670  /// TODO: This class could be generalized to know about other ObjC-specific
671  /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
672  /// even though their offsets are dynamic.
673  class ObjCARCAliasAnalysis : public ImmutablePass,
674                               public AliasAnalysis {
675  public:
676    static char ID; // Class identification, replacement for typeinfo
677    ObjCARCAliasAnalysis() : ImmutablePass(ID) {
678      initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
679    }
680
681  private:
682    virtual void initializePass() {
683      InitializeAliasAnalysis(this);
684    }
685
686    /// getAdjustedAnalysisPointer - This method is used when a pass implements
687    /// an analysis interface through multiple inheritance.  If needed, it
688    /// should override this to adjust the this pointer as needed for the
689    /// specified pass info.
690    virtual void *getAdjustedAnalysisPointer(const void *PI) {
691      if (PI == &AliasAnalysis::ID)
692        return static_cast<AliasAnalysis *>(this);
693      return this;
694    }
695
696    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
697    virtual AliasResult alias(const Location &LocA, const Location &LocB);
698    virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
699    virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
700    virtual ModRefBehavior getModRefBehavior(const Function *F);
701    virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
702                                       const Location &Loc);
703    virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
704                                       ImmutableCallSite CS2);
705  };
706}  // End of anonymous namespace
707
708// Register this pass...
709char ObjCARCAliasAnalysis::ID = 0;
710INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
711                   "ObjC-ARC-Based Alias Analysis", false, true, false)
712
713ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
714  return new ObjCARCAliasAnalysis();
715}
716
717void
718ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
719  AU.setPreservesAll();
720  AliasAnalysis::getAnalysisUsage(AU);
721}
722
723AliasAnalysis::AliasResult
724ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
725  if (!EnableARCOpts)
726    return AliasAnalysis::alias(LocA, LocB);
727
728  // First, strip off no-ops, including ObjC-specific no-ops, and try making a
729  // precise alias query.
730  const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
731  const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
732  AliasResult Result =
733    AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
734                         Location(SB, LocB.Size, LocB.TBAATag));
735  if (Result != MayAlias)
736    return Result;
737
738  // If that failed, climb to the underlying object, including climbing through
739  // ObjC-specific no-ops, and try making an imprecise alias query.
740  const Value *UA = GetUnderlyingObjCPtr(SA);
741  const Value *UB = GetUnderlyingObjCPtr(SB);
742  if (UA != SA || UB != SB) {
743    Result = AliasAnalysis::alias(Location(UA), Location(UB));
744    // We can't use MustAlias or PartialAlias results here because
745    // GetUnderlyingObjCPtr may return an offsetted pointer value.
746    if (Result == NoAlias)
747      return NoAlias;
748  }
749
750  // If that failed, fail. We don't need to chain here, since that's covered
751  // by the earlier precise query.
752  return MayAlias;
753}
754
755bool
756ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
757                                             bool OrLocal) {
758  if (!EnableARCOpts)
759    return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
760
761  // First, strip off no-ops, including ObjC-specific no-ops, and try making
762  // a precise alias query.
763  const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
764  if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
765                                            OrLocal))
766    return true;
767
768  // If that failed, climb to the underlying object, including climbing through
769  // ObjC-specific no-ops, and try making an imprecise alias query.
770  const Value *U = GetUnderlyingObjCPtr(S);
771  if (U != S)
772    return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
773
774  // If that failed, fail. We don't need to chain here, since that's covered
775  // by the earlier precise query.
776  return false;
777}
778
779AliasAnalysis::ModRefBehavior
780ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
781  // We have nothing to do. Just chain to the next AliasAnalysis.
782  return AliasAnalysis::getModRefBehavior(CS);
783}
784
785AliasAnalysis::ModRefBehavior
786ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
787  if (!EnableARCOpts)
788    return AliasAnalysis::getModRefBehavior(F);
789
790  switch (GetFunctionClass(F)) {
791  case IC_NoopCast:
792    return DoesNotAccessMemory;
793  default:
794    break;
795  }
796
797  return AliasAnalysis::getModRefBehavior(F);
798}
799
800AliasAnalysis::ModRefResult
801ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
802  if (!EnableARCOpts)
803    return AliasAnalysis::getModRefInfo(CS, Loc);
804
805  switch (GetBasicInstructionClass(CS.getInstruction())) {
806  case IC_Retain:
807  case IC_RetainRV:
808  case IC_Autorelease:
809  case IC_AutoreleaseRV:
810  case IC_NoopCast:
811  case IC_AutoreleasepoolPush:
812  case IC_FusedRetainAutorelease:
813  case IC_FusedRetainAutoreleaseRV:
814    // These functions don't access any memory visible to the compiler.
815    // Note that this doesn't include objc_retainBlock, because it updates
816    // pointers when it copies block data.
817    return NoModRef;
818  default:
819    break;
820  }
821
822  return AliasAnalysis::getModRefInfo(CS, Loc);
823}
824
825AliasAnalysis::ModRefResult
826ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
827                                    ImmutableCallSite CS2) {
828  // TODO: Theoretically we could check for dependencies between objc_* calls
829  // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
830  return AliasAnalysis::getModRefInfo(CS1, CS2);
831}
832
833//===----------------------------------------------------------------------===//
834// ARC expansion.
835//===----------------------------------------------------------------------===//
836
837#include "llvm/Support/InstIterator.h"
838#include "llvm/Transforms/Scalar.h"
839
840namespace {
841  /// ObjCARCExpand - Early ARC transformations.
842  class ObjCARCExpand : public FunctionPass {
843    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
844    virtual bool doInitialization(Module &M);
845    virtual bool runOnFunction(Function &F);
846
847    /// Run - A flag indicating whether this optimization pass should run.
848    bool Run;
849
850  public:
851    static char ID;
852    ObjCARCExpand() : FunctionPass(ID) {
853      initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
854    }
855  };
856}
857
858char ObjCARCExpand::ID = 0;
859INITIALIZE_PASS(ObjCARCExpand,
860                "objc-arc-expand", "ObjC ARC expansion", false, false)
861
862Pass *llvm::createObjCARCExpandPass() {
863  return new ObjCARCExpand();
864}
865
866void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
867  AU.setPreservesCFG();
868}
869
870bool ObjCARCExpand::doInitialization(Module &M) {
871  Run = ModuleHasARC(M);
872  return false;
873}
874
875bool ObjCARCExpand::runOnFunction(Function &F) {
876  if (!EnableARCOpts)
877    return false;
878
879  // If nothing in the Module uses ARC, don't do anything.
880  if (!Run)
881    return false;
882
883  bool Changed = false;
884
885  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
886    Instruction *Inst = &*I;
887
888    switch (GetBasicInstructionClass(Inst)) {
889    case IC_Retain:
890    case IC_RetainRV:
891    case IC_Autorelease:
892    case IC_AutoreleaseRV:
893    case IC_FusedRetainAutorelease:
894    case IC_FusedRetainAutoreleaseRV:
895      // These calls return their argument verbatim, as a low-level
896      // optimization. However, this makes high-level optimizations
897      // harder. Undo any uses of this optimization that the front-end
898      // emitted here. We'll redo them in the contract pass.
899      Changed = true;
900      Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
901      break;
902    default:
903      break;
904    }
905  }
906
907  return Changed;
908}
909
910//===----------------------------------------------------------------------===//
911// ARC autorelease pool elimination.
912//===----------------------------------------------------------------------===//
913
914#include "llvm/Constants.h"
915#include "llvm/ADT/STLExtras.h"
916
917namespace {
918  /// ObjCARCAPElim - Autorelease pool elimination.
919  class ObjCARCAPElim : public ModulePass {
920    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
921    virtual bool runOnModule(Module &M);
922
923    static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
924    static bool OptimizeBB(BasicBlock *BB);
925
926  public:
927    static char ID;
928    ObjCARCAPElim() : ModulePass(ID) {
929      initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
930    }
931  };
932}
933
934char ObjCARCAPElim::ID = 0;
935INITIALIZE_PASS(ObjCARCAPElim,
936                "objc-arc-apelim",
937                "ObjC ARC autorelease pool elimination",
938                false, false)
939
940Pass *llvm::createObjCARCAPElimPass() {
941  return new ObjCARCAPElim();
942}
943
944void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
945  AU.setPreservesCFG();
946}
947
948/// MayAutorelease - Interprocedurally determine if calls made by the
949/// given call site can possibly produce autoreleases.
950bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
951  if (const Function *Callee = CS.getCalledFunction()) {
952    if (Callee->isDeclaration() || Callee->mayBeOverridden())
953      return true;
954    for (Function::const_iterator I = Callee->begin(), E = Callee->end();
955         I != E; ++I) {
956      const BasicBlock *BB = I;
957      for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
958           J != F; ++J)
959        if (ImmutableCallSite JCS = ImmutableCallSite(J))
960          // This recursion depth limit is arbitrary. It's just great
961          // enough to cover known interesting testcases.
962          if (Depth < 3 &&
963              !JCS.onlyReadsMemory() &&
964              MayAutorelease(JCS, Depth + 1))
965            return true;
966    }
967    return false;
968  }
969
970  return true;
971}
972
973bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
974  bool Changed = false;
975
976  Instruction *Push = 0;
977  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
978    Instruction *Inst = I++;
979    switch (GetBasicInstructionClass(Inst)) {
980    case IC_AutoreleasepoolPush:
981      Push = Inst;
982      break;
983    case IC_AutoreleasepoolPop:
984      // If this pop matches a push and nothing in between can autorelease,
985      // zap the pair.
986      if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
987        Changed = true;
988        Inst->eraseFromParent();
989        Push->eraseFromParent();
990      }
991      Push = 0;
992      break;
993    case IC_CallOrUser:
994      if (MayAutorelease(ImmutableCallSite(Inst)))
995        Push = 0;
996      break;
997    default:
998      break;
999    }
1000  }
1001
1002  return Changed;
1003}
1004
1005bool ObjCARCAPElim::runOnModule(Module &M) {
1006  if (!EnableARCOpts)
1007    return false;
1008
1009  // If nothing in the Module uses ARC, don't do anything.
1010  if (!ModuleHasARC(M))
1011    return false;
1012
1013  // Find the llvm.global_ctors variable, as the first step in
1014  // identifying the global constructors. In theory, unnecessary autorelease
1015  // pools could occur anywhere, but in practice it's pretty rare. Global
1016  // ctors are a place where autorelease pools get inserted automatically,
1017  // so it's pretty common for them to be unnecessary, and it's pretty
1018  // profitable to eliminate them.
1019  GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1020  if (!GV)
1021    return false;
1022
1023  assert(GV->hasDefinitiveInitializer() &&
1024         "llvm.global_ctors is uncooperative!");
1025
1026  bool Changed = false;
1027
1028  // Dig the constructor functions out of GV's initializer.
1029  ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1030  for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1031       OI != OE; ++OI) {
1032    Value *Op = *OI;
1033    // llvm.global_ctors is an array of pairs where the second members
1034    // are constructor functions.
1035    Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1036    // If the user used a constructor function with the wrong signature and
1037    // it got bitcasted or whatever, look the other way.
1038    if (!F)
1039      continue;
1040    // Only look at function definitions.
1041    if (F->isDeclaration())
1042      continue;
1043    // Only look at functions with one basic block.
1044    if (llvm::next(F->begin()) != F->end())
1045      continue;
1046    // Ok, a single-block constructor function definition. Try to optimize it.
1047    Changed |= OptimizeBB(F->begin());
1048  }
1049
1050  return Changed;
1051}
1052
1053//===----------------------------------------------------------------------===//
1054// ARC optimization.
1055//===----------------------------------------------------------------------===//
1056
1057// TODO: On code like this:
1058//
1059// objc_retain(%x)
1060// stuff_that_cannot_release()
1061// objc_autorelease(%x)
1062// stuff_that_cannot_release()
1063// objc_retain(%x)
1064// stuff_that_cannot_release()
1065// objc_autorelease(%x)
1066//
1067// The second retain and autorelease can be deleted.
1068
1069// TODO: It should be possible to delete
1070// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1071// pairs if nothing is actually autoreleased between them. Also, autorelease
1072// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1073// after inlining) can be turned into plain release calls.
1074
1075// TODO: Critical-edge splitting. If the optimial insertion point is
1076// a critical edge, the current algorithm has to fail, because it doesn't
1077// know how to split edges. It should be possible to make the optimizer
1078// think in terms of edges, rather than blocks, and then split critical
1079// edges on demand.
1080
1081// TODO: OptimizeSequences could generalized to be Interprocedural.
1082
1083// TODO: Recognize that a bunch of other objc runtime calls have
1084// non-escaping arguments and non-releasing arguments, and may be
1085// non-autoreleasing.
1086
1087// TODO: Sink autorelease calls as far as possible. Unfortunately we
1088// usually can't sink them past other calls, which would be the main
1089// case where it would be useful.
1090
1091// TODO: The pointer returned from objc_loadWeakRetained is retained.
1092
1093// TODO: Delete release+retain pairs (rare).
1094
1095#include "llvm/LLVMContext.h"
1096#include "llvm/Support/CFG.h"
1097#include "llvm/ADT/Statistic.h"
1098#include "llvm/ADT/SmallPtrSet.h"
1099
1100STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
1101STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1102STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1103STATISTIC(NumRets,        "Number of return value forwarding "
1104                          "retain+autoreleaes eliminated");
1105STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
1106STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
1107
1108namespace {
1109  /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1110  /// uses many of the same techniques, except it uses special ObjC-specific
1111  /// reasoning about pointer relationships.
1112  class ProvenanceAnalysis {
1113    AliasAnalysis *AA;
1114
1115    typedef std::pair<const Value *, const Value *> ValuePairTy;
1116    typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1117    CachedResultsTy CachedResults;
1118
1119    bool relatedCheck(const Value *A, const Value *B);
1120    bool relatedSelect(const SelectInst *A, const Value *B);
1121    bool relatedPHI(const PHINode *A, const Value *B);
1122
1123    // Do not implement.
1124    void operator=(const ProvenanceAnalysis &);
1125    ProvenanceAnalysis(const ProvenanceAnalysis &);
1126
1127  public:
1128    ProvenanceAnalysis() {}
1129
1130    void setAA(AliasAnalysis *aa) { AA = aa; }
1131
1132    AliasAnalysis *getAA() const { return AA; }
1133
1134    bool related(const Value *A, const Value *B);
1135
1136    void clear() {
1137      CachedResults.clear();
1138    }
1139  };
1140}
1141
1142bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1143  // If the values are Selects with the same condition, we can do a more precise
1144  // check: just check for relations between the values on corresponding arms.
1145  if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1146    if (A->getCondition() == SB->getCondition())
1147      return related(A->getTrueValue(), SB->getTrueValue()) ||
1148             related(A->getFalseValue(), SB->getFalseValue());
1149
1150  // Check both arms of the Select node individually.
1151  return related(A->getTrueValue(), B) ||
1152         related(A->getFalseValue(), B);
1153}
1154
1155bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1156  // If the values are PHIs in the same block, we can do a more precise as well
1157  // as efficient check: just check for relations between the values on
1158  // corresponding edges.
1159  if (const PHINode *PNB = dyn_cast<PHINode>(B))
1160    if (PNB->getParent() == A->getParent()) {
1161      for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1162        if (related(A->getIncomingValue(i),
1163                    PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1164          return true;
1165      return false;
1166    }
1167
1168  // Check each unique source of the PHI node against B.
1169  SmallPtrSet<const Value *, 4> UniqueSrc;
1170  for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1171    const Value *PV1 = A->getIncomingValue(i);
1172    if (UniqueSrc.insert(PV1) && related(PV1, B))
1173      return true;
1174  }
1175
1176  // All of the arms checked out.
1177  return false;
1178}
1179
1180/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1181/// provenance, is ever stored within the function (not counting callees).
1182static bool isStoredObjCPointer(const Value *P) {
1183  SmallPtrSet<const Value *, 8> Visited;
1184  SmallVector<const Value *, 8> Worklist;
1185  Worklist.push_back(P);
1186  Visited.insert(P);
1187  do {
1188    P = Worklist.pop_back_val();
1189    for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1190         UI != UE; ++UI) {
1191      const User *Ur = *UI;
1192      if (isa<StoreInst>(Ur)) {
1193        if (UI.getOperandNo() == 0)
1194          // The pointer is stored.
1195          return true;
1196        // The pointed is stored through.
1197        continue;
1198      }
1199      if (isa<CallInst>(Ur))
1200        // The pointer is passed as an argument, ignore this.
1201        continue;
1202      if (isa<PtrToIntInst>(P))
1203        // Assume the worst.
1204        return true;
1205      if (Visited.insert(Ur))
1206        Worklist.push_back(Ur);
1207    }
1208  } while (!Worklist.empty());
1209
1210  // Everything checked out.
1211  return false;
1212}
1213
1214bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1215  // Skip past provenance pass-throughs.
1216  A = GetUnderlyingObjCPtr(A);
1217  B = GetUnderlyingObjCPtr(B);
1218
1219  // Quick check.
1220  if (A == B)
1221    return true;
1222
1223  // Ask regular AliasAnalysis, for a first approximation.
1224  switch (AA->alias(A, B)) {
1225  case AliasAnalysis::NoAlias:
1226    return false;
1227  case AliasAnalysis::MustAlias:
1228  case AliasAnalysis::PartialAlias:
1229    return true;
1230  case AliasAnalysis::MayAlias:
1231    break;
1232  }
1233
1234  bool AIsIdentified = IsObjCIdentifiedObject(A);
1235  bool BIsIdentified = IsObjCIdentifiedObject(B);
1236
1237  // An ObjC-Identified object can't alias a load if it is never locally stored.
1238  if (AIsIdentified) {
1239    // Check for an obvious escape.
1240    if (isa<LoadInst>(B))
1241      return isStoredObjCPointer(A);
1242    if (BIsIdentified) {
1243      // Check for an obvious escape.
1244      if (isa<LoadInst>(A))
1245        return isStoredObjCPointer(B);
1246      // Both pointers are identified and escapes aren't an evident problem.
1247      return false;
1248    }
1249  } else if (BIsIdentified) {
1250    // Check for an obvious escape.
1251    if (isa<LoadInst>(A))
1252      return isStoredObjCPointer(B);
1253  }
1254
1255   // Special handling for PHI and Select.
1256  if (const PHINode *PN = dyn_cast<PHINode>(A))
1257    return relatedPHI(PN, B);
1258  if (const PHINode *PN = dyn_cast<PHINode>(B))
1259    return relatedPHI(PN, A);
1260  if (const SelectInst *S = dyn_cast<SelectInst>(A))
1261    return relatedSelect(S, B);
1262  if (const SelectInst *S = dyn_cast<SelectInst>(B))
1263    return relatedSelect(S, A);
1264
1265  // Conservative.
1266  return true;
1267}
1268
1269bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1270  // Begin by inserting a conservative value into the map. If the insertion
1271  // fails, we have the answer already. If it succeeds, leave it there until we
1272  // compute the real answer to guard against recursive queries.
1273  if (A > B) std::swap(A, B);
1274  std::pair<CachedResultsTy::iterator, bool> Pair =
1275    CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1276  if (!Pair.second)
1277    return Pair.first->second;
1278
1279  bool Result = relatedCheck(A, B);
1280  CachedResults[ValuePairTy(A, B)] = Result;
1281  return Result;
1282}
1283
1284namespace {
1285  // Sequence - A sequence of states that a pointer may go through in which an
1286  // objc_retain and objc_release are actually needed.
1287  enum Sequence {
1288    S_None,
1289    S_Retain,         ///< objc_retain(x)
1290    S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement
1291    S_Use,            ///< any use of x
1292    S_Stop,           ///< like S_Release, but code motion is stopped
1293    S_Release,        ///< objc_release(x)
1294    S_MovableRelease  ///< objc_release(x), !clang.imprecise_release
1295  };
1296}
1297
1298static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1299  // The easy cases.
1300  if (A == B)
1301    return A;
1302  if (A == S_None || B == S_None)
1303    return S_None;
1304
1305  if (A > B) std::swap(A, B);
1306  if (TopDown) {
1307    // Choose the side which is further along in the sequence.
1308    if ((A == S_Retain || A == S_CanRelease) &&
1309        (B == S_CanRelease || B == S_Use))
1310      return B;
1311  } else {
1312    // Choose the side which is further along in the sequence.
1313    if ((A == S_Use || A == S_CanRelease) &&
1314        (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1315      return A;
1316    // If both sides are releases, choose the more conservative one.
1317    if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1318      return A;
1319    if (A == S_Release && B == S_MovableRelease)
1320      return A;
1321  }
1322
1323  return S_None;
1324}
1325
1326namespace {
1327  /// RRInfo - Unidirectional information about either a
1328  /// retain-decrement-use-release sequence or release-use-decrement-retain
1329  /// reverese sequence.
1330  struct RRInfo {
1331    /// KnownSafe - After an objc_retain, the reference count of the referenced
1332    /// object is known to be positive. Similarly, before an objc_release, the
1333    /// reference count of the referenced object is known to be positive. If
1334    /// there are retain-release pairs in code regions where the retain count
1335    /// is known to be positive, they can be eliminated, regardless of any side
1336    /// effects between them.
1337    ///
1338    /// Also, a retain+release pair nested within another retain+release
1339    /// pair all on the known same pointer value can be eliminated, regardless
1340    /// of any intervening side effects.
1341    ///
1342    /// KnownSafe is true when either of these conditions is satisfied.
1343    bool KnownSafe;
1344
1345    /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1346    /// opposed to objc_retain calls).
1347    bool IsRetainBlock;
1348
1349    /// IsTailCallRelease - True of the objc_release calls are all marked
1350    /// with the "tail" keyword.
1351    bool IsTailCallRelease;
1352
1353    /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1354    /// a clang.imprecise_release tag, this is the metadata tag.
1355    MDNode *ReleaseMetadata;
1356
1357    /// Calls - For a top-down sequence, the set of objc_retains or
1358    /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1359    SmallPtrSet<Instruction *, 2> Calls;
1360
1361    /// ReverseInsertPts - The set of optimal insert positions for
1362    /// moving calls in the opposite sequence.
1363    SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1364
1365    RRInfo() :
1366      KnownSafe(false), IsRetainBlock(false),
1367      IsTailCallRelease(false),
1368      ReleaseMetadata(0) {}
1369
1370    void clear();
1371  };
1372}
1373
1374void RRInfo::clear() {
1375  KnownSafe = false;
1376  IsRetainBlock = false;
1377  IsTailCallRelease = false;
1378  ReleaseMetadata = 0;
1379  Calls.clear();
1380  ReverseInsertPts.clear();
1381}
1382
1383namespace {
1384  /// PtrState - This class summarizes several per-pointer runtime properties
1385  /// which are propogated through the flow graph.
1386  class PtrState {
1387    /// KnownPositiveRefCount - True if the reference count is known to
1388    /// be incremented.
1389    bool KnownPositiveRefCount;
1390
1391    /// Partial - True of we've seen an opportunity for partial RR elimination,
1392    /// such as pushing calls into a CFG triangle or into one side of a
1393    /// CFG diamond.
1394    bool Partial;
1395
1396    /// Seq - The current position in the sequence.
1397    Sequence Seq : 8;
1398
1399  public:
1400    /// RRI - Unidirectional information about the current sequence.
1401    /// TODO: Encapsulate this better.
1402    RRInfo RRI;
1403
1404    PtrState() : KnownPositiveRefCount(false), Partial(false),
1405                 Seq(S_None) {}
1406
1407    void SetKnownPositiveRefCount() {
1408      KnownPositiveRefCount = true;
1409    }
1410
1411    void ClearRefCount() {
1412      KnownPositiveRefCount = false;
1413    }
1414
1415    bool IsKnownIncremented() const {
1416      return KnownPositiveRefCount;
1417    }
1418
1419    void SetSeq(Sequence NewSeq) {
1420      Seq = NewSeq;
1421    }
1422
1423    Sequence GetSeq() const {
1424      return Seq;
1425    }
1426
1427    void ClearSequenceProgress() {
1428      ResetSequenceProgress(S_None);
1429    }
1430
1431    void ResetSequenceProgress(Sequence NewSeq) {
1432      Seq = NewSeq;
1433      Partial = false;
1434      RRI.clear();
1435    }
1436
1437    void Merge(const PtrState &Other, bool TopDown);
1438  };
1439}
1440
1441void
1442PtrState::Merge(const PtrState &Other, bool TopDown) {
1443  Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1444  KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1445
1446  // We can't merge a plain objc_retain with an objc_retainBlock.
1447  if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1448    Seq = S_None;
1449
1450  // If we're not in a sequence (anymore), drop all associated state.
1451  if (Seq == S_None) {
1452    Partial = false;
1453    RRI.clear();
1454  } else if (Partial || Other.Partial) {
1455    // If we're doing a merge on a path that's previously seen a partial
1456    // merge, conservatively drop the sequence, to avoid doing partial
1457    // RR elimination. If the branch predicates for the two merge differ,
1458    // mixing them is unsafe.
1459    ClearSequenceProgress();
1460  } else {
1461    // Conservatively merge the ReleaseMetadata information.
1462    if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1463      RRI.ReleaseMetadata = 0;
1464
1465    RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1466    RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1467                            Other.RRI.IsTailCallRelease;
1468    RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1469
1470    // Merge the insert point sets. If there are any differences,
1471    // that makes this a partial merge.
1472    Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1473    for (SmallPtrSet<Instruction *, 2>::const_iterator
1474         I = Other.RRI.ReverseInsertPts.begin(),
1475         E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1476      Partial |= RRI.ReverseInsertPts.insert(*I);
1477  }
1478}
1479
1480namespace {
1481  /// BBState - Per-BasicBlock state.
1482  class BBState {
1483    /// TopDownPathCount - The number of unique control paths from the entry
1484    /// which can reach this block.
1485    unsigned TopDownPathCount;
1486
1487    /// BottomUpPathCount - The number of unique control paths to exits
1488    /// from this block.
1489    unsigned BottomUpPathCount;
1490
1491    /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1492    typedef MapVector<const Value *, PtrState> MapTy;
1493
1494    /// PerPtrTopDown - The top-down traversal uses this to record information
1495    /// known about a pointer at the bottom of each block.
1496    MapTy PerPtrTopDown;
1497
1498    /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1499    /// known about a pointer at the top of each block.
1500    MapTy PerPtrBottomUp;
1501
1502    /// Preds, Succs - Effective successors and predecessors of the current
1503    /// block (this ignores ignorable edges and ignored backedges).
1504    SmallVector<BasicBlock *, 2> Preds;
1505    SmallVector<BasicBlock *, 2> Succs;
1506
1507  public:
1508    BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1509
1510    typedef MapTy::iterator ptr_iterator;
1511    typedef MapTy::const_iterator ptr_const_iterator;
1512
1513    ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1514    ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1515    ptr_const_iterator top_down_ptr_begin() const {
1516      return PerPtrTopDown.begin();
1517    }
1518    ptr_const_iterator top_down_ptr_end() const {
1519      return PerPtrTopDown.end();
1520    }
1521
1522    ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1523    ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1524    ptr_const_iterator bottom_up_ptr_begin() const {
1525      return PerPtrBottomUp.begin();
1526    }
1527    ptr_const_iterator bottom_up_ptr_end() const {
1528      return PerPtrBottomUp.end();
1529    }
1530
1531    /// SetAsEntry - Mark this block as being an entry block, which has one
1532    /// path from the entry by definition.
1533    void SetAsEntry() { TopDownPathCount = 1; }
1534
1535    /// SetAsExit - Mark this block as being an exit block, which has one
1536    /// path to an exit by definition.
1537    void SetAsExit()  { BottomUpPathCount = 1; }
1538
1539    PtrState &getPtrTopDownState(const Value *Arg) {
1540      return PerPtrTopDown[Arg];
1541    }
1542
1543    PtrState &getPtrBottomUpState(const Value *Arg) {
1544      return PerPtrBottomUp[Arg];
1545    }
1546
1547    void clearBottomUpPointers() {
1548      PerPtrBottomUp.clear();
1549    }
1550
1551    void clearTopDownPointers() {
1552      PerPtrTopDown.clear();
1553    }
1554
1555    void InitFromPred(const BBState &Other);
1556    void InitFromSucc(const BBState &Other);
1557    void MergePred(const BBState &Other);
1558    void MergeSucc(const BBState &Other);
1559
1560    /// GetAllPathCount - Return the number of possible unique paths from an
1561    /// entry to an exit which pass through this block. This is only valid
1562    /// after both the top-down and bottom-up traversals are complete.
1563    unsigned GetAllPathCount() const {
1564      assert(TopDownPathCount != 0);
1565      assert(BottomUpPathCount != 0);
1566      return TopDownPathCount * BottomUpPathCount;
1567    }
1568
1569    // Specialized CFG utilities.
1570    typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1571    edge_iterator pred_begin() { return Preds.begin(); }
1572    edge_iterator pred_end() { return Preds.end(); }
1573    edge_iterator succ_begin() { return Succs.begin(); }
1574    edge_iterator succ_end() { return Succs.end(); }
1575
1576    void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1577    void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1578
1579    bool isExit() const { return Succs.empty(); }
1580  };
1581}
1582
1583void BBState::InitFromPred(const BBState &Other) {
1584  PerPtrTopDown = Other.PerPtrTopDown;
1585  TopDownPathCount = Other.TopDownPathCount;
1586}
1587
1588void BBState::InitFromSucc(const BBState &Other) {
1589  PerPtrBottomUp = Other.PerPtrBottomUp;
1590  BottomUpPathCount = Other.BottomUpPathCount;
1591}
1592
1593/// MergePred - The top-down traversal uses this to merge information about
1594/// predecessors to form the initial state for a new block.
1595void BBState::MergePred(const BBState &Other) {
1596  // Other.TopDownPathCount can be 0, in which case it is either dead or a
1597  // loop backedge. Loop backedges are special.
1598  TopDownPathCount += Other.TopDownPathCount;
1599
1600  // For each entry in the other set, if our set has an entry with the same key,
1601  // merge the entries. Otherwise, copy the entry and merge it with an empty
1602  // entry.
1603  for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1604       ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1605    std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1606    Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1607                             /*TopDown=*/true);
1608  }
1609
1610  // For each entry in our set, if the other set doesn't have an entry with the
1611  // same key, force it to merge with an empty entry.
1612  for (ptr_iterator MI = top_down_ptr_begin(),
1613       ME = top_down_ptr_end(); MI != ME; ++MI)
1614    if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1615      MI->second.Merge(PtrState(), /*TopDown=*/true);
1616}
1617
1618/// MergeSucc - The bottom-up traversal uses this to merge information about
1619/// successors to form the initial state for a new block.
1620void BBState::MergeSucc(const BBState &Other) {
1621  // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1622  // loop backedge. Loop backedges are special.
1623  BottomUpPathCount += Other.BottomUpPathCount;
1624
1625  // For each entry in the other set, if our set has an entry with the
1626  // same key, merge the entries. Otherwise, copy the entry and merge
1627  // it with an empty entry.
1628  for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1629       ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1630    std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1631    Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1632                             /*TopDown=*/false);
1633  }
1634
1635  // For each entry in our set, if the other set doesn't have an entry
1636  // with the same key, force it to merge with an empty entry.
1637  for (ptr_iterator MI = bottom_up_ptr_begin(),
1638       ME = bottom_up_ptr_end(); MI != ME; ++MI)
1639    if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1640      MI->second.Merge(PtrState(), /*TopDown=*/false);
1641}
1642
1643namespace {
1644  /// ObjCARCOpt - The main ARC optimization pass.
1645  class ObjCARCOpt : public FunctionPass {
1646    bool Changed;
1647    ProvenanceAnalysis PA;
1648
1649    /// Run - A flag indicating whether this optimization pass should run.
1650    bool Run;
1651
1652    /// RetainRVCallee, etc. - Declarations for ObjC runtime
1653    /// functions, for use in creating calls to them. These are initialized
1654    /// lazily to avoid cluttering up the Module with unused declarations.
1655    Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1656             *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1657
1658    /// UsedInThisFunciton - Flags which determine whether each of the
1659    /// interesting runtine functions is in fact used in the current function.
1660    unsigned UsedInThisFunction;
1661
1662    /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1663    /// metadata.
1664    unsigned ImpreciseReleaseMDKind;
1665
1666    /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1667    /// metadata.
1668    unsigned CopyOnEscapeMDKind;
1669
1670    /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1671    /// clang.arc.no_objc_arc_exceptions metadata.
1672    unsigned NoObjCARCExceptionsMDKind;
1673
1674    Constant *getRetainRVCallee(Module *M);
1675    Constant *getAutoreleaseRVCallee(Module *M);
1676    Constant *getReleaseCallee(Module *M);
1677    Constant *getRetainCallee(Module *M);
1678    Constant *getRetainBlockCallee(Module *M);
1679    Constant *getAutoreleaseCallee(Module *M);
1680
1681    bool IsRetainBlockOptimizable(const Instruction *Inst);
1682
1683    void OptimizeRetainCall(Function &F, Instruction *Retain);
1684    bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1685    void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1686    void OptimizeIndividualCalls(Function &F);
1687
1688    void CheckForCFGHazards(const BasicBlock *BB,
1689                            DenseMap<const BasicBlock *, BBState> &BBStates,
1690                            BBState &MyStates) const;
1691    bool VisitInstructionBottomUp(Instruction *Inst,
1692                                  BasicBlock *BB,
1693                                  MapVector<Value *, RRInfo> &Retains,
1694                                  BBState &MyStates);
1695    bool VisitBottomUp(BasicBlock *BB,
1696                       DenseMap<const BasicBlock *, BBState> &BBStates,
1697                       MapVector<Value *, RRInfo> &Retains);
1698    bool VisitInstructionTopDown(Instruction *Inst,
1699                                 DenseMap<Value *, RRInfo> &Releases,
1700                                 BBState &MyStates);
1701    bool VisitTopDown(BasicBlock *BB,
1702                      DenseMap<const BasicBlock *, BBState> &BBStates,
1703                      DenseMap<Value *, RRInfo> &Releases);
1704    bool Visit(Function &F,
1705               DenseMap<const BasicBlock *, BBState> &BBStates,
1706               MapVector<Value *, RRInfo> &Retains,
1707               DenseMap<Value *, RRInfo> &Releases);
1708
1709    void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1710                   MapVector<Value *, RRInfo> &Retains,
1711                   DenseMap<Value *, RRInfo> &Releases,
1712                   SmallVectorImpl<Instruction *> &DeadInsts,
1713                   Module *M);
1714
1715    bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1716                              MapVector<Value *, RRInfo> &Retains,
1717                              DenseMap<Value *, RRInfo> &Releases,
1718                              Module *M);
1719
1720    void OptimizeWeakCalls(Function &F);
1721
1722    bool OptimizeSequences(Function &F);
1723
1724    void OptimizeReturns(Function &F);
1725
1726    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1727    virtual bool doInitialization(Module &M);
1728    virtual bool runOnFunction(Function &F);
1729    virtual void releaseMemory();
1730
1731  public:
1732    static char ID;
1733    ObjCARCOpt() : FunctionPass(ID) {
1734      initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1735    }
1736  };
1737}
1738
1739char ObjCARCOpt::ID = 0;
1740INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1741                      "objc-arc", "ObjC ARC optimization", false, false)
1742INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1743INITIALIZE_PASS_END(ObjCARCOpt,
1744                    "objc-arc", "ObjC ARC optimization", false, false)
1745
1746Pass *llvm::createObjCARCOptPass() {
1747  return new ObjCARCOpt();
1748}
1749
1750void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1751  AU.addRequired<ObjCARCAliasAnalysis>();
1752  AU.addRequired<AliasAnalysis>();
1753  // ARC optimization doesn't currently split critical edges.
1754  AU.setPreservesCFG();
1755}
1756
1757bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1758  // Without the magic metadata tag, we have to assume this might be an
1759  // objc_retainBlock call inserted to convert a block pointer to an id,
1760  // in which case it really is needed.
1761  if (!Inst->getMetadata(CopyOnEscapeMDKind))
1762    return false;
1763
1764  // If the pointer "escapes" (not including being used in a call),
1765  // the copy may be needed.
1766  if (DoesObjCBlockEscape(Inst))
1767    return false;
1768
1769  // Otherwise, it's not needed.
1770  return true;
1771}
1772
1773Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1774  if (!RetainRVCallee) {
1775    LLVMContext &C = M->getContext();
1776    Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1777    Type *Params[] = { I8X };
1778    FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1779    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1780    RetainRVCallee =
1781      M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1782                             Attributes);
1783  }
1784  return RetainRVCallee;
1785}
1786
1787Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1788  if (!AutoreleaseRVCallee) {
1789    LLVMContext &C = M->getContext();
1790    Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1791    Type *Params[] = { I8X };
1792    FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1793    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1794    AutoreleaseRVCallee =
1795      M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1796                             Attributes);
1797  }
1798  return AutoreleaseRVCallee;
1799}
1800
1801Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1802  if (!ReleaseCallee) {
1803    LLVMContext &C = M->getContext();
1804    Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1805    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1806    ReleaseCallee =
1807      M->getOrInsertFunction(
1808        "objc_release",
1809        FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1810        Attributes);
1811  }
1812  return ReleaseCallee;
1813}
1814
1815Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1816  if (!RetainCallee) {
1817    LLVMContext &C = M->getContext();
1818    Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1819    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1820    RetainCallee =
1821      M->getOrInsertFunction(
1822        "objc_retain",
1823        FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1824        Attributes);
1825  }
1826  return RetainCallee;
1827}
1828
1829Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1830  if (!RetainBlockCallee) {
1831    LLVMContext &C = M->getContext();
1832    Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1833    // objc_retainBlock is not nounwind because it calls user copy constructors
1834    // which could theoretically throw.
1835    RetainBlockCallee =
1836      M->getOrInsertFunction(
1837        "objc_retainBlock",
1838        FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1839        AttrListPtr());
1840  }
1841  return RetainBlockCallee;
1842}
1843
1844Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1845  if (!AutoreleaseCallee) {
1846    LLVMContext &C = M->getContext();
1847    Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1848    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1849    AutoreleaseCallee =
1850      M->getOrInsertFunction(
1851        "objc_autorelease",
1852        FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1853        Attributes);
1854  }
1855  return AutoreleaseCallee;
1856}
1857
1858/// IsPotentialUse - Test whether the given value is possible a
1859/// reference-counted pointer, including tests which utilize AliasAnalysis.
1860static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1861  // First make the rudimentary check.
1862  if (!IsPotentialUse(Op))
1863    return false;
1864
1865  // Objects in constant memory are not reference-counted.
1866  if (AA.pointsToConstantMemory(Op))
1867    return false;
1868
1869  // Pointers in constant memory are not pointing to reference-counted objects.
1870  if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1871    if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1872      return false;
1873
1874  // Otherwise assume the worst.
1875  return true;
1876}
1877
1878/// CanAlterRefCount - Test whether the given instruction can result in a
1879/// reference count modification (positive or negative) for the pointer's
1880/// object.
1881static bool
1882CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1883                 ProvenanceAnalysis &PA, InstructionClass Class) {
1884  switch (Class) {
1885  case IC_Autorelease:
1886  case IC_AutoreleaseRV:
1887  case IC_User:
1888    // These operations never directly modify a reference count.
1889    return false;
1890  default: break;
1891  }
1892
1893  ImmutableCallSite CS = static_cast<const Value *>(Inst);
1894  assert(CS && "Only calls can alter reference counts!");
1895
1896  // See if AliasAnalysis can help us with the call.
1897  AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1898  if (AliasAnalysis::onlyReadsMemory(MRB))
1899    return false;
1900  if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1901    for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1902         I != E; ++I) {
1903      const Value *Op = *I;
1904      if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1905        return true;
1906    }
1907    return false;
1908  }
1909
1910  // Assume the worst.
1911  return true;
1912}
1913
1914/// CanUse - Test whether the given instruction can "use" the given pointer's
1915/// object in a way that requires the reference count to be positive.
1916static bool
1917CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1918       InstructionClass Class) {
1919  // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1920  if (Class == IC_Call)
1921    return false;
1922
1923  // Consider various instructions which may have pointer arguments which are
1924  // not "uses".
1925  if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1926    // Comparing a pointer with null, or any other constant, isn't really a use,
1927    // because we don't care what the pointer points to, or about the values
1928    // of any other dynamic reference-counted pointers.
1929    if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
1930      return false;
1931  } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1932    // For calls, just check the arguments (and not the callee operand).
1933    for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1934         OE = CS.arg_end(); OI != OE; ++OI) {
1935      const Value *Op = *OI;
1936      if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1937        return true;
1938    }
1939    return false;
1940  } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1941    // Special-case stores, because we don't care about the stored value, just
1942    // the store address.
1943    const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1944    // If we can't tell what the underlying object was, assume there is a
1945    // dependence.
1946    return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
1947  }
1948
1949  // Check each operand for a match.
1950  for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1951       OI != OE; ++OI) {
1952    const Value *Op = *OI;
1953    if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1954      return true;
1955  }
1956  return false;
1957}
1958
1959/// CanInterruptRV - Test whether the given instruction can autorelease
1960/// any pointer or cause an autoreleasepool pop.
1961static bool
1962CanInterruptRV(InstructionClass Class) {
1963  switch (Class) {
1964  case IC_AutoreleasepoolPop:
1965  case IC_CallOrUser:
1966  case IC_Call:
1967  case IC_Autorelease:
1968  case IC_AutoreleaseRV:
1969  case IC_FusedRetainAutorelease:
1970  case IC_FusedRetainAutoreleaseRV:
1971    return true;
1972  default:
1973    return false;
1974  }
1975}
1976
1977namespace {
1978  /// DependenceKind - There are several kinds of dependence-like concepts in
1979  /// use here.
1980  enum DependenceKind {
1981    NeedsPositiveRetainCount,
1982    AutoreleasePoolBoundary,
1983    CanChangeRetainCount,
1984    RetainAutoreleaseDep,       ///< Blocks objc_retainAutorelease.
1985    RetainAutoreleaseRVDep,     ///< Blocks objc_retainAutoreleaseReturnValue.
1986    RetainRVDep                 ///< Blocks objc_retainAutoreleasedReturnValue.
1987  };
1988}
1989
1990/// Depends - Test if there can be dependencies on Inst through Arg. This
1991/// function only tests dependencies relevant for removing pairs of calls.
1992static bool
1993Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1994        ProvenanceAnalysis &PA) {
1995  // If we've reached the definition of Arg, stop.
1996  if (Inst == Arg)
1997    return true;
1998
1999  switch (Flavor) {
2000  case NeedsPositiveRetainCount: {
2001    InstructionClass Class = GetInstructionClass(Inst);
2002    switch (Class) {
2003    case IC_AutoreleasepoolPop:
2004    case IC_AutoreleasepoolPush:
2005    case IC_None:
2006      return false;
2007    default:
2008      return CanUse(Inst, Arg, PA, Class);
2009    }
2010  }
2011
2012  case AutoreleasePoolBoundary: {
2013    InstructionClass Class = GetInstructionClass(Inst);
2014    switch (Class) {
2015    case IC_AutoreleasepoolPop:
2016    case IC_AutoreleasepoolPush:
2017      // These mark the end and begin of an autorelease pool scope.
2018      return true;
2019    default:
2020      // Nothing else does this.
2021      return false;
2022    }
2023  }
2024
2025  case CanChangeRetainCount: {
2026    InstructionClass Class = GetInstructionClass(Inst);
2027    switch (Class) {
2028    case IC_AutoreleasepoolPop:
2029      // Conservatively assume this can decrement any count.
2030      return true;
2031    case IC_AutoreleasepoolPush:
2032    case IC_None:
2033      return false;
2034    default:
2035      return CanAlterRefCount(Inst, Arg, PA, Class);
2036    }
2037  }
2038
2039  case RetainAutoreleaseDep:
2040    switch (GetBasicInstructionClass(Inst)) {
2041    case IC_AutoreleasepoolPop:
2042    case IC_AutoreleasepoolPush:
2043      // Don't merge an objc_autorelease with an objc_retain inside a different
2044      // autoreleasepool scope.
2045      return true;
2046    case IC_Retain:
2047    case IC_RetainRV:
2048      // Check for a retain of the same pointer for merging.
2049      return GetObjCArg(Inst) == Arg;
2050    default:
2051      // Nothing else matters for objc_retainAutorelease formation.
2052      return false;
2053    }
2054
2055  case RetainAutoreleaseRVDep: {
2056    InstructionClass Class = GetBasicInstructionClass(Inst);
2057    switch (Class) {
2058    case IC_Retain:
2059    case IC_RetainRV:
2060      // Check for a retain of the same pointer for merging.
2061      return GetObjCArg(Inst) == Arg;
2062    default:
2063      // Anything that can autorelease interrupts
2064      // retainAutoreleaseReturnValue formation.
2065      return CanInterruptRV(Class);
2066    }
2067  }
2068
2069  case RetainRVDep:
2070    return CanInterruptRV(GetBasicInstructionClass(Inst));
2071  }
2072
2073  llvm_unreachable("Invalid dependence flavor");
2074}
2075
2076/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2077/// find local and non-local dependencies on Arg.
2078/// TODO: Cache results?
2079static void
2080FindDependencies(DependenceKind Flavor,
2081                 const Value *Arg,
2082                 BasicBlock *StartBB, Instruction *StartInst,
2083                 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2084                 SmallPtrSet<const BasicBlock *, 4> &Visited,
2085                 ProvenanceAnalysis &PA) {
2086  BasicBlock::iterator StartPos = StartInst;
2087
2088  SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2089  Worklist.push_back(std::make_pair(StartBB, StartPos));
2090  do {
2091    std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2092      Worklist.pop_back_val();
2093    BasicBlock *LocalStartBB = Pair.first;
2094    BasicBlock::iterator LocalStartPos = Pair.second;
2095    BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2096    for (;;) {
2097      if (LocalStartPos == StartBBBegin) {
2098        pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2099        if (PI == PE)
2100          // If we've reached the function entry, produce a null dependence.
2101          DependingInstructions.insert(0);
2102        else
2103          // Add the predecessors to the worklist.
2104          do {
2105            BasicBlock *PredBB = *PI;
2106            if (Visited.insert(PredBB))
2107              Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2108          } while (++PI != PE);
2109        break;
2110      }
2111
2112      Instruction *Inst = --LocalStartPos;
2113      if (Depends(Flavor, Inst, Arg, PA)) {
2114        DependingInstructions.insert(Inst);
2115        break;
2116      }
2117    }
2118  } while (!Worklist.empty());
2119
2120  // Determine whether the original StartBB post-dominates all of the blocks we
2121  // visited. If not, insert a sentinal indicating that most optimizations are
2122  // not safe.
2123  for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2124       E = Visited.end(); I != E; ++I) {
2125    const BasicBlock *BB = *I;
2126    if (BB == StartBB)
2127      continue;
2128    const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2129    for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2130      const BasicBlock *Succ = *SI;
2131      if (Succ != StartBB && !Visited.count(Succ)) {
2132        DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2133        return;
2134      }
2135    }
2136  }
2137}
2138
2139static bool isNullOrUndef(const Value *V) {
2140  return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2141}
2142
2143static bool isNoopInstruction(const Instruction *I) {
2144  return isa<BitCastInst>(I) ||
2145         (isa<GetElementPtrInst>(I) &&
2146          cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2147}
2148
2149/// OptimizeRetainCall - Turn objc_retain into
2150/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2151void
2152ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2153  ImmutableCallSite CS(GetObjCArg(Retain));
2154  const Instruction *Call = CS.getInstruction();
2155  if (!Call) return;
2156  if (Call->getParent() != Retain->getParent()) return;
2157
2158  // Check that the call is next to the retain.
2159  BasicBlock::const_iterator I = Call;
2160  ++I;
2161  while (isNoopInstruction(I)) ++I;
2162  if (&*I != Retain)
2163    return;
2164
2165  // Turn it to an objc_retainAutoreleasedReturnValue..
2166  Changed = true;
2167  ++NumPeeps;
2168  cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2169}
2170
2171/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2172/// objc_retain if the operand is not a return value.  Or, if it can be paired
2173/// with an objc_autoreleaseReturnValue, delete the pair and return true.
2174bool
2175ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2176  // Check for the argument being from an immediately preceding call or invoke.
2177  const Value *Arg = GetObjCArg(RetainRV);
2178  ImmutableCallSite CS(Arg);
2179  if (const Instruction *Call = CS.getInstruction()) {
2180    if (Call->getParent() == RetainRV->getParent()) {
2181      BasicBlock::const_iterator I = Call;
2182      ++I;
2183      while (isNoopInstruction(I)) ++I;
2184      if (&*I == RetainRV)
2185        return false;
2186    } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2187      BasicBlock *RetainRVParent = RetainRV->getParent();
2188      if (II->getNormalDest() == RetainRVParent) {
2189        BasicBlock::const_iterator I = RetainRVParent->begin();
2190        while (isNoopInstruction(I)) ++I;
2191        if (&*I == RetainRV)
2192          return false;
2193      }
2194    }
2195  }
2196
2197  // Check for being preceded by an objc_autoreleaseReturnValue on the same
2198  // pointer. In this case, we can delete the pair.
2199  BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2200  if (I != Begin) {
2201    do --I; while (I != Begin && isNoopInstruction(I));
2202    if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2203        GetObjCArg(I) == Arg) {
2204      Changed = true;
2205      ++NumPeeps;
2206      EraseInstruction(I);
2207      EraseInstruction(RetainRV);
2208      return true;
2209    }
2210  }
2211
2212  // Turn it to a plain objc_retain.
2213  Changed = true;
2214  ++NumPeeps;
2215  cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2216  return false;
2217}
2218
2219/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2220/// objc_autorelease if the result is not used as a return value.
2221void
2222ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2223  // Check for a return of the pointer value.
2224  const Value *Ptr = GetObjCArg(AutoreleaseRV);
2225  SmallVector<const Value *, 2> Users;
2226  Users.push_back(Ptr);
2227  do {
2228    Ptr = Users.pop_back_val();
2229    for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2230         UI != UE; ++UI) {
2231      const User *I = *UI;
2232      if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2233        return;
2234      if (isa<BitCastInst>(I))
2235        Users.push_back(I);
2236    }
2237  } while (!Users.empty());
2238
2239  Changed = true;
2240  ++NumPeeps;
2241  cast<CallInst>(AutoreleaseRV)->
2242    setCalledFunction(getAutoreleaseCallee(F.getParent()));
2243}
2244
2245/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2246/// simplifications without doing any additional analysis.
2247void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2248  // Reset all the flags in preparation for recomputing them.
2249  UsedInThisFunction = 0;
2250
2251  // Visit all objc_* calls in F.
2252  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2253    Instruction *Inst = &*I++;
2254    InstructionClass Class = GetBasicInstructionClass(Inst);
2255
2256    switch (Class) {
2257    default: break;
2258
2259    // Delete no-op casts. These function calls have special semantics, but
2260    // the semantics are entirely implemented via lowering in the front-end,
2261    // so by the time they reach the optimizer, they are just no-op calls
2262    // which return their argument.
2263    //
2264    // There are gray areas here, as the ability to cast reference-counted
2265    // pointers to raw void* and back allows code to break ARC assumptions,
2266    // however these are currently considered to be unimportant.
2267    case IC_NoopCast:
2268      Changed = true;
2269      ++NumNoops;
2270      EraseInstruction(Inst);
2271      continue;
2272
2273    // If the pointer-to-weak-pointer is null, it's undefined behavior.
2274    case IC_StoreWeak:
2275    case IC_LoadWeak:
2276    case IC_LoadWeakRetained:
2277    case IC_InitWeak:
2278    case IC_DestroyWeak: {
2279      CallInst *CI = cast<CallInst>(Inst);
2280      if (isNullOrUndef(CI->getArgOperand(0))) {
2281        Changed = true;
2282        Type *Ty = CI->getArgOperand(0)->getType();
2283        new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2284                      Constant::getNullValue(Ty),
2285                      CI);
2286        CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2287        CI->eraseFromParent();
2288        continue;
2289      }
2290      break;
2291    }
2292    case IC_CopyWeak:
2293    case IC_MoveWeak: {
2294      CallInst *CI = cast<CallInst>(Inst);
2295      if (isNullOrUndef(CI->getArgOperand(0)) ||
2296          isNullOrUndef(CI->getArgOperand(1))) {
2297        Changed = true;
2298        Type *Ty = CI->getArgOperand(0)->getType();
2299        new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2300                      Constant::getNullValue(Ty),
2301                      CI);
2302        CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2303        CI->eraseFromParent();
2304        continue;
2305      }
2306      break;
2307    }
2308    case IC_Retain:
2309      OptimizeRetainCall(F, Inst);
2310      break;
2311    case IC_RetainRV:
2312      if (OptimizeRetainRVCall(F, Inst))
2313        continue;
2314      break;
2315    case IC_AutoreleaseRV:
2316      OptimizeAutoreleaseRVCall(F, Inst);
2317      break;
2318    }
2319
2320    // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2321    if (IsAutorelease(Class) && Inst->use_empty()) {
2322      CallInst *Call = cast<CallInst>(Inst);
2323      const Value *Arg = Call->getArgOperand(0);
2324      Arg = FindSingleUseIdentifiedObject(Arg);
2325      if (Arg) {
2326        Changed = true;
2327        ++NumAutoreleases;
2328
2329        // Create the declaration lazily.
2330        LLVMContext &C = Inst->getContext();
2331        CallInst *NewCall =
2332          CallInst::Create(getReleaseCallee(F.getParent()),
2333                           Call->getArgOperand(0), "", Call);
2334        NewCall->setMetadata(ImpreciseReleaseMDKind,
2335                             MDNode::get(C, ArrayRef<Value *>()));
2336        EraseInstruction(Call);
2337        Inst = NewCall;
2338        Class = IC_Release;
2339      }
2340    }
2341
2342    // For functions which can never be passed stack arguments, add
2343    // a tail keyword.
2344    if (IsAlwaysTail(Class)) {
2345      Changed = true;
2346      cast<CallInst>(Inst)->setTailCall();
2347    }
2348
2349    // Set nounwind as needed.
2350    if (IsNoThrow(Class)) {
2351      Changed = true;
2352      cast<CallInst>(Inst)->setDoesNotThrow();
2353    }
2354
2355    if (!IsNoopOnNull(Class)) {
2356      UsedInThisFunction |= 1 << Class;
2357      continue;
2358    }
2359
2360    const Value *Arg = GetObjCArg(Inst);
2361
2362    // ARC calls with null are no-ops. Delete them.
2363    if (isNullOrUndef(Arg)) {
2364      Changed = true;
2365      ++NumNoops;
2366      EraseInstruction(Inst);
2367      continue;
2368    }
2369
2370    // Keep track of which of retain, release, autorelease, and retain_block
2371    // are actually present in this function.
2372    UsedInThisFunction |= 1 << Class;
2373
2374    // If Arg is a PHI, and one or more incoming values to the
2375    // PHI are null, and the call is control-equivalent to the PHI, and there
2376    // are no relevant side effects between the PHI and the call, the call
2377    // could be pushed up to just those paths with non-null incoming values.
2378    // For now, don't bother splitting critical edges for this.
2379    SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2380    Worklist.push_back(std::make_pair(Inst, Arg));
2381    do {
2382      std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2383      Inst = Pair.first;
2384      Arg = Pair.second;
2385
2386      const PHINode *PN = dyn_cast<PHINode>(Arg);
2387      if (!PN) continue;
2388
2389      // Determine if the PHI has any null operands, or any incoming
2390      // critical edges.
2391      bool HasNull = false;
2392      bool HasCriticalEdges = false;
2393      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2394        Value *Incoming =
2395          StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2396        if (isNullOrUndef(Incoming))
2397          HasNull = true;
2398        else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2399                   .getNumSuccessors() != 1) {
2400          HasCriticalEdges = true;
2401          break;
2402        }
2403      }
2404      // If we have null operands and no critical edges, optimize.
2405      if (!HasCriticalEdges && HasNull) {
2406        SmallPtrSet<Instruction *, 4> DependingInstructions;
2407        SmallPtrSet<const BasicBlock *, 4> Visited;
2408
2409        // Check that there is nothing that cares about the reference
2410        // count between the call and the phi.
2411        switch (Class) {
2412        case IC_Retain:
2413        case IC_RetainBlock:
2414          // These can always be moved up.
2415          break;
2416        case IC_Release:
2417          // These can't be moved across things that care about the retain
2418          // count.
2419          FindDependencies(NeedsPositiveRetainCount, Arg,
2420                           Inst->getParent(), Inst,
2421                           DependingInstructions, Visited, PA);
2422          break;
2423        case IC_Autorelease:
2424          // These can't be moved across autorelease pool scope boundaries.
2425          FindDependencies(AutoreleasePoolBoundary, Arg,
2426                           Inst->getParent(), Inst,
2427                           DependingInstructions, Visited, PA);
2428          break;
2429        case IC_RetainRV:
2430        case IC_AutoreleaseRV:
2431          // Don't move these; the RV optimization depends on the autoreleaseRV
2432          // being tail called, and the retainRV being immediately after a call
2433          // (which might still happen if we get lucky with codegen layout, but
2434          // it's not worth taking the chance).
2435          continue;
2436        default:
2437          llvm_unreachable("Invalid dependence flavor");
2438        }
2439
2440        if (DependingInstructions.size() == 1 &&
2441            *DependingInstructions.begin() == PN) {
2442          Changed = true;
2443          ++NumPartialNoops;
2444          // Clone the call into each predecessor that has a non-null value.
2445          CallInst *CInst = cast<CallInst>(Inst);
2446          Type *ParamTy = CInst->getArgOperand(0)->getType();
2447          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2448            Value *Incoming =
2449              StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2450            if (!isNullOrUndef(Incoming)) {
2451              CallInst *Clone = cast<CallInst>(CInst->clone());
2452              Value *Op = PN->getIncomingValue(i);
2453              Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2454              if (Op->getType() != ParamTy)
2455                Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2456              Clone->setArgOperand(0, Op);
2457              Clone->insertBefore(InsertPos);
2458              Worklist.push_back(std::make_pair(Clone, Incoming));
2459            }
2460          }
2461          // Erase the original call.
2462          EraseInstruction(CInst);
2463          continue;
2464        }
2465      }
2466    } while (!Worklist.empty());
2467  }
2468}
2469
2470/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2471/// control flow, or other CFG structures where moving code across the edge
2472/// would result in it being executed more.
2473void
2474ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2475                               DenseMap<const BasicBlock *, BBState> &BBStates,
2476                               BBState &MyStates) const {
2477  // If any top-down local-use or possible-dec has a succ which is earlier in
2478  // the sequence, forget it.
2479  for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2480       E = MyStates.top_down_ptr_end(); I != E; ++I)
2481    switch (I->second.GetSeq()) {
2482    default: break;
2483    case S_Use: {
2484      const Value *Arg = I->first;
2485      const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2486      bool SomeSuccHasSame = false;
2487      bool AllSuccsHaveSame = true;
2488      PtrState &S = I->second;
2489      succ_const_iterator SI(TI), SE(TI, false);
2490
2491      // If the terminator is an invoke marked with the
2492      // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2493      // ignored, for ARC purposes.
2494      if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2495        --SE;
2496
2497      for (; SI != SE; ++SI) {
2498        Sequence SuccSSeq = S_None;
2499        bool SuccSRRIKnownSafe = false;
2500        // If VisitBottomUp has pointer information for this successor, take
2501        // what we know about it.
2502        DenseMap<const BasicBlock *, BBState>::iterator BBI =
2503          BBStates.find(*SI);
2504        assert(BBI != BBStates.end());
2505        const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2506        SuccSSeq = SuccS.GetSeq();
2507        SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2508        switch (SuccSSeq) {
2509        case S_None:
2510        case S_CanRelease: {
2511          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2512            S.ClearSequenceProgress();
2513            break;
2514          }
2515          continue;
2516        }
2517        case S_Use:
2518          SomeSuccHasSame = true;
2519          break;
2520        case S_Stop:
2521        case S_Release:
2522        case S_MovableRelease:
2523          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2524            AllSuccsHaveSame = false;
2525          break;
2526        case S_Retain:
2527          llvm_unreachable("bottom-up pointer in retain state!");
2528        }
2529      }
2530      // If the state at the other end of any of the successor edges
2531      // matches the current state, require all edges to match. This
2532      // guards against loops in the middle of a sequence.
2533      if (SomeSuccHasSame && !AllSuccsHaveSame)
2534        S.ClearSequenceProgress();
2535      break;
2536    }
2537    case S_CanRelease: {
2538      const Value *Arg = I->first;
2539      const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2540      bool SomeSuccHasSame = false;
2541      bool AllSuccsHaveSame = true;
2542      PtrState &S = I->second;
2543      succ_const_iterator SI(TI), SE(TI, false);
2544
2545      // If the terminator is an invoke marked with the
2546      // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2547      // ignored, for ARC purposes.
2548      if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2549        --SE;
2550
2551      for (; SI != SE; ++SI) {
2552        Sequence SuccSSeq = S_None;
2553        bool SuccSRRIKnownSafe = false;
2554        // If VisitBottomUp has pointer information for this successor, take
2555        // what we know about it.
2556        DenseMap<const BasicBlock *, BBState>::iterator BBI =
2557          BBStates.find(*SI);
2558        assert(BBI != BBStates.end());
2559        const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2560        SuccSSeq = SuccS.GetSeq();
2561        SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2562        switch (SuccSSeq) {
2563        case S_None: {
2564          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2565            S.ClearSequenceProgress();
2566            break;
2567          }
2568          continue;
2569        }
2570        case S_CanRelease:
2571          SomeSuccHasSame = true;
2572          break;
2573        case S_Stop:
2574        case S_Release:
2575        case S_MovableRelease:
2576        case S_Use:
2577          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2578            AllSuccsHaveSame = false;
2579          break;
2580        case S_Retain:
2581          llvm_unreachable("bottom-up pointer in retain state!");
2582        }
2583      }
2584      // If the state at the other end of any of the successor edges
2585      // matches the current state, require all edges to match. This
2586      // guards against loops in the middle of a sequence.
2587      if (SomeSuccHasSame && !AllSuccsHaveSame)
2588        S.ClearSequenceProgress();
2589      break;
2590    }
2591    }
2592}
2593
2594bool
2595ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2596                                     BasicBlock *BB,
2597                                     MapVector<Value *, RRInfo> &Retains,
2598                                     BBState &MyStates) {
2599  bool NestingDetected = false;
2600  InstructionClass Class = GetInstructionClass(Inst);
2601  const Value *Arg = 0;
2602
2603  switch (Class) {
2604  case IC_Release: {
2605    Arg = GetObjCArg(Inst);
2606
2607    PtrState &S = MyStates.getPtrBottomUpState(Arg);
2608
2609    // If we see two releases in a row on the same pointer. If so, make
2610    // a note, and we'll cicle back to revisit it after we've
2611    // hopefully eliminated the second release, which may allow us to
2612    // eliminate the first release too.
2613    // Theoretically we could implement removal of nested retain+release
2614    // pairs by making PtrState hold a stack of states, but this is
2615    // simple and avoids adding overhead for the non-nested case.
2616    if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2617      NestingDetected = true;
2618
2619    MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2620    S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2621    S.RRI.ReleaseMetadata = ReleaseMetadata;
2622    S.RRI.KnownSafe = S.IsKnownIncremented();
2623    S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2624    S.RRI.Calls.insert(Inst);
2625
2626    S.SetKnownPositiveRefCount();
2627    break;
2628  }
2629  case IC_RetainBlock:
2630    // An objc_retainBlock call with just a use may need to be kept,
2631    // because it may be copying a block from the stack to the heap.
2632    if (!IsRetainBlockOptimizable(Inst))
2633      break;
2634    // FALLTHROUGH
2635  case IC_Retain:
2636  case IC_RetainRV: {
2637    Arg = GetObjCArg(Inst);
2638
2639    PtrState &S = MyStates.getPtrBottomUpState(Arg);
2640    S.SetKnownPositiveRefCount();
2641
2642    switch (S.GetSeq()) {
2643    case S_Stop:
2644    case S_Release:
2645    case S_MovableRelease:
2646    case S_Use:
2647      S.RRI.ReverseInsertPts.clear();
2648      // FALL THROUGH
2649    case S_CanRelease:
2650      // Don't do retain+release tracking for IC_RetainRV, because it's
2651      // better to let it remain as the first instruction after a call.
2652      if (Class != IC_RetainRV) {
2653        S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2654        Retains[Inst] = S.RRI;
2655      }
2656      S.ClearSequenceProgress();
2657      break;
2658    case S_None:
2659      break;
2660    case S_Retain:
2661      llvm_unreachable("bottom-up pointer in retain state!");
2662    }
2663    return NestingDetected;
2664  }
2665  case IC_AutoreleasepoolPop:
2666    // Conservatively, clear MyStates for all known pointers.
2667    MyStates.clearBottomUpPointers();
2668    return NestingDetected;
2669  case IC_AutoreleasepoolPush:
2670  case IC_None:
2671    // These are irrelevant.
2672    return NestingDetected;
2673  default:
2674    break;
2675  }
2676
2677  // Consider any other possible effects of this instruction on each
2678  // pointer being tracked.
2679  for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2680       ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2681    const Value *Ptr = MI->first;
2682    if (Ptr == Arg)
2683      continue; // Handled above.
2684    PtrState &S = MI->second;
2685    Sequence Seq = S.GetSeq();
2686
2687    // Check for possible releases.
2688    if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2689      S.ClearRefCount();
2690      switch (Seq) {
2691      case S_Use:
2692        S.SetSeq(S_CanRelease);
2693        continue;
2694      case S_CanRelease:
2695      case S_Release:
2696      case S_MovableRelease:
2697      case S_Stop:
2698      case S_None:
2699        break;
2700      case S_Retain:
2701        llvm_unreachable("bottom-up pointer in retain state!");
2702      }
2703    }
2704
2705    // Check for possible direct uses.
2706    switch (Seq) {
2707    case S_Release:
2708    case S_MovableRelease:
2709      if (CanUse(Inst, Ptr, PA, Class)) {
2710        assert(S.RRI.ReverseInsertPts.empty());
2711        // If this is an invoke instruction, we're scanning it as part of
2712        // one of its successor blocks, since we can't insert code after it
2713        // in its own block, and we don't want to split critical edges.
2714        if (isa<InvokeInst>(Inst))
2715          S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2716        else
2717          S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2718        S.SetSeq(S_Use);
2719      } else if (Seq == S_Release &&
2720                 (Class == IC_User || Class == IC_CallOrUser)) {
2721        // Non-movable releases depend on any possible objc pointer use.
2722        S.SetSeq(S_Stop);
2723        assert(S.RRI.ReverseInsertPts.empty());
2724        // As above; handle invoke specially.
2725        if (isa<InvokeInst>(Inst))
2726          S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2727        else
2728          S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2729      }
2730      break;
2731    case S_Stop:
2732      if (CanUse(Inst, Ptr, PA, Class))
2733        S.SetSeq(S_Use);
2734      break;
2735    case S_CanRelease:
2736    case S_Use:
2737    case S_None:
2738      break;
2739    case S_Retain:
2740      llvm_unreachable("bottom-up pointer in retain state!");
2741    }
2742  }
2743
2744  return NestingDetected;
2745}
2746
2747bool
2748ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2749                          DenseMap<const BasicBlock *, BBState> &BBStates,
2750                          MapVector<Value *, RRInfo> &Retains) {
2751  bool NestingDetected = false;
2752  BBState &MyStates = BBStates[BB];
2753
2754  // Merge the states from each successor to compute the initial state
2755  // for the current block.
2756  BBState::edge_iterator SI(MyStates.succ_begin()),
2757                         SE(MyStates.succ_end());
2758  if (SI != SE) {
2759    const BasicBlock *Succ = *SI;
2760    DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2761    assert(I != BBStates.end());
2762    MyStates.InitFromSucc(I->second);
2763    ++SI;
2764    for (; SI != SE; ++SI) {
2765      Succ = *SI;
2766      I = BBStates.find(Succ);
2767      assert(I != BBStates.end());
2768      MyStates.MergeSucc(I->second);
2769    }
2770  }
2771
2772  // Visit all the instructions, bottom-up.
2773  for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2774    Instruction *Inst = llvm::prior(I);
2775
2776    // Invoke instructions are visited as part of their successors (below).
2777    if (isa<InvokeInst>(Inst))
2778      continue;
2779
2780    NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2781  }
2782
2783  // If there's a predecessor with an invoke, visit the invoke as if it were
2784  // part of this block, since we can't insert code after an invoke in its own
2785  // block, and we don't want to split critical edges.
2786  for (BBState::edge_iterator PI(MyStates.pred_begin()),
2787       PE(MyStates.pred_end()); PI != PE; ++PI) {
2788    BasicBlock *Pred = *PI;
2789    if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2790      NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2791  }
2792
2793  return NestingDetected;
2794}
2795
2796bool
2797ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2798                                    DenseMap<Value *, RRInfo> &Releases,
2799                                    BBState &MyStates) {
2800  bool NestingDetected = false;
2801  InstructionClass Class = GetInstructionClass(Inst);
2802  const Value *Arg = 0;
2803
2804  switch (Class) {
2805  case IC_RetainBlock:
2806    // An objc_retainBlock call with just a use may need to be kept,
2807    // because it may be copying a block from the stack to the heap.
2808    if (!IsRetainBlockOptimizable(Inst))
2809      break;
2810    // FALLTHROUGH
2811  case IC_Retain:
2812  case IC_RetainRV: {
2813    Arg = GetObjCArg(Inst);
2814
2815    PtrState &S = MyStates.getPtrTopDownState(Arg);
2816
2817    // Don't do retain+release tracking for IC_RetainRV, because it's
2818    // better to let it remain as the first instruction after a call.
2819    if (Class != IC_RetainRV) {
2820      // If we see two retains in a row on the same pointer. If so, make
2821      // a note, and we'll cicle back to revisit it after we've
2822      // hopefully eliminated the second retain, which may allow us to
2823      // eliminate the first retain too.
2824      // Theoretically we could implement removal of nested retain+release
2825      // pairs by making PtrState hold a stack of states, but this is
2826      // simple and avoids adding overhead for the non-nested case.
2827      if (S.GetSeq() == S_Retain)
2828        NestingDetected = true;
2829
2830      S.ResetSequenceProgress(S_Retain);
2831      S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2832      S.RRI.KnownSafe = S.IsKnownIncremented();
2833      S.RRI.Calls.insert(Inst);
2834    }
2835
2836    S.SetKnownPositiveRefCount();
2837
2838    // A retain can be a potential use; procede to the generic checking
2839    // code below.
2840    break;
2841  }
2842  case IC_Release: {
2843    Arg = GetObjCArg(Inst);
2844
2845    PtrState &S = MyStates.getPtrTopDownState(Arg);
2846    S.ClearRefCount();
2847
2848    switch (S.GetSeq()) {
2849    case S_Retain:
2850    case S_CanRelease:
2851      S.RRI.ReverseInsertPts.clear();
2852      // FALL THROUGH
2853    case S_Use:
2854      S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2855      S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2856      Releases[Inst] = S.RRI;
2857      S.ClearSequenceProgress();
2858      break;
2859    case S_None:
2860      break;
2861    case S_Stop:
2862    case S_Release:
2863    case S_MovableRelease:
2864      llvm_unreachable("top-down pointer in release state!");
2865    }
2866    break;
2867  }
2868  case IC_AutoreleasepoolPop:
2869    // Conservatively, clear MyStates for all known pointers.
2870    MyStates.clearTopDownPointers();
2871    return NestingDetected;
2872  case IC_AutoreleasepoolPush:
2873  case IC_None:
2874    // These are irrelevant.
2875    return NestingDetected;
2876  default:
2877    break;
2878  }
2879
2880  // Consider any other possible effects of this instruction on each
2881  // pointer being tracked.
2882  for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2883       ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2884    const Value *Ptr = MI->first;
2885    if (Ptr == Arg)
2886      continue; // Handled above.
2887    PtrState &S = MI->second;
2888    Sequence Seq = S.GetSeq();
2889
2890    // Check for possible releases.
2891    if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2892      S.ClearRefCount();
2893      switch (Seq) {
2894      case S_Retain:
2895        S.SetSeq(S_CanRelease);
2896        assert(S.RRI.ReverseInsertPts.empty());
2897        S.RRI.ReverseInsertPts.insert(Inst);
2898
2899        // One call can't cause a transition from S_Retain to S_CanRelease
2900        // and S_CanRelease to S_Use. If we've made the first transition,
2901        // we're done.
2902        continue;
2903      case S_Use:
2904      case S_CanRelease:
2905      case S_None:
2906        break;
2907      case S_Stop:
2908      case S_Release:
2909      case S_MovableRelease:
2910        llvm_unreachable("top-down pointer in release state!");
2911      }
2912    }
2913
2914    // Check for possible direct uses.
2915    switch (Seq) {
2916    case S_CanRelease:
2917      if (CanUse(Inst, Ptr, PA, Class))
2918        S.SetSeq(S_Use);
2919      break;
2920    case S_Retain:
2921    case S_Use:
2922    case S_None:
2923      break;
2924    case S_Stop:
2925    case S_Release:
2926    case S_MovableRelease:
2927      llvm_unreachable("top-down pointer in release state!");
2928    }
2929  }
2930
2931  return NestingDetected;
2932}
2933
2934bool
2935ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2936                         DenseMap<const BasicBlock *, BBState> &BBStates,
2937                         DenseMap<Value *, RRInfo> &Releases) {
2938  bool NestingDetected = false;
2939  BBState &MyStates = BBStates[BB];
2940
2941  // Merge the states from each predecessor to compute the initial state
2942  // for the current block.
2943  BBState::edge_iterator PI(MyStates.pred_begin()),
2944                         PE(MyStates.pred_end());
2945  if (PI != PE) {
2946    const BasicBlock *Pred = *PI;
2947    DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2948    assert(I != BBStates.end());
2949    MyStates.InitFromPred(I->second);
2950    ++PI;
2951    for (; PI != PE; ++PI) {
2952      Pred = *PI;
2953      I = BBStates.find(Pred);
2954      assert(I != BBStates.end());
2955      MyStates.MergePred(I->second);
2956    }
2957  }
2958
2959  // Visit all the instructions, top-down.
2960  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2961    Instruction *Inst = I;
2962    NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2963  }
2964
2965  CheckForCFGHazards(BB, BBStates, MyStates);
2966  return NestingDetected;
2967}
2968
2969static void
2970ComputePostOrders(Function &F,
2971                  SmallVectorImpl<BasicBlock *> &PostOrder,
2972                  SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2973                  unsigned NoObjCARCExceptionsMDKind,
2974                  DenseMap<const BasicBlock *, BBState> &BBStates) {
2975  /// Visited - The visited set, for doing DFS walks.
2976  SmallPtrSet<BasicBlock *, 16> Visited;
2977
2978  // Do DFS, computing the PostOrder.
2979  SmallPtrSet<BasicBlock *, 16> OnStack;
2980  SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2981
2982  // Functions always have exactly one entry block, and we don't have
2983  // any other block that we treat like an entry block.
2984  BasicBlock *EntryBB = &F.getEntryBlock();
2985  BBState &MyStates = BBStates[EntryBB];
2986  MyStates.SetAsEntry();
2987  TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2988  SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2989  Visited.insert(EntryBB);
2990  OnStack.insert(EntryBB);
2991  do {
2992  dfs_next_succ:
2993    BasicBlock *CurrBB = SuccStack.back().first;
2994    TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2995    succ_iterator SE(TI, false);
2996
2997    // If the terminator is an invoke marked with the
2998    // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2999    // ignored, for ARC purposes.
3000    if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3001      --SE;
3002
3003    while (SuccStack.back().second != SE) {
3004      BasicBlock *SuccBB = *SuccStack.back().second++;
3005      if (Visited.insert(SuccBB)) {
3006        TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3007        SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3008        BBStates[CurrBB].addSucc(SuccBB);
3009        BBState &SuccStates = BBStates[SuccBB];
3010        SuccStates.addPred(CurrBB);
3011        OnStack.insert(SuccBB);
3012        goto dfs_next_succ;
3013      }
3014
3015      if (!OnStack.count(SuccBB)) {
3016        BBStates[CurrBB].addSucc(SuccBB);
3017        BBStates[SuccBB].addPred(CurrBB);
3018      }
3019    }
3020    OnStack.erase(CurrBB);
3021    PostOrder.push_back(CurrBB);
3022    SuccStack.pop_back();
3023  } while (!SuccStack.empty());
3024
3025  Visited.clear();
3026
3027  // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3028  // Functions may have many exits, and there also blocks which we treat
3029  // as exits due to ignored edges.
3030  SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3031  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3032    BasicBlock *ExitBB = I;
3033    BBState &MyStates = BBStates[ExitBB];
3034    if (!MyStates.isExit())
3035      continue;
3036
3037    MyStates.SetAsExit();
3038
3039    PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3040    Visited.insert(ExitBB);
3041    while (!PredStack.empty()) {
3042    reverse_dfs_next_succ:
3043      BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3044      while (PredStack.back().second != PE) {
3045        BasicBlock *BB = *PredStack.back().second++;
3046        if (Visited.insert(BB)) {
3047          PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3048          goto reverse_dfs_next_succ;
3049        }
3050      }
3051      ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3052    }
3053  }
3054}
3055
3056// Visit - Visit the function both top-down and bottom-up.
3057bool
3058ObjCARCOpt::Visit(Function &F,
3059                  DenseMap<const BasicBlock *, BBState> &BBStates,
3060                  MapVector<Value *, RRInfo> &Retains,
3061                  DenseMap<Value *, RRInfo> &Releases) {
3062
3063  // Use reverse-postorder traversals, because we magically know that loops
3064  // will be well behaved, i.e. they won't repeatedly call retain on a single
3065  // pointer without doing a release. We can't use the ReversePostOrderTraversal
3066  // class here because we want the reverse-CFG postorder to consider each
3067  // function exit point, and we want to ignore selected cycle edges.
3068  SmallVector<BasicBlock *, 16> PostOrder;
3069  SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3070  ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3071                    NoObjCARCExceptionsMDKind,
3072                    BBStates);
3073
3074  // Use reverse-postorder on the reverse CFG for bottom-up.
3075  bool BottomUpNestingDetected = false;
3076  for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3077       ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3078       I != E; ++I)
3079    BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3080
3081  // Use reverse-postorder for top-down.
3082  bool TopDownNestingDetected = false;
3083  for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3084       PostOrder.rbegin(), E = PostOrder.rend();
3085       I != E; ++I)
3086    TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3087
3088  return TopDownNestingDetected && BottomUpNestingDetected;
3089}
3090
3091/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3092void ObjCARCOpt::MoveCalls(Value *Arg,
3093                           RRInfo &RetainsToMove,
3094                           RRInfo &ReleasesToMove,
3095                           MapVector<Value *, RRInfo> &Retains,
3096                           DenseMap<Value *, RRInfo> &Releases,
3097                           SmallVectorImpl<Instruction *> &DeadInsts,
3098                           Module *M) {
3099  Type *ArgTy = Arg->getType();
3100  Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3101
3102  // Insert the new retain and release calls.
3103  for (SmallPtrSet<Instruction *, 2>::const_iterator
3104       PI = ReleasesToMove.ReverseInsertPts.begin(),
3105       PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3106    Instruction *InsertPt = *PI;
3107    Value *MyArg = ArgTy == ParamTy ? Arg :
3108                   new BitCastInst(Arg, ParamTy, "", InsertPt);
3109    CallInst *Call =
3110      CallInst::Create(RetainsToMove.IsRetainBlock ?
3111                         getRetainBlockCallee(M) : getRetainCallee(M),
3112                       MyArg, "", InsertPt);
3113    Call->setDoesNotThrow();
3114    if (RetainsToMove.IsRetainBlock)
3115      Call->setMetadata(CopyOnEscapeMDKind,
3116                        MDNode::get(M->getContext(), ArrayRef<Value *>()));
3117    else
3118      Call->setTailCall();
3119  }
3120  for (SmallPtrSet<Instruction *, 2>::const_iterator
3121       PI = RetainsToMove.ReverseInsertPts.begin(),
3122       PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3123    Instruction *InsertPt = *PI;
3124    Value *MyArg = ArgTy == ParamTy ? Arg :
3125                   new BitCastInst(Arg, ParamTy, "", InsertPt);
3126    CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3127                                      "", InsertPt);
3128    // Attach a clang.imprecise_release metadata tag, if appropriate.
3129    if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3130      Call->setMetadata(ImpreciseReleaseMDKind, M);
3131    Call->setDoesNotThrow();
3132    if (ReleasesToMove.IsTailCallRelease)
3133      Call->setTailCall();
3134  }
3135
3136  // Delete the original retain and release calls.
3137  for (SmallPtrSet<Instruction *, 2>::const_iterator
3138       AI = RetainsToMove.Calls.begin(),
3139       AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3140    Instruction *OrigRetain = *AI;
3141    Retains.blot(OrigRetain);
3142    DeadInsts.push_back(OrigRetain);
3143  }
3144  for (SmallPtrSet<Instruction *, 2>::const_iterator
3145       AI = ReleasesToMove.Calls.begin(),
3146       AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3147    Instruction *OrigRelease = *AI;
3148    Releases.erase(OrigRelease);
3149    DeadInsts.push_back(OrigRelease);
3150  }
3151}
3152
3153/// PerformCodePlacement - Identify pairings between the retains and releases,
3154/// and delete and/or move them.
3155bool
3156ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3157                                   &BBStates,
3158                                 MapVector<Value *, RRInfo> &Retains,
3159                                 DenseMap<Value *, RRInfo> &Releases,
3160                                 Module *M) {
3161  bool AnyPairsCompletelyEliminated = false;
3162  RRInfo RetainsToMove;
3163  RRInfo ReleasesToMove;
3164  SmallVector<Instruction *, 4> NewRetains;
3165  SmallVector<Instruction *, 4> NewReleases;
3166  SmallVector<Instruction *, 8> DeadInsts;
3167
3168  // Visit each retain.
3169  for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3170       E = Retains.end(); I != E; ++I) {
3171    Value *V = I->first;
3172    if (!V) continue; // blotted
3173
3174    Instruction *Retain = cast<Instruction>(V);
3175    Value *Arg = GetObjCArg(Retain);
3176
3177    // If the object being released is in static or stack storage, we know it's
3178    // not being managed by ObjC reference counting, so we can delete pairs
3179    // regardless of what possible decrements or uses lie between them.
3180    bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3181
3182    // A constant pointer can't be pointing to an object on the heap. It may
3183    // be reference-counted, but it won't be deleted.
3184    if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3185      if (const GlobalVariable *GV =
3186            dyn_cast<GlobalVariable>(
3187              StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3188        if (GV->isConstant())
3189          KnownSafe = true;
3190
3191    // If a pair happens in a region where it is known that the reference count
3192    // is already incremented, we can similarly ignore possible decrements.
3193    bool KnownSafeTD = true, KnownSafeBU = true;
3194
3195    // Connect the dots between the top-down-collected RetainsToMove and
3196    // bottom-up-collected ReleasesToMove to form sets of related calls.
3197    // This is an iterative process so that we connect multiple releases
3198    // to multiple retains if needed.
3199    unsigned OldDelta = 0;
3200    unsigned NewDelta = 0;
3201    unsigned OldCount = 0;
3202    unsigned NewCount = 0;
3203    bool FirstRelease = true;
3204    bool FirstRetain = true;
3205    NewRetains.push_back(Retain);
3206    for (;;) {
3207      for (SmallVectorImpl<Instruction *>::const_iterator
3208           NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3209        Instruction *NewRetain = *NI;
3210        MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3211        assert(It != Retains.end());
3212        const RRInfo &NewRetainRRI = It->second;
3213        KnownSafeTD &= NewRetainRRI.KnownSafe;
3214        for (SmallPtrSet<Instruction *, 2>::const_iterator
3215             LI = NewRetainRRI.Calls.begin(),
3216             LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3217          Instruction *NewRetainRelease = *LI;
3218          DenseMap<Value *, RRInfo>::const_iterator Jt =
3219            Releases.find(NewRetainRelease);
3220          if (Jt == Releases.end())
3221            goto next_retain;
3222          const RRInfo &NewRetainReleaseRRI = Jt->second;
3223          assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3224          if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3225            OldDelta -=
3226              BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3227
3228            // Merge the ReleaseMetadata and IsTailCallRelease values.
3229            if (FirstRelease) {
3230              ReleasesToMove.ReleaseMetadata =
3231                NewRetainReleaseRRI.ReleaseMetadata;
3232              ReleasesToMove.IsTailCallRelease =
3233                NewRetainReleaseRRI.IsTailCallRelease;
3234              FirstRelease = false;
3235            } else {
3236              if (ReleasesToMove.ReleaseMetadata !=
3237                    NewRetainReleaseRRI.ReleaseMetadata)
3238                ReleasesToMove.ReleaseMetadata = 0;
3239              if (ReleasesToMove.IsTailCallRelease !=
3240                    NewRetainReleaseRRI.IsTailCallRelease)
3241                ReleasesToMove.IsTailCallRelease = false;
3242            }
3243
3244            // Collect the optimal insertion points.
3245            if (!KnownSafe)
3246              for (SmallPtrSet<Instruction *, 2>::const_iterator
3247                   RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3248                   RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3249                   RI != RE; ++RI) {
3250                Instruction *RIP = *RI;
3251                if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3252                  NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3253              }
3254            NewReleases.push_back(NewRetainRelease);
3255          }
3256        }
3257      }
3258      NewRetains.clear();
3259      if (NewReleases.empty()) break;
3260
3261      // Back the other way.
3262      for (SmallVectorImpl<Instruction *>::const_iterator
3263           NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3264        Instruction *NewRelease = *NI;
3265        DenseMap<Value *, RRInfo>::const_iterator It =
3266          Releases.find(NewRelease);
3267        assert(It != Releases.end());
3268        const RRInfo &NewReleaseRRI = It->second;
3269        KnownSafeBU &= NewReleaseRRI.KnownSafe;
3270        for (SmallPtrSet<Instruction *, 2>::const_iterator
3271             LI = NewReleaseRRI.Calls.begin(),
3272             LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3273          Instruction *NewReleaseRetain = *LI;
3274          MapVector<Value *, RRInfo>::const_iterator Jt =
3275            Retains.find(NewReleaseRetain);
3276          if (Jt == Retains.end())
3277            goto next_retain;
3278          const RRInfo &NewReleaseRetainRRI = Jt->second;
3279          assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3280          if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3281            unsigned PathCount =
3282              BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3283            OldDelta += PathCount;
3284            OldCount += PathCount;
3285
3286            // Merge the IsRetainBlock values.
3287            if (FirstRetain) {
3288              RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3289              FirstRetain = false;
3290            } else if (ReleasesToMove.IsRetainBlock !=
3291                       NewReleaseRetainRRI.IsRetainBlock)
3292              // It's not possible to merge the sequences if one uses
3293              // objc_retain and the other uses objc_retainBlock.
3294              goto next_retain;
3295
3296            // Collect the optimal insertion points.
3297            if (!KnownSafe)
3298              for (SmallPtrSet<Instruction *, 2>::const_iterator
3299                   RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3300                   RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3301                   RI != RE; ++RI) {
3302                Instruction *RIP = *RI;
3303                if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3304                  PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3305                  NewDelta += PathCount;
3306                  NewCount += PathCount;
3307                }
3308              }
3309            NewRetains.push_back(NewReleaseRetain);
3310          }
3311        }
3312      }
3313      NewReleases.clear();
3314      if (NewRetains.empty()) break;
3315    }
3316
3317    // If the pointer is known incremented or nested, we can safely delete the
3318    // pair regardless of what's between them.
3319    if (KnownSafeTD || KnownSafeBU) {
3320      RetainsToMove.ReverseInsertPts.clear();
3321      ReleasesToMove.ReverseInsertPts.clear();
3322      NewCount = 0;
3323    } else {
3324      // Determine whether the new insertion points we computed preserve the
3325      // balance of retain and release calls through the program.
3326      // TODO: If the fully aggressive solution isn't valid, try to find a
3327      // less aggressive solution which is.
3328      if (NewDelta != 0)
3329        goto next_retain;
3330    }
3331
3332    // Determine whether the original call points are balanced in the retain and
3333    // release calls through the program. If not, conservatively don't touch
3334    // them.
3335    // TODO: It's theoretically possible to do code motion in this case, as
3336    // long as the existing imbalances are maintained.
3337    if (OldDelta != 0)
3338      goto next_retain;
3339
3340    // Ok, everything checks out and we're all set. Let's move some code!
3341    Changed = true;
3342    assert(OldCount != 0 && "Unreachable code?");
3343    AnyPairsCompletelyEliminated = NewCount == 0;
3344    NumRRs += OldCount - NewCount;
3345    MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3346              Retains, Releases, DeadInsts, M);
3347
3348  next_retain:
3349    NewReleases.clear();
3350    NewRetains.clear();
3351    RetainsToMove.clear();
3352    ReleasesToMove.clear();
3353  }
3354
3355  // Now that we're done moving everything, we can delete the newly dead
3356  // instructions, as we no longer need them as insert points.
3357  while (!DeadInsts.empty())
3358    EraseInstruction(DeadInsts.pop_back_val());
3359
3360  return AnyPairsCompletelyEliminated;
3361}
3362
3363/// OptimizeWeakCalls - Weak pointer optimizations.
3364void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3365  // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3366  // itself because it uses AliasAnalysis and we need to do provenance
3367  // queries instead.
3368  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3369    Instruction *Inst = &*I++;
3370    InstructionClass Class = GetBasicInstructionClass(Inst);
3371    if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3372      continue;
3373
3374    // Delete objc_loadWeak calls with no users.
3375    if (Class == IC_LoadWeak && Inst->use_empty()) {
3376      Inst->eraseFromParent();
3377      continue;
3378    }
3379
3380    // TODO: For now, just look for an earlier available version of this value
3381    // within the same block. Theoretically, we could do memdep-style non-local
3382    // analysis too, but that would want caching. A better approach would be to
3383    // use the technique that EarlyCSE uses.
3384    inst_iterator Current = llvm::prior(I);
3385    BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3386    for (BasicBlock::iterator B = CurrentBB->begin(),
3387                              J = Current.getInstructionIterator();
3388         J != B; --J) {
3389      Instruction *EarlierInst = &*llvm::prior(J);
3390      InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3391      switch (EarlierClass) {
3392      case IC_LoadWeak:
3393      case IC_LoadWeakRetained: {
3394        // If this is loading from the same pointer, replace this load's value
3395        // with that one.
3396        CallInst *Call = cast<CallInst>(Inst);
3397        CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3398        Value *Arg = Call->getArgOperand(0);
3399        Value *EarlierArg = EarlierCall->getArgOperand(0);
3400        switch (PA.getAA()->alias(Arg, EarlierArg)) {
3401        case AliasAnalysis::MustAlias:
3402          Changed = true;
3403          // If the load has a builtin retain, insert a plain retain for it.
3404          if (Class == IC_LoadWeakRetained) {
3405            CallInst *CI =
3406              CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3407                               "", Call);
3408            CI->setTailCall();
3409          }
3410          // Zap the fully redundant load.
3411          Call->replaceAllUsesWith(EarlierCall);
3412          Call->eraseFromParent();
3413          goto clobbered;
3414        case AliasAnalysis::MayAlias:
3415        case AliasAnalysis::PartialAlias:
3416          goto clobbered;
3417        case AliasAnalysis::NoAlias:
3418          break;
3419        }
3420        break;
3421      }
3422      case IC_StoreWeak:
3423      case IC_InitWeak: {
3424        // If this is storing to the same pointer and has the same size etc.
3425        // replace this load's value with the stored value.
3426        CallInst *Call = cast<CallInst>(Inst);
3427        CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3428        Value *Arg = Call->getArgOperand(0);
3429        Value *EarlierArg = EarlierCall->getArgOperand(0);
3430        switch (PA.getAA()->alias(Arg, EarlierArg)) {
3431        case AliasAnalysis::MustAlias:
3432          Changed = true;
3433          // If the load has a builtin retain, insert a plain retain for it.
3434          if (Class == IC_LoadWeakRetained) {
3435            CallInst *CI =
3436              CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3437                               "", Call);
3438            CI->setTailCall();
3439          }
3440          // Zap the fully redundant load.
3441          Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3442          Call->eraseFromParent();
3443          goto clobbered;
3444        case AliasAnalysis::MayAlias:
3445        case AliasAnalysis::PartialAlias:
3446          goto clobbered;
3447        case AliasAnalysis::NoAlias:
3448          break;
3449        }
3450        break;
3451      }
3452      case IC_MoveWeak:
3453      case IC_CopyWeak:
3454        // TOOD: Grab the copied value.
3455        goto clobbered;
3456      case IC_AutoreleasepoolPush:
3457      case IC_None:
3458      case IC_User:
3459        // Weak pointers are only modified through the weak entry points
3460        // (and arbitrary calls, which could call the weak entry points).
3461        break;
3462      default:
3463        // Anything else could modify the weak pointer.
3464        goto clobbered;
3465      }
3466    }
3467  clobbered:;
3468  }
3469
3470  // Then, for each destroyWeak with an alloca operand, check to see if
3471  // the alloca and all its users can be zapped.
3472  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3473    Instruction *Inst = &*I++;
3474    InstructionClass Class = GetBasicInstructionClass(Inst);
3475    if (Class != IC_DestroyWeak)
3476      continue;
3477
3478    CallInst *Call = cast<CallInst>(Inst);
3479    Value *Arg = Call->getArgOperand(0);
3480    if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3481      for (Value::use_iterator UI = Alloca->use_begin(),
3482           UE = Alloca->use_end(); UI != UE; ++UI) {
3483        const Instruction *UserInst = cast<Instruction>(*UI);
3484        switch (GetBasicInstructionClass(UserInst)) {
3485        case IC_InitWeak:
3486        case IC_StoreWeak:
3487        case IC_DestroyWeak:
3488          continue;
3489        default:
3490          goto done;
3491        }
3492      }
3493      Changed = true;
3494      for (Value::use_iterator UI = Alloca->use_begin(),
3495           UE = Alloca->use_end(); UI != UE; ) {
3496        CallInst *UserInst = cast<CallInst>(*UI++);
3497        switch (GetBasicInstructionClass(UserInst)) {
3498        case IC_InitWeak:
3499        case IC_StoreWeak:
3500          // These functions return their second argument.
3501          UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3502          break;
3503        case IC_DestroyWeak:
3504          // No return value.
3505          break;
3506        default:
3507          llvm_unreachable("alloca really is used!");
3508        }
3509        UserInst->eraseFromParent();
3510      }
3511      Alloca->eraseFromParent();
3512    done:;
3513    }
3514  }
3515}
3516
3517/// OptimizeSequences - Identify program paths which execute sequences of
3518/// retains and releases which can be eliminated.
3519bool ObjCARCOpt::OptimizeSequences(Function &F) {
3520  /// Releases, Retains - These are used to store the results of the main flow
3521  /// analysis. These use Value* as the key instead of Instruction* so that the
3522  /// map stays valid when we get around to rewriting code and calls get
3523  /// replaced by arguments.
3524  DenseMap<Value *, RRInfo> Releases;
3525  MapVector<Value *, RRInfo> Retains;
3526
3527  /// BBStates, This is used during the traversal of the function to track the
3528  /// states for each identified object at each block.
3529  DenseMap<const BasicBlock *, BBState> BBStates;
3530
3531  // Analyze the CFG of the function, and all instructions.
3532  bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3533
3534  // Transform.
3535  return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3536         NestingDetected;
3537}
3538
3539/// OptimizeReturns - Look for this pattern:
3540///
3541///    %call = call i8* @something(...)
3542///    %2 = call i8* @objc_retain(i8* %call)
3543///    %3 = call i8* @objc_autorelease(i8* %2)
3544///    ret i8* %3
3545///
3546/// And delete the retain and autorelease.
3547///
3548/// Otherwise if it's just this:
3549///
3550///    %3 = call i8* @objc_autorelease(i8* %2)
3551///    ret i8* %3
3552///
3553/// convert the autorelease to autoreleaseRV.
3554void ObjCARCOpt::OptimizeReturns(Function &F) {
3555  if (!F.getReturnType()->isPointerTy())
3556    return;
3557
3558  SmallPtrSet<Instruction *, 4> DependingInstructions;
3559  SmallPtrSet<const BasicBlock *, 4> Visited;
3560  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3561    BasicBlock *BB = FI;
3562    ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3563    if (!Ret) continue;
3564
3565    const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3566    FindDependencies(NeedsPositiveRetainCount, Arg,
3567                     BB, Ret, DependingInstructions, Visited, PA);
3568    if (DependingInstructions.size() != 1)
3569      goto next_block;
3570
3571    {
3572      CallInst *Autorelease =
3573        dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3574      if (!Autorelease)
3575        goto next_block;
3576      InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3577      if (!IsAutorelease(AutoreleaseClass))
3578        goto next_block;
3579      if (GetObjCArg(Autorelease) != Arg)
3580        goto next_block;
3581
3582      DependingInstructions.clear();
3583      Visited.clear();
3584
3585      // Check that there is nothing that can affect the reference
3586      // count between the autorelease and the retain.
3587      FindDependencies(CanChangeRetainCount, Arg,
3588                       BB, Autorelease, DependingInstructions, Visited, PA);
3589      if (DependingInstructions.size() != 1)
3590        goto next_block;
3591
3592      {
3593        CallInst *Retain =
3594          dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3595
3596        // Check that we found a retain with the same argument.
3597        if (!Retain ||
3598            !IsRetain(GetBasicInstructionClass(Retain)) ||
3599            GetObjCArg(Retain) != Arg)
3600          goto next_block;
3601
3602        DependingInstructions.clear();
3603        Visited.clear();
3604
3605        // Convert the autorelease to an autoreleaseRV, since it's
3606        // returning the value.
3607        if (AutoreleaseClass == IC_Autorelease) {
3608          Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3609          AutoreleaseClass = IC_AutoreleaseRV;
3610        }
3611
3612        // Check that there is nothing that can affect the reference
3613        // count between the retain and the call.
3614        // Note that Retain need not be in BB.
3615        FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3616                         DependingInstructions, Visited, PA);
3617        if (DependingInstructions.size() != 1)
3618          goto next_block;
3619
3620        {
3621          CallInst *Call =
3622            dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3623
3624          // Check that the pointer is the return value of the call.
3625          if (!Call || Arg != Call)
3626            goto next_block;
3627
3628          // Check that the call is a regular call.
3629          InstructionClass Class = GetBasicInstructionClass(Call);
3630          if (Class != IC_CallOrUser && Class != IC_Call)
3631            goto next_block;
3632
3633          // If so, we can zap the retain and autorelease.
3634          Changed = true;
3635          ++NumRets;
3636          EraseInstruction(Retain);
3637          EraseInstruction(Autorelease);
3638        }
3639      }
3640    }
3641
3642  next_block:
3643    DependingInstructions.clear();
3644    Visited.clear();
3645  }
3646}
3647
3648bool ObjCARCOpt::doInitialization(Module &M) {
3649  if (!EnableARCOpts)
3650    return false;
3651
3652  // If nothing in the Module uses ARC, don't do anything.
3653  Run = ModuleHasARC(M);
3654  if (!Run)
3655    return false;
3656
3657  // Identify the imprecise release metadata kind.
3658  ImpreciseReleaseMDKind =
3659    M.getContext().getMDKindID("clang.imprecise_release");
3660  CopyOnEscapeMDKind =
3661    M.getContext().getMDKindID("clang.arc.copy_on_escape");
3662  NoObjCARCExceptionsMDKind =
3663    M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3664
3665  // Intuitively, objc_retain and others are nocapture, however in practice
3666  // they are not, because they return their argument value. And objc_release
3667  // calls finalizers which can have arbitrary side effects.
3668
3669  // These are initialized lazily.
3670  RetainRVCallee = 0;
3671  AutoreleaseRVCallee = 0;
3672  ReleaseCallee = 0;
3673  RetainCallee = 0;
3674  RetainBlockCallee = 0;
3675  AutoreleaseCallee = 0;
3676
3677  return false;
3678}
3679
3680bool ObjCARCOpt::runOnFunction(Function &F) {
3681  if (!EnableARCOpts)
3682    return false;
3683
3684  // If nothing in the Module uses ARC, don't do anything.
3685  if (!Run)
3686    return false;
3687
3688  Changed = false;
3689
3690  PA.setAA(&getAnalysis<AliasAnalysis>());
3691
3692  // This pass performs several distinct transformations. As a compile-time aid
3693  // when compiling code that isn't ObjC, skip these if the relevant ObjC
3694  // library functions aren't declared.
3695
3696  // Preliminary optimizations. This also computs UsedInThisFunction.
3697  OptimizeIndividualCalls(F);
3698
3699  // Optimizations for weak pointers.
3700  if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3701                            (1 << IC_LoadWeakRetained) |
3702                            (1 << IC_StoreWeak) |
3703                            (1 << IC_InitWeak) |
3704                            (1 << IC_CopyWeak) |
3705                            (1 << IC_MoveWeak) |
3706                            (1 << IC_DestroyWeak)))
3707    OptimizeWeakCalls(F);
3708
3709  // Optimizations for retain+release pairs.
3710  if (UsedInThisFunction & ((1 << IC_Retain) |
3711                            (1 << IC_RetainRV) |
3712                            (1 << IC_RetainBlock)))
3713    if (UsedInThisFunction & (1 << IC_Release))
3714      // Run OptimizeSequences until it either stops making changes or
3715      // no retain+release pair nesting is detected.
3716      while (OptimizeSequences(F)) {}
3717
3718  // Optimizations if objc_autorelease is used.
3719  if (UsedInThisFunction & ((1 << IC_Autorelease) |
3720                            (1 << IC_AutoreleaseRV)))
3721    OptimizeReturns(F);
3722
3723  return Changed;
3724}
3725
3726void ObjCARCOpt::releaseMemory() {
3727  PA.clear();
3728}
3729
3730//===----------------------------------------------------------------------===//
3731// ARC contraction.
3732//===----------------------------------------------------------------------===//
3733
3734// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3735// dominated by single calls.
3736
3737#include "llvm/Operator.h"
3738#include "llvm/InlineAsm.h"
3739#include "llvm/Analysis/Dominators.h"
3740
3741STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3742
3743namespace {
3744  /// ObjCARCContract - Late ARC optimizations.  These change the IR in a way
3745  /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3746  class ObjCARCContract : public FunctionPass {
3747    bool Changed;
3748    AliasAnalysis *AA;
3749    DominatorTree *DT;
3750    ProvenanceAnalysis PA;
3751
3752    /// Run - A flag indicating whether this optimization pass should run.
3753    bool Run;
3754
3755    /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3756    /// functions, for use in creating calls to them. These are initialized
3757    /// lazily to avoid cluttering up the Module with unused declarations.
3758    Constant *StoreStrongCallee,
3759             *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3760
3761    /// RetainRVMarker - The inline asm string to insert between calls and
3762    /// RetainRV calls to make the optimization work on targets which need it.
3763    const MDString *RetainRVMarker;
3764
3765    /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3766    /// at the end of walking the function we have found no alloca
3767    /// instructions, these calls can be marked "tail".
3768    SmallPtrSet<CallInst *, 8> StoreStrongCalls;
3769
3770    Constant *getStoreStrongCallee(Module *M);
3771    Constant *getRetainAutoreleaseCallee(Module *M);
3772    Constant *getRetainAutoreleaseRVCallee(Module *M);
3773
3774    bool ContractAutorelease(Function &F, Instruction *Autorelease,
3775                             InstructionClass Class,
3776                             SmallPtrSet<Instruction *, 4>
3777                               &DependingInstructions,
3778                             SmallPtrSet<const BasicBlock *, 4>
3779                               &Visited);
3780
3781    void ContractRelease(Instruction *Release,
3782                         inst_iterator &Iter);
3783
3784    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3785    virtual bool doInitialization(Module &M);
3786    virtual bool runOnFunction(Function &F);
3787
3788  public:
3789    static char ID;
3790    ObjCARCContract() : FunctionPass(ID) {
3791      initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3792    }
3793  };
3794}
3795
3796char ObjCARCContract::ID = 0;
3797INITIALIZE_PASS_BEGIN(ObjCARCContract,
3798                      "objc-arc-contract", "ObjC ARC contraction", false, false)
3799INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3800INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3801INITIALIZE_PASS_END(ObjCARCContract,
3802                    "objc-arc-contract", "ObjC ARC contraction", false, false)
3803
3804Pass *llvm::createObjCARCContractPass() {
3805  return new ObjCARCContract();
3806}
3807
3808void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3809  AU.addRequired<AliasAnalysis>();
3810  AU.addRequired<DominatorTree>();
3811  AU.setPreservesCFG();
3812}
3813
3814Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3815  if (!StoreStrongCallee) {
3816    LLVMContext &C = M->getContext();
3817    Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3818    Type *I8XX = PointerType::getUnqual(I8X);
3819    Type *Params[] = { I8XX, I8X };
3820
3821    AttrListPtr Attributes = AttrListPtr()
3822      .addAttr(~0u, Attribute::NoUnwind)
3823      .addAttr(1, Attribute::NoCapture);
3824
3825    StoreStrongCallee =
3826      M->getOrInsertFunction(
3827        "objc_storeStrong",
3828        FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3829        Attributes);
3830  }
3831  return StoreStrongCallee;
3832}
3833
3834Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3835  if (!RetainAutoreleaseCallee) {
3836    LLVMContext &C = M->getContext();
3837    Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3838    Type *Params[] = { I8X };
3839    FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3840    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
3841    RetainAutoreleaseCallee =
3842      M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3843  }
3844  return RetainAutoreleaseCallee;
3845}
3846
3847Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3848  if (!RetainAutoreleaseRVCallee) {
3849    LLVMContext &C = M->getContext();
3850    Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3851    Type *Params[] = { I8X };
3852    FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3853    AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
3854    RetainAutoreleaseRVCallee =
3855      M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3856                             Attributes);
3857  }
3858  return RetainAutoreleaseRVCallee;
3859}
3860
3861/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
3862bool
3863ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3864                                     InstructionClass Class,
3865                                     SmallPtrSet<Instruction *, 4>
3866                                       &DependingInstructions,
3867                                     SmallPtrSet<const BasicBlock *, 4>
3868                                       &Visited) {
3869  const Value *Arg = GetObjCArg(Autorelease);
3870
3871  // Check that there are no instructions between the retain and the autorelease
3872  // (such as an autorelease_pop) which may change the count.
3873  CallInst *Retain = 0;
3874  if (Class == IC_AutoreleaseRV)
3875    FindDependencies(RetainAutoreleaseRVDep, Arg,
3876                     Autorelease->getParent(), Autorelease,
3877                     DependingInstructions, Visited, PA);
3878  else
3879    FindDependencies(RetainAutoreleaseDep, Arg,
3880                     Autorelease->getParent(), Autorelease,
3881                     DependingInstructions, Visited, PA);
3882
3883  Visited.clear();
3884  if (DependingInstructions.size() != 1) {
3885    DependingInstructions.clear();
3886    return false;
3887  }
3888
3889  Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3890  DependingInstructions.clear();
3891
3892  if (!Retain ||
3893      GetBasicInstructionClass(Retain) != IC_Retain ||
3894      GetObjCArg(Retain) != Arg)
3895    return false;
3896
3897  Changed = true;
3898  ++NumPeeps;
3899
3900  if (Class == IC_AutoreleaseRV)
3901    Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3902  else
3903    Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3904
3905  EraseInstruction(Autorelease);
3906  return true;
3907}
3908
3909/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3910/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3911/// the instructions don't always appear in order, and there may be unrelated
3912/// intervening instructions.
3913void ObjCARCContract::ContractRelease(Instruction *Release,
3914                                      inst_iterator &Iter) {
3915  LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3916  if (!Load || !Load->isSimple()) return;
3917
3918  // For now, require everything to be in one basic block.
3919  BasicBlock *BB = Release->getParent();
3920  if (Load->getParent() != BB) return;
3921
3922  // Walk down to find the store and the release, which may be in either order.
3923  BasicBlock::iterator I = Load, End = BB->end();
3924  ++I;
3925  AliasAnalysis::Location Loc = AA->getLocation(Load);
3926  StoreInst *Store = 0;
3927  bool SawRelease = false;
3928  for (; !Store || !SawRelease; ++I) {
3929    if (I == End)
3930      return;
3931
3932    Instruction *Inst = I;
3933    if (Inst == Release) {
3934      SawRelease = true;
3935      continue;
3936    }
3937
3938    InstructionClass Class = GetBasicInstructionClass(Inst);
3939
3940    // Unrelated retains are harmless.
3941    if (IsRetain(Class))
3942      continue;
3943
3944    if (Store) {
3945      // The store is the point where we're going to put the objc_storeStrong,
3946      // so make sure there are no uses after it.
3947      if (CanUse(Inst, Load, PA, Class))
3948        return;
3949    } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3950      // We are moving the load down to the store, so check for anything
3951      // else which writes to the memory between the load and the store.
3952      Store = dyn_cast<StoreInst>(Inst);
3953      if (!Store || !Store->isSimple()) return;
3954      if (Store->getPointerOperand() != Loc.Ptr) return;
3955    }
3956  }
3957
3958  Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3959
3960  // Walk up to find the retain.
3961  I = Store;
3962  BasicBlock::iterator Begin = BB->begin();
3963  while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3964    --I;
3965  Instruction *Retain = I;
3966  if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3967  if (GetObjCArg(Retain) != New) return;
3968
3969  Changed = true;
3970  ++NumStoreStrongs;
3971
3972  LLVMContext &C = Release->getContext();
3973  Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3974  Type *I8XX = PointerType::getUnqual(I8X);
3975
3976  Value *Args[] = { Load->getPointerOperand(), New };
3977  if (Args[0]->getType() != I8XX)
3978    Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3979  if (Args[1]->getType() != I8X)
3980    Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3981  CallInst *StoreStrong =
3982    CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3983                     Args, "", Store);
3984  StoreStrong->setDoesNotThrow();
3985  StoreStrong->setDebugLoc(Store->getDebugLoc());
3986
3987  // We can't set the tail flag yet, because we haven't yet determined
3988  // whether there are any escaping allocas. Remember this call, so that
3989  // we can set the tail flag once we know it's safe.
3990  StoreStrongCalls.insert(StoreStrong);
3991
3992  if (&*Iter == Store) ++Iter;
3993  Store->eraseFromParent();
3994  Release->eraseFromParent();
3995  EraseInstruction(Retain);
3996  if (Load->use_empty())
3997    Load->eraseFromParent();
3998}
3999
4000bool ObjCARCContract::doInitialization(Module &M) {
4001  // If nothing in the Module uses ARC, don't do anything.
4002  Run = ModuleHasARC(M);
4003  if (!Run)
4004    return false;
4005
4006  // These are initialized lazily.
4007  StoreStrongCallee = 0;
4008  RetainAutoreleaseCallee = 0;
4009  RetainAutoreleaseRVCallee = 0;
4010
4011  // Initialize RetainRVMarker.
4012  RetainRVMarker = 0;
4013  if (NamedMDNode *NMD =
4014        M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4015    if (NMD->getNumOperands() == 1) {
4016      const MDNode *N = NMD->getOperand(0);
4017      if (N->getNumOperands() == 1)
4018        if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4019          RetainRVMarker = S;
4020    }
4021
4022  return false;
4023}
4024
4025bool ObjCARCContract::runOnFunction(Function &F) {
4026  if (!EnableARCOpts)
4027    return false;
4028
4029  // If nothing in the Module uses ARC, don't do anything.
4030  if (!Run)
4031    return false;
4032
4033  Changed = false;
4034  AA = &getAnalysis<AliasAnalysis>();
4035  DT = &getAnalysis<DominatorTree>();
4036
4037  PA.setAA(&getAnalysis<AliasAnalysis>());
4038
4039  // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4040  // keyword. Be conservative if the function has variadic arguments.
4041  // It seems that functions which "return twice" are also unsafe for the
4042  // "tail" argument, because they are setjmp, which could need to
4043  // return to an earlier stack state.
4044  bool TailOkForStoreStrongs = !F.isVarArg() &&
4045                               !F.callsFunctionThatReturnsTwice();
4046
4047  // For ObjC library calls which return their argument, replace uses of the
4048  // argument with uses of the call return value, if it dominates the use. This
4049  // reduces register pressure.
4050  SmallPtrSet<Instruction *, 4> DependingInstructions;
4051  SmallPtrSet<const BasicBlock *, 4> Visited;
4052  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4053    Instruction *Inst = &*I++;
4054
4055    // Only these library routines return their argument. In particular,
4056    // objc_retainBlock does not necessarily return its argument.
4057    InstructionClass Class = GetBasicInstructionClass(Inst);
4058    switch (Class) {
4059    case IC_Retain:
4060    case IC_FusedRetainAutorelease:
4061    case IC_FusedRetainAutoreleaseRV:
4062      break;
4063    case IC_Autorelease:
4064    case IC_AutoreleaseRV:
4065      if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4066        continue;
4067      break;
4068    case IC_RetainRV: {
4069      // If we're compiling for a target which needs a special inline-asm
4070      // marker to do the retainAutoreleasedReturnValue optimization,
4071      // insert it now.
4072      if (!RetainRVMarker)
4073        break;
4074      BasicBlock::iterator BBI = Inst;
4075      BasicBlock *InstParent = Inst->getParent();
4076
4077      // Step up to see if the call immediately precedes the RetainRV call.
4078      // If it's an invoke, we have to cross a block boundary. And we have
4079      // to carefully dodge no-op instructions.
4080      do {
4081        if (&*BBI == InstParent->begin()) {
4082          BasicBlock *Pred = InstParent->getSinglePredecessor();
4083          if (!Pred)
4084            goto decline_rv_optimization;
4085          BBI = Pred->getTerminator();
4086          break;
4087        }
4088        --BBI;
4089      } while (isNoopInstruction(BBI));
4090
4091      if (&*BBI == GetObjCArg(Inst)) {
4092        Changed = true;
4093        InlineAsm *IA =
4094          InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4095                                           /*isVarArg=*/false),
4096                         RetainRVMarker->getString(),
4097                         /*Constraints=*/"", /*hasSideEffects=*/true);
4098        CallInst::Create(IA, "", Inst);
4099      }
4100    decline_rv_optimization:
4101      break;
4102    }
4103    case IC_InitWeak: {
4104      // objc_initWeak(p, null) => *p = null
4105      CallInst *CI = cast<CallInst>(Inst);
4106      if (isNullOrUndef(CI->getArgOperand(1))) {
4107        Value *Null =
4108          ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4109        Changed = true;
4110        new StoreInst(Null, CI->getArgOperand(0), CI);
4111        CI->replaceAllUsesWith(Null);
4112        CI->eraseFromParent();
4113      }
4114      continue;
4115    }
4116    case IC_Release:
4117      ContractRelease(Inst, I);
4118      continue;
4119    case IC_User:
4120      // Be conservative if the function has any alloca instructions.
4121      // Technically we only care about escaping alloca instructions,
4122      // but this is sufficient to handle some interesting cases.
4123      if (isa<AllocaInst>(Inst))
4124        TailOkForStoreStrongs = false;
4125      continue;
4126    default:
4127      continue;
4128    }
4129
4130    // Don't use GetObjCArg because we don't want to look through bitcasts
4131    // and such; to do the replacement, the argument must have type i8*.
4132    const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4133    for (;;) {
4134      // If we're compiling bugpointed code, don't get in trouble.
4135      if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4136        break;
4137      // Look through the uses of the pointer.
4138      for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4139           UI != UE; ) {
4140        Use &U = UI.getUse();
4141        unsigned OperandNo = UI.getOperandNo();
4142        ++UI; // Increment UI now, because we may unlink its element.
4143
4144        // If the call's return value dominates a use of the call's argument
4145        // value, rewrite the use to use the return value. We check for
4146        // reachability here because an unreachable call is considered to
4147        // trivially dominate itself, which would lead us to rewriting its
4148        // argument in terms of its return value, which would lead to
4149        // infinite loops in GetObjCArg.
4150        if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4151          Changed = true;
4152          Instruction *Replacement = Inst;
4153          Type *UseTy = U.get()->getType();
4154          if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4155            // For PHI nodes, insert the bitcast in the predecessor block.
4156            unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4157            BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4158            if (Replacement->getType() != UseTy)
4159              Replacement = new BitCastInst(Replacement, UseTy, "",
4160                                            &BB->back());
4161            // While we're here, rewrite all edges for this PHI, rather
4162            // than just one use at a time, to minimize the number of
4163            // bitcasts we emit.
4164            for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4165              if (PHI->getIncomingBlock(i) == BB) {
4166                // Keep the UI iterator valid.
4167                if (&PHI->getOperandUse(
4168                      PHINode::getOperandNumForIncomingValue(i)) ==
4169                    &UI.getUse())
4170                  ++UI;
4171                PHI->setIncomingValue(i, Replacement);
4172              }
4173          } else {
4174            if (Replacement->getType() != UseTy)
4175              Replacement = new BitCastInst(Replacement, UseTy, "",
4176                                            cast<Instruction>(U.getUser()));
4177            U.set(Replacement);
4178          }
4179        }
4180      }
4181
4182      // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4183      if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4184        Arg = BI->getOperand(0);
4185      else if (isa<GEPOperator>(Arg) &&
4186               cast<GEPOperator>(Arg)->hasAllZeroIndices())
4187        Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4188      else if (isa<GlobalAlias>(Arg) &&
4189               !cast<GlobalAlias>(Arg)->mayBeOverridden())
4190        Arg = cast<GlobalAlias>(Arg)->getAliasee();
4191      else
4192        break;
4193    }
4194  }
4195
4196  // If this function has no escaping allocas or suspicious vararg usage,
4197  // objc_storeStrong calls can be marked with the "tail" keyword.
4198  if (TailOkForStoreStrongs)
4199    for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4200         E = StoreStrongCalls.end(); I != E; ++I)
4201      (*I)->setTailCall();
4202  StoreStrongCalls.clear();
4203
4204  return Changed;
4205}
4206