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