1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
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.
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
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.
25 //===----------------------------------------------------------------------===//
27 #define DEBUG_TYPE "objc-arc-opts"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm::objcarc;
46 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
50 /// \brief An associative container with fast insertion-order (deterministic)
51 /// iteration over its elements. Plus the special blot operation.
52 template<class KeyT, class ValueT>
54 /// Map keys to indices in Vector.
55 typedef DenseMap<KeyT, size_t> MapTy;
58 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
63 typedef typename VectorTy::iterator iterator;
64 typedef typename VectorTy::const_iterator const_iterator;
65 iterator begin() { return Vector.begin(); }
66 iterator end() { return Vector.end(); }
67 const_iterator begin() const { return Vector.begin(); }
68 const_iterator end() const { return Vector.end(); }
72 assert(Vector.size() >= Map.size()); // May differ due to blotting.
73 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
75 assert(I->second < Vector.size());
76 assert(Vector[I->second].first == I->first);
78 for (typename VectorTy::const_iterator I = Vector.begin(),
79 E = Vector.end(); I != E; ++I)
81 (Map.count(I->first) &&
82 Map[I->first] == size_t(I - Vector.begin())));
86 ValueT &operator[](const KeyT &Arg) {
87 std::pair<typename MapTy::iterator, bool> Pair =
88 Map.insert(std::make_pair(Arg, size_t(0)));
90 size_t Num = Vector.size();
91 Pair.first->second = Num;
92 Vector.push_back(std::make_pair(Arg, ValueT()));
93 return Vector[Num].second;
95 return Vector[Pair.first->second].second;
98 std::pair<iterator, bool>
99 insert(const std::pair<KeyT, ValueT> &InsertPair) {
100 std::pair<typename MapTy::iterator, bool> Pair =
101 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
103 size_t Num = Vector.size();
104 Pair.first->second = Num;
105 Vector.push_back(InsertPair);
106 return std::make_pair(Vector.begin() + Num, true);
108 return std::make_pair(Vector.begin() + Pair.first->second, false);
111 iterator find(const KeyT &Key) {
112 typename MapTy::iterator It = Map.find(Key);
113 if (It == Map.end()) return Vector.end();
114 return Vector.begin() + It->second;
117 const_iterator find(const KeyT &Key) const {
118 typename MapTy::const_iterator It = Map.find(Key);
119 if (It == Map.end()) return Vector.end();
120 return Vector.begin() + It->second;
123 /// This is similar to erase, but instead of removing the element from the
124 /// vector, it just zeros out the key in the vector. This leaves iterators
125 /// intact, but clients must be prepared for zeroed-out keys when iterating.
126 void blot(const KeyT &Key) {
127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
142 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
145 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146 /// as it finds a value with multiple uses.
147 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148 if (Arg->hasOneUse()) {
149 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150 return FindSingleUseIdentifiedObject(BC->getOperand(0));
151 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152 if (GEP->hasAllZeroIndices())
153 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154 if (IsForwarding(GetBasicInstructionClass(Arg)))
155 return FindSingleUseIdentifiedObject(
156 cast<CallInst>(Arg)->getArgOperand(0));
157 if (!IsObjCIdentifiedObject(Arg))
162 // If we found an identifiable object but it has multiple uses, but they are
163 // trivial uses, we can still consider this to be a single-use value.
164 if (IsObjCIdentifiedObject(Arg)) {
165 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
178 /// \brief Test whether the given retainable object pointer escapes.
180 /// This differs from regular escape analysis in that a use as an
181 /// argument to a call is not considered an escape.
183 static bool DoesRetainableObjPtrEscape(const User *Ptr) {
184 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
186 // Walk the def-use chains.
187 SmallVector<const Value *, 4> Worklist;
188 Worklist.push_back(Ptr);
189 // If Ptr has any operands add them as well.
190 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
192 Worklist.push_back(*I);
195 // Ensure we do not visit any value twice.
196 SmallPtrSet<const Value *, 8> VisitedSet;
199 const Value *V = Worklist.pop_back_val();
201 DEBUG(dbgs() << "Visiting: " << *V << "\n");
203 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
205 const User *UUser = *UI;
207 DEBUG(dbgs() << "User: " << *UUser << "\n");
209 // Special - Use by a call (callee or argument) is not considered
211 switch (GetBasicInstructionClass(UUser)) {
216 case IC_AutoreleaseRV: {
217 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
218 // These special functions make copies of their pointer arguments.
221 case IC_IntrinsicUser:
222 // Use by the use intrinsic is not an escape.
226 // Use by an instruction which copies the value is an escape if the
227 // result is an escape.
228 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
231 if (VisitedSet.insert(UUser)) {
232 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233 " Adding to list.\n");
234 Worklist.push_back(UUser);
236 DEBUG(dbgs() << "Already visited node.\n");
240 // Use by a load is not an escape.
241 if (isa<LoadInst>(UUser))
243 // Use by a store is not an escape if the use is the address.
244 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245 if (V != SI->getValueOperand())
249 // Regular calls and other stuff are not considered escapes.
252 // Otherwise, conservatively assume an escape.
253 DEBUG(dbgs() << "Assuming ptr escapes.\n");
256 } while (!Worklist.empty());
259 DEBUG(dbgs() << "Ptr does not escape.\n");
263 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
264 /// GetUnderlyingObjects except that it returns early when it sees the first
266 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267 SmallPtrSet<const Value *, 4> Visited;
268 SmallVector<const Value *, 4> Worklist;
269 Worklist.push_back(V);
271 const Value *P = Worklist.pop_back_val();
272 P = GetUnderlyingObjCPtr(P);
274 if (isa<AllocaInst>(P))
277 if (!Visited.insert(P))
280 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281 Worklist.push_back(SI->getTrueValue());
282 Worklist.push_back(SI->getFalseValue());
286 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288 Worklist.push_back(PN->getIncomingValue(i));
291 } while (!Worklist.empty());
299 /// \defgroup ARCOpt ARC Optimization.
302 // TODO: On code like this:
305 // stuff_that_cannot_release()
306 // objc_autorelease(%x)
307 // stuff_that_cannot_release()
309 // stuff_that_cannot_release()
310 // objc_autorelease(%x)
312 // The second retain and autorelease can be deleted.
314 // TODO: It should be possible to delete
315 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
316 // pairs if nothing is actually autoreleased between them. Also, autorelease
317 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318 // after inlining) can be turned into plain release calls.
320 // TODO: Critical-edge splitting. If the optimial insertion point is
321 // a critical edge, the current algorithm has to fail, because it doesn't
322 // know how to split edges. It should be possible to make the optimizer
323 // think in terms of edges, rather than blocks, and then split critical
326 // TODO: OptimizeSequences could generalized to be Interprocedural.
328 // TODO: Recognize that a bunch of other objc runtime calls have
329 // non-escaping arguments and non-releasing arguments, and may be
330 // non-autoreleasing.
332 // TODO: Sink autorelease calls as far as possible. Unfortunately we
333 // usually can't sink them past other calls, which would be the main
334 // case where it would be useful.
336 // TODO: The pointer returned from objc_loadWeakRetained is retained.
338 // TODO: Delete release+retain pairs (rare).
340 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
341 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343 STATISTIC(NumRets, "Number of return value forwarding "
344 "retain+autoreleases eliminated");
345 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
346 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
348 STATISTIC(NumRetainsBeforeOpt,
349 "Number of retains before optimization");
350 STATISTIC(NumReleasesBeforeOpt,
351 "Number of releases before optimization");
352 STATISTIC(NumRetainsAfterOpt,
353 "Number of retains after optimization");
354 STATISTIC(NumReleasesAfterOpt,
355 "Number of releases after optimization");
361 /// \brief A sequence of states that a pointer may go through in which an
362 /// objc_retain and objc_release are actually needed.
365 S_Retain, ///< objc_retain(x).
366 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
367 S_Use, ///< any use of x.
368 S_Stop, ///< like S_Release, but code motion is stopped.
369 S_Release, ///< objc_release(x).
370 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
373 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374 LLVM_ATTRIBUTE_UNUSED;
375 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
378 return OS << "S_None";
380 return OS << "S_Retain";
382 return OS << "S_CanRelease";
384 return OS << "S_Use";
386 return OS << "S_Release";
387 case S_MovableRelease:
388 return OS << "S_MovableRelease";
390 return OS << "S_Stop";
392 llvm_unreachable("Unknown sequence type.");
396 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
400 if (A == S_None || B == S_None)
403 if (A > B) std::swap(A, B);
405 // Choose the side which is further along in the sequence.
406 if ((A == S_Retain || A == S_CanRelease) &&
407 (B == S_CanRelease || B == S_Use))
410 // Choose the side which is further along in the sequence.
411 if ((A == S_Use || A == S_CanRelease) &&
412 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
414 // If both sides are releases, choose the more conservative one.
415 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
417 if (A == S_Release && B == S_MovableRelease)
425 /// \brief Unidirectional information about either a
426 /// retain-decrement-use-release sequence or release-use-decrement-retain
427 /// reverse sequence.
429 /// After an objc_retain, the reference count of the referenced
430 /// object is known to be positive. Similarly, before an objc_release, the
431 /// reference count of the referenced object is known to be positive. If
432 /// there are retain-release pairs in code regions where the retain count
433 /// is known to be positive, they can be eliminated, regardless of any side
434 /// effects between them.
436 /// Also, a retain+release pair nested within another retain+release
437 /// pair all on the known same pointer value can be eliminated, regardless
438 /// of any intervening side effects.
440 /// KnownSafe is true when either of these conditions is satisfied.
443 /// True of the objc_release calls are all marked with the "tail" keyword.
444 bool IsTailCallRelease;
446 /// If the Calls are objc_release calls and they all have a
447 /// clang.imprecise_release tag, this is the metadata tag.
448 MDNode *ReleaseMetadata;
450 /// For a top-down sequence, the set of objc_retains or
451 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452 SmallPtrSet<Instruction *, 2> Calls;
454 /// The set of optimal insert positions for moving calls in the opposite
456 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
458 /// If this is true, we cannot perform code motion but can still remove
459 /// retain/release pairs.
460 bool CFGHazardAfflicted;
463 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464 CFGHazardAfflicted(false) {}
468 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
469 /// occured, false otherwise.
470 bool Merge(const RRInfo &Other);
475 void RRInfo::clear() {
477 IsTailCallRelease = false;
480 ReverseInsertPts.clear();
481 CFGHazardAfflicted = false;
484 bool RRInfo::Merge(const RRInfo &Other) {
485 // Conservatively merge the ReleaseMetadata information.
486 if (ReleaseMetadata != Other.ReleaseMetadata)
489 // Conservatively merge the boolean state.
490 KnownSafe &= Other.KnownSafe;
491 IsTailCallRelease &= Other.IsTailCallRelease;
492 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
494 // Merge the call sets.
495 Calls.insert(Other.Calls.begin(), Other.Calls.end());
497 // Merge the insert point sets. If there are any differences,
498 // that makes this a partial merge.
499 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
500 for (SmallPtrSet<Instruction *, 2>::const_iterator
501 I = Other.ReverseInsertPts.begin(),
502 E = Other.ReverseInsertPts.end(); I != E; ++I)
503 Partial |= ReverseInsertPts.insert(*I);
508 /// \brief This class summarizes several per-pointer runtime properties which
509 /// are propogated through the flow graph.
511 /// True if the reference count is known to be incremented.
512 bool KnownPositiveRefCount;
514 /// True if we've seen an opportunity for partial RR elimination, such as
515 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
518 /// The current position in the sequence.
522 /// Unidirectional information about the current sequence.
524 /// TODO: Encapsulate this better.
527 PtrState() : KnownPositiveRefCount(false), Partial(false),
531 bool IsKnownSafe() const {
532 return RRI.KnownSafe;
535 void SetKnownSafe(const bool NewValue) {
536 RRI.KnownSafe = NewValue;
539 bool IsTailCallRelease() const {
540 return RRI.IsTailCallRelease;
543 void SetTailCallRelease(const bool NewValue) {
544 RRI.IsTailCallRelease = NewValue;
547 bool IsTrackingImpreciseReleases() {
548 return RRI.ReleaseMetadata != 0;
551 const MDNode *GetReleaseMetadata() const {
552 return RRI.ReleaseMetadata;
555 void SetReleaseMetadata(MDNode *NewValue) {
556 RRI.ReleaseMetadata = NewValue;
559 bool IsCFGHazardAfflicted() const {
560 return RRI.CFGHazardAfflicted;
563 void SetCFGHazardAfflicted(const bool NewValue) {
564 RRI.CFGHazardAfflicted = NewValue;
567 void SetKnownPositiveRefCount() {
568 DEBUG(dbgs() << "Setting Known Positive.\n");
569 KnownPositiveRefCount = true;
572 void ClearKnownPositiveRefCount() {
573 DEBUG(dbgs() << "Clearing Known Positive.\n");
574 KnownPositiveRefCount = false;
577 bool HasKnownPositiveRefCount() const {
578 return KnownPositiveRefCount;
581 void SetSeq(Sequence NewSeq) {
582 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
586 Sequence GetSeq() const {
590 void ClearSequenceProgress() {
591 ResetSequenceProgress(S_None);
594 void ResetSequenceProgress(Sequence NewSeq) {
595 DEBUG(dbgs() << "Resetting sequence progress.\n");
601 void Merge(const PtrState &Other, bool TopDown);
606 PtrState::Merge(const PtrState &Other, bool TopDown) {
607 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
608 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
610 // If we're not in a sequence (anymore), drop all associated state.
614 } else if (Partial || Other.Partial) {
615 // If we're doing a merge on a path that's previously seen a partial
616 // merge, conservatively drop the sequence, to avoid doing partial
617 // RR elimination. If the branch predicates for the two merge differ,
618 // mixing them is unsafe.
619 ClearSequenceProgress();
621 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
622 // point, we know that currently we are not partial. Stash whether or not
623 // the merge operation caused us to undergo a partial merging of reverse
625 Partial = RRI.Merge(Other.RRI);
630 /// \brief Per-BasicBlock state.
632 /// The number of unique control paths from the entry which can reach this
634 unsigned TopDownPathCount;
636 /// The number of unique control paths to exits from this block.
637 unsigned BottomUpPathCount;
639 /// A type for PerPtrTopDown and PerPtrBottomUp.
640 typedef MapVector<const Value *, PtrState> MapTy;
642 /// The top-down traversal uses this to record information known about a
643 /// pointer at the bottom of each block.
646 /// The bottom-up traversal uses this to record information known about a
647 /// pointer at the top of each block.
648 MapTy PerPtrBottomUp;
650 /// Effective predecessors of the current block ignoring ignorable edges and
651 /// ignored backedges.
652 SmallVector<BasicBlock *, 2> Preds;
653 /// Effective successors of the current block ignoring ignorable edges and
654 /// ignored backedges.
655 SmallVector<BasicBlock *, 2> Succs;
658 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
660 typedef MapTy::iterator ptr_iterator;
661 typedef MapTy::const_iterator ptr_const_iterator;
663 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
664 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
665 ptr_const_iterator top_down_ptr_begin() const {
666 return PerPtrTopDown.begin();
668 ptr_const_iterator top_down_ptr_end() const {
669 return PerPtrTopDown.end();
672 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
673 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
674 ptr_const_iterator bottom_up_ptr_begin() const {
675 return PerPtrBottomUp.begin();
677 ptr_const_iterator bottom_up_ptr_end() const {
678 return PerPtrBottomUp.end();
681 /// Mark this block as being an entry block, which has one path from the
682 /// entry by definition.
683 void SetAsEntry() { TopDownPathCount = 1; }
685 /// Mark this block as being an exit block, which has one path to an exit by
687 void SetAsExit() { BottomUpPathCount = 1; }
689 /// Attempt to find the PtrState object describing the top down state for
690 /// pointer Arg. Return a new initialized PtrState describing the top down
691 /// state for Arg if we do not find one.
692 PtrState &getPtrTopDownState(const Value *Arg) {
693 return PerPtrTopDown[Arg];
696 /// Attempt to find the PtrState object describing the bottom up state for
697 /// pointer Arg. Return a new initialized PtrState describing the bottom up
698 /// state for Arg if we do not find one.
699 PtrState &getPtrBottomUpState(const Value *Arg) {
700 return PerPtrBottomUp[Arg];
703 /// Attempt to find the PtrState object describing the bottom up state for
705 ptr_iterator findPtrBottomUpState(const Value *Arg) {
706 return PerPtrBottomUp.find(Arg);
709 void clearBottomUpPointers() {
710 PerPtrBottomUp.clear();
713 void clearTopDownPointers() {
714 PerPtrTopDown.clear();
717 void InitFromPred(const BBState &Other);
718 void InitFromSucc(const BBState &Other);
719 void MergePred(const BBState &Other);
720 void MergeSucc(const BBState &Other);
722 /// Compute the number of possible unique paths from an entry to an exit
723 /// which pass through this block. This is only valid after both the
724 /// top-down and bottom-up traversals are complete.
726 /// Returns true if overflow occured. Returns false if overflow did not
728 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
729 assert(TopDownPathCount != 0);
730 assert(BottomUpPathCount != 0);
731 unsigned long long Product =
732 (unsigned long long)TopDownPathCount*BottomUpPathCount;
734 // Overflow occured if any of the upper bits of Product are set.
735 return Product >> 32;
738 // Specialized CFG utilities.
739 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
740 edge_iterator pred_begin() { return Preds.begin(); }
741 edge_iterator pred_end() { return Preds.end(); }
742 edge_iterator succ_begin() { return Succs.begin(); }
743 edge_iterator succ_end() { return Succs.end(); }
745 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
746 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
748 bool isExit() const { return Succs.empty(); }
752 void BBState::InitFromPred(const BBState &Other) {
753 PerPtrTopDown = Other.PerPtrTopDown;
754 TopDownPathCount = Other.TopDownPathCount;
757 void BBState::InitFromSucc(const BBState &Other) {
758 PerPtrBottomUp = Other.PerPtrBottomUp;
759 BottomUpPathCount = Other.BottomUpPathCount;
762 /// The top-down traversal uses this to merge information about predecessors to
763 /// form the initial state for a new block.
764 void BBState::MergePred(const BBState &Other) {
765 // Other.TopDownPathCount can be 0, in which case it is either dead or a
766 // loop backedge. Loop backedges are special.
767 TopDownPathCount += Other.TopDownPathCount;
769 // Check for overflow. If we have overflow, fall back to conservative
771 if (TopDownPathCount < Other.TopDownPathCount) {
772 clearTopDownPointers();
776 // For each entry in the other set, if our set has an entry with the same key,
777 // merge the entries. Otherwise, copy the entry and merge it with an empty
779 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
780 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
781 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
782 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
786 // For each entry in our set, if the other set doesn't have an entry with the
787 // same key, force it to merge with an empty entry.
788 for (ptr_iterator MI = top_down_ptr_begin(),
789 ME = top_down_ptr_end(); MI != ME; ++MI)
790 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
791 MI->second.Merge(PtrState(), /*TopDown=*/true);
794 /// The bottom-up traversal uses this to merge information about successors to
795 /// form the initial state for a new block.
796 void BBState::MergeSucc(const BBState &Other) {
797 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
798 // loop backedge. Loop backedges are special.
799 BottomUpPathCount += Other.BottomUpPathCount;
801 // Check for overflow. If we have overflow, fall back to conservative
803 if (BottomUpPathCount < Other.BottomUpPathCount) {
804 clearBottomUpPointers();
808 // For each entry in the other set, if our set has an entry with the
809 // same key, merge the entries. Otherwise, copy the entry and merge
810 // it with an empty entry.
811 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
812 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
813 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
814 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
818 // For each entry in our set, if the other set doesn't have an entry
819 // with the same key, force it to merge with an empty entry.
820 for (ptr_iterator MI = bottom_up_ptr_begin(),
821 ME = bottom_up_ptr_end(); MI != ME; ++MI)
822 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
823 MI->second.Merge(PtrState(), /*TopDown=*/false);
826 // Only enable ARC Annotations if we are building a debug version of
829 #define ARC_ANNOTATIONS
832 // Define some macros along the lines of DEBUG and some helper functions to make
833 // it cleaner to create annotations in the source code and to no-op when not
834 // building in debug mode.
835 #ifdef ARC_ANNOTATIONS
837 #include "llvm/Support/CommandLine.h"
839 /// Enable/disable ARC sequence annotations.
841 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
842 cl::desc("Enable emission of arc data flow analysis "
845 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
846 cl::desc("Disable check for cfg hazards when "
848 static cl::opt<std::string>
849 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
851 cl::desc("filter out all data flow annotations "
852 "but those that apply to the given "
853 "target llvm identifier."));
855 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
856 /// instruction so that we can track backwards when post processing via the llvm
857 /// arc annotation processor tool. If the function is an
858 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
862 // If pointer is a result of an instruction and it does not have a source
863 // MDNode it, attach a new MDNode onto it. If pointer is a result of
864 // an instruction and does have a source MDNode attached to it, return a
865 // reference to said Node. Otherwise just return 0.
866 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
868 if (!(Node = Inst->getMetadata(NodeId))) {
869 // We do not have any node. Generate and attatch the hash MDString to the
872 // We just use an MDString to ensure that this metadata gets written out
873 // of line at the module level and to provide a very simple format
874 // encoding the information herein. Both of these makes it simpler to
875 // parse the annotations by a simple external program.
877 raw_string_ostream os(Str);
878 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
879 << Inst->getName() << ")";
881 Hash = MDString::get(Inst->getContext(), os.str());
882 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
884 // We have a node. Grab its hash and return it.
885 assert(Node->getNumOperands() == 1 &&
886 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
887 Hash = cast<MDString>(Node->getOperand(0));
889 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
891 raw_string_ostream os(str);
892 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
894 Hash = MDString::get(Arg->getContext(), os.str());
900 static std::string SequenceToString(Sequence A) {
902 raw_string_ostream os(str);
907 /// Helper function to change a Sequence into a String object using our overload
908 /// for raw_ostream so we only have printing code in one location.
909 static MDString *SequenceToMDString(LLVMContext &Context,
911 return MDString::get(Context, SequenceToString(A));
914 /// A simple function to generate a MDNode which describes the change in state
915 /// for Value *Ptr caused by Instruction *Inst.
916 static void AppendMDNodeToInstForPtr(unsigned NodeId,
919 MDString *PtrSourceMDNodeID,
923 Value *tmp[3] = {PtrSourceMDNodeID,
924 SequenceToMDString(Inst->getContext(),
926 SequenceToMDString(Inst->getContext(),
928 Node = MDNode::get(Inst->getContext(),
929 ArrayRef<Value*>(tmp, 3));
931 Inst->setMetadata(NodeId, Node);
934 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
935 /// state of a pointer at the entrance to a basic block.
936 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
937 Value *Ptr, Sequence Seq) {
938 // If we have a target identifier, make sure that we match it before
940 if(!ARCAnnotationTargetIdentifier.empty() &&
941 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
944 Module *M = BB->getParent()->getParent();
945 LLVMContext &C = M->getContext();
946 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
947 Type *I8XX = PointerType::getUnqual(I8X);
948 Type *Params[] = {I8XX, I8XX};
949 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
950 ArrayRef<Type*>(Params, 2),
952 Constant *Callee = M->getOrInsertFunction(Name, FTy);
954 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
957 StringRef Tmp = Ptr->getName();
958 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
959 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
961 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
962 cast<Constant>(ActualPtrName), Tmp);
966 std::string SeqStr = SequenceToString(Seq);
967 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
968 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
970 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
971 cast<Constant>(ActualPtrName), SeqStr);
974 Builder.CreateCall2(Callee, PtrName, S);
977 /// Add to the end of the basic block llvm.ptr.annotations which show the state
978 /// of the pointer at the bottom of the basic block.
979 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
980 Value *Ptr, Sequence Seq) {
981 // If we have a target identifier, make sure that we match it before emitting
983 if(!ARCAnnotationTargetIdentifier.empty() &&
984 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
987 Module *M = BB->getParent()->getParent();
988 LLVMContext &C = M->getContext();
989 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
990 Type *I8XX = PointerType::getUnqual(I8X);
991 Type *Params[] = {I8XX, I8XX};
992 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
993 ArrayRef<Type*>(Params, 2),
995 Constant *Callee = M->getOrInsertFunction(Name, FTy);
997 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
1000 StringRef Tmp = Ptr->getName();
1001 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
1002 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
1004 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1005 cast<Constant>(ActualPtrName), Tmp);
1009 std::string SeqStr = SequenceToString(Seq);
1010 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1011 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1013 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1014 cast<Constant>(ActualPtrName), SeqStr);
1016 Builder.CreateCall2(Callee, PtrName, S);
1019 /// Adds a source annotation to pointer and a state change annotation to Inst
1020 /// referencing the source annotation and the old/new state of pointer.
1021 static void GenerateARCAnnotation(unsigned InstMDId,
1027 if (EnableARCAnnotations) {
1028 // If we have a target identifier, make sure that we match it before
1029 // emitting an annotation.
1030 if(!ARCAnnotationTargetIdentifier.empty() &&
1031 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1034 // First generate the source annotation on our pointer. This will return an
1035 // MDString* if Ptr actually comes from an instruction implying we can put
1036 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1037 // then we know that our pointer is from an Argument so we put a reference
1038 // to the argument number.
1040 // The point of this is to make it easy for the
1041 // llvm-arc-annotation-processor tool to cross reference where the source
1042 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1043 // information via debug info for backends to use (since why would anyone
1044 // need such a thing from LLVM IR besides in non standard cases
1046 MDString *SourcePtrMDNode =
1047 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1048 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1053 // The actual interface for accessing the above functionality is defined via
1054 // some simple macros which are defined below. We do this so that the user does
1055 // not need to pass in what metadata id is needed resulting in cleaner code and
1056 // additionally since it provides an easy way to conditionally no-op all
1057 // annotation support in a non-debug build.
1059 /// Use this macro to annotate a sequence state change when processing
1060 /// instructions bottom up,
1061 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1062 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1063 ARCAnnotationProvenanceSourceMDKind, (inst), \
1064 const_cast<Value*>(ptr), (old), (new))
1065 /// Use this macro to annotate a sequence state change when processing
1066 /// instructions top down.
1067 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1068 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1069 ARCAnnotationProvenanceSourceMDKind, (inst), \
1070 const_cast<Value*>(ptr), (old), (new))
1072 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1074 if (EnableARCAnnotations) { \
1075 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1076 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1077 Value *Ptr = const_cast<Value*>(I->first); \
1078 Sequence Seq = I->second.GetSeq(); \
1079 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1084 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1085 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1086 Entrance, bottom_up)
1087 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1088 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1089 Terminator, bottom_up)
1090 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1091 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1093 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1094 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1095 Terminator, top_down)
1097 #else // !ARC_ANNOTATION
1098 // If annotations are off, noop.
1099 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1100 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1101 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1102 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1103 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1104 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1105 #endif // !ARC_ANNOTATION
1108 /// \brief The main ARC optimization pass.
1109 class ObjCARCOpt : public FunctionPass {
1111 ProvenanceAnalysis PA;
1113 // This is used to track if a pointer is stored into an alloca.
1114 DenseSet<const Value *> MultiOwnersSet;
1116 /// A flag indicating whether this optimization pass should run.
1119 /// Declarations for ObjC runtime functions, for use in creating calls to
1120 /// them. These are initialized lazily to avoid cluttering up the Module
1121 /// with unused declarations.
1123 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1124 Constant *AutoreleaseRVCallee;
1125 /// Declaration for ObjC runtime function objc_release.
1126 Constant *ReleaseCallee;
1127 /// Declaration for ObjC runtime function objc_retain.
1128 Constant *RetainCallee;
1129 /// Declaration for ObjC runtime function objc_retainBlock.
1130 Constant *RetainBlockCallee;
1131 /// Declaration for ObjC runtime function objc_autorelease.
1132 Constant *AutoreleaseCallee;
1134 /// Flags which determine whether each of the interesting runtine functions
1135 /// is in fact used in the current function.
1136 unsigned UsedInThisFunction;
1138 /// The Metadata Kind for clang.imprecise_release metadata.
1139 unsigned ImpreciseReleaseMDKind;
1141 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1142 unsigned CopyOnEscapeMDKind;
1144 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1145 unsigned NoObjCARCExceptionsMDKind;
1147 #ifdef ARC_ANNOTATIONS
1148 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1149 unsigned ARCAnnotationBottomUpMDKind;
1150 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1151 unsigned ARCAnnotationTopDownMDKind;
1152 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1153 unsigned ARCAnnotationProvenanceSourceMDKind;
1154 #endif // ARC_ANNOATIONS
1156 Constant *getAutoreleaseRVCallee(Module *M);
1157 Constant *getReleaseCallee(Module *M);
1158 Constant *getRetainCallee(Module *M);
1159 Constant *getRetainBlockCallee(Module *M);
1160 Constant *getAutoreleaseCallee(Module *M);
1162 bool IsRetainBlockOptimizable(const Instruction *Inst);
1164 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1165 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1166 InstructionClass &Class);
1167 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1168 InstructionClass &Class);
1169 void OptimizeIndividualCalls(Function &F);
1171 void CheckForCFGHazards(const BasicBlock *BB,
1172 DenseMap<const BasicBlock *, BBState> &BBStates,
1173 BBState &MyStates) const;
1174 bool VisitInstructionBottomUp(Instruction *Inst,
1176 MapVector<Value *, RRInfo> &Retains,
1178 bool VisitBottomUp(BasicBlock *BB,
1179 DenseMap<const BasicBlock *, BBState> &BBStates,
1180 MapVector<Value *, RRInfo> &Retains);
1181 bool VisitInstructionTopDown(Instruction *Inst,
1182 DenseMap<Value *, RRInfo> &Releases,
1184 bool VisitTopDown(BasicBlock *BB,
1185 DenseMap<const BasicBlock *, BBState> &BBStates,
1186 DenseMap<Value *, RRInfo> &Releases);
1187 bool Visit(Function &F,
1188 DenseMap<const BasicBlock *, BBState> &BBStates,
1189 MapVector<Value *, RRInfo> &Retains,
1190 DenseMap<Value *, RRInfo> &Releases);
1192 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1193 MapVector<Value *, RRInfo> &Retains,
1194 DenseMap<Value *, RRInfo> &Releases,
1195 SmallVectorImpl<Instruction *> &DeadInsts,
1198 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1199 MapVector<Value *, RRInfo> &Retains,
1200 DenseMap<Value *, RRInfo> &Releases,
1202 SmallVector<Instruction *, 4> &NewRetains,
1203 SmallVector<Instruction *, 4> &NewReleases,
1204 SmallVector<Instruction *, 8> &DeadInsts,
1205 RRInfo &RetainsToMove,
1206 RRInfo &ReleasesToMove,
1209 bool &AnyPairsCompletelyEliminated);
1211 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1212 MapVector<Value *, RRInfo> &Retains,
1213 DenseMap<Value *, RRInfo> &Releases,
1216 void OptimizeWeakCalls(Function &F);
1218 bool OptimizeSequences(Function &F);
1220 void OptimizeReturns(Function &F);
1223 void GatherStatistics(Function &F, bool AfterOptimization = false);
1226 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1227 virtual bool doInitialization(Module &M);
1228 virtual bool runOnFunction(Function &F);
1229 virtual void releaseMemory();
1233 ObjCARCOpt() : FunctionPass(ID) {
1234 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1239 char ObjCARCOpt::ID = 0;
1240 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1241 "objc-arc", "ObjC ARC optimization", false, false)
1242 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1243 INITIALIZE_PASS_END(ObjCARCOpt,
1244 "objc-arc", "ObjC ARC optimization", false, false)
1246 Pass *llvm::createObjCARCOptPass() {
1247 return new ObjCARCOpt();
1250 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1251 AU.addRequired<ObjCARCAliasAnalysis>();
1252 AU.addRequired<AliasAnalysis>();
1253 // ARC optimization doesn't currently split critical edges.
1254 AU.setPreservesCFG();
1257 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1258 // Without the magic metadata tag, we have to assume this might be an
1259 // objc_retainBlock call inserted to convert a block pointer to an id,
1260 // in which case it really is needed.
1261 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1264 // If the pointer "escapes" (not including being used in a call),
1265 // the copy may be needed.
1266 if (DoesRetainableObjPtrEscape(Inst))
1269 // Otherwise, it's not needed.
1273 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1274 if (!AutoreleaseRVCallee) {
1275 LLVMContext &C = M->getContext();
1276 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1277 Type *Params[] = { I8X };
1278 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1279 AttributeSet Attribute =
1280 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1281 Attribute::NoUnwind);
1282 AutoreleaseRVCallee =
1283 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1286 return AutoreleaseRVCallee;
1289 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1290 if (!ReleaseCallee) {
1291 LLVMContext &C = M->getContext();
1292 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1293 AttributeSet Attribute =
1294 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1295 Attribute::NoUnwind);
1297 M->getOrInsertFunction(
1299 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1302 return ReleaseCallee;
1305 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1306 if (!RetainCallee) {
1307 LLVMContext &C = M->getContext();
1308 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1309 AttributeSet Attribute =
1310 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1311 Attribute::NoUnwind);
1313 M->getOrInsertFunction(
1315 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1318 return RetainCallee;
1321 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1322 if (!RetainBlockCallee) {
1323 LLVMContext &C = M->getContext();
1324 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1325 // objc_retainBlock is not nounwind because it calls user copy constructors
1326 // which could theoretically throw.
1328 M->getOrInsertFunction(
1330 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1333 return RetainBlockCallee;
1336 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1337 if (!AutoreleaseCallee) {
1338 LLVMContext &C = M->getContext();
1339 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1340 AttributeSet Attribute =
1341 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1342 Attribute::NoUnwind);
1344 M->getOrInsertFunction(
1346 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1349 return AutoreleaseCallee;
1352 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1353 /// not a return value. Or, if it can be paired with an
1354 /// objc_autoreleaseReturnValue, delete the pair and return true.
1356 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1357 // Check for the argument being from an immediately preceding call or invoke.
1358 const Value *Arg = GetObjCArg(RetainRV);
1359 ImmutableCallSite CS(Arg);
1360 if (const Instruction *Call = CS.getInstruction()) {
1361 if (Call->getParent() == RetainRV->getParent()) {
1362 BasicBlock::const_iterator I = Call;
1364 while (IsNoopInstruction(I)) ++I;
1365 if (&*I == RetainRV)
1367 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1368 BasicBlock *RetainRVParent = RetainRV->getParent();
1369 if (II->getNormalDest() == RetainRVParent) {
1370 BasicBlock::const_iterator I = RetainRVParent->begin();
1371 while (IsNoopInstruction(I)) ++I;
1372 if (&*I == RetainRV)
1378 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1379 // pointer. In this case, we can delete the pair.
1380 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1382 do --I; while (I != Begin && IsNoopInstruction(I));
1383 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1384 GetObjCArg(I) == Arg) {
1388 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1389 << "Erasing " << *RetainRV << "\n");
1391 EraseInstruction(I);
1392 EraseInstruction(RetainRV);
1397 // Turn it to a plain objc_retain.
1401 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1402 "objc_retain since the operand is not a return value.\n"
1403 "Old = " << *RetainRV << "\n");
1405 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1407 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1412 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1413 /// used as a return value.
1415 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1416 InstructionClass &Class) {
1417 // Check for a return of the pointer value.
1418 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1419 SmallVector<const Value *, 2> Users;
1420 Users.push_back(Ptr);
1422 Ptr = Users.pop_back_val();
1423 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1425 const User *I = *UI;
1426 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1428 if (isa<BitCastInst>(I))
1431 } while (!Users.empty());
1436 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1437 "objc_autorelease since its operand is not used as a return "
1439 "Old = " << *AutoreleaseRV << "\n");
1441 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1443 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1444 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1445 Class = IC_Autorelease;
1447 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1451 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1454 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1455 // does not escape (following the rules of block escaping), strength reduce the
1456 // objc_retainBlock to an objc_retain.
1458 // TODO: If an objc_retainBlock call is dominated period by a previous
1459 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1462 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1463 InstructionClass &Class) {
1464 assert(GetBasicInstructionClass(Inst) == Class);
1465 assert(IC_RetainBlock == Class);
1467 // If we can not optimize Inst, return false.
1468 if (!IsRetainBlockOptimizable(Inst))
1474 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1475 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1476 CallInst *RetainBlock = cast<CallInst>(Inst);
1477 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1478 // Remove copy_on_escape metadata.
1479 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1481 DEBUG(dbgs() << "New: " << *Inst << "\n");
1485 /// Visit each call, one at a time, and make simplifications without doing any
1486 /// additional analysis.
1487 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1488 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1489 // Reset all the flags in preparation for recomputing them.
1490 UsedInThisFunction = 0;
1492 // Visit all objc_* calls in F.
1493 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1494 Instruction *Inst = &*I++;
1496 InstructionClass Class = GetBasicInstructionClass(Inst);
1498 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1503 // Delete no-op casts. These function calls have special semantics, but
1504 // the semantics are entirely implemented via lowering in the front-end,
1505 // so by the time they reach the optimizer, they are just no-op calls
1506 // which return their argument.
1508 // There are gray areas here, as the ability to cast reference-counted
1509 // pointers to raw void* and back allows code to break ARC assumptions,
1510 // however these are currently considered to be unimportant.
1514 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1515 EraseInstruction(Inst);
1518 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1521 case IC_LoadWeakRetained:
1523 case IC_DestroyWeak: {
1524 CallInst *CI = cast<CallInst>(Inst);
1525 if (IsNullOrUndef(CI->getArgOperand(0))) {
1527 Type *Ty = CI->getArgOperand(0)->getType();
1528 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1529 Constant::getNullValue(Ty),
1531 llvm::Value *NewValue = UndefValue::get(CI->getType());
1532 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1533 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1534 CI->replaceAllUsesWith(NewValue);
1535 CI->eraseFromParent();
1542 CallInst *CI = cast<CallInst>(Inst);
1543 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1544 IsNullOrUndef(CI->getArgOperand(1))) {
1546 Type *Ty = CI->getArgOperand(0)->getType();
1547 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1548 Constant::getNullValue(Ty),
1551 llvm::Value *NewValue = UndefValue::get(CI->getType());
1552 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1553 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1555 CI->replaceAllUsesWith(NewValue);
1556 CI->eraseFromParent();
1561 case IC_RetainBlock:
1562 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1563 // onto the objc_retain peephole optimizations. Otherwise break.
1564 OptimizeRetainBlockCall(F, Inst, Class);
1567 if (OptimizeRetainRVCall(F, Inst))
1570 case IC_AutoreleaseRV:
1571 OptimizeAutoreleaseRVCall(F, Inst, Class);
1575 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1576 if (IsAutorelease(Class) && Inst->use_empty()) {
1577 CallInst *Call = cast<CallInst>(Inst);
1578 const Value *Arg = Call->getArgOperand(0);
1579 Arg = FindSingleUseIdentifiedObject(Arg);
1584 // Create the declaration lazily.
1585 LLVMContext &C = Inst->getContext();
1587 CallInst::Create(getReleaseCallee(F.getParent()),
1588 Call->getArgOperand(0), "", Call);
1589 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1591 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1592 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1593 << *NewCall << "\n");
1595 EraseInstruction(Call);
1601 // For functions which can never be passed stack arguments, add
1603 if (IsAlwaysTail(Class)) {
1605 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1606 "passed stack args: " << *Inst << "\n");
1607 cast<CallInst>(Inst)->setTailCall();
1610 // Ensure that functions that can never have a "tail" keyword due to the
1611 // semantics of ARC truly do not do so.
1612 if (IsNeverTail(Class)) {
1614 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1616 cast<CallInst>(Inst)->setTailCall(false);
1619 // Set nounwind as needed.
1620 if (IsNoThrow(Class)) {
1622 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1624 cast<CallInst>(Inst)->setDoesNotThrow();
1627 if (!IsNoopOnNull(Class)) {
1628 UsedInThisFunction |= 1 << Class;
1632 const Value *Arg = GetObjCArg(Inst);
1634 // ARC calls with null are no-ops. Delete them.
1635 if (IsNullOrUndef(Arg)) {
1638 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1640 EraseInstruction(Inst);
1644 // Keep track of which of retain, release, autorelease, and retain_block
1645 // are actually present in this function.
1646 UsedInThisFunction |= 1 << Class;
1648 // If Arg is a PHI, and one or more incoming values to the
1649 // PHI are null, and the call is control-equivalent to the PHI, and there
1650 // are no relevant side effects between the PHI and the call, the call
1651 // could be pushed up to just those paths with non-null incoming values.
1652 // For now, don't bother splitting critical edges for this.
1653 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1654 Worklist.push_back(std::make_pair(Inst, Arg));
1656 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1660 const PHINode *PN = dyn_cast<PHINode>(Arg);
1663 // Determine if the PHI has any null operands, or any incoming
1665 bool HasNull = false;
1666 bool HasCriticalEdges = false;
1667 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1669 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1670 if (IsNullOrUndef(Incoming))
1672 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1673 .getNumSuccessors() != 1) {
1674 HasCriticalEdges = true;
1678 // If we have null operands and no critical edges, optimize.
1679 if (!HasCriticalEdges && HasNull) {
1680 SmallPtrSet<Instruction *, 4> DependingInstructions;
1681 SmallPtrSet<const BasicBlock *, 4> Visited;
1683 // Check that there is nothing that cares about the reference
1684 // count between the call and the phi.
1687 case IC_RetainBlock:
1688 // These can always be moved up.
1691 // These can't be moved across things that care about the retain
1693 FindDependencies(NeedsPositiveRetainCount, Arg,
1694 Inst->getParent(), Inst,
1695 DependingInstructions, Visited, PA);
1697 case IC_Autorelease:
1698 // These can't be moved across autorelease pool scope boundaries.
1699 FindDependencies(AutoreleasePoolBoundary, Arg,
1700 Inst->getParent(), Inst,
1701 DependingInstructions, Visited, PA);
1704 case IC_AutoreleaseRV:
1705 // Don't move these; the RV optimization depends on the autoreleaseRV
1706 // being tail called, and the retainRV being immediately after a call
1707 // (which might still happen if we get lucky with codegen layout, but
1708 // it's not worth taking the chance).
1711 llvm_unreachable("Invalid dependence flavor");
1714 if (DependingInstructions.size() == 1 &&
1715 *DependingInstructions.begin() == PN) {
1718 // Clone the call into each predecessor that has a non-null value.
1719 CallInst *CInst = cast<CallInst>(Inst);
1720 Type *ParamTy = CInst->getArgOperand(0)->getType();
1721 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1723 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1724 if (!IsNullOrUndef(Incoming)) {
1725 CallInst *Clone = cast<CallInst>(CInst->clone());
1726 Value *Op = PN->getIncomingValue(i);
1727 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1728 if (Op->getType() != ParamTy)
1729 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1730 Clone->setArgOperand(0, Op);
1731 Clone->insertBefore(InsertPos);
1733 DEBUG(dbgs() << "Cloning "
1735 "And inserting clone at " << *InsertPos << "\n");
1736 Worklist.push_back(std::make_pair(Clone, Incoming));
1739 // Erase the original call.
1740 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1741 EraseInstruction(CInst);
1745 } while (!Worklist.empty());
1749 /// If we have a top down pointer in the S_Use state, make sure that there are
1750 /// no CFG hazards by checking the states of various bottom up pointers.
1751 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1752 const bool SuccSRRIKnownSafe,
1754 bool &SomeSuccHasSame,
1755 bool &AllSuccsHaveSame,
1756 bool &NotAllSeqEqualButKnownSafe,
1757 bool &ShouldContinue) {
1759 case S_CanRelease: {
1760 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
1761 S.ClearSequenceProgress();
1764 S.SetCFGHazardAfflicted(true);
1765 ShouldContinue = true;
1769 SomeSuccHasSame = true;
1773 case S_MovableRelease:
1774 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1775 AllSuccsHaveSame = false;
1777 NotAllSeqEqualButKnownSafe = true;
1780 llvm_unreachable("bottom-up pointer in retain state!");
1782 llvm_unreachable("This should have been handled earlier.");
1786 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1787 /// there are no CFG hazards by checking the states of various bottom up
1789 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1790 const bool SuccSRRIKnownSafe,
1792 bool &SomeSuccHasSame,
1793 bool &AllSuccsHaveSame,
1794 bool &NotAllSeqEqualButKnownSafe) {
1797 SomeSuccHasSame = true;
1801 case S_MovableRelease:
1803 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1804 AllSuccsHaveSame = false;
1806 NotAllSeqEqualButKnownSafe = true;
1809 llvm_unreachable("bottom-up pointer in retain state!");
1811 llvm_unreachable("This should have been handled earlier.");
1815 /// Check for critical edges, loop boundaries, irreducible control flow, or
1816 /// other CFG structures where moving code across the edge would result in it
1817 /// being executed more.
1819 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1820 DenseMap<const BasicBlock *, BBState> &BBStates,
1821 BBState &MyStates) const {
1822 // If any top-down local-use or possible-dec has a succ which is earlier in
1823 // the sequence, forget it.
1824 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1825 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1826 PtrState &S = I->second;
1827 const Sequence Seq = I->second.GetSeq();
1829 // We only care about S_Retain, S_CanRelease, and S_Use.
1833 // Make sure that if extra top down states are added in the future that this
1834 // code is updated to handle it.
1835 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1836 "Unknown top down sequence state.");
1838 const Value *Arg = I->first;
1839 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1840 bool SomeSuccHasSame = false;
1841 bool AllSuccsHaveSame = true;
1842 bool NotAllSeqEqualButKnownSafe = false;
1844 succ_const_iterator SI(TI), SE(TI, false);
1846 for (; SI != SE; ++SI) {
1847 // If VisitBottomUp has pointer information for this successor, take
1848 // what we know about it.
1849 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1851 assert(BBI != BBStates.end());
1852 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1853 const Sequence SuccSSeq = SuccS.GetSeq();
1855 // If bottom up, the pointer is in an S_None state, clear the sequence
1856 // progress since the sequence in the bottom up state finished
1857 // suggesting a mismatch in between retains/releases. This is true for
1858 // all three cases that we are handling here: S_Retain, S_Use, and
1860 if (SuccSSeq == S_None) {
1861 S.ClearSequenceProgress();
1865 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1867 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1869 // *NOTE* We do not use Seq from above here since we are allowing for
1870 // S.GetSeq() to change while we are visiting basic blocks.
1871 switch(S.GetSeq()) {
1873 bool ShouldContinue = false;
1874 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1875 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1881 case S_CanRelease: {
1882 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1883 SomeSuccHasSame, AllSuccsHaveSame,
1884 NotAllSeqEqualButKnownSafe);
1891 case S_MovableRelease:
1896 // If the state at the other end of any of the successor edges
1897 // matches the current state, require all edges to match. This
1898 // guards against loops in the middle of a sequence.
1899 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1900 S.ClearSequenceProgress();
1901 } else if (NotAllSeqEqualButKnownSafe) {
1902 // If we would have cleared the state foregoing the fact that we are known
1903 // safe, stop code motion. This is because whether or not it is safe to
1904 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1905 // are allowed to perform code motion.
1906 S.SetCFGHazardAfflicted(true);
1912 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1914 MapVector<Value *, RRInfo> &Retains,
1915 BBState &MyStates) {
1916 bool NestingDetected = false;
1917 InstructionClass Class = GetInstructionClass(Inst);
1918 const Value *Arg = 0;
1920 DEBUG(dbgs() << "Class: " << Class << "\n");
1924 Arg = GetObjCArg(Inst);
1926 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1928 // If we see two releases in a row on the same pointer. If so, make
1929 // a note, and we'll cicle back to revisit it after we've
1930 // hopefully eliminated the second release, which may allow us to
1931 // eliminate the first release too.
1932 // Theoretically we could implement removal of nested retain+release
1933 // pairs by making PtrState hold a stack of states, but this is
1934 // simple and avoids adding overhead for the non-nested case.
1935 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1936 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1937 NestingDetected = true;
1940 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1941 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1942 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1943 S.ResetSequenceProgress(NewSeq);
1944 S.SetReleaseMetadata(ReleaseMetadata);
1945 S.SetKnownSafe(S.HasKnownPositiveRefCount());
1946 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1947 S.RRI.Calls.insert(Inst);
1948 S.SetKnownPositiveRefCount();
1951 case IC_RetainBlock:
1952 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1953 // objc_retainBlocks to objc_retains. Thus at this point any
1954 // objc_retainBlocks that we see are not optimizable.
1958 Arg = GetObjCArg(Inst);
1960 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1961 S.SetKnownPositiveRefCount();
1963 Sequence OldSeq = S.GetSeq();
1967 case S_MovableRelease:
1969 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1970 // imprecise release, clear our reverse insertion points.
1971 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
1972 S.RRI.ReverseInsertPts.clear();
1975 // Don't do retain+release tracking for IC_RetainRV, because it's
1976 // better to let it remain as the first instruction after a call.
1977 if (Class != IC_RetainRV)
1978 Retains[Inst] = S.RRI;
1979 S.ClearSequenceProgress();
1984 llvm_unreachable("bottom-up pointer in retain state!");
1986 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1987 // A retain moving bottom up can be a use.
1990 case IC_AutoreleasepoolPop:
1991 // Conservatively, clear MyStates for all known pointers.
1992 MyStates.clearBottomUpPointers();
1993 return NestingDetected;
1994 case IC_AutoreleasepoolPush:
1996 // These are irrelevant.
1997 return NestingDetected;
1999 // If we have a store into an alloca of a pointer we are tracking, the
2000 // pointer has multiple owners implying that we must be more conservative.
2002 // This comes up in the context of a pointer being ``KnownSafe''. In the
2003 // presense of a block being initialized, the frontend will emit the
2004 // objc_retain on the original pointer and the release on the pointer loaded
2005 // from the alloca. The optimizer will through the provenance analysis
2006 // realize that the two are related, but since we only require KnownSafe in
2007 // one direction, will match the inner retain on the original pointer with
2008 // the guard release on the original pointer. This is fixed by ensuring that
2009 // in the presense of allocas we only unconditionally remove pointers if
2010 // both our retain and our release are KnownSafe.
2011 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2012 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
2013 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
2014 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
2015 if (I != MyStates.bottom_up_ptr_end())
2016 MultiOwnersSet.insert(I->first);
2024 // Consider any other possible effects of this instruction on each
2025 // pointer being tracked.
2026 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2027 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2028 const Value *Ptr = MI->first;
2030 continue; // Handled above.
2031 PtrState &S = MI->second;
2032 Sequence Seq = S.GetSeq();
2034 // Check for possible releases.
2035 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2036 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2038 S.ClearKnownPositiveRefCount();
2041 S.SetSeq(S_CanRelease);
2042 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
2046 case S_MovableRelease:
2051 llvm_unreachable("bottom-up pointer in retain state!");
2055 // Check for possible direct uses.
2058 case S_MovableRelease:
2059 if (CanUse(Inst, Ptr, PA, Class)) {
2060 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2062 assert(S.RRI.ReverseInsertPts.empty());
2063 // If this is an invoke instruction, we're scanning it as part of
2064 // one of its successor blocks, since we can't insert code after it
2065 // in its own block, and we don't want to split critical edges.
2066 if (isa<InvokeInst>(Inst))
2067 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2069 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2071 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2072 } else if (Seq == S_Release && IsUser(Class)) {
2073 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2075 // Non-movable releases depend on any possible objc pointer use.
2077 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2078 assert(S.RRI.ReverseInsertPts.empty());
2079 // As above; handle invoke specially.
2080 if (isa<InvokeInst>(Inst))
2081 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2083 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2087 if (CanUse(Inst, Ptr, PA, Class)) {
2088 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2091 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2099 llvm_unreachable("bottom-up pointer in retain state!");
2103 return NestingDetected;
2107 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2108 DenseMap<const BasicBlock *, BBState> &BBStates,
2109 MapVector<Value *, RRInfo> &Retains) {
2111 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2113 bool NestingDetected = false;
2114 BBState &MyStates = BBStates[BB];
2116 // Merge the states from each successor to compute the initial state
2117 // for the current block.
2118 BBState::edge_iterator SI(MyStates.succ_begin()),
2119 SE(MyStates.succ_end());
2121 const BasicBlock *Succ = *SI;
2122 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2123 assert(I != BBStates.end());
2124 MyStates.InitFromSucc(I->second);
2126 for (; SI != SE; ++SI) {
2128 I = BBStates.find(Succ);
2129 assert(I != BBStates.end());
2130 MyStates.MergeSucc(I->second);
2134 // If ARC Annotations are enabled, output the current state of pointers at the
2135 // bottom of the basic block.
2136 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2138 // Visit all the instructions, bottom-up.
2139 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2140 Instruction *Inst = llvm::prior(I);
2142 // Invoke instructions are visited as part of their successors (below).
2143 if (isa<InvokeInst>(Inst))
2146 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2148 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2151 // If there's a predecessor with an invoke, visit the invoke as if it were
2152 // part of this block, since we can't insert code after an invoke in its own
2153 // block, and we don't want to split critical edges.
2154 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2155 PE(MyStates.pred_end()); PI != PE; ++PI) {
2156 BasicBlock *Pred = *PI;
2157 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2158 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2161 // If ARC Annotations are enabled, output the current state of pointers at the
2162 // top of the basic block.
2163 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2165 return NestingDetected;
2169 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2170 DenseMap<Value *, RRInfo> &Releases,
2171 BBState &MyStates) {
2172 bool NestingDetected = false;
2173 InstructionClass Class = GetInstructionClass(Inst);
2174 const Value *Arg = 0;
2177 case IC_RetainBlock:
2178 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2179 // objc_retainBlocks to objc_retains. Thus at this point any
2180 // objc_retainBlocks that we see are not optimizable.
2184 Arg = GetObjCArg(Inst);
2186 PtrState &S = MyStates.getPtrTopDownState(Arg);
2188 // Don't do retain+release tracking for IC_RetainRV, because it's
2189 // better to let it remain as the first instruction after a call.
2190 if (Class != IC_RetainRV) {
2191 // If we see two retains in a row on the same pointer. If so, make
2192 // a note, and we'll cicle back to revisit it after we've
2193 // hopefully eliminated the second retain, which may allow us to
2194 // eliminate the first retain too.
2195 // Theoretically we could implement removal of nested retain+release
2196 // pairs by making PtrState hold a stack of states, but this is
2197 // simple and avoids adding overhead for the non-nested case.
2198 if (S.GetSeq() == S_Retain)
2199 NestingDetected = true;
2201 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2202 S.ResetSequenceProgress(S_Retain);
2203 S.SetKnownSafe(S.HasKnownPositiveRefCount());
2204 S.RRI.Calls.insert(Inst);
2207 S.SetKnownPositiveRefCount();
2209 // A retain can be a potential use; procede to the generic checking
2214 Arg = GetObjCArg(Inst);
2216 PtrState &S = MyStates.getPtrTopDownState(Arg);
2217 S.ClearKnownPositiveRefCount();
2219 Sequence OldSeq = S.GetSeq();
2221 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2226 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2227 S.RRI.ReverseInsertPts.clear();
2230 S.SetReleaseMetadata(ReleaseMetadata);
2231 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
2232 Releases[Inst] = S.RRI;
2233 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2234 S.ClearSequenceProgress();
2240 case S_MovableRelease:
2241 llvm_unreachable("top-down pointer in release state!");
2245 case IC_AutoreleasepoolPop:
2246 // Conservatively, clear MyStates for all known pointers.
2247 MyStates.clearTopDownPointers();
2248 return NestingDetected;
2249 case IC_AutoreleasepoolPush:
2251 // These are irrelevant.
2252 return NestingDetected;
2257 // Consider any other possible effects of this instruction on each
2258 // pointer being tracked.
2259 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2260 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2261 const Value *Ptr = MI->first;
2263 continue; // Handled above.
2264 PtrState &S = MI->second;
2265 Sequence Seq = S.GetSeq();
2267 // Check for possible releases.
2268 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2269 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2271 S.ClearKnownPositiveRefCount();
2274 S.SetSeq(S_CanRelease);
2275 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2276 assert(S.RRI.ReverseInsertPts.empty());
2277 S.RRI.ReverseInsertPts.insert(Inst);
2279 // One call can't cause a transition from S_Retain to S_CanRelease
2280 // and S_CanRelease to S_Use. If we've made the first transition,
2289 case S_MovableRelease:
2290 llvm_unreachable("top-down pointer in release state!");
2294 // Check for possible direct uses.
2297 if (CanUse(Inst, Ptr, PA, Class)) {
2298 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2301 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2310 case S_MovableRelease:
2311 llvm_unreachable("top-down pointer in release state!");
2315 return NestingDetected;
2319 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2320 DenseMap<const BasicBlock *, BBState> &BBStates,
2321 DenseMap<Value *, RRInfo> &Releases) {
2322 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2323 bool NestingDetected = false;
2324 BBState &MyStates = BBStates[BB];
2326 // Merge the states from each predecessor to compute the initial state
2327 // for the current block.
2328 BBState::edge_iterator PI(MyStates.pred_begin()),
2329 PE(MyStates.pred_end());
2331 const BasicBlock *Pred = *PI;
2332 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2333 assert(I != BBStates.end());
2334 MyStates.InitFromPred(I->second);
2336 for (; PI != PE; ++PI) {
2338 I = BBStates.find(Pred);
2339 assert(I != BBStates.end());
2340 MyStates.MergePred(I->second);
2344 // If ARC Annotations are enabled, output the current state of pointers at the
2345 // top of the basic block.
2346 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2348 // Visit all the instructions, top-down.
2349 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2350 Instruction *Inst = I;
2352 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2354 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2357 // If ARC Annotations are enabled, output the current state of pointers at the
2358 // bottom of the basic block.
2359 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2361 #ifdef ARC_ANNOTATIONS
2362 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2364 CheckForCFGHazards(BB, BBStates, MyStates);
2365 return NestingDetected;
2369 ComputePostOrders(Function &F,
2370 SmallVectorImpl<BasicBlock *> &PostOrder,
2371 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2372 unsigned NoObjCARCExceptionsMDKind,
2373 DenseMap<const BasicBlock *, BBState> &BBStates) {
2374 /// The visited set, for doing DFS walks.
2375 SmallPtrSet<BasicBlock *, 16> Visited;
2377 // Do DFS, computing the PostOrder.
2378 SmallPtrSet<BasicBlock *, 16> OnStack;
2379 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2381 // Functions always have exactly one entry block, and we don't have
2382 // any other block that we treat like an entry block.
2383 BasicBlock *EntryBB = &F.getEntryBlock();
2384 BBState &MyStates = BBStates[EntryBB];
2385 MyStates.SetAsEntry();
2386 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2387 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2388 Visited.insert(EntryBB);
2389 OnStack.insert(EntryBB);
2392 BasicBlock *CurrBB = SuccStack.back().first;
2393 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2394 succ_iterator SE(TI, false);
2396 while (SuccStack.back().second != SE) {
2397 BasicBlock *SuccBB = *SuccStack.back().second++;
2398 if (Visited.insert(SuccBB)) {
2399 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2400 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2401 BBStates[CurrBB].addSucc(SuccBB);
2402 BBState &SuccStates = BBStates[SuccBB];
2403 SuccStates.addPred(CurrBB);
2404 OnStack.insert(SuccBB);
2408 if (!OnStack.count(SuccBB)) {
2409 BBStates[CurrBB].addSucc(SuccBB);
2410 BBStates[SuccBB].addPred(CurrBB);
2413 OnStack.erase(CurrBB);
2414 PostOrder.push_back(CurrBB);
2415 SuccStack.pop_back();
2416 } while (!SuccStack.empty());
2420 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2421 // Functions may have many exits, and there also blocks which we treat
2422 // as exits due to ignored edges.
2423 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2424 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2425 BasicBlock *ExitBB = I;
2426 BBState &MyStates = BBStates[ExitBB];
2427 if (!MyStates.isExit())
2430 MyStates.SetAsExit();
2432 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2433 Visited.insert(ExitBB);
2434 while (!PredStack.empty()) {
2435 reverse_dfs_next_succ:
2436 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2437 while (PredStack.back().second != PE) {
2438 BasicBlock *BB = *PredStack.back().second++;
2439 if (Visited.insert(BB)) {
2440 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2441 goto reverse_dfs_next_succ;
2444 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2449 // Visit the function both top-down and bottom-up.
2451 ObjCARCOpt::Visit(Function &F,
2452 DenseMap<const BasicBlock *, BBState> &BBStates,
2453 MapVector<Value *, RRInfo> &Retains,
2454 DenseMap<Value *, RRInfo> &Releases) {
2456 // Use reverse-postorder traversals, because we magically know that loops
2457 // will be well behaved, i.e. they won't repeatedly call retain on a single
2458 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2459 // class here because we want the reverse-CFG postorder to consider each
2460 // function exit point, and we want to ignore selected cycle edges.
2461 SmallVector<BasicBlock *, 16> PostOrder;
2462 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2463 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2464 NoObjCARCExceptionsMDKind,
2467 // Use reverse-postorder on the reverse CFG for bottom-up.
2468 bool BottomUpNestingDetected = false;
2469 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2470 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2472 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2474 // Use reverse-postorder for top-down.
2475 bool TopDownNestingDetected = false;
2476 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2477 PostOrder.rbegin(), E = PostOrder.rend();
2479 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2481 return TopDownNestingDetected && BottomUpNestingDetected;
2484 /// Move the calls in RetainsToMove and ReleasesToMove.
2485 void ObjCARCOpt::MoveCalls(Value *Arg,
2486 RRInfo &RetainsToMove,
2487 RRInfo &ReleasesToMove,
2488 MapVector<Value *, RRInfo> &Retains,
2489 DenseMap<Value *, RRInfo> &Releases,
2490 SmallVectorImpl<Instruction *> &DeadInsts,
2492 Type *ArgTy = Arg->getType();
2493 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2495 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2497 // Insert the new retain and release calls.
2498 for (SmallPtrSet<Instruction *, 2>::const_iterator
2499 PI = ReleasesToMove.ReverseInsertPts.begin(),
2500 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2501 Instruction *InsertPt = *PI;
2502 Value *MyArg = ArgTy == ParamTy ? Arg :
2503 new BitCastInst(Arg, ParamTy, "", InsertPt);
2505 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2506 Call->setDoesNotThrow();
2507 Call->setTailCall();
2509 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2510 "At insertion point: " << *InsertPt << "\n");
2512 for (SmallPtrSet<Instruction *, 2>::const_iterator
2513 PI = RetainsToMove.ReverseInsertPts.begin(),
2514 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2515 Instruction *InsertPt = *PI;
2516 Value *MyArg = ArgTy == ParamTy ? Arg :
2517 new BitCastInst(Arg, ParamTy, "", InsertPt);
2518 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2520 // Attach a clang.imprecise_release metadata tag, if appropriate.
2521 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2522 Call->setMetadata(ImpreciseReleaseMDKind, M);
2523 Call->setDoesNotThrow();
2524 if (ReleasesToMove.IsTailCallRelease)
2525 Call->setTailCall();
2527 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2528 "At insertion point: " << *InsertPt << "\n");
2531 // Delete the original retain and release calls.
2532 for (SmallPtrSet<Instruction *, 2>::const_iterator
2533 AI = RetainsToMove.Calls.begin(),
2534 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2535 Instruction *OrigRetain = *AI;
2536 Retains.blot(OrigRetain);
2537 DeadInsts.push_back(OrigRetain);
2538 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2540 for (SmallPtrSet<Instruction *, 2>::const_iterator
2541 AI = ReleasesToMove.Calls.begin(),
2542 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2543 Instruction *OrigRelease = *AI;
2544 Releases.erase(OrigRelease);
2545 DeadInsts.push_back(OrigRelease);
2546 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2552 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2554 MapVector<Value *, RRInfo> &Retains,
2555 DenseMap<Value *, RRInfo> &Releases,
2557 SmallVector<Instruction *, 4> &NewRetains,
2558 SmallVector<Instruction *, 4> &NewReleases,
2559 SmallVector<Instruction *, 8> &DeadInsts,
2560 RRInfo &RetainsToMove,
2561 RRInfo &ReleasesToMove,
2564 bool &AnyPairsCompletelyEliminated) {
2565 // If a pair happens in a region where it is known that the reference count
2566 // is already incremented, we can similarly ignore possible decrements unless
2567 // we are dealing with a retainable object with multiple provenance sources.
2568 bool KnownSafeTD = true, KnownSafeBU = true;
2569 bool MultipleOwners = false;
2570 bool CFGHazardAfflicted = false;
2572 // Connect the dots between the top-down-collected RetainsToMove and
2573 // bottom-up-collected ReleasesToMove to form sets of related calls.
2574 // This is an iterative process so that we connect multiple releases
2575 // to multiple retains if needed.
2576 unsigned OldDelta = 0;
2577 unsigned NewDelta = 0;
2578 unsigned OldCount = 0;
2579 unsigned NewCount = 0;
2580 bool FirstRelease = true;
2582 for (SmallVectorImpl<Instruction *>::const_iterator
2583 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2584 Instruction *NewRetain = *NI;
2585 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2586 assert(It != Retains.end());
2587 const RRInfo &NewRetainRRI = It->second;
2588 KnownSafeTD &= NewRetainRRI.KnownSafe;
2590 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2591 for (SmallPtrSet<Instruction *, 2>::const_iterator
2592 LI = NewRetainRRI.Calls.begin(),
2593 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2594 Instruction *NewRetainRelease = *LI;
2595 DenseMap<Value *, RRInfo>::const_iterator Jt =
2596 Releases.find(NewRetainRelease);
2597 if (Jt == Releases.end())
2599 const RRInfo &NewRetainReleaseRRI = Jt->second;
2600 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2601 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2603 // If we overflow when we compute the path count, don't remove/move
2605 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2607 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2609 OldDelta -= PathCount;
2611 // Merge the ReleaseMetadata and IsTailCallRelease values.
2613 ReleasesToMove.ReleaseMetadata =
2614 NewRetainReleaseRRI.ReleaseMetadata;
2615 ReleasesToMove.IsTailCallRelease =
2616 NewRetainReleaseRRI.IsTailCallRelease;
2617 FirstRelease = false;
2619 if (ReleasesToMove.ReleaseMetadata !=
2620 NewRetainReleaseRRI.ReleaseMetadata)
2621 ReleasesToMove.ReleaseMetadata = 0;
2622 if (ReleasesToMove.IsTailCallRelease !=
2623 NewRetainReleaseRRI.IsTailCallRelease)
2624 ReleasesToMove.IsTailCallRelease = false;
2627 // Collect the optimal insertion points.
2629 for (SmallPtrSet<Instruction *, 2>::const_iterator
2630 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2631 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2633 Instruction *RIP = *RI;
2634 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2635 // If we overflow when we compute the path count, don't
2636 // remove/move anything.
2637 const BBState &RIPBBState = BBStates[RIP->getParent()];
2638 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2640 NewDelta -= PathCount;
2643 NewReleases.push_back(NewRetainRelease);
2648 if (NewReleases.empty()) break;
2650 // Back the other way.
2651 for (SmallVectorImpl<Instruction *>::const_iterator
2652 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2653 Instruction *NewRelease = *NI;
2654 DenseMap<Value *, RRInfo>::const_iterator It =
2655 Releases.find(NewRelease);
2656 assert(It != Releases.end());
2657 const RRInfo &NewReleaseRRI = It->second;
2658 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2659 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2660 for (SmallPtrSet<Instruction *, 2>::const_iterator
2661 LI = NewReleaseRRI.Calls.begin(),
2662 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2663 Instruction *NewReleaseRetain = *LI;
2664 MapVector<Value *, RRInfo>::const_iterator Jt =
2665 Retains.find(NewReleaseRetain);
2666 if (Jt == Retains.end())
2668 const RRInfo &NewReleaseRetainRRI = Jt->second;
2669 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2670 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2672 // If we overflow when we compute the path count, don't remove/move
2674 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2676 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2678 OldDelta += PathCount;
2679 OldCount += PathCount;
2681 // Collect the optimal insertion points.
2683 for (SmallPtrSet<Instruction *, 2>::const_iterator
2684 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2685 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2687 Instruction *RIP = *RI;
2688 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2689 // If we overflow when we compute the path count, don't
2690 // remove/move anything.
2691 const BBState &RIPBBState = BBStates[RIP->getParent()];
2692 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2694 NewDelta += PathCount;
2695 NewCount += PathCount;
2698 NewRetains.push_back(NewReleaseRetain);
2702 NewReleases.clear();
2703 if (NewRetains.empty()) break;
2706 // If the pointer is known incremented in 1 direction and we do not have
2707 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2708 // to be known safe in both directions.
2709 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2710 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2711 if (UnconditionallySafe) {
2712 RetainsToMove.ReverseInsertPts.clear();
2713 ReleasesToMove.ReverseInsertPts.clear();
2716 // Determine whether the new insertion points we computed preserve the
2717 // balance of retain and release calls through the program.
2718 // TODO: If the fully aggressive solution isn't valid, try to find a
2719 // less aggressive solution which is.
2723 // At this point, we are not going to remove any RR pairs, but we still are
2724 // able to move RR pairs. If one of our pointers is afflicted with
2725 // CFGHazards, we cannot perform such code motion so exit early.
2726 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2727 ReleasesToMove.ReverseInsertPts.size();
2728 if (CFGHazardAfflicted && WillPerformCodeMotion)
2732 // Determine whether the original call points are balanced in the retain and
2733 // release calls through the program. If not, conservatively don't touch
2735 // TODO: It's theoretically possible to do code motion in this case, as
2736 // long as the existing imbalances are maintained.
2740 #ifdef ARC_ANNOTATIONS
2741 // Do not move calls if ARC annotations are requested.
2742 if (EnableARCAnnotations)
2744 #endif // ARC_ANNOTATIONS
2747 assert(OldCount != 0 && "Unreachable code?");
2748 NumRRs += OldCount - NewCount;
2749 // Set to true if we completely removed any RR pairs.
2750 AnyPairsCompletelyEliminated = NewCount == 0;
2752 // We can move calls!
2756 /// Identify pairings between the retains and releases, and delete and/or move
2759 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2761 MapVector<Value *, RRInfo> &Retains,
2762 DenseMap<Value *, RRInfo> &Releases,
2764 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2766 bool AnyPairsCompletelyEliminated = false;
2767 RRInfo RetainsToMove;
2768 RRInfo ReleasesToMove;
2769 SmallVector<Instruction *, 4> NewRetains;
2770 SmallVector<Instruction *, 4> NewReleases;
2771 SmallVector<Instruction *, 8> DeadInsts;
2773 // Visit each retain.
2774 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2775 E = Retains.end(); I != E; ++I) {
2776 Value *V = I->first;
2777 if (!V) continue; // blotted
2779 Instruction *Retain = cast<Instruction>(V);
2781 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2783 Value *Arg = GetObjCArg(Retain);
2785 // If the object being released is in static or stack storage, we know it's
2786 // not being managed by ObjC reference counting, so we can delete pairs
2787 // regardless of what possible decrements or uses lie between them.
2788 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2790 // A constant pointer can't be pointing to an object on the heap. It may
2791 // be reference-counted, but it won't be deleted.
2792 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2793 if (const GlobalVariable *GV =
2794 dyn_cast<GlobalVariable>(
2795 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2796 if (GV->isConstant())
2799 // Connect the dots between the top-down-collected RetainsToMove and
2800 // bottom-up-collected ReleasesToMove to form sets of related calls.
2801 NewRetains.push_back(Retain);
2802 bool PerformMoveCalls =
2803 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2804 NewReleases, DeadInsts, RetainsToMove,
2805 ReleasesToMove, Arg, KnownSafe,
2806 AnyPairsCompletelyEliminated);
2808 if (PerformMoveCalls) {
2809 // Ok, everything checks out and we're all set. Let's move/delete some
2811 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2812 Retains, Releases, DeadInsts, M);
2815 // Clean up state for next retain.
2816 NewReleases.clear();
2818 RetainsToMove.clear();
2819 ReleasesToMove.clear();
2822 // Now that we're done moving everything, we can delete the newly dead
2823 // instructions, as we no longer need them as insert points.
2824 while (!DeadInsts.empty())
2825 EraseInstruction(DeadInsts.pop_back_val());
2827 return AnyPairsCompletelyEliminated;
2830 /// Weak pointer optimizations.
2831 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2832 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2834 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2835 // itself because it uses AliasAnalysis and we need to do provenance
2837 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2838 Instruction *Inst = &*I++;
2840 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2842 InstructionClass Class = GetBasicInstructionClass(Inst);
2843 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2846 // Delete objc_loadWeak calls with no users.
2847 if (Class == IC_LoadWeak && Inst->use_empty()) {
2848 Inst->eraseFromParent();
2852 // TODO: For now, just look for an earlier available version of this value
2853 // within the same block. Theoretically, we could do memdep-style non-local
2854 // analysis too, but that would want caching. A better approach would be to
2855 // use the technique that EarlyCSE uses.
2856 inst_iterator Current = llvm::prior(I);
2857 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2858 for (BasicBlock::iterator B = CurrentBB->begin(),
2859 J = Current.getInstructionIterator();
2861 Instruction *EarlierInst = &*llvm::prior(J);
2862 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2863 switch (EarlierClass) {
2865 case IC_LoadWeakRetained: {
2866 // If this is loading from the same pointer, replace this load's value
2868 CallInst *Call = cast<CallInst>(Inst);
2869 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2870 Value *Arg = Call->getArgOperand(0);
2871 Value *EarlierArg = EarlierCall->getArgOperand(0);
2872 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2873 case AliasAnalysis::MustAlias:
2875 // If the load has a builtin retain, insert a plain retain for it.
2876 if (Class == IC_LoadWeakRetained) {
2878 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2882 // Zap the fully redundant load.
2883 Call->replaceAllUsesWith(EarlierCall);
2884 Call->eraseFromParent();
2886 case AliasAnalysis::MayAlias:
2887 case AliasAnalysis::PartialAlias:
2889 case AliasAnalysis::NoAlias:
2896 // If this is storing to the same pointer and has the same size etc.
2897 // replace this load's value with the stored value.
2898 CallInst *Call = cast<CallInst>(Inst);
2899 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2900 Value *Arg = Call->getArgOperand(0);
2901 Value *EarlierArg = EarlierCall->getArgOperand(0);
2902 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2903 case AliasAnalysis::MustAlias:
2905 // If the load has a builtin retain, insert a plain retain for it.
2906 if (Class == IC_LoadWeakRetained) {
2908 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2912 // Zap the fully redundant load.
2913 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2914 Call->eraseFromParent();
2916 case AliasAnalysis::MayAlias:
2917 case AliasAnalysis::PartialAlias:
2919 case AliasAnalysis::NoAlias:
2926 // TOOD: Grab the copied value.
2928 case IC_AutoreleasepoolPush:
2930 case IC_IntrinsicUser:
2932 // Weak pointers are only modified through the weak entry points
2933 // (and arbitrary calls, which could call the weak entry points).
2936 // Anything else could modify the weak pointer.
2943 // Then, for each destroyWeak with an alloca operand, check to see if
2944 // the alloca and all its users can be zapped.
2945 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2946 Instruction *Inst = &*I++;
2947 InstructionClass Class = GetBasicInstructionClass(Inst);
2948 if (Class != IC_DestroyWeak)
2951 CallInst *Call = cast<CallInst>(Inst);
2952 Value *Arg = Call->getArgOperand(0);
2953 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2954 for (Value::use_iterator UI = Alloca->use_begin(),
2955 UE = Alloca->use_end(); UI != UE; ++UI) {
2956 const Instruction *UserInst = cast<Instruction>(*UI);
2957 switch (GetBasicInstructionClass(UserInst)) {
2960 case IC_DestroyWeak:
2967 for (Value::use_iterator UI = Alloca->use_begin(),
2968 UE = Alloca->use_end(); UI != UE; ) {
2969 CallInst *UserInst = cast<CallInst>(*UI++);
2970 switch (GetBasicInstructionClass(UserInst)) {
2973 // These functions return their second argument.
2974 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2976 case IC_DestroyWeak:
2980 llvm_unreachable("alloca really is used!");
2982 UserInst->eraseFromParent();
2984 Alloca->eraseFromParent();
2990 /// Identify program paths which execute sequences of retains and releases which
2991 /// can be eliminated.
2992 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2993 // Releases, Retains - These are used to store the results of the main flow
2994 // analysis. These use Value* as the key instead of Instruction* so that the
2995 // map stays valid when we get around to rewriting code and calls get
2996 // replaced by arguments.
2997 DenseMap<Value *, RRInfo> Releases;
2998 MapVector<Value *, RRInfo> Retains;
3000 // This is used during the traversal of the function to track the
3001 // states for each identified object at each block.
3002 DenseMap<const BasicBlock *, BBState> BBStates;
3004 // Analyze the CFG of the function, and all instructions.
3005 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3008 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
3013 MultiOwnersSet.clear();
3015 return AnyPairsCompletelyEliminated && NestingDetected;
3018 /// Check if there is a dependent call earlier that does not have anything in
3019 /// between the Retain and the call that can affect the reference count of their
3020 /// shared pointer argument. Note that Retain need not be in BB.
3022 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
3023 SmallPtrSet<Instruction *, 4> &DepInsts,
3024 SmallPtrSet<const BasicBlock *, 4> &Visited,
3025 ProvenanceAnalysis &PA) {
3026 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3027 DepInsts, Visited, PA);
3028 if (DepInsts.size() != 1)
3032 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3034 // Check that the pointer is the return value of the call.
3035 if (!Call || Arg != Call)
3038 // Check that the call is a regular call.
3039 InstructionClass Class = GetBasicInstructionClass(Call);
3040 if (Class != IC_CallOrUser && Class != IC_Call)
3046 /// Find a dependent retain that precedes the given autorelease for which there
3047 /// is nothing in between the two instructions that can affect the ref count of
3050 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3051 Instruction *Autorelease,
3052 SmallPtrSet<Instruction *, 4> &DepInsts,
3053 SmallPtrSet<const BasicBlock *, 4> &Visited,
3054 ProvenanceAnalysis &PA) {
3055 FindDependencies(CanChangeRetainCount, Arg,
3056 BB, Autorelease, DepInsts, Visited, PA);
3057 if (DepInsts.size() != 1)
3061 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3063 // Check that we found a retain with the same argument.
3065 !IsRetain(GetBasicInstructionClass(Retain)) ||
3066 GetObjCArg(Retain) != Arg) {
3073 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3074 /// no instructions dependent on Arg that need a positive ref count in between
3075 /// the autorelease and the ret.
3077 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3079 SmallPtrSet<Instruction *, 4> &DepInsts,
3080 SmallPtrSet<const BasicBlock *, 4> &V,
3081 ProvenanceAnalysis &PA) {
3082 FindDependencies(NeedsPositiveRetainCount, Arg,
3083 BB, Ret, DepInsts, V, PA);
3084 if (DepInsts.size() != 1)
3087 CallInst *Autorelease =
3088 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3091 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3092 if (!IsAutorelease(AutoreleaseClass))
3094 if (GetObjCArg(Autorelease) != Arg)
3100 /// Look for this pattern:
3102 /// %call = call i8* @something(...)
3103 /// %2 = call i8* @objc_retain(i8* %call)
3104 /// %3 = call i8* @objc_autorelease(i8* %2)
3107 /// And delete the retain and autorelease.
3108 void ObjCARCOpt::OptimizeReturns(Function &F) {
3109 if (!F.getReturnType()->isPointerTy())
3112 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3114 SmallPtrSet<Instruction *, 4> DependingInstructions;
3115 SmallPtrSet<const BasicBlock *, 4> Visited;
3116 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3117 BasicBlock *BB = FI;
3118 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3120 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3125 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3127 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3128 // dependent on Arg such that there are no instructions dependent on Arg
3129 // that need a positive ref count in between the autorelease and Ret.
3130 CallInst *Autorelease =
3131 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3132 DependingInstructions, Visited,
3134 DependingInstructions.clear();
3141 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3142 DependingInstructions, Visited, PA);
3143 DependingInstructions.clear();
3149 // Check that there is nothing that can affect the reference count
3150 // between the retain and the call. Note that Retain need not be in BB.
3151 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3152 DependingInstructions,
3154 DependingInstructions.clear();
3157 if (!HasSafePathToCall)
3160 // If so, we can zap the retain and autorelease.
3163 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3164 << *Autorelease << "\n");
3165 EraseInstruction(Retain);
3166 EraseInstruction(Autorelease);
3172 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3173 llvm::Statistic &NumRetains =
3174 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3175 llvm::Statistic &NumReleases =
3176 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3178 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3179 Instruction *Inst = &*I++;
3180 switch (GetBasicInstructionClass(Inst)) {
3194 bool ObjCARCOpt::doInitialization(Module &M) {
3198 // If nothing in the Module uses ARC, don't do anything.
3199 Run = ModuleHasARC(M);
3203 // Identify the imprecise release metadata kind.
3204 ImpreciseReleaseMDKind =
3205 M.getContext().getMDKindID("clang.imprecise_release");
3206 CopyOnEscapeMDKind =
3207 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3208 NoObjCARCExceptionsMDKind =
3209 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3210 #ifdef ARC_ANNOTATIONS
3211 ARCAnnotationBottomUpMDKind =
3212 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3213 ARCAnnotationTopDownMDKind =
3214 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3215 ARCAnnotationProvenanceSourceMDKind =
3216 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3217 #endif // ARC_ANNOTATIONS
3219 // Intuitively, objc_retain and others are nocapture, however in practice
3220 // they are not, because they return their argument value. And objc_release
3221 // calls finalizers which can have arbitrary side effects.
3223 // These are initialized lazily.
3224 AutoreleaseRVCallee = 0;
3227 RetainBlockCallee = 0;
3228 AutoreleaseCallee = 0;
3233 bool ObjCARCOpt::runOnFunction(Function &F) {
3237 // If nothing in the Module uses ARC, don't do anything.
3243 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3246 PA.setAA(&getAnalysis<AliasAnalysis>());
3249 if (AreStatisticsEnabled()) {
3250 GatherStatistics(F, false);
3254 // This pass performs several distinct transformations. As a compile-time aid
3255 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3256 // library functions aren't declared.
3258 // Preliminary optimizations. This also computes UsedInThisFunction.
3259 OptimizeIndividualCalls(F);
3261 // Optimizations for weak pointers.
3262 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3263 (1 << IC_LoadWeakRetained) |
3264 (1 << IC_StoreWeak) |
3265 (1 << IC_InitWeak) |
3266 (1 << IC_CopyWeak) |
3267 (1 << IC_MoveWeak) |
3268 (1 << IC_DestroyWeak)))
3269 OptimizeWeakCalls(F);
3271 // Optimizations for retain+release pairs.
3272 if (UsedInThisFunction & ((1 << IC_Retain) |
3273 (1 << IC_RetainRV) |
3274 (1 << IC_RetainBlock)))
3275 if (UsedInThisFunction & (1 << IC_Release))
3276 // Run OptimizeSequences until it either stops making changes or
3277 // no retain+release pair nesting is detected.
3278 while (OptimizeSequences(F)) {}
3280 // Optimizations if objc_autorelease is used.
3281 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3282 (1 << IC_AutoreleaseRV)))
3285 // Gather statistics after optimization.
3287 if (AreStatisticsEnabled()) {
3288 GatherStatistics(F, true);
3292 DEBUG(dbgs() << "\n");
3297 void ObjCARCOpt::releaseMemory() {