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