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