[objcarcopts] Refactor out the RRInfo merging code from PtrState into RRInfo::Merge.
[oota-llvm.git] / lib / Transforms / ObjCARC / ObjCARCOpts.cpp
1 //===- ObjCARCOpts.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 /// \file
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
12 /// 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, and numerous minor simplifications.
17 ///
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
20 ///
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
24 ///
25 //===----------------------------------------------------------------------===//
26
27 #define DEBUG_TYPE "objc-arc-opts"
28 #include "ObjCARC.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42
43 using namespace llvm;
44 using namespace llvm::objcarc;
45
46 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
47 /// @{
48
49 namespace {
50   /// \brief An associative container with fast insertion-order (deterministic)
51   /// iteration over its elements. Plus the special blot operation.
52   template<class KeyT, class ValueT>
53   class MapVector {
54     /// Map keys to indices in Vector.
55     typedef DenseMap<KeyT, size_t> MapTy;
56     MapTy Map;
57
58     typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
59     /// Keys and values.
60     VectorTy Vector;
61
62   public:
63     typedef typename VectorTy::iterator iterator;
64     typedef typename VectorTy::const_iterator const_iterator;
65     iterator begin() { return Vector.begin(); }
66     iterator end() { return Vector.end(); }
67     const_iterator begin() const { return Vector.begin(); }
68     const_iterator end() const { return Vector.end(); }
69
70 #ifdef XDEBUG
71     ~MapVector() {
72       assert(Vector.size() >= Map.size()); // May differ due to blotting.
73       for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
74            I != E; ++I) {
75         assert(I->second < Vector.size());
76         assert(Vector[I->second].first == I->first);
77       }
78       for (typename VectorTy::const_iterator I = Vector.begin(),
79            E = Vector.end(); I != E; ++I)
80         assert(!I->first ||
81                (Map.count(I->first) &&
82                 Map[I->first] == size_t(I - Vector.begin())));
83     }
84 #endif
85
86     ValueT &operator[](const KeyT &Arg) {
87       std::pair<typename MapTy::iterator, bool> Pair =
88         Map.insert(std::make_pair(Arg, size_t(0)));
89       if (Pair.second) {
90         size_t Num = Vector.size();
91         Pair.first->second = Num;
92         Vector.push_back(std::make_pair(Arg, ValueT()));
93         return Vector[Num].second;
94       }
95       return Vector[Pair.first->second].second;
96     }
97
98     std::pair<iterator, bool>
99     insert(const std::pair<KeyT, ValueT> &InsertPair) {
100       std::pair<typename MapTy::iterator, bool> Pair =
101         Map.insert(std::make_pair(InsertPair.first, size_t(0)));
102       if (Pair.second) {
103         size_t Num = Vector.size();
104         Pair.first->second = Num;
105         Vector.push_back(InsertPair);
106         return std::make_pair(Vector.begin() + Num, true);
107       }
108       return std::make_pair(Vector.begin() + Pair.first->second, false);
109     }
110
111     iterator find(const KeyT &Key) {
112       typename MapTy::iterator It = Map.find(Key);
113       if (It == Map.end()) return Vector.end();
114       return Vector.begin() + It->second;
115     }
116
117     const_iterator find(const KeyT &Key) const {
118       typename MapTy::const_iterator It = Map.find(Key);
119       if (It == Map.end()) return Vector.end();
120       return Vector.begin() + It->second;
121     }
122
123     /// This is similar to erase, but instead of removing the element from the
124     /// vector, it just zeros out the key in the vector. This leaves iterators
125     /// intact, but clients must be prepared for zeroed-out keys when iterating.
126     void blot(const KeyT &Key) {
127       typename MapTy::iterator It = Map.find(Key);
128       if (It == Map.end()) return;
129       Vector[It->second].first = KeyT();
130       Map.erase(It);
131     }
132
133     void clear() {
134       Map.clear();
135       Vector.clear();
136     }
137   };
138 }
139
140 /// @}
141 ///
142 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
143 /// @{
144
145 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146 /// as it finds a value with multiple uses.
147 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148   if (Arg->hasOneUse()) {
149     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150       return FindSingleUseIdentifiedObject(BC->getOperand(0));
151     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152       if (GEP->hasAllZeroIndices())
153         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154     if (IsForwarding(GetBasicInstructionClass(Arg)))
155       return FindSingleUseIdentifiedObject(
156                cast<CallInst>(Arg)->getArgOperand(0));
157     if (!IsObjCIdentifiedObject(Arg))
158       return 0;
159     return Arg;
160   }
161
162   // If we found an identifiable object but it has multiple uses, but they are
163   // trivial uses, we can still consider this to be a single-use value.
164   if (IsObjCIdentifiedObject(Arg)) {
165     for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
166          UI != UE; ++UI) {
167       const User *U = *UI;
168       if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
169          return 0;
170     }
171
172     return Arg;
173   }
174
175   return 0;
176 }
177
178 /// \brief Test whether the given retainable object pointer escapes.
179 ///
180 /// This differs from regular escape analysis in that a use as an
181 /// argument to a call is not considered an escape.
182 ///
183 static bool DoesRetainableObjPtrEscape(const User *Ptr) {
184   DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
185
186   // Walk the def-use chains.
187   SmallVector<const Value *, 4> Worklist;
188   Worklist.push_back(Ptr);
189   // If Ptr has any operands add them as well.
190   for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
191        ++I) {
192     Worklist.push_back(*I);
193   }
194
195   // Ensure we do not visit any value twice.
196   SmallPtrSet<const Value *, 8> VisitedSet;
197
198   do {
199     const Value *V = Worklist.pop_back_val();
200
201     DEBUG(dbgs() << "Visiting: " << *V << "\n");
202
203     for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
204          UI != UE; ++UI) {
205       const User *UUser = *UI;
206
207       DEBUG(dbgs() << "User: " << *UUser << "\n");
208
209       // Special - Use by a call (callee or argument) is not considered
210       // to be an escape.
211       switch (GetBasicInstructionClass(UUser)) {
212       case IC_StoreWeak:
213       case IC_InitWeak:
214       case IC_StoreStrong:
215       case IC_Autorelease:
216       case IC_AutoreleaseRV: {
217         DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
218         // These special functions make copies of their pointer arguments.
219         return true;
220       }
221       case IC_IntrinsicUser:
222         // Use by the use intrinsic is not an escape.
223         continue;
224       case IC_User:
225       case IC_None:
226         // Use by an instruction which copies the value is an escape if the
227         // result is an escape.
228         if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229             isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
230
231           if (VisitedSet.insert(UUser)) {
232             DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233                   " Adding to list.\n");
234             Worklist.push_back(UUser);
235           } else {
236             DEBUG(dbgs() << "Already visited node.\n");
237           }
238           continue;
239         }
240         // Use by a load is not an escape.
241         if (isa<LoadInst>(UUser))
242           continue;
243         // Use by a store is not an escape if the use is the address.
244         if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245           if (V != SI->getValueOperand())
246             continue;
247         break;
248       default:
249         // Regular calls and other stuff are not considered escapes.
250         continue;
251       }
252       // Otherwise, conservatively assume an escape.
253       DEBUG(dbgs() << "Assuming ptr escapes.\n");
254       return true;
255     }
256   } while (!Worklist.empty());
257
258   // No escapes found.
259   DEBUG(dbgs() << "Ptr does not escape.\n");
260   return false;
261 }
262
263 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
264 /// GetUnderlyingObjects except that it returns early when it sees the first
265 /// alloca.
266 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267   SmallPtrSet<const Value *, 4> Visited;
268   SmallVector<const Value *, 4> Worklist;
269   Worklist.push_back(V);
270   do {
271     const Value *P = Worklist.pop_back_val();
272     P = GetUnderlyingObjCPtr(P);
273
274     if (isa<AllocaInst>(P))
275       return true;
276
277     if (!Visited.insert(P))
278       continue;
279
280     if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281       Worklist.push_back(SI->getTrueValue());
282       Worklist.push_back(SI->getFalseValue());
283       continue;
284     }
285
286     if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288         Worklist.push_back(PN->getIncomingValue(i));
289       continue;
290     }
291   } while (!Worklist.empty());
292
293   return false;
294 }
295
296
297 /// @}
298 ///
299 /// \defgroup ARCOpt ARC Optimization.
300 /// @{
301
302 // TODO: On code like this:
303 //
304 // objc_retain(%x)
305 // stuff_that_cannot_release()
306 // objc_autorelease(%x)
307 // stuff_that_cannot_release()
308 // objc_retain(%x)
309 // stuff_that_cannot_release()
310 // objc_autorelease(%x)
311 //
312 // The second retain and autorelease can be deleted.
313
314 // TODO: It should be possible to delete
315 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
316 // pairs if nothing is actually autoreleased between them. Also, autorelease
317 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318 // after inlining) can be turned into plain release calls.
319
320 // TODO: Critical-edge splitting. If the optimial insertion point is
321 // a critical edge, the current algorithm has to fail, because it doesn't
322 // know how to split edges. It should be possible to make the optimizer
323 // think in terms of edges, rather than blocks, and then split critical
324 // edges on demand.
325
326 // TODO: OptimizeSequences could generalized to be Interprocedural.
327
328 // TODO: Recognize that a bunch of other objc runtime calls have
329 // non-escaping arguments and non-releasing arguments, and may be
330 // non-autoreleasing.
331
332 // TODO: Sink autorelease calls as far as possible. Unfortunately we
333 // usually can't sink them past other calls, which would be the main
334 // case where it would be useful.
335
336 // TODO: The pointer returned from objc_loadWeakRetained is retained.
337
338 // TODO: Delete release+retain pairs (rare).
339
340 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
341 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343 STATISTIC(NumRets,        "Number of return value forwarding "
344                           "retain+autoreleases eliminated");
345 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
346 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
347 #ifndef NDEBUG
348 STATISTIC(NumRetainsBeforeOpt,
349           "Number of retains before optimization");
350 STATISTIC(NumReleasesBeforeOpt,
351           "Number of releases before optimization");
352 STATISTIC(NumRetainsAfterOpt,
353           "Number of retains after optimization");
354 STATISTIC(NumReleasesAfterOpt,
355           "Number of releases after optimization");
356 #endif
357
358 namespace {
359   /// \enum Sequence
360   ///
361   /// \brief A sequence of states that a pointer may go through in which an
362   /// objc_retain and objc_release are actually needed.
363   enum Sequence {
364     S_None,
365     S_Retain,         ///< objc_retain(x).
366     S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement.
367     S_Use,            ///< any use of x.
368     S_Stop,           ///< like S_Release, but code motion is stopped.
369     S_Release,        ///< objc_release(x).
370     S_MovableRelease  ///< objc_release(x), !clang.imprecise_release.
371   };
372
373   raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374     LLVM_ATTRIBUTE_UNUSED;
375   raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
376     switch (S) {
377     case S_None:
378       return OS << "S_None";
379     case S_Retain:
380       return OS << "S_Retain";
381     case S_CanRelease:
382       return OS << "S_CanRelease";
383     case S_Use:
384       return OS << "S_Use";
385     case S_Release:
386       return OS << "S_Release";
387     case S_MovableRelease:
388       return OS << "S_MovableRelease";
389     case S_Stop:
390       return OS << "S_Stop";
391     }
392     llvm_unreachable("Unknown sequence type.");
393   }
394 }
395
396 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
397   // The easy cases.
398   if (A == B)
399     return A;
400   if (A == S_None || B == S_None)
401     return S_None;
402
403   if (A > B) std::swap(A, B);
404   if (TopDown) {
405     // Choose the side which is further along in the sequence.
406     if ((A == S_Retain || A == S_CanRelease) &&
407         (B == S_CanRelease || B == S_Use))
408       return B;
409   } else {
410     // Choose the side which is further along in the sequence.
411     if ((A == S_Use || A == S_CanRelease) &&
412         (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
413       return A;
414     // If both sides are releases, choose the more conservative one.
415     if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
416       return A;
417     if (A == S_Release && B == S_MovableRelease)
418       return A;
419   }
420
421   return S_None;
422 }
423
424 namespace {
425   /// \brief Unidirectional information about either a
426   /// retain-decrement-use-release sequence or release-use-decrement-retain
427   /// reverse sequence.
428   struct RRInfo {
429     /// After an objc_retain, the reference count of the referenced
430     /// object is known to be positive. Similarly, before an objc_release, the
431     /// reference count of the referenced object is known to be positive. If
432     /// there are retain-release pairs in code regions where the retain count
433     /// is known to be positive, they can be eliminated, regardless of any side
434     /// effects between them.
435     ///
436     /// Also, a retain+release pair nested within another retain+release
437     /// pair all on the known same pointer value can be eliminated, regardless
438     /// of any intervening side effects.
439     ///
440     /// KnownSafe is true when either of these conditions is satisfied.
441     bool KnownSafe;
442
443     /// True of the objc_release calls are all marked with the "tail" keyword.
444     bool IsTailCallRelease;
445
446     /// If the Calls are objc_release calls and they all have a
447     /// clang.imprecise_release tag, this is the metadata tag.
448     MDNode *ReleaseMetadata;
449
450     /// For a top-down sequence, the set of objc_retains or
451     /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452     SmallPtrSet<Instruction *, 2> Calls;
453
454     /// The set of optimal insert positions for moving calls in the opposite
455     /// sequence.
456     SmallPtrSet<Instruction *, 2> ReverseInsertPts;
457
458     /// If this is true, we cannot perform code motion but can still remove
459     /// retain/release pairs.
460     bool CFGHazardAfflicted;
461
462     RRInfo() :
463       KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464       CFGHazardAfflicted(false) {}
465
466     void clear();
467
468     /// Conservatively merge the two RRInfo. Returns true if a partial merge has
469     /// occured, false otherwise.
470     bool Merge(const RRInfo &Other);
471
472     bool IsTrackingImpreciseReleases() {
473       return ReleaseMetadata != 0;
474     }
475   };
476 }
477
478 void RRInfo::clear() {
479   KnownSafe = false;
480   IsTailCallRelease = false;
481   ReleaseMetadata = 0;
482   Calls.clear();
483   ReverseInsertPts.clear();
484   CFGHazardAfflicted = false;
485 }
486
487 bool RRInfo::Merge(const RRInfo &Other) {
488     // Conservatively merge the ReleaseMetadata information.
489     if (ReleaseMetadata != Other.ReleaseMetadata)
490       ReleaseMetadata = 0;
491
492     // Conservatively merge the boolean state.
493     KnownSafe &= Other.KnownSafe;
494     IsTailCallRelease &= Other.IsTailCallRelease;
495     CFGHazardAfflicted |= Other.CFGHazardAfflicted;
496
497     // Merge the call sets.
498     Calls.insert(Other.Calls.begin(), Other.Calls.end());
499
500     // Merge the insert point sets. If there are any differences,
501     // that makes this a partial merge.
502     bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
503     for (SmallPtrSet<Instruction *, 2>::const_iterator
504          I = Other.ReverseInsertPts.begin(),
505          E = Other.ReverseInsertPts.end(); I != E; ++I)
506       Partial |= ReverseInsertPts.insert(*I);
507     return Partial;
508 }
509
510 namespace {
511   /// \brief This class summarizes several per-pointer runtime properties which
512   /// are propogated through the flow graph.
513   class PtrState {
514     /// True if the reference count is known to be incremented.
515     bool KnownPositiveRefCount;
516
517     /// True if we've seen an opportunity for partial RR elimination, such as
518     /// pushing calls into a CFG triangle or into one side of a CFG diamond.
519     bool Partial;
520
521     /// The current position in the sequence.
522     Sequence Seq : 8;
523
524   public:
525     /// Unidirectional information about the current sequence.
526     ///
527     /// TODO: Encapsulate this better.
528     RRInfo RRI;
529
530     PtrState() : KnownPositiveRefCount(false), Partial(false),
531                  Seq(S_None) {}
532
533     void SetKnownPositiveRefCount() {
534       DEBUG(dbgs() << "Setting Known Positive.\n");
535       KnownPositiveRefCount = true;
536     }
537
538     void ClearKnownPositiveRefCount() {
539       DEBUG(dbgs() << "Clearing Known Positive.\n");
540       KnownPositiveRefCount = false;
541     }
542
543     bool HasKnownPositiveRefCount() const {
544       return KnownPositiveRefCount;
545     }
546
547     void SetSeq(Sequence NewSeq) {
548       DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
549       Seq = NewSeq;
550     }
551
552     Sequence GetSeq() const {
553       return Seq;
554     }
555
556     void ClearSequenceProgress() {
557       ResetSequenceProgress(S_None);
558     }
559
560     void ResetSequenceProgress(Sequence NewSeq) {
561       DEBUG(dbgs() << "Resetting sequence progress.\n");
562       SetSeq(NewSeq);
563       Partial = false;
564       RRI.clear();
565     }
566
567     void Merge(const PtrState &Other, bool TopDown);
568   };
569 }
570
571 void
572 PtrState::Merge(const PtrState &Other, bool TopDown) {
573   Seq = MergeSeqs(Seq, Other.Seq, TopDown);
574   KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
575
576   // If we're not in a sequence (anymore), drop all associated state.
577   if (Seq == S_None) {
578     Partial = false;
579     RRI.clear();
580   } else if (Partial || Other.Partial) {
581     // If we're doing a merge on a path that's previously seen a partial
582     // merge, conservatively drop the sequence, to avoid doing partial
583     // RR elimination. If the branch predicates for the two merge differ,
584     // mixing them is unsafe.
585     ClearSequenceProgress();
586   } else {
587     Partial = RRI.Merge(Other.RRI);
588   }
589 }
590
591 namespace {
592   /// \brief Per-BasicBlock state.
593   class BBState {
594     /// The number of unique control paths from the entry which can reach this
595     /// block.
596     unsigned TopDownPathCount;
597
598     /// The number of unique control paths to exits from this block.
599     unsigned BottomUpPathCount;
600
601     /// A type for PerPtrTopDown and PerPtrBottomUp.
602     typedef MapVector<const Value *, PtrState> MapTy;
603
604     /// The top-down traversal uses this to record information known about a
605     /// pointer at the bottom of each block.
606     MapTy PerPtrTopDown;
607
608     /// The bottom-up traversal uses this to record information known about a
609     /// pointer at the top of each block.
610     MapTy PerPtrBottomUp;
611
612     /// Effective predecessors of the current block ignoring ignorable edges and
613     /// ignored backedges.
614     SmallVector<BasicBlock *, 2> Preds;
615     /// Effective successors of the current block ignoring ignorable edges and
616     /// ignored backedges.
617     SmallVector<BasicBlock *, 2> Succs;
618
619   public:
620     BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
621
622     typedef MapTy::iterator ptr_iterator;
623     typedef MapTy::const_iterator ptr_const_iterator;
624
625     ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
626     ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
627     ptr_const_iterator top_down_ptr_begin() const {
628       return PerPtrTopDown.begin();
629     }
630     ptr_const_iterator top_down_ptr_end() const {
631       return PerPtrTopDown.end();
632     }
633
634     ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
635     ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
636     ptr_const_iterator bottom_up_ptr_begin() const {
637       return PerPtrBottomUp.begin();
638     }
639     ptr_const_iterator bottom_up_ptr_end() const {
640       return PerPtrBottomUp.end();
641     }
642
643     /// Mark this block as being an entry block, which has one path from the
644     /// entry by definition.
645     void SetAsEntry() { TopDownPathCount = 1; }
646
647     /// Mark this block as being an exit block, which has one path to an exit by
648     /// definition.
649     void SetAsExit()  { BottomUpPathCount = 1; }
650
651     /// Attempt to find the PtrState object describing the top down state for
652     /// pointer Arg. Return a new initialized PtrState describing the top down
653     /// state for Arg if we do not find one.
654     PtrState &getPtrTopDownState(const Value *Arg) {
655       return PerPtrTopDown[Arg];
656     }
657
658     /// Attempt to find the PtrState object describing the bottom up state for
659     /// pointer Arg. Return a new initialized PtrState describing the bottom up
660     /// state for Arg if we do not find one.
661     PtrState &getPtrBottomUpState(const Value *Arg) {
662       return PerPtrBottomUp[Arg];
663     }
664
665     /// Attempt to find the PtrState object describing the bottom up state for
666     /// pointer Arg.
667     ptr_iterator findPtrBottomUpState(const Value *Arg) {
668       return PerPtrBottomUp.find(Arg);
669     }
670
671     void clearBottomUpPointers() {
672       PerPtrBottomUp.clear();
673     }
674
675     void clearTopDownPointers() {
676       PerPtrTopDown.clear();
677     }
678
679     void InitFromPred(const BBState &Other);
680     void InitFromSucc(const BBState &Other);
681     void MergePred(const BBState &Other);
682     void MergeSucc(const BBState &Other);
683
684     /// Compute the number of possible unique paths from an entry to an exit
685     /// which pass through this block. This is only valid after both the
686     /// top-down and bottom-up traversals are complete.
687     ///
688     /// Returns true if overflow occured. Returns false if overflow did not
689     /// occur.
690     bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
691       assert(TopDownPathCount != 0);
692       assert(BottomUpPathCount != 0);
693       unsigned long long Product =
694         (unsigned long long)TopDownPathCount*BottomUpPathCount;
695       PathCount = Product;
696       // Overflow occured if any of the upper bits of Product are set.
697       return Product >> 32;
698     }
699
700     // Specialized CFG utilities.
701     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
702     edge_iterator pred_begin() { return Preds.begin(); }
703     edge_iterator pred_end() { return Preds.end(); }
704     edge_iterator succ_begin() { return Succs.begin(); }
705     edge_iterator succ_end() { return Succs.end(); }
706
707     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
708     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
709
710     bool isExit() const { return Succs.empty(); }
711   };
712 }
713
714 void BBState::InitFromPred(const BBState &Other) {
715   PerPtrTopDown = Other.PerPtrTopDown;
716   TopDownPathCount = Other.TopDownPathCount;
717 }
718
719 void BBState::InitFromSucc(const BBState &Other) {
720   PerPtrBottomUp = Other.PerPtrBottomUp;
721   BottomUpPathCount = Other.BottomUpPathCount;
722 }
723
724 /// The top-down traversal uses this to merge information about predecessors to
725 /// form the initial state for a new block.
726 void BBState::MergePred(const BBState &Other) {
727   // Other.TopDownPathCount can be 0, in which case it is either dead or a
728   // loop backedge. Loop backedges are special.
729   TopDownPathCount += Other.TopDownPathCount;
730
731   // Check for overflow. If we have overflow, fall back to conservative
732   // behavior.
733   if (TopDownPathCount < Other.TopDownPathCount) {
734     clearTopDownPointers();
735     return;
736   }
737
738   // For each entry in the other set, if our set has an entry with the same key,
739   // merge the entries. Otherwise, copy the entry and merge it with an empty
740   // entry.
741   for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
742        ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
743     std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
744     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
745                              /*TopDown=*/true);
746   }
747
748   // For each entry in our set, if the other set doesn't have an entry with the
749   // same key, force it to merge with an empty entry.
750   for (ptr_iterator MI = top_down_ptr_begin(),
751        ME = top_down_ptr_end(); MI != ME; ++MI)
752     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
753       MI->second.Merge(PtrState(), /*TopDown=*/true);
754 }
755
756 /// The bottom-up traversal uses this to merge information about successors to
757 /// form the initial state for a new block.
758 void BBState::MergeSucc(const BBState &Other) {
759   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
760   // loop backedge. Loop backedges are special.
761   BottomUpPathCount += Other.BottomUpPathCount;
762
763   // Check for overflow. If we have overflow, fall back to conservative
764   // behavior.
765   if (BottomUpPathCount < Other.BottomUpPathCount) {
766     clearBottomUpPointers();
767     return;
768   }
769
770   // For each entry in the other set, if our set has an entry with the
771   // same key, merge the entries. Otherwise, copy the entry and merge
772   // it with an empty entry.
773   for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
774        ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
775     std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
776     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
777                              /*TopDown=*/false);
778   }
779
780   // For each entry in our set, if the other set doesn't have an entry
781   // with the same key, force it to merge with an empty entry.
782   for (ptr_iterator MI = bottom_up_ptr_begin(),
783        ME = bottom_up_ptr_end(); MI != ME; ++MI)
784     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
785       MI->second.Merge(PtrState(), /*TopDown=*/false);
786 }
787
788 // Only enable ARC Annotations if we are building a debug version of
789 // libObjCARCOpts.
790 #ifndef NDEBUG
791 #define ARC_ANNOTATIONS
792 #endif
793
794 // Define some macros along the lines of DEBUG and some helper functions to make
795 // it cleaner to create annotations in the source code and to no-op when not
796 // building in debug mode.
797 #ifdef ARC_ANNOTATIONS
798
799 #include "llvm/Support/CommandLine.h"
800
801 /// Enable/disable ARC sequence annotations.
802 static cl::opt<bool>
803 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
804                      cl::desc("Enable emission of arc data flow analysis "
805                               "annotations"));
806 static cl::opt<bool>
807 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
808                           cl::desc("Disable check for cfg hazards when "
809                                    "annotating"));
810 static cl::opt<std::string>
811 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
812                               cl::init(""),
813                               cl::desc("filter out all data flow annotations "
814                                        "but those that apply to the given "
815                                        "target llvm identifier."));
816
817 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
818 /// instruction so that we can track backwards when post processing via the llvm
819 /// arc annotation processor tool. If the function is an
820 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
821                                          Value *Ptr) {
822   MDString *Hash = 0;
823
824   // If pointer is a result of an instruction and it does not have a source
825   // MDNode it, attach a new MDNode onto it. If pointer is a result of
826   // an instruction and does have a source MDNode attached to it, return a
827   // reference to said Node. Otherwise just return 0.
828   if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
829     MDNode *Node;
830     if (!(Node = Inst->getMetadata(NodeId))) {
831       // We do not have any node. Generate and attatch the hash MDString to the
832       // instruction.
833
834       // We just use an MDString to ensure that this metadata gets written out
835       // of line at the module level and to provide a very simple format
836       // encoding the information herein. Both of these makes it simpler to
837       // parse the annotations by a simple external program.
838       std::string Str;
839       raw_string_ostream os(Str);
840       os << "(" << Inst->getParent()->getParent()->getName() << ",%"
841          << Inst->getName() << ")";
842
843       Hash = MDString::get(Inst->getContext(), os.str());
844       Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
845     } else {
846       // We have a node. Grab its hash and return it.
847       assert(Node->getNumOperands() == 1 &&
848         "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
849       Hash = cast<MDString>(Node->getOperand(0));
850     }
851   } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
852     std::string str;
853     raw_string_ostream os(str);
854     os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
855        << ")";
856     Hash = MDString::get(Arg->getContext(), os.str());
857   }
858
859   return Hash;
860 }
861
862 static std::string SequenceToString(Sequence A) {
863   std::string str;
864   raw_string_ostream os(str);
865   os << A;
866   return os.str();
867 }
868
869 /// Helper function to change a Sequence into a String object using our overload
870 /// for raw_ostream so we only have printing code in one location.
871 static MDString *SequenceToMDString(LLVMContext &Context,
872                                     Sequence A) {
873   return MDString::get(Context, SequenceToString(A));
874 }
875
876 /// A simple function to generate a MDNode which describes the change in state
877 /// for Value *Ptr caused by Instruction *Inst.
878 static void AppendMDNodeToInstForPtr(unsigned NodeId,
879                                      Instruction *Inst,
880                                      Value *Ptr,
881                                      MDString *PtrSourceMDNodeID,
882                                      Sequence OldSeq,
883                                      Sequence NewSeq) {
884   MDNode *Node = 0;
885   Value *tmp[3] = {PtrSourceMDNodeID,
886                    SequenceToMDString(Inst->getContext(),
887                                       OldSeq),
888                    SequenceToMDString(Inst->getContext(),
889                                       NewSeq)};
890   Node = MDNode::get(Inst->getContext(),
891                      ArrayRef<Value*>(tmp, 3));
892
893   Inst->setMetadata(NodeId, Node);
894 }
895
896 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
897 /// state of a pointer at the entrance to a basic block.
898 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
899                                             Value *Ptr, Sequence Seq) {
900   // If we have a target identifier, make sure that we match it before
901   // continuing.
902   if(!ARCAnnotationTargetIdentifier.empty() &&
903      !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
904     return;
905
906   Module *M = BB->getParent()->getParent();
907   LLVMContext &C = M->getContext();
908   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
909   Type *I8XX = PointerType::getUnqual(I8X);
910   Type *Params[] = {I8XX, I8XX};
911   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
912                                         ArrayRef<Type*>(Params, 2),
913                                         /*isVarArg=*/false);
914   Constant *Callee = M->getOrInsertFunction(Name, FTy);
915
916   IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
917
918   Value *PtrName;
919   StringRef Tmp = Ptr->getName();
920   if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
921     Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
922                                                          Tmp + "_STR");
923     PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
924                                  cast<Constant>(ActualPtrName), Tmp);
925   }
926
927   Value *S;
928   std::string SeqStr = SequenceToString(Seq);
929   if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
930     Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
931                                                          SeqStr + "_STR");
932     S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
933                            cast<Constant>(ActualPtrName), SeqStr);
934   }
935
936   Builder.CreateCall2(Callee, PtrName, S);
937 }
938
939 /// Add to the end of the basic block llvm.ptr.annotations which show the state
940 /// of the pointer at the bottom of the basic block.
941 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
942                                               Value *Ptr, Sequence Seq) {
943   // If we have a target identifier, make sure that we match it before emitting
944   // an annotation.
945   if(!ARCAnnotationTargetIdentifier.empty() &&
946      !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
947     return;
948
949   Module *M = BB->getParent()->getParent();
950   LLVMContext &C = M->getContext();
951   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
952   Type *I8XX = PointerType::getUnqual(I8X);
953   Type *Params[] = {I8XX, I8XX};
954   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
955                                         ArrayRef<Type*>(Params, 2),
956                                         /*isVarArg=*/false);
957   Constant *Callee = M->getOrInsertFunction(Name, FTy);
958
959   IRBuilder<> Builder(BB, llvm::prior(BB->end()));
960
961   Value *PtrName;
962   StringRef Tmp = Ptr->getName();
963   if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
964     Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
965                                                          Tmp + "_STR");
966     PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
967                                  cast<Constant>(ActualPtrName), Tmp);
968   }
969
970   Value *S;
971   std::string SeqStr = SequenceToString(Seq);
972   if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
973     Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
974                                                          SeqStr + "_STR");
975     S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
976                            cast<Constant>(ActualPtrName), SeqStr);
977   }
978   Builder.CreateCall2(Callee, PtrName, S);
979 }
980
981 /// Adds a source annotation to pointer and a state change annotation to Inst
982 /// referencing the source annotation and the old/new state of pointer.
983 static void GenerateARCAnnotation(unsigned InstMDId,
984                                   unsigned PtrMDId,
985                                   Instruction *Inst,
986                                   Value *Ptr,
987                                   Sequence OldSeq,
988                                   Sequence NewSeq) {
989   if (EnableARCAnnotations) {
990     // If we have a target identifier, make sure that we match it before
991     // emitting an annotation.
992     if(!ARCAnnotationTargetIdentifier.empty() &&
993        !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
994       return;
995
996     // First generate the source annotation on our pointer. This will return an
997     // MDString* if Ptr actually comes from an instruction implying we can put
998     // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
999     // then we know that our pointer is from an Argument so we put a reference
1000     // to the argument number.
1001     //
1002     // The point of this is to make it easy for the
1003     // llvm-arc-annotation-processor tool to cross reference where the source
1004     // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1005     // information via debug info for backends to use (since why would anyone
1006     // need such a thing from LLVM IR besides in non standard cases
1007     // [i.e. this]).
1008     MDString *SourcePtrMDNode =
1009       AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1010     AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1011                              NewSeq);
1012   }
1013 }
1014
1015 // The actual interface for accessing the above functionality is defined via
1016 // some simple macros which are defined below. We do this so that the user does
1017 // not need to pass in what metadata id is needed resulting in cleaner code and
1018 // additionally since it provides an easy way to conditionally no-op all
1019 // annotation support in a non-debug build.
1020
1021 /// Use this macro to annotate a sequence state change when processing
1022 /// instructions bottom up,
1023 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)                          \
1024   GenerateARCAnnotation(ARCAnnotationBottomUpMDKind,                    \
1025                         ARCAnnotationProvenanceSourceMDKind, (inst),    \
1026                         const_cast<Value*>(ptr), (old), (new))
1027 /// Use this macro to annotate a sequence state change when processing
1028 /// instructions top down.
1029 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)                           \
1030   GenerateARCAnnotation(ARCAnnotationTopDownMDKind,                     \
1031                         ARCAnnotationProvenanceSourceMDKind, (inst),    \
1032                         const_cast<Value*>(ptr), (old), (new))
1033
1034 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction)                   \
1035   do {                                                                        \
1036     if (EnableARCAnnotations) {                                               \
1037       for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1038           E = (_states)._direction##_ptr_end(); I != E; ++I) {                \
1039         Value *Ptr = const_cast<Value*>(I->first);                            \
1040         Sequence Seq = I->second.GetSeq();                                    \
1041         GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq);         \
1042       }                                                                       \
1043     }                                                                         \
1044   } while (0)
1045
1046 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock)                       \
1047     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1048                 Entrance, bottom_up)
1049 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock)                         \
1050     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend",   \
1051                 Terminator, bottom_up)
1052 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock)                        \
1053     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart",  \
1054                 Entrance, top_down)
1055 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock)                          \
1056     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend",    \
1057                 Terminator, top_down)
1058
1059 #else // !ARC_ANNOTATION
1060 // If annotations are off, noop.
1061 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1062 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1063 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1064 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1065 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1066 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1067 #endif // !ARC_ANNOTATION
1068
1069 namespace {
1070   /// \brief The main ARC optimization pass.
1071   class ObjCARCOpt : public FunctionPass {
1072     bool Changed;
1073     ProvenanceAnalysis PA;
1074
1075     // This is used to track if a pointer is stored into an alloca.
1076     DenseSet<const Value *> MultiOwnersSet;
1077
1078     /// A flag indicating whether this optimization pass should run.
1079     bool Run;
1080
1081     /// Declarations for ObjC runtime functions, for use in creating calls to
1082     /// them. These are initialized lazily to avoid cluttering up the Module
1083     /// with unused declarations.
1084
1085     /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1086     Constant *AutoreleaseRVCallee;
1087     /// Declaration for ObjC runtime function objc_release.
1088     Constant *ReleaseCallee;
1089     /// Declaration for ObjC runtime function objc_retain.
1090     Constant *RetainCallee;
1091     /// Declaration for ObjC runtime function objc_retainBlock.
1092     Constant *RetainBlockCallee;
1093     /// Declaration for ObjC runtime function objc_autorelease.
1094     Constant *AutoreleaseCallee;
1095
1096     /// Flags which determine whether each of the interesting runtine functions
1097     /// is in fact used in the current function.
1098     unsigned UsedInThisFunction;
1099
1100     /// The Metadata Kind for clang.imprecise_release metadata.
1101     unsigned ImpreciseReleaseMDKind;
1102
1103     /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1104     unsigned CopyOnEscapeMDKind;
1105
1106     /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1107     unsigned NoObjCARCExceptionsMDKind;
1108
1109 #ifdef ARC_ANNOTATIONS
1110     /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1111     unsigned ARCAnnotationBottomUpMDKind;
1112     /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1113     unsigned ARCAnnotationTopDownMDKind;
1114     /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1115     unsigned ARCAnnotationProvenanceSourceMDKind;
1116 #endif // ARC_ANNOATIONS
1117
1118     Constant *getAutoreleaseRVCallee(Module *M);
1119     Constant *getReleaseCallee(Module *M);
1120     Constant *getRetainCallee(Module *M);
1121     Constant *getRetainBlockCallee(Module *M);
1122     Constant *getAutoreleaseCallee(Module *M);
1123
1124     bool IsRetainBlockOptimizable(const Instruction *Inst);
1125
1126     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1127     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1128                                    InstructionClass &Class);
1129     bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1130                                  InstructionClass &Class);
1131     void OptimizeIndividualCalls(Function &F);
1132
1133     void CheckForCFGHazards(const BasicBlock *BB,
1134                             DenseMap<const BasicBlock *, BBState> &BBStates,
1135                             BBState &MyStates) const;
1136     bool VisitInstructionBottomUp(Instruction *Inst,
1137                                   BasicBlock *BB,
1138                                   MapVector<Value *, RRInfo> &Retains,
1139                                   BBState &MyStates);
1140     bool VisitBottomUp(BasicBlock *BB,
1141                        DenseMap<const BasicBlock *, BBState> &BBStates,
1142                        MapVector<Value *, RRInfo> &Retains);
1143     bool VisitInstructionTopDown(Instruction *Inst,
1144                                  DenseMap<Value *, RRInfo> &Releases,
1145                                  BBState &MyStates);
1146     bool VisitTopDown(BasicBlock *BB,
1147                       DenseMap<const BasicBlock *, BBState> &BBStates,
1148                       DenseMap<Value *, RRInfo> &Releases);
1149     bool Visit(Function &F,
1150                DenseMap<const BasicBlock *, BBState> &BBStates,
1151                MapVector<Value *, RRInfo> &Retains,
1152                DenseMap<Value *, RRInfo> &Releases);
1153
1154     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1155                    MapVector<Value *, RRInfo> &Retains,
1156                    DenseMap<Value *, RRInfo> &Releases,
1157                    SmallVectorImpl<Instruction *> &DeadInsts,
1158                    Module *M);
1159
1160     bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1161                                MapVector<Value *, RRInfo> &Retains,
1162                                DenseMap<Value *, RRInfo> &Releases,
1163                                Module *M,
1164                                SmallVector<Instruction *, 4> &NewRetains,
1165                                SmallVector<Instruction *, 4> &NewReleases,
1166                                SmallVector<Instruction *, 8> &DeadInsts,
1167                                RRInfo &RetainsToMove,
1168                                RRInfo &ReleasesToMove,
1169                                Value *Arg,
1170                                bool KnownSafe,
1171                                bool &AnyPairsCompletelyEliminated);
1172
1173     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1174                               MapVector<Value *, RRInfo> &Retains,
1175                               DenseMap<Value *, RRInfo> &Releases,
1176                               Module *M);
1177
1178     void OptimizeWeakCalls(Function &F);
1179
1180     bool OptimizeSequences(Function &F);
1181
1182     void OptimizeReturns(Function &F);
1183
1184 #ifndef NDEBUG
1185     void GatherStatistics(Function &F, bool AfterOptimization = false);
1186 #endif
1187
1188     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1189     virtual bool doInitialization(Module &M);
1190     virtual bool runOnFunction(Function &F);
1191     virtual void releaseMemory();
1192
1193   public:
1194     static char ID;
1195     ObjCARCOpt() : FunctionPass(ID) {
1196       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1197     }
1198   };
1199 }
1200
1201 char ObjCARCOpt::ID = 0;
1202 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1203                       "objc-arc", "ObjC ARC optimization", false, false)
1204 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1205 INITIALIZE_PASS_END(ObjCARCOpt,
1206                     "objc-arc", "ObjC ARC optimization", false, false)
1207
1208 Pass *llvm::createObjCARCOptPass() {
1209   return new ObjCARCOpt();
1210 }
1211
1212 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1213   AU.addRequired<ObjCARCAliasAnalysis>();
1214   AU.addRequired<AliasAnalysis>();
1215   // ARC optimization doesn't currently split critical edges.
1216   AU.setPreservesCFG();
1217 }
1218
1219 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1220   // Without the magic metadata tag, we have to assume this might be an
1221   // objc_retainBlock call inserted to convert a block pointer to an id,
1222   // in which case it really is needed.
1223   if (!Inst->getMetadata(CopyOnEscapeMDKind))
1224     return false;
1225
1226   // If the pointer "escapes" (not including being used in a call),
1227   // the copy may be needed.
1228   if (DoesRetainableObjPtrEscape(Inst))
1229     return false;
1230
1231   // Otherwise, it's not needed.
1232   return true;
1233 }
1234
1235 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1236   if (!AutoreleaseRVCallee) {
1237     LLVMContext &C = M->getContext();
1238     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1239     Type *Params[] = { I8X };
1240     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1241     AttributeSet Attribute =
1242       AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1243                                   Attribute::NoUnwind);
1244     AutoreleaseRVCallee =
1245       M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1246                              Attribute);
1247   }
1248   return AutoreleaseRVCallee;
1249 }
1250
1251 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1252   if (!ReleaseCallee) {
1253     LLVMContext &C = M->getContext();
1254     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1255     AttributeSet Attribute =
1256       AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1257                                   Attribute::NoUnwind);
1258     ReleaseCallee =
1259       M->getOrInsertFunction(
1260         "objc_release",
1261         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1262         Attribute);
1263   }
1264   return ReleaseCallee;
1265 }
1266
1267 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1268   if (!RetainCallee) {
1269     LLVMContext &C = M->getContext();
1270     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1271     AttributeSet Attribute =
1272       AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1273                                   Attribute::NoUnwind);
1274     RetainCallee =
1275       M->getOrInsertFunction(
1276         "objc_retain",
1277         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1278         Attribute);
1279   }
1280   return RetainCallee;
1281 }
1282
1283 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1284   if (!RetainBlockCallee) {
1285     LLVMContext &C = M->getContext();
1286     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1287     // objc_retainBlock is not nounwind because it calls user copy constructors
1288     // which could theoretically throw.
1289     RetainBlockCallee =
1290       M->getOrInsertFunction(
1291         "objc_retainBlock",
1292         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1293         AttributeSet());
1294   }
1295   return RetainBlockCallee;
1296 }
1297
1298 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1299   if (!AutoreleaseCallee) {
1300     LLVMContext &C = M->getContext();
1301     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1302     AttributeSet Attribute =
1303       AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1304                                   Attribute::NoUnwind);
1305     AutoreleaseCallee =
1306       M->getOrInsertFunction(
1307         "objc_autorelease",
1308         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1309         Attribute);
1310   }
1311   return AutoreleaseCallee;
1312 }
1313
1314 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1315 /// not a return value.  Or, if it can be paired with an
1316 /// objc_autoreleaseReturnValue, delete the pair and return true.
1317 bool
1318 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1319   // Check for the argument being from an immediately preceding call or invoke.
1320   const Value *Arg = GetObjCArg(RetainRV);
1321   ImmutableCallSite CS(Arg);
1322   if (const Instruction *Call = CS.getInstruction()) {
1323     if (Call->getParent() == RetainRV->getParent()) {
1324       BasicBlock::const_iterator I = Call;
1325       ++I;
1326       while (IsNoopInstruction(I)) ++I;
1327       if (&*I == RetainRV)
1328         return false;
1329     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1330       BasicBlock *RetainRVParent = RetainRV->getParent();
1331       if (II->getNormalDest() == RetainRVParent) {
1332         BasicBlock::const_iterator I = RetainRVParent->begin();
1333         while (IsNoopInstruction(I)) ++I;
1334         if (&*I == RetainRV)
1335           return false;
1336       }
1337     }
1338   }
1339
1340   // Check for being preceded by an objc_autoreleaseReturnValue on the same
1341   // pointer. In this case, we can delete the pair.
1342   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1343   if (I != Begin) {
1344     do --I; while (I != Begin && IsNoopInstruction(I));
1345     if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1346         GetObjCArg(I) == Arg) {
1347       Changed = true;
1348       ++NumPeeps;
1349
1350       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1351                    << "Erasing " << *RetainRV << "\n");
1352
1353       EraseInstruction(I);
1354       EraseInstruction(RetainRV);
1355       return true;
1356     }
1357   }
1358
1359   // Turn it to a plain objc_retain.
1360   Changed = true;
1361   ++NumPeeps;
1362
1363   DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1364                   "objc_retain since the operand is not a return value.\n"
1365                   "Old = " << *RetainRV << "\n");
1366
1367   cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1368
1369   DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1370
1371   return false;
1372 }
1373
1374 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1375 /// used as a return value.
1376 void
1377 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1378                                       InstructionClass &Class) {
1379   // Check for a return of the pointer value.
1380   const Value *Ptr = GetObjCArg(AutoreleaseRV);
1381   SmallVector<const Value *, 2> Users;
1382   Users.push_back(Ptr);
1383   do {
1384     Ptr = Users.pop_back_val();
1385     for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1386          UI != UE; ++UI) {
1387       const User *I = *UI;
1388       if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1389         return;
1390       if (isa<BitCastInst>(I))
1391         Users.push_back(I);
1392     }
1393   } while (!Users.empty());
1394
1395   Changed = true;
1396   ++NumPeeps;
1397
1398   DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1399                   "objc_autorelease since its operand is not used as a return "
1400                   "value.\n"
1401                   "Old = " << *AutoreleaseRV << "\n");
1402
1403   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1404   AutoreleaseRVCI->
1405     setCalledFunction(getAutoreleaseCallee(F.getParent()));
1406   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1407   Class = IC_Autorelease;
1408
1409   DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1410
1411 }
1412
1413 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1414 // calls.
1415 //
1416 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1417 // does not escape (following the rules of block escaping), strength reduce the
1418 // objc_retainBlock to an objc_retain.
1419 //
1420 // TODO: If an objc_retainBlock call is dominated period by a previous
1421 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1422 // objc_retain.
1423 bool
1424 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1425                                     InstructionClass &Class) {
1426   assert(GetBasicInstructionClass(Inst) == Class);
1427   assert(IC_RetainBlock == Class);
1428
1429   // If we can not optimize Inst, return false.
1430   if (!IsRetainBlockOptimizable(Inst))
1431     return false;
1432
1433   Changed = true;
1434   ++NumPeeps;
1435
1436   DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1437   DEBUG(dbgs() << "Old: " << *Inst << "\n");
1438   CallInst *RetainBlock = cast<CallInst>(Inst);
1439   RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1440   // Remove copy_on_escape metadata.
1441   RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1442   Class = IC_Retain;
1443   DEBUG(dbgs() << "New: " << *Inst << "\n");
1444   return true;
1445 }
1446
1447 /// Visit each call, one at a time, and make simplifications without doing any
1448 /// additional analysis.
1449 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1450   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1451   // Reset all the flags in preparation for recomputing them.
1452   UsedInThisFunction = 0;
1453
1454   // Visit all objc_* calls in F.
1455   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1456     Instruction *Inst = &*I++;
1457
1458     InstructionClass Class = GetBasicInstructionClass(Inst);
1459
1460     DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1461
1462     switch (Class) {
1463     default: break;
1464
1465     // Delete no-op casts. These function calls have special semantics, but
1466     // the semantics are entirely implemented via lowering in the front-end,
1467     // so by the time they reach the optimizer, they are just no-op calls
1468     // which return their argument.
1469     //
1470     // There are gray areas here, as the ability to cast reference-counted
1471     // pointers to raw void* and back allows code to break ARC assumptions,
1472     // however these are currently considered to be unimportant.
1473     case IC_NoopCast:
1474       Changed = true;
1475       ++NumNoops;
1476       DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1477       EraseInstruction(Inst);
1478       continue;
1479
1480     // If the pointer-to-weak-pointer is null, it's undefined behavior.
1481     case IC_StoreWeak:
1482     case IC_LoadWeak:
1483     case IC_LoadWeakRetained:
1484     case IC_InitWeak:
1485     case IC_DestroyWeak: {
1486       CallInst *CI = cast<CallInst>(Inst);
1487       if (IsNullOrUndef(CI->getArgOperand(0))) {
1488         Changed = true;
1489         Type *Ty = CI->getArgOperand(0)->getType();
1490         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1491                       Constant::getNullValue(Ty),
1492                       CI);
1493         llvm::Value *NewValue = UndefValue::get(CI->getType());
1494         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1495                        "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1496         CI->replaceAllUsesWith(NewValue);
1497         CI->eraseFromParent();
1498         continue;
1499       }
1500       break;
1501     }
1502     case IC_CopyWeak:
1503     case IC_MoveWeak: {
1504       CallInst *CI = cast<CallInst>(Inst);
1505       if (IsNullOrUndef(CI->getArgOperand(0)) ||
1506           IsNullOrUndef(CI->getArgOperand(1))) {
1507         Changed = true;
1508         Type *Ty = CI->getArgOperand(0)->getType();
1509         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1510                       Constant::getNullValue(Ty),
1511                       CI);
1512
1513         llvm::Value *NewValue = UndefValue::get(CI->getType());
1514         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1515                         "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1516
1517         CI->replaceAllUsesWith(NewValue);
1518         CI->eraseFromParent();
1519         continue;
1520       }
1521       break;
1522     }
1523     case IC_RetainBlock:
1524       // If we strength reduce an objc_retainBlock to an objc_retain, continue
1525       // onto the objc_retain peephole optimizations. Otherwise break.
1526       OptimizeRetainBlockCall(F, Inst, Class);
1527       break;
1528     case IC_RetainRV:
1529       if (OptimizeRetainRVCall(F, Inst))
1530         continue;
1531       break;
1532     case IC_AutoreleaseRV:
1533       OptimizeAutoreleaseRVCall(F, Inst, Class);
1534       break;
1535     }
1536
1537     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1538     if (IsAutorelease(Class) && Inst->use_empty()) {
1539       CallInst *Call = cast<CallInst>(Inst);
1540       const Value *Arg = Call->getArgOperand(0);
1541       Arg = FindSingleUseIdentifiedObject(Arg);
1542       if (Arg) {
1543         Changed = true;
1544         ++NumAutoreleases;
1545
1546         // Create the declaration lazily.
1547         LLVMContext &C = Inst->getContext();
1548         CallInst *NewCall =
1549           CallInst::Create(getReleaseCallee(F.getParent()),
1550                            Call->getArgOperand(0), "", Call);
1551         NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1552
1553         DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1554               "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1555               << *NewCall << "\n");
1556
1557         EraseInstruction(Call);
1558         Inst = NewCall;
1559         Class = IC_Release;
1560       }
1561     }
1562
1563     // For functions which can never be passed stack arguments, add
1564     // a tail keyword.
1565     if (IsAlwaysTail(Class)) {
1566       Changed = true;
1567       DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1568                       "passed stack args: " << *Inst << "\n");
1569       cast<CallInst>(Inst)->setTailCall();
1570     }
1571
1572     // Ensure that functions that can never have a "tail" keyword due to the
1573     // semantics of ARC truly do not do so.
1574     if (IsNeverTail(Class)) {
1575       Changed = true;
1576       DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1577             "\n");
1578       cast<CallInst>(Inst)->setTailCall(false);
1579     }
1580
1581     // Set nounwind as needed.
1582     if (IsNoThrow(Class)) {
1583       Changed = true;
1584       DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1585                    << "\n");
1586       cast<CallInst>(Inst)->setDoesNotThrow();
1587     }
1588
1589     if (!IsNoopOnNull(Class)) {
1590       UsedInThisFunction |= 1 << Class;
1591       continue;
1592     }
1593
1594     const Value *Arg = GetObjCArg(Inst);
1595
1596     // ARC calls with null are no-ops. Delete them.
1597     if (IsNullOrUndef(Arg)) {
1598       Changed = true;
1599       ++NumNoops;
1600       DEBUG(dbgs() << "ARC calls with  null are no-ops. Erasing: " << *Inst
1601             << "\n");
1602       EraseInstruction(Inst);
1603       continue;
1604     }
1605
1606     // Keep track of which of retain, release, autorelease, and retain_block
1607     // are actually present in this function.
1608     UsedInThisFunction |= 1 << Class;
1609
1610     // If Arg is a PHI, and one or more incoming values to the
1611     // PHI are null, and the call is control-equivalent to the PHI, and there
1612     // are no relevant side effects between the PHI and the call, the call
1613     // could be pushed up to just those paths with non-null incoming values.
1614     // For now, don't bother splitting critical edges for this.
1615     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1616     Worklist.push_back(std::make_pair(Inst, Arg));
1617     do {
1618       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1619       Inst = Pair.first;
1620       Arg = Pair.second;
1621
1622       const PHINode *PN = dyn_cast<PHINode>(Arg);
1623       if (!PN) continue;
1624
1625       // Determine if the PHI has any null operands, or any incoming
1626       // critical edges.
1627       bool HasNull = false;
1628       bool HasCriticalEdges = false;
1629       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1630         Value *Incoming =
1631           StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1632         if (IsNullOrUndef(Incoming))
1633           HasNull = true;
1634         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1635                    .getNumSuccessors() != 1) {
1636           HasCriticalEdges = true;
1637           break;
1638         }
1639       }
1640       // If we have null operands and no critical edges, optimize.
1641       if (!HasCriticalEdges && HasNull) {
1642         SmallPtrSet<Instruction *, 4> DependingInstructions;
1643         SmallPtrSet<const BasicBlock *, 4> Visited;
1644
1645         // Check that there is nothing that cares about the reference
1646         // count between the call and the phi.
1647         switch (Class) {
1648         case IC_Retain:
1649         case IC_RetainBlock:
1650           // These can always be moved up.
1651           break;
1652         case IC_Release:
1653           // These can't be moved across things that care about the retain
1654           // count.
1655           FindDependencies(NeedsPositiveRetainCount, Arg,
1656                            Inst->getParent(), Inst,
1657                            DependingInstructions, Visited, PA);
1658           break;
1659         case IC_Autorelease:
1660           // These can't be moved across autorelease pool scope boundaries.
1661           FindDependencies(AutoreleasePoolBoundary, Arg,
1662                            Inst->getParent(), Inst,
1663                            DependingInstructions, Visited, PA);
1664           break;
1665         case IC_RetainRV:
1666         case IC_AutoreleaseRV:
1667           // Don't move these; the RV optimization depends on the autoreleaseRV
1668           // being tail called, and the retainRV being immediately after a call
1669           // (which might still happen if we get lucky with codegen layout, but
1670           // it's not worth taking the chance).
1671           continue;
1672         default:
1673           llvm_unreachable("Invalid dependence flavor");
1674         }
1675
1676         if (DependingInstructions.size() == 1 &&
1677             *DependingInstructions.begin() == PN) {
1678           Changed = true;
1679           ++NumPartialNoops;
1680           // Clone the call into each predecessor that has a non-null value.
1681           CallInst *CInst = cast<CallInst>(Inst);
1682           Type *ParamTy = CInst->getArgOperand(0)->getType();
1683           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1684             Value *Incoming =
1685               StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1686             if (!IsNullOrUndef(Incoming)) {
1687               CallInst *Clone = cast<CallInst>(CInst->clone());
1688               Value *Op = PN->getIncomingValue(i);
1689               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1690               if (Op->getType() != ParamTy)
1691                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1692               Clone->setArgOperand(0, Op);
1693               Clone->insertBefore(InsertPos);
1694
1695               DEBUG(dbgs() << "Cloning "
1696                            << *CInst << "\n"
1697                            "And inserting clone at " << *InsertPos << "\n");
1698               Worklist.push_back(std::make_pair(Clone, Incoming));
1699             }
1700           }
1701           // Erase the original call.
1702           DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1703           EraseInstruction(CInst);
1704           continue;
1705         }
1706       }
1707     } while (!Worklist.empty());
1708   }
1709 }
1710
1711 /// If we have a top down pointer in the S_Use state, make sure that there are
1712 /// no CFG hazards by checking the states of various bottom up pointers.
1713 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1714                                  const bool SuccSRRIKnownSafe,
1715                                  PtrState &S,
1716                                  bool &SomeSuccHasSame,
1717                                  bool &AllSuccsHaveSame,
1718                                  bool &NotAllSeqEqualButKnownSafe,
1719                                  bool &ShouldContinue) {
1720   switch (SuccSSeq) {
1721   case S_CanRelease: {
1722     if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1723       S.ClearSequenceProgress();
1724       break;
1725     }
1726     S.RRI.CFGHazardAfflicted = true;
1727     ShouldContinue = true;
1728     break;
1729   }
1730   case S_Use:
1731     SomeSuccHasSame = true;
1732     break;
1733   case S_Stop:
1734   case S_Release:
1735   case S_MovableRelease:
1736     if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1737       AllSuccsHaveSame = false;
1738     else
1739       NotAllSeqEqualButKnownSafe = true;
1740     break;
1741   case S_Retain:
1742     llvm_unreachable("bottom-up pointer in retain state!");
1743   case S_None:
1744     llvm_unreachable("This should have been handled earlier.");
1745   }
1746 }
1747
1748 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1749 /// there are no CFG hazards by checking the states of various bottom up
1750 /// pointers.
1751 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1752                                         const bool SuccSRRIKnownSafe,
1753                                         PtrState &S,
1754                                         bool &SomeSuccHasSame,
1755                                         bool &AllSuccsHaveSame,
1756                                         bool &NotAllSeqEqualButKnownSafe) {
1757   switch (SuccSSeq) {
1758   case S_CanRelease:
1759     SomeSuccHasSame = true;
1760     break;
1761   case S_Stop:
1762   case S_Release:
1763   case S_MovableRelease:
1764   case S_Use:
1765     if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1766       AllSuccsHaveSame = false;
1767     else
1768       NotAllSeqEqualButKnownSafe = true;
1769     break;
1770   case S_Retain:
1771     llvm_unreachable("bottom-up pointer in retain state!");
1772   case S_None:
1773     llvm_unreachable("This should have been handled earlier.");
1774   }
1775 }
1776
1777 /// Check for critical edges, loop boundaries, irreducible control flow, or
1778 /// other CFG structures where moving code across the edge would result in it
1779 /// being executed more.
1780 void
1781 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1782                                DenseMap<const BasicBlock *, BBState> &BBStates,
1783                                BBState &MyStates) const {
1784   // If any top-down local-use or possible-dec has a succ which is earlier in
1785   // the sequence, forget it.
1786   for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1787          E = MyStates.top_down_ptr_end(); I != E; ++I) {
1788     PtrState &S = I->second;
1789     const Sequence Seq = I->second.GetSeq();
1790
1791     // We only care about S_Retain, S_CanRelease, and S_Use.
1792     if (Seq == S_None)
1793       continue;
1794
1795     // Make sure that if extra top down states are added in the future that this
1796     // code is updated to handle it.
1797     assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1798            "Unknown top down sequence state.");
1799
1800     const Value *Arg = I->first;
1801     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1802     bool SomeSuccHasSame = false;
1803     bool AllSuccsHaveSame = true;
1804     bool NotAllSeqEqualButKnownSafe = false;
1805
1806     succ_const_iterator SI(TI), SE(TI, false);
1807
1808     for (; SI != SE; ++SI) {
1809       // If VisitBottomUp has pointer information for this successor, take
1810       // what we know about it.
1811       const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1812         BBStates.find(*SI);
1813       assert(BBI != BBStates.end());
1814       const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1815       const Sequence SuccSSeq = SuccS.GetSeq();
1816
1817       // If bottom up, the pointer is in an S_None state, clear the sequence
1818       // progress since the sequence in the bottom up state finished
1819       // suggesting a mismatch in between retains/releases. This is true for
1820       // all three cases that we are handling here: S_Retain, S_Use, and
1821       // S_CanRelease.
1822       if (SuccSSeq == S_None) {
1823         S.ClearSequenceProgress();
1824         continue;
1825       }
1826
1827       // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1828       // checks.
1829       const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1830
1831       // *NOTE* We do not use Seq from above here since we are allowing for
1832       // S.GetSeq() to change while we are visiting basic blocks.
1833       switch(S.GetSeq()) {
1834       case S_Use: {
1835         bool ShouldContinue = false;
1836         CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1837                              AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1838                              ShouldContinue);
1839         if (ShouldContinue)
1840           continue;
1841         break;
1842       }
1843       case S_CanRelease: {
1844         CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1845                                     SomeSuccHasSame, AllSuccsHaveSame,
1846                                     NotAllSeqEqualButKnownSafe);
1847         break;
1848       }
1849       case S_Retain:
1850       case S_None:
1851       case S_Stop:
1852       case S_Release:
1853       case S_MovableRelease:
1854         break;
1855       }
1856     }
1857
1858     // If the state at the other end of any of the successor edges
1859     // matches the current state, require all edges to match. This
1860     // guards against loops in the middle of a sequence.
1861     if (SomeSuccHasSame && !AllSuccsHaveSame) {
1862       S.ClearSequenceProgress();
1863     } else if (NotAllSeqEqualButKnownSafe) {
1864       // If we would have cleared the state foregoing the fact that we are known
1865       // safe, stop code motion. This is because whether or not it is safe to
1866       // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1867       // are allowed to perform code motion.
1868       S.RRI.CFGHazardAfflicted = true;
1869     }
1870   }
1871 }
1872
1873 bool
1874 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1875                                      BasicBlock *BB,
1876                                      MapVector<Value *, RRInfo> &Retains,
1877                                      BBState &MyStates) {
1878   bool NestingDetected = false;
1879   InstructionClass Class = GetInstructionClass(Inst);
1880   const Value *Arg = 0;
1881
1882   DEBUG(dbgs() << "Class: " << Class << "\n");
1883
1884   switch (Class) {
1885   case IC_Release: {
1886     Arg = GetObjCArg(Inst);
1887
1888     PtrState &S = MyStates.getPtrBottomUpState(Arg);
1889
1890     // If we see two releases in a row on the same pointer. If so, make
1891     // a note, and we'll cicle back to revisit it after we've
1892     // hopefully eliminated the second release, which may allow us to
1893     // eliminate the first release too.
1894     // Theoretically we could implement removal of nested retain+release
1895     // pairs by making PtrState hold a stack of states, but this is
1896     // simple and avoids adding overhead for the non-nested case.
1897     if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1898       DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1899       NestingDetected = true;
1900     }
1901
1902     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1903     Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1904     ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1905     S.ResetSequenceProgress(NewSeq);
1906     S.RRI.ReleaseMetadata = ReleaseMetadata;
1907     S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1908     S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1909     S.RRI.Calls.insert(Inst);
1910     S.SetKnownPositiveRefCount();
1911     break;
1912   }
1913   case IC_RetainBlock:
1914     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1915     // objc_retainBlocks to objc_retains. Thus at this point any
1916     // objc_retainBlocks that we see are not optimizable.
1917     break;
1918   case IC_Retain:
1919   case IC_RetainRV: {
1920     Arg = GetObjCArg(Inst);
1921
1922     PtrState &S = MyStates.getPtrBottomUpState(Arg);
1923     S.SetKnownPositiveRefCount();
1924
1925     Sequence OldSeq = S.GetSeq();
1926     switch (OldSeq) {
1927     case S_Stop:
1928     case S_Release:
1929     case S_MovableRelease:
1930     case S_Use:
1931       // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1932       // imprecise release, clear our reverse insertion points.
1933       if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1934         S.RRI.ReverseInsertPts.clear();
1935       // FALL THROUGH
1936     case S_CanRelease:
1937       // Don't do retain+release tracking for IC_RetainRV, because it's
1938       // better to let it remain as the first instruction after a call.
1939       if (Class != IC_RetainRV)
1940         Retains[Inst] = S.RRI;
1941       S.ClearSequenceProgress();
1942       break;
1943     case S_None:
1944       break;
1945     case S_Retain:
1946       llvm_unreachable("bottom-up pointer in retain state!");
1947     }
1948     ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1949     // A retain moving bottom up can be a use.
1950     break;
1951   }
1952   case IC_AutoreleasepoolPop:
1953     // Conservatively, clear MyStates for all known pointers.
1954     MyStates.clearBottomUpPointers();
1955     return NestingDetected;
1956   case IC_AutoreleasepoolPush:
1957   case IC_None:
1958     // These are irrelevant.
1959     return NestingDetected;
1960   case IC_User:
1961     // If we have a store into an alloca of a pointer we are tracking, the
1962     // pointer has multiple owners implying that we must be more conservative.
1963     //
1964     // This comes up in the context of a pointer being ``KnownSafe''. In the
1965     // presense of a block being initialized, the frontend will emit the
1966     // objc_retain on the original pointer and the release on the pointer loaded
1967     // from the alloca. The optimizer will through the provenance analysis
1968     // realize that the two are related, but since we only require KnownSafe in
1969     // one direction, will match the inner retain on the original pointer with
1970     // the guard release on the original pointer. This is fixed by ensuring that
1971     // in the presense of allocas we only unconditionally remove pointers if
1972     // both our retain and our release are KnownSafe.
1973     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1974       if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1975         BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1976           StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1977         if (I != MyStates.bottom_up_ptr_end())
1978           MultiOwnersSet.insert(I->first);
1979       }
1980     }
1981     break;
1982   default:
1983     break;
1984   }
1985
1986   // Consider any other possible effects of this instruction on each
1987   // pointer being tracked.
1988   for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1989        ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1990     const Value *Ptr = MI->first;
1991     if (Ptr == Arg)
1992       continue; // Handled above.
1993     PtrState &S = MI->second;
1994     Sequence Seq = S.GetSeq();
1995
1996     // Check for possible releases.
1997     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1998       DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1999             << "\n");
2000       S.ClearKnownPositiveRefCount();
2001       switch (Seq) {
2002       case S_Use:
2003         S.SetSeq(S_CanRelease);
2004         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
2005         continue;
2006       case S_CanRelease:
2007       case S_Release:
2008       case S_MovableRelease:
2009       case S_Stop:
2010       case S_None:
2011         break;
2012       case S_Retain:
2013         llvm_unreachable("bottom-up pointer in retain state!");
2014       }
2015     }
2016
2017     // Check for possible direct uses.
2018     switch (Seq) {
2019     case S_Release:
2020     case S_MovableRelease:
2021       if (CanUse(Inst, Ptr, PA, Class)) {
2022         DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2023               << "\n");
2024         assert(S.RRI.ReverseInsertPts.empty());
2025         // If this is an invoke instruction, we're scanning it as part of
2026         // one of its successor blocks, since we can't insert code after it
2027         // in its own block, and we don't want to split critical edges.
2028         if (isa<InvokeInst>(Inst))
2029           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2030         else
2031           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2032         S.SetSeq(S_Use);
2033         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2034       } else if (Seq == S_Release && IsUser(Class)) {
2035         DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2036               << "\n");
2037         // Non-movable releases depend on any possible objc pointer use.
2038         S.SetSeq(S_Stop);
2039         ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2040         assert(S.RRI.ReverseInsertPts.empty());
2041         // As above; handle invoke specially.
2042         if (isa<InvokeInst>(Inst))
2043           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2044         else
2045           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2046       }
2047       break;
2048     case S_Stop:
2049       if (CanUse(Inst, Ptr, PA, Class)) {
2050         DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2051               << "\n");
2052         S.SetSeq(S_Use);
2053         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2054       }
2055       break;
2056     case S_CanRelease:
2057     case S_Use:
2058     case S_None:
2059       break;
2060     case S_Retain:
2061       llvm_unreachable("bottom-up pointer in retain state!");
2062     }
2063   }
2064
2065   return NestingDetected;
2066 }
2067
2068 bool
2069 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2070                           DenseMap<const BasicBlock *, BBState> &BBStates,
2071                           MapVector<Value *, RRInfo> &Retains) {
2072
2073   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2074
2075   bool NestingDetected = false;
2076   BBState &MyStates = BBStates[BB];
2077
2078   // Merge the states from each successor to compute the initial state
2079   // for the current block.
2080   BBState::edge_iterator SI(MyStates.succ_begin()),
2081                          SE(MyStates.succ_end());
2082   if (SI != SE) {
2083     const BasicBlock *Succ = *SI;
2084     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2085     assert(I != BBStates.end());
2086     MyStates.InitFromSucc(I->second);
2087     ++SI;
2088     for (; SI != SE; ++SI) {
2089       Succ = *SI;
2090       I = BBStates.find(Succ);
2091       assert(I != BBStates.end());
2092       MyStates.MergeSucc(I->second);
2093     }
2094   }
2095
2096   // If ARC Annotations are enabled, output the current state of pointers at the
2097   // bottom of the basic block.
2098   ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2099
2100   // Visit all the instructions, bottom-up.
2101   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2102     Instruction *Inst = llvm::prior(I);
2103
2104     // Invoke instructions are visited as part of their successors (below).
2105     if (isa<InvokeInst>(Inst))
2106       continue;
2107
2108     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2109
2110     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2111   }
2112
2113   // If there's a predecessor with an invoke, visit the invoke as if it were
2114   // part of this block, since we can't insert code after an invoke in its own
2115   // block, and we don't want to split critical edges.
2116   for (BBState::edge_iterator PI(MyStates.pred_begin()),
2117        PE(MyStates.pred_end()); PI != PE; ++PI) {
2118     BasicBlock *Pred = *PI;
2119     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2120       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2121   }
2122
2123   // If ARC Annotations are enabled, output the current state of pointers at the
2124   // top of the basic block.
2125   ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2126
2127   return NestingDetected;
2128 }
2129
2130 bool
2131 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2132                                     DenseMap<Value *, RRInfo> &Releases,
2133                                     BBState &MyStates) {
2134   bool NestingDetected = false;
2135   InstructionClass Class = GetInstructionClass(Inst);
2136   const Value *Arg = 0;
2137
2138   switch (Class) {
2139   case IC_RetainBlock:
2140     // In OptimizeIndividualCalls, we have strength reduced all optimizable
2141     // objc_retainBlocks to objc_retains. Thus at this point any
2142     // objc_retainBlocks that we see are not optimizable.
2143     break;
2144   case IC_Retain:
2145   case IC_RetainRV: {
2146     Arg = GetObjCArg(Inst);
2147
2148     PtrState &S = MyStates.getPtrTopDownState(Arg);
2149
2150     // Don't do retain+release tracking for IC_RetainRV, because it's
2151     // better to let it remain as the first instruction after a call.
2152     if (Class != IC_RetainRV) {
2153       // If we see two retains in a row on the same pointer. If so, make
2154       // a note, and we'll cicle back to revisit it after we've
2155       // hopefully eliminated the second retain, which may allow us to
2156       // eliminate the first retain too.
2157       // Theoretically we could implement removal of nested retain+release
2158       // pairs by making PtrState hold a stack of states, but this is
2159       // simple and avoids adding overhead for the non-nested case.
2160       if (S.GetSeq() == S_Retain)
2161         NestingDetected = true;
2162
2163       ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2164       S.ResetSequenceProgress(S_Retain);
2165       S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2166       S.RRI.Calls.insert(Inst);
2167     }
2168
2169     S.SetKnownPositiveRefCount();
2170
2171     // A retain can be a potential use; procede to the generic checking
2172     // code below.
2173     break;
2174   }
2175   case IC_Release: {
2176     Arg = GetObjCArg(Inst);
2177
2178     PtrState &S = MyStates.getPtrTopDownState(Arg);
2179     S.ClearKnownPositiveRefCount();
2180
2181     Sequence OldSeq = S.GetSeq();
2182
2183     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2184
2185     switch (OldSeq) {
2186     case S_Retain:
2187     case S_CanRelease:
2188       if (OldSeq == S_Retain || ReleaseMetadata != 0)
2189         S.RRI.ReverseInsertPts.clear();
2190       // FALL THROUGH
2191     case S_Use:
2192       S.RRI.ReleaseMetadata = ReleaseMetadata;
2193       S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2194       Releases[Inst] = S.RRI;
2195       ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2196       S.ClearSequenceProgress();
2197       break;
2198     case S_None:
2199       break;
2200     case S_Stop:
2201     case S_Release:
2202     case S_MovableRelease:
2203       llvm_unreachable("top-down pointer in release state!");
2204     }
2205     break;
2206   }
2207   case IC_AutoreleasepoolPop:
2208     // Conservatively, clear MyStates for all known pointers.
2209     MyStates.clearTopDownPointers();
2210     return NestingDetected;
2211   case IC_AutoreleasepoolPush:
2212   case IC_None:
2213     // These are irrelevant.
2214     return NestingDetected;
2215   default:
2216     break;
2217   }
2218
2219   // Consider any other possible effects of this instruction on each
2220   // pointer being tracked.
2221   for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2222        ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2223     const Value *Ptr = MI->first;
2224     if (Ptr == Arg)
2225       continue; // Handled above.
2226     PtrState &S = MI->second;
2227     Sequence Seq = S.GetSeq();
2228
2229     // Check for possible releases.
2230     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2231       DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2232             << "\n");
2233       S.ClearKnownPositiveRefCount();
2234       switch (Seq) {
2235       case S_Retain:
2236         S.SetSeq(S_CanRelease);
2237         ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2238         assert(S.RRI.ReverseInsertPts.empty());
2239         S.RRI.ReverseInsertPts.insert(Inst);
2240
2241         // One call can't cause a transition from S_Retain to S_CanRelease
2242         // and S_CanRelease to S_Use. If we've made the first transition,
2243         // we're done.
2244         continue;
2245       case S_Use:
2246       case S_CanRelease:
2247       case S_None:
2248         break;
2249       case S_Stop:
2250       case S_Release:
2251       case S_MovableRelease:
2252         llvm_unreachable("top-down pointer in release state!");
2253       }
2254     }
2255
2256     // Check for possible direct uses.
2257     switch (Seq) {
2258     case S_CanRelease:
2259       if (CanUse(Inst, Ptr, PA, Class)) {
2260         DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2261               << "\n");
2262         S.SetSeq(S_Use);
2263         ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2264       }
2265       break;
2266     case S_Retain:
2267     case S_Use:
2268     case S_None:
2269       break;
2270     case S_Stop:
2271     case S_Release:
2272     case S_MovableRelease:
2273       llvm_unreachable("top-down pointer in release state!");
2274     }
2275   }
2276
2277   return NestingDetected;
2278 }
2279
2280 bool
2281 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2282                          DenseMap<const BasicBlock *, BBState> &BBStates,
2283                          DenseMap<Value *, RRInfo> &Releases) {
2284   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2285   bool NestingDetected = false;
2286   BBState &MyStates = BBStates[BB];
2287
2288   // Merge the states from each predecessor to compute the initial state
2289   // for the current block.
2290   BBState::edge_iterator PI(MyStates.pred_begin()),
2291                          PE(MyStates.pred_end());
2292   if (PI != PE) {
2293     const BasicBlock *Pred = *PI;
2294     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2295     assert(I != BBStates.end());
2296     MyStates.InitFromPred(I->second);
2297     ++PI;
2298     for (; PI != PE; ++PI) {
2299       Pred = *PI;
2300       I = BBStates.find(Pred);
2301       assert(I != BBStates.end());
2302       MyStates.MergePred(I->second);
2303     }
2304   }
2305
2306   // If ARC Annotations are enabled, output the current state of pointers at the
2307   // top of the basic block.
2308   ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2309
2310   // Visit all the instructions, top-down.
2311   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2312     Instruction *Inst = I;
2313
2314     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2315
2316     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2317   }
2318
2319   // If ARC Annotations are enabled, output the current state of pointers at the
2320   // bottom of the basic block.
2321   ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2322
2323 #ifdef ARC_ANNOTATIONS
2324   if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2325 #endif
2326   CheckForCFGHazards(BB, BBStates, MyStates);
2327   return NestingDetected;
2328 }
2329
2330 static void
2331 ComputePostOrders(Function &F,
2332                   SmallVectorImpl<BasicBlock *> &PostOrder,
2333                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2334                   unsigned NoObjCARCExceptionsMDKind,
2335                   DenseMap<const BasicBlock *, BBState> &BBStates) {
2336   /// The visited set, for doing DFS walks.
2337   SmallPtrSet<BasicBlock *, 16> Visited;
2338
2339   // Do DFS, computing the PostOrder.
2340   SmallPtrSet<BasicBlock *, 16> OnStack;
2341   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2342
2343   // Functions always have exactly one entry block, and we don't have
2344   // any other block that we treat like an entry block.
2345   BasicBlock *EntryBB = &F.getEntryBlock();
2346   BBState &MyStates = BBStates[EntryBB];
2347   MyStates.SetAsEntry();
2348   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2349   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2350   Visited.insert(EntryBB);
2351   OnStack.insert(EntryBB);
2352   do {
2353   dfs_next_succ:
2354     BasicBlock *CurrBB = SuccStack.back().first;
2355     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2356     succ_iterator SE(TI, false);
2357
2358     while (SuccStack.back().second != SE) {
2359       BasicBlock *SuccBB = *SuccStack.back().second++;
2360       if (Visited.insert(SuccBB)) {
2361         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2362         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2363         BBStates[CurrBB].addSucc(SuccBB);
2364         BBState &SuccStates = BBStates[SuccBB];
2365         SuccStates.addPred(CurrBB);
2366         OnStack.insert(SuccBB);
2367         goto dfs_next_succ;
2368       }
2369
2370       if (!OnStack.count(SuccBB)) {
2371         BBStates[CurrBB].addSucc(SuccBB);
2372         BBStates[SuccBB].addPred(CurrBB);
2373       }
2374     }
2375     OnStack.erase(CurrBB);
2376     PostOrder.push_back(CurrBB);
2377     SuccStack.pop_back();
2378   } while (!SuccStack.empty());
2379
2380   Visited.clear();
2381
2382   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2383   // Functions may have many exits, and there also blocks which we treat
2384   // as exits due to ignored edges.
2385   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2386   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2387     BasicBlock *ExitBB = I;
2388     BBState &MyStates = BBStates[ExitBB];
2389     if (!MyStates.isExit())
2390       continue;
2391
2392     MyStates.SetAsExit();
2393
2394     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2395     Visited.insert(ExitBB);
2396     while (!PredStack.empty()) {
2397     reverse_dfs_next_succ:
2398       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2399       while (PredStack.back().second != PE) {
2400         BasicBlock *BB = *PredStack.back().second++;
2401         if (Visited.insert(BB)) {
2402           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2403           goto reverse_dfs_next_succ;
2404         }
2405       }
2406       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2407     }
2408   }
2409 }
2410
2411 // Visit the function both top-down and bottom-up.
2412 bool
2413 ObjCARCOpt::Visit(Function &F,
2414                   DenseMap<const BasicBlock *, BBState> &BBStates,
2415                   MapVector<Value *, RRInfo> &Retains,
2416                   DenseMap<Value *, RRInfo> &Releases) {
2417
2418   // Use reverse-postorder traversals, because we magically know that loops
2419   // will be well behaved, i.e. they won't repeatedly call retain on a single
2420   // pointer without doing a release. We can't use the ReversePostOrderTraversal
2421   // class here because we want the reverse-CFG postorder to consider each
2422   // function exit point, and we want to ignore selected cycle edges.
2423   SmallVector<BasicBlock *, 16> PostOrder;
2424   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2425   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2426                     NoObjCARCExceptionsMDKind,
2427                     BBStates);
2428
2429   // Use reverse-postorder on the reverse CFG for bottom-up.
2430   bool BottomUpNestingDetected = false;
2431   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2432        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2433        I != E; ++I)
2434     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2435
2436   // Use reverse-postorder for top-down.
2437   bool TopDownNestingDetected = false;
2438   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2439        PostOrder.rbegin(), E = PostOrder.rend();
2440        I != E; ++I)
2441     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2442
2443   return TopDownNestingDetected && BottomUpNestingDetected;
2444 }
2445
2446 /// Move the calls in RetainsToMove and ReleasesToMove.
2447 void ObjCARCOpt::MoveCalls(Value *Arg,
2448                            RRInfo &RetainsToMove,
2449                            RRInfo &ReleasesToMove,
2450                            MapVector<Value *, RRInfo> &Retains,
2451                            DenseMap<Value *, RRInfo> &Releases,
2452                            SmallVectorImpl<Instruction *> &DeadInsts,
2453                            Module *M) {
2454   Type *ArgTy = Arg->getType();
2455   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2456
2457   DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2458
2459   // Insert the new retain and release calls.
2460   for (SmallPtrSet<Instruction *, 2>::const_iterator
2461        PI = ReleasesToMove.ReverseInsertPts.begin(),
2462        PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2463     Instruction *InsertPt = *PI;
2464     Value *MyArg = ArgTy == ParamTy ? Arg :
2465                    new BitCastInst(Arg, ParamTy, "", InsertPt);
2466     CallInst *Call =
2467       CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2468     Call->setDoesNotThrow();
2469     Call->setTailCall();
2470
2471     DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2472                     "At insertion point: " << *InsertPt << "\n");
2473   }
2474   for (SmallPtrSet<Instruction *, 2>::const_iterator
2475        PI = RetainsToMove.ReverseInsertPts.begin(),
2476        PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2477     Instruction *InsertPt = *PI;
2478     Value *MyArg = ArgTy == ParamTy ? Arg :
2479                    new BitCastInst(Arg, ParamTy, "", InsertPt);
2480     CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2481                                       "", InsertPt);
2482     // Attach a clang.imprecise_release metadata tag, if appropriate.
2483     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2484       Call->setMetadata(ImpreciseReleaseMDKind, M);
2485     Call->setDoesNotThrow();
2486     if (ReleasesToMove.IsTailCallRelease)
2487       Call->setTailCall();
2488
2489     DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2490                     "At insertion point: " << *InsertPt << "\n");
2491   }
2492
2493   // Delete the original retain and release calls.
2494   for (SmallPtrSet<Instruction *, 2>::const_iterator
2495        AI = RetainsToMove.Calls.begin(),
2496        AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2497     Instruction *OrigRetain = *AI;
2498     Retains.blot(OrigRetain);
2499     DeadInsts.push_back(OrigRetain);
2500     DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2501   }
2502   for (SmallPtrSet<Instruction *, 2>::const_iterator
2503        AI = ReleasesToMove.Calls.begin(),
2504        AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2505     Instruction *OrigRelease = *AI;
2506     Releases.erase(OrigRelease);
2507     DeadInsts.push_back(OrigRelease);
2508     DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2509   }
2510
2511 }
2512
2513 bool
2514 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2515                                     &BBStates,
2516                                   MapVector<Value *, RRInfo> &Retains,
2517                                   DenseMap<Value *, RRInfo> &Releases,
2518                                   Module *M,
2519                                   SmallVector<Instruction *, 4> &NewRetains,
2520                                   SmallVector<Instruction *, 4> &NewReleases,
2521                                   SmallVector<Instruction *, 8> &DeadInsts,
2522                                   RRInfo &RetainsToMove,
2523                                   RRInfo &ReleasesToMove,
2524                                   Value *Arg,
2525                                   bool KnownSafe,
2526                                   bool &AnyPairsCompletelyEliminated) {
2527   // If a pair happens in a region where it is known that the reference count
2528   // is already incremented, we can similarly ignore possible decrements unless
2529   // we are dealing with a retainable object with multiple provenance sources.
2530   bool KnownSafeTD = true, KnownSafeBU = true;
2531   bool MultipleOwners = false;
2532   bool CFGHazardAfflicted = false;
2533
2534   // Connect the dots between the top-down-collected RetainsToMove and
2535   // bottom-up-collected ReleasesToMove to form sets of related calls.
2536   // This is an iterative process so that we connect multiple releases
2537   // to multiple retains if needed.
2538   unsigned OldDelta = 0;
2539   unsigned NewDelta = 0;
2540   unsigned OldCount = 0;
2541   unsigned NewCount = 0;
2542   bool FirstRelease = true;
2543   for (;;) {
2544     for (SmallVectorImpl<Instruction *>::const_iterator
2545            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2546       Instruction *NewRetain = *NI;
2547       MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2548       assert(It != Retains.end());
2549       const RRInfo &NewRetainRRI = It->second;
2550       KnownSafeTD &= NewRetainRRI.KnownSafe;
2551       MultipleOwners =
2552         MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2553       for (SmallPtrSet<Instruction *, 2>::const_iterator
2554              LI = NewRetainRRI.Calls.begin(),
2555              LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2556         Instruction *NewRetainRelease = *LI;
2557         DenseMap<Value *, RRInfo>::const_iterator Jt =
2558           Releases.find(NewRetainRelease);
2559         if (Jt == Releases.end())
2560           return false;
2561         const RRInfo &NewRetainReleaseRRI = Jt->second;
2562         assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2563         if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2564
2565           // If we overflow when we compute the path count, don't remove/move
2566           // anything.
2567           const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2568           unsigned PathCount;
2569           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2570             return false;
2571           OldDelta -= PathCount;
2572
2573           // Merge the ReleaseMetadata and IsTailCallRelease values.
2574           if (FirstRelease) {
2575             ReleasesToMove.ReleaseMetadata =
2576               NewRetainReleaseRRI.ReleaseMetadata;
2577             ReleasesToMove.IsTailCallRelease =
2578               NewRetainReleaseRRI.IsTailCallRelease;
2579             FirstRelease = false;
2580           } else {
2581             if (ReleasesToMove.ReleaseMetadata !=
2582                 NewRetainReleaseRRI.ReleaseMetadata)
2583               ReleasesToMove.ReleaseMetadata = 0;
2584             if (ReleasesToMove.IsTailCallRelease !=
2585                 NewRetainReleaseRRI.IsTailCallRelease)
2586               ReleasesToMove.IsTailCallRelease = false;
2587           }
2588
2589           // Collect the optimal insertion points.
2590           if (!KnownSafe)
2591             for (SmallPtrSet<Instruction *, 2>::const_iterator
2592                    RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2593                    RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2594                  RI != RE; ++RI) {
2595               Instruction *RIP = *RI;
2596               if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2597                 // If we overflow when we compute the path count, don't
2598                 // remove/move anything.
2599                 const BBState &RIPBBState = BBStates[RIP->getParent()];
2600                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2601                   return false;
2602                 NewDelta -= PathCount;
2603               }
2604             }
2605           NewReleases.push_back(NewRetainRelease);
2606         }
2607       }
2608     }
2609     NewRetains.clear();
2610     if (NewReleases.empty()) break;
2611
2612     // Back the other way.
2613     for (SmallVectorImpl<Instruction *>::const_iterator
2614            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2615       Instruction *NewRelease = *NI;
2616       DenseMap<Value *, RRInfo>::const_iterator It =
2617         Releases.find(NewRelease);
2618       assert(It != Releases.end());
2619       const RRInfo &NewReleaseRRI = It->second;
2620       KnownSafeBU &= NewReleaseRRI.KnownSafe;
2621       CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2622       for (SmallPtrSet<Instruction *, 2>::const_iterator
2623              LI = NewReleaseRRI.Calls.begin(),
2624              LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2625         Instruction *NewReleaseRetain = *LI;
2626         MapVector<Value *, RRInfo>::const_iterator Jt =
2627           Retains.find(NewReleaseRetain);
2628         if (Jt == Retains.end())
2629           return false;
2630         const RRInfo &NewReleaseRetainRRI = Jt->second;
2631         assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2632         if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2633
2634           // If we overflow when we compute the path count, don't remove/move
2635           // anything.
2636           const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2637           unsigned PathCount;
2638           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2639             return false;
2640           OldDelta += PathCount;
2641           OldCount += PathCount;
2642
2643           // Collect the optimal insertion points.
2644           if (!KnownSafe)
2645             for (SmallPtrSet<Instruction *, 2>::const_iterator
2646                    RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2647                    RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2648                  RI != RE; ++RI) {
2649               Instruction *RIP = *RI;
2650               if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2651                 // If we overflow when we compute the path count, don't
2652                 // remove/move anything.
2653                 const BBState &RIPBBState = BBStates[RIP->getParent()];
2654                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2655                   return false;
2656                 NewDelta += PathCount;
2657                 NewCount += PathCount;
2658               }
2659             }
2660           NewRetains.push_back(NewReleaseRetain);
2661         }
2662       }
2663     }
2664     NewReleases.clear();
2665     if (NewRetains.empty()) break;
2666   }
2667
2668   // If the pointer is known incremented in 1 direction and we do not have
2669   // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2670   // to be known safe in both directions.
2671   bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2672     ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2673   if (UnconditionallySafe) {
2674     RetainsToMove.ReverseInsertPts.clear();
2675     ReleasesToMove.ReverseInsertPts.clear();
2676     NewCount = 0;
2677   } else {
2678     // Determine whether the new insertion points we computed preserve the
2679     // balance of retain and release calls through the program.
2680     // TODO: If the fully aggressive solution isn't valid, try to find a
2681     // less aggressive solution which is.
2682     if (NewDelta != 0)
2683       return false;
2684
2685     // At this point, we are not going to remove any RR pairs, but we still are
2686     // able to move RR pairs. If one of our pointers is afflicted with
2687     // CFGHazards, we cannot perform such code motion so exit early.
2688     const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2689       ReleasesToMove.ReverseInsertPts.size();
2690     if (CFGHazardAfflicted && WillPerformCodeMotion)
2691       return false;
2692   }
2693
2694   // Determine whether the original call points are balanced in the retain and
2695   // release calls through the program. If not, conservatively don't touch
2696   // them.
2697   // TODO: It's theoretically possible to do code motion in this case, as
2698   // long as the existing imbalances are maintained.
2699   if (OldDelta != 0)
2700     return false;
2701
2702 #ifdef ARC_ANNOTATIONS
2703   // Do not move calls if ARC annotations are requested.
2704   if (EnableARCAnnotations)
2705     return false;
2706 #endif // ARC_ANNOTATIONS
2707
2708   Changed = true;
2709   assert(OldCount != 0 && "Unreachable code?");
2710   NumRRs += OldCount - NewCount;
2711   // Set to true if we completely removed any RR pairs.
2712   AnyPairsCompletelyEliminated = NewCount == 0;
2713
2714   // We can move calls!
2715   return true;
2716 }
2717
2718 /// Identify pairings between the retains and releases, and delete and/or move
2719 /// them.
2720 bool
2721 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2722                                    &BBStates,
2723                                  MapVector<Value *, RRInfo> &Retains,
2724                                  DenseMap<Value *, RRInfo> &Releases,
2725                                  Module *M) {
2726   DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2727
2728   bool AnyPairsCompletelyEliminated = false;
2729   RRInfo RetainsToMove;
2730   RRInfo ReleasesToMove;
2731   SmallVector<Instruction *, 4> NewRetains;
2732   SmallVector<Instruction *, 4> NewReleases;
2733   SmallVector<Instruction *, 8> DeadInsts;
2734
2735   // Visit each retain.
2736   for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2737        E = Retains.end(); I != E; ++I) {
2738     Value *V = I->first;
2739     if (!V) continue; // blotted
2740
2741     Instruction *Retain = cast<Instruction>(V);
2742
2743     DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2744
2745     Value *Arg = GetObjCArg(Retain);
2746
2747     // If the object being released is in static or stack storage, we know it's
2748     // not being managed by ObjC reference counting, so we can delete pairs
2749     // regardless of what possible decrements or uses lie between them.
2750     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2751
2752     // A constant pointer can't be pointing to an object on the heap. It may
2753     // be reference-counted, but it won't be deleted.
2754     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2755       if (const GlobalVariable *GV =
2756             dyn_cast<GlobalVariable>(
2757               StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2758         if (GV->isConstant())
2759           KnownSafe = true;
2760
2761     // Connect the dots between the top-down-collected RetainsToMove and
2762     // bottom-up-collected ReleasesToMove to form sets of related calls.
2763     NewRetains.push_back(Retain);
2764     bool PerformMoveCalls =
2765       ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2766                             NewReleases, DeadInsts, RetainsToMove,
2767                             ReleasesToMove, Arg, KnownSafe,
2768                             AnyPairsCompletelyEliminated);
2769
2770     if (PerformMoveCalls) {
2771       // Ok, everything checks out and we're all set. Let's move/delete some
2772       // code!
2773       MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2774                 Retains, Releases, DeadInsts, M);
2775     }
2776
2777     // Clean up state for next retain.
2778     NewReleases.clear();
2779     NewRetains.clear();
2780     RetainsToMove.clear();
2781     ReleasesToMove.clear();
2782   }
2783
2784   // Now that we're done moving everything, we can delete the newly dead
2785   // instructions, as we no longer need them as insert points.
2786   while (!DeadInsts.empty())
2787     EraseInstruction(DeadInsts.pop_back_val());
2788
2789   return AnyPairsCompletelyEliminated;
2790 }
2791
2792 /// Weak pointer optimizations.
2793 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2794   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2795
2796   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2797   // itself because it uses AliasAnalysis and we need to do provenance
2798   // queries instead.
2799   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2800     Instruction *Inst = &*I++;
2801
2802     DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2803
2804     InstructionClass Class = GetBasicInstructionClass(Inst);
2805     if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2806       continue;
2807
2808     // Delete objc_loadWeak calls with no users.
2809     if (Class == IC_LoadWeak && Inst->use_empty()) {
2810       Inst->eraseFromParent();
2811       continue;
2812     }
2813
2814     // TODO: For now, just look for an earlier available version of this value
2815     // within the same block. Theoretically, we could do memdep-style non-local
2816     // analysis too, but that would want caching. A better approach would be to
2817     // use the technique that EarlyCSE uses.
2818     inst_iterator Current = llvm::prior(I);
2819     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2820     for (BasicBlock::iterator B = CurrentBB->begin(),
2821                               J = Current.getInstructionIterator();
2822          J != B; --J) {
2823       Instruction *EarlierInst = &*llvm::prior(J);
2824       InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2825       switch (EarlierClass) {
2826       case IC_LoadWeak:
2827       case IC_LoadWeakRetained: {
2828         // If this is loading from the same pointer, replace this load's value
2829         // with that one.
2830         CallInst *Call = cast<CallInst>(Inst);
2831         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2832         Value *Arg = Call->getArgOperand(0);
2833         Value *EarlierArg = EarlierCall->getArgOperand(0);
2834         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2835         case AliasAnalysis::MustAlias:
2836           Changed = true;
2837           // If the load has a builtin retain, insert a plain retain for it.
2838           if (Class == IC_LoadWeakRetained) {
2839             CallInst *CI =
2840               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2841                                "", Call);
2842             CI->setTailCall();
2843           }
2844           // Zap the fully redundant load.
2845           Call->replaceAllUsesWith(EarlierCall);
2846           Call->eraseFromParent();
2847           goto clobbered;
2848         case AliasAnalysis::MayAlias:
2849         case AliasAnalysis::PartialAlias:
2850           goto clobbered;
2851         case AliasAnalysis::NoAlias:
2852           break;
2853         }
2854         break;
2855       }
2856       case IC_StoreWeak:
2857       case IC_InitWeak: {
2858         // If this is storing to the same pointer and has the same size etc.
2859         // replace this load's value with the stored value.
2860         CallInst *Call = cast<CallInst>(Inst);
2861         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2862         Value *Arg = Call->getArgOperand(0);
2863         Value *EarlierArg = EarlierCall->getArgOperand(0);
2864         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2865         case AliasAnalysis::MustAlias:
2866           Changed = true;
2867           // If the load has a builtin retain, insert a plain retain for it.
2868           if (Class == IC_LoadWeakRetained) {
2869             CallInst *CI =
2870               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2871                                "", Call);
2872             CI->setTailCall();
2873           }
2874           // Zap the fully redundant load.
2875           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2876           Call->eraseFromParent();
2877           goto clobbered;
2878         case AliasAnalysis::MayAlias:
2879         case AliasAnalysis::PartialAlias:
2880           goto clobbered;
2881         case AliasAnalysis::NoAlias:
2882           break;
2883         }
2884         break;
2885       }
2886       case IC_MoveWeak:
2887       case IC_CopyWeak:
2888         // TOOD: Grab the copied value.
2889         goto clobbered;
2890       case IC_AutoreleasepoolPush:
2891       case IC_None:
2892       case IC_IntrinsicUser:
2893       case IC_User:
2894         // Weak pointers are only modified through the weak entry points
2895         // (and arbitrary calls, which could call the weak entry points).
2896         break;
2897       default:
2898         // Anything else could modify the weak pointer.
2899         goto clobbered;
2900       }
2901     }
2902   clobbered:;
2903   }
2904
2905   // Then, for each destroyWeak with an alloca operand, check to see if
2906   // the alloca and all its users can be zapped.
2907   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2908     Instruction *Inst = &*I++;
2909     InstructionClass Class = GetBasicInstructionClass(Inst);
2910     if (Class != IC_DestroyWeak)
2911       continue;
2912
2913     CallInst *Call = cast<CallInst>(Inst);
2914     Value *Arg = Call->getArgOperand(0);
2915     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2916       for (Value::use_iterator UI = Alloca->use_begin(),
2917            UE = Alloca->use_end(); UI != UE; ++UI) {
2918         const Instruction *UserInst = cast<Instruction>(*UI);
2919         switch (GetBasicInstructionClass(UserInst)) {
2920         case IC_InitWeak:
2921         case IC_StoreWeak:
2922         case IC_DestroyWeak:
2923           continue;
2924         default:
2925           goto done;
2926         }
2927       }
2928       Changed = true;
2929       for (Value::use_iterator UI = Alloca->use_begin(),
2930            UE = Alloca->use_end(); UI != UE; ) {
2931         CallInst *UserInst = cast<CallInst>(*UI++);
2932         switch (GetBasicInstructionClass(UserInst)) {
2933         case IC_InitWeak:
2934         case IC_StoreWeak:
2935           // These functions return their second argument.
2936           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2937           break;
2938         case IC_DestroyWeak:
2939           // No return value.
2940           break;
2941         default:
2942           llvm_unreachable("alloca really is used!");
2943         }
2944         UserInst->eraseFromParent();
2945       }
2946       Alloca->eraseFromParent();
2947     done:;
2948     }
2949   }
2950 }
2951
2952 /// Identify program paths which execute sequences of retains and releases which
2953 /// can be eliminated.
2954 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2955   // Releases, Retains - These are used to store the results of the main flow
2956   // analysis. These use Value* as the key instead of Instruction* so that the
2957   // map stays valid when we get around to rewriting code and calls get
2958   // replaced by arguments.
2959   DenseMap<Value *, RRInfo> Releases;
2960   MapVector<Value *, RRInfo> Retains;
2961
2962   // This is used during the traversal of the function to track the
2963   // states for each identified object at each block.
2964   DenseMap<const BasicBlock *, BBState> BBStates;
2965
2966   // Analyze the CFG of the function, and all instructions.
2967   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2968
2969   // Transform.
2970   bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2971                                                            Releases,
2972                                                            F.getParent());
2973
2974   // Cleanup.
2975   MultiOwnersSet.clear();
2976
2977   return AnyPairsCompletelyEliminated && NestingDetected;
2978 }
2979
2980 /// Check if there is a dependent call earlier that does not have anything in
2981 /// between the Retain and the call that can affect the reference count of their
2982 /// shared pointer argument. Note that Retain need not be in BB.
2983 static bool
2984 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2985                              SmallPtrSet<Instruction *, 4> &DepInsts,
2986                              SmallPtrSet<const BasicBlock *, 4> &Visited,
2987                              ProvenanceAnalysis &PA) {
2988   FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2989                    DepInsts, Visited, PA);
2990   if (DepInsts.size() != 1)
2991     return false;
2992
2993   CallInst *Call =
2994     dyn_cast_or_null<CallInst>(*DepInsts.begin());
2995
2996   // Check that the pointer is the return value of the call.
2997   if (!Call || Arg != Call)
2998     return false;
2999
3000   // Check that the call is a regular call.
3001   InstructionClass Class = GetBasicInstructionClass(Call);
3002   if (Class != IC_CallOrUser && Class != IC_Call)
3003     return false;
3004
3005   return true;
3006 }
3007
3008 /// Find a dependent retain that precedes the given autorelease for which there
3009 /// is nothing in between the two instructions that can affect the ref count of
3010 /// Arg.
3011 static CallInst *
3012 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3013                                   Instruction *Autorelease,
3014                                   SmallPtrSet<Instruction *, 4> &DepInsts,
3015                                   SmallPtrSet<const BasicBlock *, 4> &Visited,
3016                                   ProvenanceAnalysis &PA) {
3017   FindDependencies(CanChangeRetainCount, Arg,
3018                    BB, Autorelease, DepInsts, Visited, PA);
3019   if (DepInsts.size() != 1)
3020     return 0;
3021
3022   CallInst *Retain =
3023     dyn_cast_or_null<CallInst>(*DepInsts.begin());
3024
3025   // Check that we found a retain with the same argument.
3026   if (!Retain ||
3027       !IsRetain(GetBasicInstructionClass(Retain)) ||
3028       GetObjCArg(Retain) != Arg) {
3029     return 0;
3030   }
3031
3032   return Retain;
3033 }
3034
3035 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3036 /// no instructions dependent on Arg that need a positive ref count in between
3037 /// the autorelease and the ret.
3038 static CallInst *
3039 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3040                                        ReturnInst *Ret,
3041                                        SmallPtrSet<Instruction *, 4> &DepInsts,
3042                                        SmallPtrSet<const BasicBlock *, 4> &V,
3043                                        ProvenanceAnalysis &PA) {
3044   FindDependencies(NeedsPositiveRetainCount, Arg,
3045                    BB, Ret, DepInsts, V, PA);
3046   if (DepInsts.size() != 1)
3047     return 0;
3048
3049   CallInst *Autorelease =
3050     dyn_cast_or_null<CallInst>(*DepInsts.begin());
3051   if (!Autorelease)
3052     return 0;
3053   InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3054   if (!IsAutorelease(AutoreleaseClass))
3055     return 0;
3056   if (GetObjCArg(Autorelease) != Arg)
3057     return 0;
3058
3059   return Autorelease;
3060 }
3061
3062 /// Look for this pattern:
3063 /// \code
3064 ///    %call = call i8* @something(...)
3065 ///    %2 = call i8* @objc_retain(i8* %call)
3066 ///    %3 = call i8* @objc_autorelease(i8* %2)
3067 ///    ret i8* %3
3068 /// \endcode
3069 /// And delete the retain and autorelease.
3070 void ObjCARCOpt::OptimizeReturns(Function &F) {
3071   if (!F.getReturnType()->isPointerTy())
3072     return;
3073
3074   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3075
3076   SmallPtrSet<Instruction *, 4> DependingInstructions;
3077   SmallPtrSet<const BasicBlock *, 4> Visited;
3078   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3079     BasicBlock *BB = FI;
3080     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3081
3082     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3083
3084     if (!Ret)
3085       continue;
3086
3087     const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3088
3089     // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3090     // dependent on Arg such that there are no instructions dependent on Arg
3091     // that need a positive ref count in between the autorelease and Ret.
3092     CallInst *Autorelease =
3093       FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3094                                              DependingInstructions, Visited,
3095                                              PA);
3096     DependingInstructions.clear();
3097     Visited.clear();
3098
3099     if (!Autorelease)
3100       continue;
3101
3102     CallInst *Retain =
3103       FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3104                                         DependingInstructions, Visited, PA);
3105     DependingInstructions.clear();
3106     Visited.clear();
3107
3108     if (!Retain)
3109       continue;
3110
3111     // Check that there is nothing that can affect the reference count
3112     // between the retain and the call.  Note that Retain need not be in BB.
3113     bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3114                                                           DependingInstructions,
3115                                                           Visited, PA);
3116     DependingInstructions.clear();
3117     Visited.clear();
3118
3119     if (!HasSafePathToCall)
3120       continue;
3121
3122     // If so, we can zap the retain and autorelease.
3123     Changed = true;
3124     ++NumRets;
3125     DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3126           << *Autorelease << "\n");
3127     EraseInstruction(Retain);
3128     EraseInstruction(Autorelease);
3129   }
3130 }
3131
3132 #ifndef NDEBUG
3133 void
3134 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3135   llvm::Statistic &NumRetains =
3136     AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3137   llvm::Statistic &NumReleases =
3138     AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3139
3140   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3141     Instruction *Inst = &*I++;
3142     switch (GetBasicInstructionClass(Inst)) {
3143     default:
3144       break;
3145     case IC_Retain:
3146       ++NumRetains;
3147       break;
3148     case IC_Release:
3149       ++NumReleases;
3150       break;
3151     }
3152   }
3153 }
3154 #endif
3155
3156 bool ObjCARCOpt::doInitialization(Module &M) {
3157   if (!EnableARCOpts)
3158     return false;
3159
3160   // If nothing in the Module uses ARC, don't do anything.
3161   Run = ModuleHasARC(M);
3162   if (!Run)
3163     return false;
3164
3165   // Identify the imprecise release metadata kind.
3166   ImpreciseReleaseMDKind =
3167     M.getContext().getMDKindID("clang.imprecise_release");
3168   CopyOnEscapeMDKind =
3169     M.getContext().getMDKindID("clang.arc.copy_on_escape");
3170   NoObjCARCExceptionsMDKind =
3171     M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3172 #ifdef ARC_ANNOTATIONS
3173   ARCAnnotationBottomUpMDKind =
3174     M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3175   ARCAnnotationTopDownMDKind =
3176     M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3177   ARCAnnotationProvenanceSourceMDKind =
3178     M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3179 #endif // ARC_ANNOTATIONS
3180
3181   // Intuitively, objc_retain and others are nocapture, however in practice
3182   // they are not, because they return their argument value. And objc_release
3183   // calls finalizers which can have arbitrary side effects.
3184
3185   // These are initialized lazily.
3186   AutoreleaseRVCallee = 0;
3187   ReleaseCallee = 0;
3188   RetainCallee = 0;
3189   RetainBlockCallee = 0;
3190   AutoreleaseCallee = 0;
3191
3192   return false;
3193 }
3194
3195 bool ObjCARCOpt::runOnFunction(Function &F) {
3196   if (!EnableARCOpts)
3197     return false;
3198
3199   // If nothing in the Module uses ARC, don't do anything.
3200   if (!Run)
3201     return false;
3202
3203   Changed = false;
3204
3205   DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3206         "\n");
3207
3208   PA.setAA(&getAnalysis<AliasAnalysis>());
3209
3210 #ifndef NDEBUG
3211   if (AreStatisticsEnabled()) {
3212     GatherStatistics(F, false);
3213   }
3214 #endif
3215
3216   // This pass performs several distinct transformations. As a compile-time aid
3217   // when compiling code that isn't ObjC, skip these if the relevant ObjC
3218   // library functions aren't declared.
3219
3220   // Preliminary optimizations. This also computes UsedInThisFunction.
3221   OptimizeIndividualCalls(F);
3222
3223   // Optimizations for weak pointers.
3224   if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3225                             (1 << IC_LoadWeakRetained) |
3226                             (1 << IC_StoreWeak) |
3227                             (1 << IC_InitWeak) |
3228                             (1 << IC_CopyWeak) |
3229                             (1 << IC_MoveWeak) |
3230                             (1 << IC_DestroyWeak)))
3231     OptimizeWeakCalls(F);
3232
3233   // Optimizations for retain+release pairs.
3234   if (UsedInThisFunction & ((1 << IC_Retain) |
3235                             (1 << IC_RetainRV) |
3236                             (1 << IC_RetainBlock)))
3237     if (UsedInThisFunction & (1 << IC_Release))
3238       // Run OptimizeSequences until it either stops making changes or
3239       // no retain+release pair nesting is detected.
3240       while (OptimizeSequences(F)) {}
3241
3242   // Optimizations if objc_autorelease is used.
3243   if (UsedInThisFunction & ((1 << IC_Autorelease) |
3244                             (1 << IC_AutoreleaseRV)))
3245     OptimizeReturns(F);
3246
3247   // Gather statistics after optimization.
3248 #ifndef NDEBUG
3249   if (AreStatisticsEnabled()) {
3250     GatherStatistics(F, true);
3251   }
3252 #endif
3253
3254   DEBUG(dbgs() << "\n");
3255
3256   return Changed;
3257 }
3258
3259 void ObjCARCOpt::releaseMemory() {
3260   PA.clear();
3261 }
3262
3263 /// @}
3264 ///