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