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