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);
472 bool IsTrackingImpreciseReleases() {
473 return ReleaseMetadata != 0;
478 void RRInfo::clear() {
480 IsTailCallRelease = false;
483 ReverseInsertPts.clear();
484 CFGHazardAfflicted = false;
487 bool RRInfo::Merge(const RRInfo &Other) {
488 // Conservatively merge the ReleaseMetadata information.
489 if (ReleaseMetadata != Other.ReleaseMetadata)
492 // Conservatively merge the boolean state.
493 KnownSafe &= Other.KnownSafe;
494 IsTailCallRelease &= Other.IsTailCallRelease;
495 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
497 // Merge the call sets.
498 Calls.insert(Other.Calls.begin(), Other.Calls.end());
500 // Merge the insert point sets. If there are any differences,
501 // that makes this a partial merge.
502 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
503 for (SmallPtrSet<Instruction *, 2>::const_iterator
504 I = Other.ReverseInsertPts.begin(),
505 E = Other.ReverseInsertPts.end(); I != E; ++I)
506 Partial |= ReverseInsertPts.insert(*I);
511 /// \brief This class summarizes several per-pointer runtime properties which
512 /// are propogated through the flow graph.
514 /// True if the reference count is known to be incremented.
515 bool KnownPositiveRefCount;
517 /// True if we've seen an opportunity for partial RR elimination, such as
518 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
521 /// The current position in the sequence.
525 /// Unidirectional information about the current sequence.
527 /// TODO: Encapsulate this better.
530 PtrState() : KnownPositiveRefCount(false), Partial(false),
534 bool IsKnownSafe() const {
535 return RRI.KnownSafe;
538 void SetKnownSafe(const bool NewValue) {
539 RRI.KnownSafe = NewValue;
542 bool IsTailCallRelease() const {
543 return RRI.IsTailCallRelease;
546 void SetTailCallRelease(const bool NewValue) {
547 RRI.IsTailCallRelease = NewValue;
550 const MDNode *GetReleaseMetadata() const {
551 return RRI.ReleaseMetadata;
554 void SetReleaseMetadata(MDNode *NewValue) {
555 RRI.ReleaseMetadata = NewValue;
558 void SetKnownPositiveRefCount() {
559 DEBUG(dbgs() << "Setting Known Positive.\n");
560 KnownPositiveRefCount = true;
563 void ClearKnownPositiveRefCount() {
564 DEBUG(dbgs() << "Clearing Known Positive.\n");
565 KnownPositiveRefCount = false;
568 bool HasKnownPositiveRefCount() const {
569 return KnownPositiveRefCount;
572 void SetSeq(Sequence NewSeq) {
573 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
577 Sequence GetSeq() const {
581 void ClearSequenceProgress() {
582 ResetSequenceProgress(S_None);
585 void ResetSequenceProgress(Sequence NewSeq) {
586 DEBUG(dbgs() << "Resetting sequence progress.\n");
592 void Merge(const PtrState &Other, bool TopDown);
597 PtrState::Merge(const PtrState &Other, bool TopDown) {
598 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
599 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
601 // If we're not in a sequence (anymore), drop all associated state.
605 } else if (Partial || Other.Partial) {
606 // If we're doing a merge on a path that's previously seen a partial
607 // merge, conservatively drop the sequence, to avoid doing partial
608 // RR elimination. If the branch predicates for the two merge differ,
609 // mixing them is unsafe.
610 ClearSequenceProgress();
612 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
613 // point, we know that currently we are not partial. Stash whether or not
614 // the merge operation caused us to undergo a partial merging of reverse
616 Partial = RRI.Merge(Other.RRI);
621 /// \brief Per-BasicBlock state.
623 /// The number of unique control paths from the entry which can reach this
625 unsigned TopDownPathCount;
627 /// The number of unique control paths to exits from this block.
628 unsigned BottomUpPathCount;
630 /// A type for PerPtrTopDown and PerPtrBottomUp.
631 typedef MapVector<const Value *, PtrState> MapTy;
633 /// The top-down traversal uses this to record information known about a
634 /// pointer at the bottom of each block.
637 /// The bottom-up traversal uses this to record information known about a
638 /// pointer at the top of each block.
639 MapTy PerPtrBottomUp;
641 /// Effective predecessors of the current block ignoring ignorable edges and
642 /// ignored backedges.
643 SmallVector<BasicBlock *, 2> Preds;
644 /// Effective successors of the current block ignoring ignorable edges and
645 /// ignored backedges.
646 SmallVector<BasicBlock *, 2> Succs;
649 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
651 typedef MapTy::iterator ptr_iterator;
652 typedef MapTy::const_iterator ptr_const_iterator;
654 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
655 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
656 ptr_const_iterator top_down_ptr_begin() const {
657 return PerPtrTopDown.begin();
659 ptr_const_iterator top_down_ptr_end() const {
660 return PerPtrTopDown.end();
663 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
664 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
665 ptr_const_iterator bottom_up_ptr_begin() const {
666 return PerPtrBottomUp.begin();
668 ptr_const_iterator bottom_up_ptr_end() const {
669 return PerPtrBottomUp.end();
672 /// Mark this block as being an entry block, which has one path from the
673 /// entry by definition.
674 void SetAsEntry() { TopDownPathCount = 1; }
676 /// Mark this block as being an exit block, which has one path to an exit by
678 void SetAsExit() { BottomUpPathCount = 1; }
680 /// Attempt to find the PtrState object describing the top down state for
681 /// pointer Arg. Return a new initialized PtrState describing the top down
682 /// state for Arg if we do not find one.
683 PtrState &getPtrTopDownState(const Value *Arg) {
684 return PerPtrTopDown[Arg];
687 /// Attempt to find the PtrState object describing the bottom up state for
688 /// pointer Arg. Return a new initialized PtrState describing the bottom up
689 /// state for Arg if we do not find one.
690 PtrState &getPtrBottomUpState(const Value *Arg) {
691 return PerPtrBottomUp[Arg];
694 /// Attempt to find the PtrState object describing the bottom up state for
696 ptr_iterator findPtrBottomUpState(const Value *Arg) {
697 return PerPtrBottomUp.find(Arg);
700 void clearBottomUpPointers() {
701 PerPtrBottomUp.clear();
704 void clearTopDownPointers() {
705 PerPtrTopDown.clear();
708 void InitFromPred(const BBState &Other);
709 void InitFromSucc(const BBState &Other);
710 void MergePred(const BBState &Other);
711 void MergeSucc(const BBState &Other);
713 /// Compute the number of possible unique paths from an entry to an exit
714 /// which pass through this block. This is only valid after both the
715 /// top-down and bottom-up traversals are complete.
717 /// Returns true if overflow occured. Returns false if overflow did not
719 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
720 assert(TopDownPathCount != 0);
721 assert(BottomUpPathCount != 0);
722 unsigned long long Product =
723 (unsigned long long)TopDownPathCount*BottomUpPathCount;
725 // Overflow occured if any of the upper bits of Product are set.
726 return Product >> 32;
729 // Specialized CFG utilities.
730 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
731 edge_iterator pred_begin() { return Preds.begin(); }
732 edge_iterator pred_end() { return Preds.end(); }
733 edge_iterator succ_begin() { return Succs.begin(); }
734 edge_iterator succ_end() { return Succs.end(); }
736 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
737 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
739 bool isExit() const { return Succs.empty(); }
743 void BBState::InitFromPred(const BBState &Other) {
744 PerPtrTopDown = Other.PerPtrTopDown;
745 TopDownPathCount = Other.TopDownPathCount;
748 void BBState::InitFromSucc(const BBState &Other) {
749 PerPtrBottomUp = Other.PerPtrBottomUp;
750 BottomUpPathCount = Other.BottomUpPathCount;
753 /// The top-down traversal uses this to merge information about predecessors to
754 /// form the initial state for a new block.
755 void BBState::MergePred(const BBState &Other) {
756 // Other.TopDownPathCount can be 0, in which case it is either dead or a
757 // loop backedge. Loop backedges are special.
758 TopDownPathCount += Other.TopDownPathCount;
760 // Check for overflow. If we have overflow, fall back to conservative
762 if (TopDownPathCount < Other.TopDownPathCount) {
763 clearTopDownPointers();
767 // For each entry in the other set, if our set has an entry with the same key,
768 // merge the entries. Otherwise, copy the entry and merge it with an empty
770 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
771 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
772 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
773 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
777 // For each entry in our set, if the other set doesn't have an entry with the
778 // same key, force it to merge with an empty entry.
779 for (ptr_iterator MI = top_down_ptr_begin(),
780 ME = top_down_ptr_end(); MI != ME; ++MI)
781 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
782 MI->second.Merge(PtrState(), /*TopDown=*/true);
785 /// The bottom-up traversal uses this to merge information about successors to
786 /// form the initial state for a new block.
787 void BBState::MergeSucc(const BBState &Other) {
788 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
789 // loop backedge. Loop backedges are special.
790 BottomUpPathCount += Other.BottomUpPathCount;
792 // Check for overflow. If we have overflow, fall back to conservative
794 if (BottomUpPathCount < Other.BottomUpPathCount) {
795 clearBottomUpPointers();
799 // For each entry in the other set, if our set has an entry with the
800 // same key, merge the entries. Otherwise, copy the entry and merge
801 // it with an empty entry.
802 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
803 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
804 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
805 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
809 // For each entry in our set, if the other set doesn't have an entry
810 // with the same key, force it to merge with an empty entry.
811 for (ptr_iterator MI = bottom_up_ptr_begin(),
812 ME = bottom_up_ptr_end(); MI != ME; ++MI)
813 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
814 MI->second.Merge(PtrState(), /*TopDown=*/false);
817 // Only enable ARC Annotations if we are building a debug version of
820 #define ARC_ANNOTATIONS
823 // Define some macros along the lines of DEBUG and some helper functions to make
824 // it cleaner to create annotations in the source code and to no-op when not
825 // building in debug mode.
826 #ifdef ARC_ANNOTATIONS
828 #include "llvm/Support/CommandLine.h"
830 /// Enable/disable ARC sequence annotations.
832 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
833 cl::desc("Enable emission of arc data flow analysis "
836 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
837 cl::desc("Disable check for cfg hazards when "
839 static cl::opt<std::string>
840 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
842 cl::desc("filter out all data flow annotations "
843 "but those that apply to the given "
844 "target llvm identifier."));
846 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
847 /// instruction so that we can track backwards when post processing via the llvm
848 /// arc annotation processor tool. If the function is an
849 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
853 // If pointer is a result of an instruction and it does not have a source
854 // MDNode it, attach a new MDNode onto it. If pointer is a result of
855 // an instruction and does have a source MDNode attached to it, return a
856 // reference to said Node. Otherwise just return 0.
857 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
859 if (!(Node = Inst->getMetadata(NodeId))) {
860 // We do not have any node. Generate and attatch the hash MDString to the
863 // We just use an MDString to ensure that this metadata gets written out
864 // of line at the module level and to provide a very simple format
865 // encoding the information herein. Both of these makes it simpler to
866 // parse the annotations by a simple external program.
868 raw_string_ostream os(Str);
869 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
870 << Inst->getName() << ")";
872 Hash = MDString::get(Inst->getContext(), os.str());
873 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
875 // We have a node. Grab its hash and return it.
876 assert(Node->getNumOperands() == 1 &&
877 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
878 Hash = cast<MDString>(Node->getOperand(0));
880 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
882 raw_string_ostream os(str);
883 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
885 Hash = MDString::get(Arg->getContext(), os.str());
891 static std::string SequenceToString(Sequence A) {
893 raw_string_ostream os(str);
898 /// Helper function to change a Sequence into a String object using our overload
899 /// for raw_ostream so we only have printing code in one location.
900 static MDString *SequenceToMDString(LLVMContext &Context,
902 return MDString::get(Context, SequenceToString(A));
905 /// A simple function to generate a MDNode which describes the change in state
906 /// for Value *Ptr caused by Instruction *Inst.
907 static void AppendMDNodeToInstForPtr(unsigned NodeId,
910 MDString *PtrSourceMDNodeID,
914 Value *tmp[3] = {PtrSourceMDNodeID,
915 SequenceToMDString(Inst->getContext(),
917 SequenceToMDString(Inst->getContext(),
919 Node = MDNode::get(Inst->getContext(),
920 ArrayRef<Value*>(tmp, 3));
922 Inst->setMetadata(NodeId, Node);
925 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
926 /// state of a pointer at the entrance to a basic block.
927 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
928 Value *Ptr, Sequence Seq) {
929 // If we have a target identifier, make sure that we match it before
931 if(!ARCAnnotationTargetIdentifier.empty() &&
932 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
935 Module *M = BB->getParent()->getParent();
936 LLVMContext &C = M->getContext();
937 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
938 Type *I8XX = PointerType::getUnqual(I8X);
939 Type *Params[] = {I8XX, I8XX};
940 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
941 ArrayRef<Type*>(Params, 2),
943 Constant *Callee = M->getOrInsertFunction(Name, FTy);
945 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
948 StringRef Tmp = Ptr->getName();
949 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
950 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
952 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
953 cast<Constant>(ActualPtrName), Tmp);
957 std::string SeqStr = SequenceToString(Seq);
958 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
959 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
961 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
962 cast<Constant>(ActualPtrName), SeqStr);
965 Builder.CreateCall2(Callee, PtrName, S);
968 /// Add to the end of the basic block llvm.ptr.annotations which show the state
969 /// of the pointer at the bottom of the basic block.
970 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
971 Value *Ptr, Sequence Seq) {
972 // If we have a target identifier, make sure that we match it before emitting
974 if(!ARCAnnotationTargetIdentifier.empty() &&
975 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
978 Module *M = BB->getParent()->getParent();
979 LLVMContext &C = M->getContext();
980 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
981 Type *I8XX = PointerType::getUnqual(I8X);
982 Type *Params[] = {I8XX, I8XX};
983 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
984 ArrayRef<Type*>(Params, 2),
986 Constant *Callee = M->getOrInsertFunction(Name, FTy);
988 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
991 StringRef Tmp = Ptr->getName();
992 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
993 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
995 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
996 cast<Constant>(ActualPtrName), Tmp);
1000 std::string SeqStr = SequenceToString(Seq);
1001 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1002 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1004 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1005 cast<Constant>(ActualPtrName), SeqStr);
1007 Builder.CreateCall2(Callee, PtrName, S);
1010 /// Adds a source annotation to pointer and a state change annotation to Inst
1011 /// referencing the source annotation and the old/new state of pointer.
1012 static void GenerateARCAnnotation(unsigned InstMDId,
1018 if (EnableARCAnnotations) {
1019 // If we have a target identifier, make sure that we match it before
1020 // emitting an annotation.
1021 if(!ARCAnnotationTargetIdentifier.empty() &&
1022 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1025 // First generate the source annotation on our pointer. This will return an
1026 // MDString* if Ptr actually comes from an instruction implying we can put
1027 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1028 // then we know that our pointer is from an Argument so we put a reference
1029 // to the argument number.
1031 // The point of this is to make it easy for the
1032 // llvm-arc-annotation-processor tool to cross reference where the source
1033 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1034 // information via debug info for backends to use (since why would anyone
1035 // need such a thing from LLVM IR besides in non standard cases
1037 MDString *SourcePtrMDNode =
1038 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1039 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1044 // The actual interface for accessing the above functionality is defined via
1045 // some simple macros which are defined below. We do this so that the user does
1046 // not need to pass in what metadata id is needed resulting in cleaner code and
1047 // additionally since it provides an easy way to conditionally no-op all
1048 // annotation support in a non-debug build.
1050 /// Use this macro to annotate a sequence state change when processing
1051 /// instructions bottom up,
1052 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1053 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1054 ARCAnnotationProvenanceSourceMDKind, (inst), \
1055 const_cast<Value*>(ptr), (old), (new))
1056 /// Use this macro to annotate a sequence state change when processing
1057 /// instructions top down.
1058 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1059 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1060 ARCAnnotationProvenanceSourceMDKind, (inst), \
1061 const_cast<Value*>(ptr), (old), (new))
1063 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1065 if (EnableARCAnnotations) { \
1066 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1067 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1068 Value *Ptr = const_cast<Value*>(I->first); \
1069 Sequence Seq = I->second.GetSeq(); \
1070 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1075 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1076 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1077 Entrance, bottom_up)
1078 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1079 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1080 Terminator, bottom_up)
1081 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1082 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1084 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1085 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1086 Terminator, top_down)
1088 #else // !ARC_ANNOTATION
1089 // If annotations are off, noop.
1090 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1091 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1092 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1093 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1094 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1095 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1096 #endif // !ARC_ANNOTATION
1099 /// \brief The main ARC optimization pass.
1100 class ObjCARCOpt : public FunctionPass {
1102 ProvenanceAnalysis PA;
1104 // This is used to track if a pointer is stored into an alloca.
1105 DenseSet<const Value *> MultiOwnersSet;
1107 /// A flag indicating whether this optimization pass should run.
1110 /// Declarations for ObjC runtime functions, for use in creating calls to
1111 /// them. These are initialized lazily to avoid cluttering up the Module
1112 /// with unused declarations.
1114 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1115 Constant *AutoreleaseRVCallee;
1116 /// Declaration for ObjC runtime function objc_release.
1117 Constant *ReleaseCallee;
1118 /// Declaration for ObjC runtime function objc_retain.
1119 Constant *RetainCallee;
1120 /// Declaration for ObjC runtime function objc_retainBlock.
1121 Constant *RetainBlockCallee;
1122 /// Declaration for ObjC runtime function objc_autorelease.
1123 Constant *AutoreleaseCallee;
1125 /// Flags which determine whether each of the interesting runtine functions
1126 /// is in fact used in the current function.
1127 unsigned UsedInThisFunction;
1129 /// The Metadata Kind for clang.imprecise_release metadata.
1130 unsigned ImpreciseReleaseMDKind;
1132 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1133 unsigned CopyOnEscapeMDKind;
1135 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1136 unsigned NoObjCARCExceptionsMDKind;
1138 #ifdef ARC_ANNOTATIONS
1139 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1140 unsigned ARCAnnotationBottomUpMDKind;
1141 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1142 unsigned ARCAnnotationTopDownMDKind;
1143 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1144 unsigned ARCAnnotationProvenanceSourceMDKind;
1145 #endif // ARC_ANNOATIONS
1147 Constant *getAutoreleaseRVCallee(Module *M);
1148 Constant *getReleaseCallee(Module *M);
1149 Constant *getRetainCallee(Module *M);
1150 Constant *getRetainBlockCallee(Module *M);
1151 Constant *getAutoreleaseCallee(Module *M);
1153 bool IsRetainBlockOptimizable(const Instruction *Inst);
1155 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1156 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1157 InstructionClass &Class);
1158 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1159 InstructionClass &Class);
1160 void OptimizeIndividualCalls(Function &F);
1162 void CheckForCFGHazards(const BasicBlock *BB,
1163 DenseMap<const BasicBlock *, BBState> &BBStates,
1164 BBState &MyStates) const;
1165 bool VisitInstructionBottomUp(Instruction *Inst,
1167 MapVector<Value *, RRInfo> &Retains,
1169 bool VisitBottomUp(BasicBlock *BB,
1170 DenseMap<const BasicBlock *, BBState> &BBStates,
1171 MapVector<Value *, RRInfo> &Retains);
1172 bool VisitInstructionTopDown(Instruction *Inst,
1173 DenseMap<Value *, RRInfo> &Releases,
1175 bool VisitTopDown(BasicBlock *BB,
1176 DenseMap<const BasicBlock *, BBState> &BBStates,
1177 DenseMap<Value *, RRInfo> &Releases);
1178 bool Visit(Function &F,
1179 DenseMap<const BasicBlock *, BBState> &BBStates,
1180 MapVector<Value *, RRInfo> &Retains,
1181 DenseMap<Value *, RRInfo> &Releases);
1183 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1184 MapVector<Value *, RRInfo> &Retains,
1185 DenseMap<Value *, RRInfo> &Releases,
1186 SmallVectorImpl<Instruction *> &DeadInsts,
1189 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1190 MapVector<Value *, RRInfo> &Retains,
1191 DenseMap<Value *, RRInfo> &Releases,
1193 SmallVector<Instruction *, 4> &NewRetains,
1194 SmallVector<Instruction *, 4> &NewReleases,
1195 SmallVector<Instruction *, 8> &DeadInsts,
1196 RRInfo &RetainsToMove,
1197 RRInfo &ReleasesToMove,
1200 bool &AnyPairsCompletelyEliminated);
1202 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1203 MapVector<Value *, RRInfo> &Retains,
1204 DenseMap<Value *, RRInfo> &Releases,
1207 void OptimizeWeakCalls(Function &F);
1209 bool OptimizeSequences(Function &F);
1211 void OptimizeReturns(Function &F);
1214 void GatherStatistics(Function &F, bool AfterOptimization = false);
1217 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1218 virtual bool doInitialization(Module &M);
1219 virtual bool runOnFunction(Function &F);
1220 virtual void releaseMemory();
1224 ObjCARCOpt() : FunctionPass(ID) {
1225 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1230 char ObjCARCOpt::ID = 0;
1231 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1232 "objc-arc", "ObjC ARC optimization", false, false)
1233 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1234 INITIALIZE_PASS_END(ObjCARCOpt,
1235 "objc-arc", "ObjC ARC optimization", false, false)
1237 Pass *llvm::createObjCARCOptPass() {
1238 return new ObjCARCOpt();
1241 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1242 AU.addRequired<ObjCARCAliasAnalysis>();
1243 AU.addRequired<AliasAnalysis>();
1244 // ARC optimization doesn't currently split critical edges.
1245 AU.setPreservesCFG();
1248 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1249 // Without the magic metadata tag, we have to assume this might be an
1250 // objc_retainBlock call inserted to convert a block pointer to an id,
1251 // in which case it really is needed.
1252 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1255 // If the pointer "escapes" (not including being used in a call),
1256 // the copy may be needed.
1257 if (DoesRetainableObjPtrEscape(Inst))
1260 // Otherwise, it's not needed.
1264 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1265 if (!AutoreleaseRVCallee) {
1266 LLVMContext &C = M->getContext();
1267 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1268 Type *Params[] = { I8X };
1269 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1270 AttributeSet Attribute =
1271 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1272 Attribute::NoUnwind);
1273 AutoreleaseRVCallee =
1274 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1277 return AutoreleaseRVCallee;
1280 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1281 if (!ReleaseCallee) {
1282 LLVMContext &C = M->getContext();
1283 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1284 AttributeSet Attribute =
1285 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1286 Attribute::NoUnwind);
1288 M->getOrInsertFunction(
1290 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1293 return ReleaseCallee;
1296 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1297 if (!RetainCallee) {
1298 LLVMContext &C = M->getContext();
1299 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1300 AttributeSet Attribute =
1301 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1302 Attribute::NoUnwind);
1304 M->getOrInsertFunction(
1306 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1309 return RetainCallee;
1312 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1313 if (!RetainBlockCallee) {
1314 LLVMContext &C = M->getContext();
1315 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1316 // objc_retainBlock is not nounwind because it calls user copy constructors
1317 // which could theoretically throw.
1319 M->getOrInsertFunction(
1321 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1324 return RetainBlockCallee;
1327 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1328 if (!AutoreleaseCallee) {
1329 LLVMContext &C = M->getContext();
1330 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1331 AttributeSet Attribute =
1332 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1333 Attribute::NoUnwind);
1335 M->getOrInsertFunction(
1337 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1340 return AutoreleaseCallee;
1343 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1344 /// not a return value. Or, if it can be paired with an
1345 /// objc_autoreleaseReturnValue, delete the pair and return true.
1347 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1348 // Check for the argument being from an immediately preceding call or invoke.
1349 const Value *Arg = GetObjCArg(RetainRV);
1350 ImmutableCallSite CS(Arg);
1351 if (const Instruction *Call = CS.getInstruction()) {
1352 if (Call->getParent() == RetainRV->getParent()) {
1353 BasicBlock::const_iterator I = Call;
1355 while (IsNoopInstruction(I)) ++I;
1356 if (&*I == RetainRV)
1358 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1359 BasicBlock *RetainRVParent = RetainRV->getParent();
1360 if (II->getNormalDest() == RetainRVParent) {
1361 BasicBlock::const_iterator I = RetainRVParent->begin();
1362 while (IsNoopInstruction(I)) ++I;
1363 if (&*I == RetainRV)
1369 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1370 // pointer. In this case, we can delete the pair.
1371 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1373 do --I; while (I != Begin && IsNoopInstruction(I));
1374 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1375 GetObjCArg(I) == Arg) {
1379 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1380 << "Erasing " << *RetainRV << "\n");
1382 EraseInstruction(I);
1383 EraseInstruction(RetainRV);
1388 // Turn it to a plain objc_retain.
1392 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1393 "objc_retain since the operand is not a return value.\n"
1394 "Old = " << *RetainRV << "\n");
1396 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1398 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1403 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1404 /// used as a return value.
1406 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1407 InstructionClass &Class) {
1408 // Check for a return of the pointer value.
1409 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1410 SmallVector<const Value *, 2> Users;
1411 Users.push_back(Ptr);
1413 Ptr = Users.pop_back_val();
1414 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1416 const User *I = *UI;
1417 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1419 if (isa<BitCastInst>(I))
1422 } while (!Users.empty());
1427 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1428 "objc_autorelease since its operand is not used as a return "
1430 "Old = " << *AutoreleaseRV << "\n");
1432 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1434 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1435 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1436 Class = IC_Autorelease;
1438 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1442 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1445 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1446 // does not escape (following the rules of block escaping), strength reduce the
1447 // objc_retainBlock to an objc_retain.
1449 // TODO: If an objc_retainBlock call is dominated period by a previous
1450 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1453 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1454 InstructionClass &Class) {
1455 assert(GetBasicInstructionClass(Inst) == Class);
1456 assert(IC_RetainBlock == Class);
1458 // If we can not optimize Inst, return false.
1459 if (!IsRetainBlockOptimizable(Inst))
1465 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1466 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1467 CallInst *RetainBlock = cast<CallInst>(Inst);
1468 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1469 // Remove copy_on_escape metadata.
1470 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1472 DEBUG(dbgs() << "New: " << *Inst << "\n");
1476 /// Visit each call, one at a time, and make simplifications without doing any
1477 /// additional analysis.
1478 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1479 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1480 // Reset all the flags in preparation for recomputing them.
1481 UsedInThisFunction = 0;
1483 // Visit all objc_* calls in F.
1484 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1485 Instruction *Inst = &*I++;
1487 InstructionClass Class = GetBasicInstructionClass(Inst);
1489 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1494 // Delete no-op casts. These function calls have special semantics, but
1495 // the semantics are entirely implemented via lowering in the front-end,
1496 // so by the time they reach the optimizer, they are just no-op calls
1497 // which return their argument.
1499 // There are gray areas here, as the ability to cast reference-counted
1500 // pointers to raw void* and back allows code to break ARC assumptions,
1501 // however these are currently considered to be unimportant.
1505 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1506 EraseInstruction(Inst);
1509 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1512 case IC_LoadWeakRetained:
1514 case IC_DestroyWeak: {
1515 CallInst *CI = cast<CallInst>(Inst);
1516 if (IsNullOrUndef(CI->getArgOperand(0))) {
1518 Type *Ty = CI->getArgOperand(0)->getType();
1519 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1520 Constant::getNullValue(Ty),
1522 llvm::Value *NewValue = UndefValue::get(CI->getType());
1523 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1524 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1525 CI->replaceAllUsesWith(NewValue);
1526 CI->eraseFromParent();
1533 CallInst *CI = cast<CallInst>(Inst);
1534 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1535 IsNullOrUndef(CI->getArgOperand(1))) {
1537 Type *Ty = CI->getArgOperand(0)->getType();
1538 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1539 Constant::getNullValue(Ty),
1542 llvm::Value *NewValue = UndefValue::get(CI->getType());
1543 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1544 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1546 CI->replaceAllUsesWith(NewValue);
1547 CI->eraseFromParent();
1552 case IC_RetainBlock:
1553 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1554 // onto the objc_retain peephole optimizations. Otherwise break.
1555 OptimizeRetainBlockCall(F, Inst, Class);
1558 if (OptimizeRetainRVCall(F, Inst))
1561 case IC_AutoreleaseRV:
1562 OptimizeAutoreleaseRVCall(F, Inst, Class);
1566 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1567 if (IsAutorelease(Class) && Inst->use_empty()) {
1568 CallInst *Call = cast<CallInst>(Inst);
1569 const Value *Arg = Call->getArgOperand(0);
1570 Arg = FindSingleUseIdentifiedObject(Arg);
1575 // Create the declaration lazily.
1576 LLVMContext &C = Inst->getContext();
1578 CallInst::Create(getReleaseCallee(F.getParent()),
1579 Call->getArgOperand(0), "", Call);
1580 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1582 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1583 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1584 << *NewCall << "\n");
1586 EraseInstruction(Call);
1592 // For functions which can never be passed stack arguments, add
1594 if (IsAlwaysTail(Class)) {
1596 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1597 "passed stack args: " << *Inst << "\n");
1598 cast<CallInst>(Inst)->setTailCall();
1601 // Ensure that functions that can never have a "tail" keyword due to the
1602 // semantics of ARC truly do not do so.
1603 if (IsNeverTail(Class)) {
1605 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1607 cast<CallInst>(Inst)->setTailCall(false);
1610 // Set nounwind as needed.
1611 if (IsNoThrow(Class)) {
1613 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1615 cast<CallInst>(Inst)->setDoesNotThrow();
1618 if (!IsNoopOnNull(Class)) {
1619 UsedInThisFunction |= 1 << Class;
1623 const Value *Arg = GetObjCArg(Inst);
1625 // ARC calls with null are no-ops. Delete them.
1626 if (IsNullOrUndef(Arg)) {
1629 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1631 EraseInstruction(Inst);
1635 // Keep track of which of retain, release, autorelease, and retain_block
1636 // are actually present in this function.
1637 UsedInThisFunction |= 1 << Class;
1639 // If Arg is a PHI, and one or more incoming values to the
1640 // PHI are null, and the call is control-equivalent to the PHI, and there
1641 // are no relevant side effects between the PHI and the call, the call
1642 // could be pushed up to just those paths with non-null incoming values.
1643 // For now, don't bother splitting critical edges for this.
1644 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1645 Worklist.push_back(std::make_pair(Inst, Arg));
1647 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1651 const PHINode *PN = dyn_cast<PHINode>(Arg);
1654 // Determine if the PHI has any null operands, or any incoming
1656 bool HasNull = false;
1657 bool HasCriticalEdges = false;
1658 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1660 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1661 if (IsNullOrUndef(Incoming))
1663 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1664 .getNumSuccessors() != 1) {
1665 HasCriticalEdges = true;
1669 // If we have null operands and no critical edges, optimize.
1670 if (!HasCriticalEdges && HasNull) {
1671 SmallPtrSet<Instruction *, 4> DependingInstructions;
1672 SmallPtrSet<const BasicBlock *, 4> Visited;
1674 // Check that there is nothing that cares about the reference
1675 // count between the call and the phi.
1678 case IC_RetainBlock:
1679 // These can always be moved up.
1682 // These can't be moved across things that care about the retain
1684 FindDependencies(NeedsPositiveRetainCount, Arg,
1685 Inst->getParent(), Inst,
1686 DependingInstructions, Visited, PA);
1688 case IC_Autorelease:
1689 // These can't be moved across autorelease pool scope boundaries.
1690 FindDependencies(AutoreleasePoolBoundary, Arg,
1691 Inst->getParent(), Inst,
1692 DependingInstructions, Visited, PA);
1695 case IC_AutoreleaseRV:
1696 // Don't move these; the RV optimization depends on the autoreleaseRV
1697 // being tail called, and the retainRV being immediately after a call
1698 // (which might still happen if we get lucky with codegen layout, but
1699 // it's not worth taking the chance).
1702 llvm_unreachable("Invalid dependence flavor");
1705 if (DependingInstructions.size() == 1 &&
1706 *DependingInstructions.begin() == PN) {
1709 // Clone the call into each predecessor that has a non-null value.
1710 CallInst *CInst = cast<CallInst>(Inst);
1711 Type *ParamTy = CInst->getArgOperand(0)->getType();
1712 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1714 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1715 if (!IsNullOrUndef(Incoming)) {
1716 CallInst *Clone = cast<CallInst>(CInst->clone());
1717 Value *Op = PN->getIncomingValue(i);
1718 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1719 if (Op->getType() != ParamTy)
1720 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1721 Clone->setArgOperand(0, Op);
1722 Clone->insertBefore(InsertPos);
1724 DEBUG(dbgs() << "Cloning "
1726 "And inserting clone at " << *InsertPos << "\n");
1727 Worklist.push_back(std::make_pair(Clone, Incoming));
1730 // Erase the original call.
1731 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1732 EraseInstruction(CInst);
1736 } while (!Worklist.empty());
1740 /// If we have a top down pointer in the S_Use state, make sure that there are
1741 /// no CFG hazards by checking the states of various bottom up pointers.
1742 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1743 const bool SuccSRRIKnownSafe,
1745 bool &SomeSuccHasSame,
1746 bool &AllSuccsHaveSame,
1747 bool &NotAllSeqEqualButKnownSafe,
1748 bool &ShouldContinue) {
1750 case S_CanRelease: {
1751 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
1752 S.ClearSequenceProgress();
1755 S.RRI.CFGHazardAfflicted = true;
1756 ShouldContinue = true;
1760 SomeSuccHasSame = true;
1764 case S_MovableRelease:
1765 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1766 AllSuccsHaveSame = false;
1768 NotAllSeqEqualButKnownSafe = true;
1771 llvm_unreachable("bottom-up pointer in retain state!");
1773 llvm_unreachable("This should have been handled earlier.");
1777 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1778 /// there are no CFG hazards by checking the states of various bottom up
1780 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1781 const bool SuccSRRIKnownSafe,
1783 bool &SomeSuccHasSame,
1784 bool &AllSuccsHaveSame,
1785 bool &NotAllSeqEqualButKnownSafe) {
1788 SomeSuccHasSame = true;
1792 case S_MovableRelease:
1794 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1795 AllSuccsHaveSame = false;
1797 NotAllSeqEqualButKnownSafe = true;
1800 llvm_unreachable("bottom-up pointer in retain state!");
1802 llvm_unreachable("This should have been handled earlier.");
1806 /// Check for critical edges, loop boundaries, irreducible control flow, or
1807 /// other CFG structures where moving code across the edge would result in it
1808 /// being executed more.
1810 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1811 DenseMap<const BasicBlock *, BBState> &BBStates,
1812 BBState &MyStates) const {
1813 // If any top-down local-use or possible-dec has a succ which is earlier in
1814 // the sequence, forget it.
1815 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1816 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1817 PtrState &S = I->second;
1818 const Sequence Seq = I->second.GetSeq();
1820 // We only care about S_Retain, S_CanRelease, and S_Use.
1824 // Make sure that if extra top down states are added in the future that this
1825 // code is updated to handle it.
1826 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1827 "Unknown top down sequence state.");
1829 const Value *Arg = I->first;
1830 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1831 bool SomeSuccHasSame = false;
1832 bool AllSuccsHaveSame = true;
1833 bool NotAllSeqEqualButKnownSafe = false;
1835 succ_const_iterator SI(TI), SE(TI, false);
1837 for (; SI != SE; ++SI) {
1838 // If VisitBottomUp has pointer information for this successor, take
1839 // what we know about it.
1840 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1842 assert(BBI != BBStates.end());
1843 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1844 const Sequence SuccSSeq = SuccS.GetSeq();
1846 // If bottom up, the pointer is in an S_None state, clear the sequence
1847 // progress since the sequence in the bottom up state finished
1848 // suggesting a mismatch in between retains/releases. This is true for
1849 // all three cases that we are handling here: S_Retain, S_Use, and
1851 if (SuccSSeq == S_None) {
1852 S.ClearSequenceProgress();
1856 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1858 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1860 // *NOTE* We do not use Seq from above here since we are allowing for
1861 // S.GetSeq() to change while we are visiting basic blocks.
1862 switch(S.GetSeq()) {
1864 bool ShouldContinue = false;
1865 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1866 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1872 case S_CanRelease: {
1873 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1874 SomeSuccHasSame, AllSuccsHaveSame,
1875 NotAllSeqEqualButKnownSafe);
1882 case S_MovableRelease:
1887 // If the state at the other end of any of the successor edges
1888 // matches the current state, require all edges to match. This
1889 // guards against loops in the middle of a sequence.
1890 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1891 S.ClearSequenceProgress();
1892 } else if (NotAllSeqEqualButKnownSafe) {
1893 // If we would have cleared the state foregoing the fact that we are known
1894 // safe, stop code motion. This is because whether or not it is safe to
1895 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1896 // are allowed to perform code motion.
1897 S.RRI.CFGHazardAfflicted = true;
1903 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1905 MapVector<Value *, RRInfo> &Retains,
1906 BBState &MyStates) {
1907 bool NestingDetected = false;
1908 InstructionClass Class = GetInstructionClass(Inst);
1909 const Value *Arg = 0;
1911 DEBUG(dbgs() << "Class: " << Class << "\n");
1915 Arg = GetObjCArg(Inst);
1917 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1919 // If we see two releases in a row on the same pointer. If so, make
1920 // a note, and we'll cicle back to revisit it after we've
1921 // hopefully eliminated the second release, which may allow us to
1922 // eliminate the first release too.
1923 // Theoretically we could implement removal of nested retain+release
1924 // pairs by making PtrState hold a stack of states, but this is
1925 // simple and avoids adding overhead for the non-nested case.
1926 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1927 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1928 NestingDetected = true;
1931 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1932 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1933 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1934 S.ResetSequenceProgress(NewSeq);
1935 S.SetReleaseMetadata(ReleaseMetadata);
1936 S.SetKnownSafe(S.HasKnownPositiveRefCount());
1937 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1938 S.RRI.Calls.insert(Inst);
1939 S.SetKnownPositiveRefCount();
1942 case IC_RetainBlock:
1943 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1944 // objc_retainBlocks to objc_retains. Thus at this point any
1945 // objc_retainBlocks that we see are not optimizable.
1949 Arg = GetObjCArg(Inst);
1951 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1952 S.SetKnownPositiveRefCount();
1954 Sequence OldSeq = S.GetSeq();
1958 case S_MovableRelease:
1960 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1961 // imprecise release, clear our reverse insertion points.
1962 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1963 S.RRI.ReverseInsertPts.clear();
1966 // Don't do retain+release tracking for IC_RetainRV, because it's
1967 // better to let it remain as the first instruction after a call.
1968 if (Class != IC_RetainRV)
1969 Retains[Inst] = S.RRI;
1970 S.ClearSequenceProgress();
1975 llvm_unreachable("bottom-up pointer in retain state!");
1977 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1978 // A retain moving bottom up can be a use.
1981 case IC_AutoreleasepoolPop:
1982 // Conservatively, clear MyStates for all known pointers.
1983 MyStates.clearBottomUpPointers();
1984 return NestingDetected;
1985 case IC_AutoreleasepoolPush:
1987 // These are irrelevant.
1988 return NestingDetected;
1990 // If we have a store into an alloca of a pointer we are tracking, the
1991 // pointer has multiple owners implying that we must be more conservative.
1993 // This comes up in the context of a pointer being ``KnownSafe''. In the
1994 // presense of a block being initialized, the frontend will emit the
1995 // objc_retain on the original pointer and the release on the pointer loaded
1996 // from the alloca. The optimizer will through the provenance analysis
1997 // realize that the two are related, but since we only require KnownSafe in
1998 // one direction, will match the inner retain on the original pointer with
1999 // the guard release on the original pointer. This is fixed by ensuring that
2000 // in the presense of allocas we only unconditionally remove pointers if
2001 // both our retain and our release are KnownSafe.
2002 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2003 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
2004 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
2005 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
2006 if (I != MyStates.bottom_up_ptr_end())
2007 MultiOwnersSet.insert(I->first);
2015 // Consider any other possible effects of this instruction on each
2016 // pointer being tracked.
2017 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2018 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2019 const Value *Ptr = MI->first;
2021 continue; // Handled above.
2022 PtrState &S = MI->second;
2023 Sequence Seq = S.GetSeq();
2025 // Check for possible releases.
2026 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2027 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2029 S.ClearKnownPositiveRefCount();
2032 S.SetSeq(S_CanRelease);
2033 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
2037 case S_MovableRelease:
2042 llvm_unreachable("bottom-up pointer in retain state!");
2046 // Check for possible direct uses.
2049 case S_MovableRelease:
2050 if (CanUse(Inst, Ptr, PA, Class)) {
2051 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2053 assert(S.RRI.ReverseInsertPts.empty());
2054 // If this is an invoke instruction, we're scanning it as part of
2055 // one of its successor blocks, since we can't insert code after it
2056 // in its own block, and we don't want to split critical edges.
2057 if (isa<InvokeInst>(Inst))
2058 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2060 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2062 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2063 } else if (Seq == S_Release && IsUser(Class)) {
2064 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2066 // Non-movable releases depend on any possible objc pointer use.
2068 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2069 assert(S.RRI.ReverseInsertPts.empty());
2070 // As above; handle invoke specially.
2071 if (isa<InvokeInst>(Inst))
2072 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2074 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2078 if (CanUse(Inst, Ptr, PA, Class)) {
2079 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2082 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2090 llvm_unreachable("bottom-up pointer in retain state!");
2094 return NestingDetected;
2098 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2099 DenseMap<const BasicBlock *, BBState> &BBStates,
2100 MapVector<Value *, RRInfo> &Retains) {
2102 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2104 bool NestingDetected = false;
2105 BBState &MyStates = BBStates[BB];
2107 // Merge the states from each successor to compute the initial state
2108 // for the current block.
2109 BBState::edge_iterator SI(MyStates.succ_begin()),
2110 SE(MyStates.succ_end());
2112 const BasicBlock *Succ = *SI;
2113 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2114 assert(I != BBStates.end());
2115 MyStates.InitFromSucc(I->second);
2117 for (; SI != SE; ++SI) {
2119 I = BBStates.find(Succ);
2120 assert(I != BBStates.end());
2121 MyStates.MergeSucc(I->second);
2125 // If ARC Annotations are enabled, output the current state of pointers at the
2126 // bottom of the basic block.
2127 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2129 // Visit all the instructions, bottom-up.
2130 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2131 Instruction *Inst = llvm::prior(I);
2133 // Invoke instructions are visited as part of their successors (below).
2134 if (isa<InvokeInst>(Inst))
2137 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2139 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2142 // If there's a predecessor with an invoke, visit the invoke as if it were
2143 // part of this block, since we can't insert code after an invoke in its own
2144 // block, and we don't want to split critical edges.
2145 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2146 PE(MyStates.pred_end()); PI != PE; ++PI) {
2147 BasicBlock *Pred = *PI;
2148 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2149 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2152 // If ARC Annotations are enabled, output the current state of pointers at the
2153 // top of the basic block.
2154 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2156 return NestingDetected;
2160 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2161 DenseMap<Value *, RRInfo> &Releases,
2162 BBState &MyStates) {
2163 bool NestingDetected = false;
2164 InstructionClass Class = GetInstructionClass(Inst);
2165 const Value *Arg = 0;
2168 case IC_RetainBlock:
2169 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2170 // objc_retainBlocks to objc_retains. Thus at this point any
2171 // objc_retainBlocks that we see are not optimizable.
2175 Arg = GetObjCArg(Inst);
2177 PtrState &S = MyStates.getPtrTopDownState(Arg);
2179 // Don't do retain+release tracking for IC_RetainRV, because it's
2180 // better to let it remain as the first instruction after a call.
2181 if (Class != IC_RetainRV) {
2182 // If we see two retains in a row on the same pointer. If so, make
2183 // a note, and we'll cicle back to revisit it after we've
2184 // hopefully eliminated the second retain, which may allow us to
2185 // eliminate the first retain too.
2186 // Theoretically we could implement removal of nested retain+release
2187 // pairs by making PtrState hold a stack of states, but this is
2188 // simple and avoids adding overhead for the non-nested case.
2189 if (S.GetSeq() == S_Retain)
2190 NestingDetected = true;
2192 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2193 S.ResetSequenceProgress(S_Retain);
2194 S.SetKnownSafe(S.HasKnownPositiveRefCount());
2195 S.RRI.Calls.insert(Inst);
2198 S.SetKnownPositiveRefCount();
2200 // A retain can be a potential use; procede to the generic checking
2205 Arg = GetObjCArg(Inst);
2207 PtrState &S = MyStates.getPtrTopDownState(Arg);
2208 S.ClearKnownPositiveRefCount();
2210 Sequence OldSeq = S.GetSeq();
2212 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2217 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2218 S.RRI.ReverseInsertPts.clear();
2221 S.SetReleaseMetadata(ReleaseMetadata);
2222 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
2223 Releases[Inst] = S.RRI;
2224 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2225 S.ClearSequenceProgress();
2231 case S_MovableRelease:
2232 llvm_unreachable("top-down pointer in release state!");
2236 case IC_AutoreleasepoolPop:
2237 // Conservatively, clear MyStates for all known pointers.
2238 MyStates.clearTopDownPointers();
2239 return NestingDetected;
2240 case IC_AutoreleasepoolPush:
2242 // These are irrelevant.
2243 return NestingDetected;
2248 // Consider any other possible effects of this instruction on each
2249 // pointer being tracked.
2250 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2251 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2252 const Value *Ptr = MI->first;
2254 continue; // Handled above.
2255 PtrState &S = MI->second;
2256 Sequence Seq = S.GetSeq();
2258 // Check for possible releases.
2259 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2260 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2262 S.ClearKnownPositiveRefCount();
2265 S.SetSeq(S_CanRelease);
2266 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2267 assert(S.RRI.ReverseInsertPts.empty());
2268 S.RRI.ReverseInsertPts.insert(Inst);
2270 // One call can't cause a transition from S_Retain to S_CanRelease
2271 // and S_CanRelease to S_Use. If we've made the first transition,
2280 case S_MovableRelease:
2281 llvm_unreachable("top-down pointer in release state!");
2285 // Check for possible direct uses.
2288 if (CanUse(Inst, Ptr, PA, Class)) {
2289 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2292 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2301 case S_MovableRelease:
2302 llvm_unreachable("top-down pointer in release state!");
2306 return NestingDetected;
2310 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2311 DenseMap<const BasicBlock *, BBState> &BBStates,
2312 DenseMap<Value *, RRInfo> &Releases) {
2313 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2314 bool NestingDetected = false;
2315 BBState &MyStates = BBStates[BB];
2317 // Merge the states from each predecessor to compute the initial state
2318 // for the current block.
2319 BBState::edge_iterator PI(MyStates.pred_begin()),
2320 PE(MyStates.pred_end());
2322 const BasicBlock *Pred = *PI;
2323 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2324 assert(I != BBStates.end());
2325 MyStates.InitFromPred(I->second);
2327 for (; PI != PE; ++PI) {
2329 I = BBStates.find(Pred);
2330 assert(I != BBStates.end());
2331 MyStates.MergePred(I->second);
2335 // If ARC Annotations are enabled, output the current state of pointers at the
2336 // top of the basic block.
2337 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2339 // Visit all the instructions, top-down.
2340 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2341 Instruction *Inst = I;
2343 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2345 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2348 // If ARC Annotations are enabled, output the current state of pointers at the
2349 // bottom of the basic block.
2350 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2352 #ifdef ARC_ANNOTATIONS
2353 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2355 CheckForCFGHazards(BB, BBStates, MyStates);
2356 return NestingDetected;
2360 ComputePostOrders(Function &F,
2361 SmallVectorImpl<BasicBlock *> &PostOrder,
2362 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2363 unsigned NoObjCARCExceptionsMDKind,
2364 DenseMap<const BasicBlock *, BBState> &BBStates) {
2365 /// The visited set, for doing DFS walks.
2366 SmallPtrSet<BasicBlock *, 16> Visited;
2368 // Do DFS, computing the PostOrder.
2369 SmallPtrSet<BasicBlock *, 16> OnStack;
2370 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2372 // Functions always have exactly one entry block, and we don't have
2373 // any other block that we treat like an entry block.
2374 BasicBlock *EntryBB = &F.getEntryBlock();
2375 BBState &MyStates = BBStates[EntryBB];
2376 MyStates.SetAsEntry();
2377 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2378 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2379 Visited.insert(EntryBB);
2380 OnStack.insert(EntryBB);
2383 BasicBlock *CurrBB = SuccStack.back().first;
2384 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2385 succ_iterator SE(TI, false);
2387 while (SuccStack.back().second != SE) {
2388 BasicBlock *SuccBB = *SuccStack.back().second++;
2389 if (Visited.insert(SuccBB)) {
2390 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2391 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2392 BBStates[CurrBB].addSucc(SuccBB);
2393 BBState &SuccStates = BBStates[SuccBB];
2394 SuccStates.addPred(CurrBB);
2395 OnStack.insert(SuccBB);
2399 if (!OnStack.count(SuccBB)) {
2400 BBStates[CurrBB].addSucc(SuccBB);
2401 BBStates[SuccBB].addPred(CurrBB);
2404 OnStack.erase(CurrBB);
2405 PostOrder.push_back(CurrBB);
2406 SuccStack.pop_back();
2407 } while (!SuccStack.empty());
2411 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2412 // Functions may have many exits, and there also blocks which we treat
2413 // as exits due to ignored edges.
2414 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2415 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2416 BasicBlock *ExitBB = I;
2417 BBState &MyStates = BBStates[ExitBB];
2418 if (!MyStates.isExit())
2421 MyStates.SetAsExit();
2423 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2424 Visited.insert(ExitBB);
2425 while (!PredStack.empty()) {
2426 reverse_dfs_next_succ:
2427 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2428 while (PredStack.back().second != PE) {
2429 BasicBlock *BB = *PredStack.back().second++;
2430 if (Visited.insert(BB)) {
2431 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2432 goto reverse_dfs_next_succ;
2435 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2440 // Visit the function both top-down and bottom-up.
2442 ObjCARCOpt::Visit(Function &F,
2443 DenseMap<const BasicBlock *, BBState> &BBStates,
2444 MapVector<Value *, RRInfo> &Retains,
2445 DenseMap<Value *, RRInfo> &Releases) {
2447 // Use reverse-postorder traversals, because we magically know that loops
2448 // will be well behaved, i.e. they won't repeatedly call retain on a single
2449 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2450 // class here because we want the reverse-CFG postorder to consider each
2451 // function exit point, and we want to ignore selected cycle edges.
2452 SmallVector<BasicBlock *, 16> PostOrder;
2453 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2454 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2455 NoObjCARCExceptionsMDKind,
2458 // Use reverse-postorder on the reverse CFG for bottom-up.
2459 bool BottomUpNestingDetected = false;
2460 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2461 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2463 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2465 // Use reverse-postorder for top-down.
2466 bool TopDownNestingDetected = false;
2467 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2468 PostOrder.rbegin(), E = PostOrder.rend();
2470 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2472 return TopDownNestingDetected && BottomUpNestingDetected;
2475 /// Move the calls in RetainsToMove and ReleasesToMove.
2476 void ObjCARCOpt::MoveCalls(Value *Arg,
2477 RRInfo &RetainsToMove,
2478 RRInfo &ReleasesToMove,
2479 MapVector<Value *, RRInfo> &Retains,
2480 DenseMap<Value *, RRInfo> &Releases,
2481 SmallVectorImpl<Instruction *> &DeadInsts,
2483 Type *ArgTy = Arg->getType();
2484 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2486 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2488 // Insert the new retain and release calls.
2489 for (SmallPtrSet<Instruction *, 2>::const_iterator
2490 PI = ReleasesToMove.ReverseInsertPts.begin(),
2491 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2492 Instruction *InsertPt = *PI;
2493 Value *MyArg = ArgTy == ParamTy ? Arg :
2494 new BitCastInst(Arg, ParamTy, "", InsertPt);
2496 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2497 Call->setDoesNotThrow();
2498 Call->setTailCall();
2500 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2501 "At insertion point: " << *InsertPt << "\n");
2503 for (SmallPtrSet<Instruction *, 2>::const_iterator
2504 PI = RetainsToMove.ReverseInsertPts.begin(),
2505 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2506 Instruction *InsertPt = *PI;
2507 Value *MyArg = ArgTy == ParamTy ? Arg :
2508 new BitCastInst(Arg, ParamTy, "", InsertPt);
2509 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2511 // Attach a clang.imprecise_release metadata tag, if appropriate.
2512 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2513 Call->setMetadata(ImpreciseReleaseMDKind, M);
2514 Call->setDoesNotThrow();
2515 if (ReleasesToMove.IsTailCallRelease)
2516 Call->setTailCall();
2518 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2519 "At insertion point: " << *InsertPt << "\n");
2522 // Delete the original retain and release calls.
2523 for (SmallPtrSet<Instruction *, 2>::const_iterator
2524 AI = RetainsToMove.Calls.begin(),
2525 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2526 Instruction *OrigRetain = *AI;
2527 Retains.blot(OrigRetain);
2528 DeadInsts.push_back(OrigRetain);
2529 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2531 for (SmallPtrSet<Instruction *, 2>::const_iterator
2532 AI = ReleasesToMove.Calls.begin(),
2533 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2534 Instruction *OrigRelease = *AI;
2535 Releases.erase(OrigRelease);
2536 DeadInsts.push_back(OrigRelease);
2537 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2543 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2545 MapVector<Value *, RRInfo> &Retains,
2546 DenseMap<Value *, RRInfo> &Releases,
2548 SmallVector<Instruction *, 4> &NewRetains,
2549 SmallVector<Instruction *, 4> &NewReleases,
2550 SmallVector<Instruction *, 8> &DeadInsts,
2551 RRInfo &RetainsToMove,
2552 RRInfo &ReleasesToMove,
2555 bool &AnyPairsCompletelyEliminated) {
2556 // If a pair happens in a region where it is known that the reference count
2557 // is already incremented, we can similarly ignore possible decrements unless
2558 // we are dealing with a retainable object with multiple provenance sources.
2559 bool KnownSafeTD = true, KnownSafeBU = true;
2560 bool MultipleOwners = false;
2561 bool CFGHazardAfflicted = false;
2563 // Connect the dots between the top-down-collected RetainsToMove and
2564 // bottom-up-collected ReleasesToMove to form sets of related calls.
2565 // This is an iterative process so that we connect multiple releases
2566 // to multiple retains if needed.
2567 unsigned OldDelta = 0;
2568 unsigned NewDelta = 0;
2569 unsigned OldCount = 0;
2570 unsigned NewCount = 0;
2571 bool FirstRelease = true;
2573 for (SmallVectorImpl<Instruction *>::const_iterator
2574 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2575 Instruction *NewRetain = *NI;
2576 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2577 assert(It != Retains.end());
2578 const RRInfo &NewRetainRRI = It->second;
2579 KnownSafeTD &= NewRetainRRI.KnownSafe;
2581 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2582 for (SmallPtrSet<Instruction *, 2>::const_iterator
2583 LI = NewRetainRRI.Calls.begin(),
2584 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2585 Instruction *NewRetainRelease = *LI;
2586 DenseMap<Value *, RRInfo>::const_iterator Jt =
2587 Releases.find(NewRetainRelease);
2588 if (Jt == Releases.end())
2590 const RRInfo &NewRetainReleaseRRI = Jt->second;
2591 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2592 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2594 // If we overflow when we compute the path count, don't remove/move
2596 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2598 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2600 OldDelta -= PathCount;
2602 // Merge the ReleaseMetadata and IsTailCallRelease values.
2604 ReleasesToMove.ReleaseMetadata =
2605 NewRetainReleaseRRI.ReleaseMetadata;
2606 ReleasesToMove.IsTailCallRelease =
2607 NewRetainReleaseRRI.IsTailCallRelease;
2608 FirstRelease = false;
2610 if (ReleasesToMove.ReleaseMetadata !=
2611 NewRetainReleaseRRI.ReleaseMetadata)
2612 ReleasesToMove.ReleaseMetadata = 0;
2613 if (ReleasesToMove.IsTailCallRelease !=
2614 NewRetainReleaseRRI.IsTailCallRelease)
2615 ReleasesToMove.IsTailCallRelease = false;
2618 // Collect the optimal insertion points.
2620 for (SmallPtrSet<Instruction *, 2>::const_iterator
2621 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2622 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2624 Instruction *RIP = *RI;
2625 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2626 // If we overflow when we compute the path count, don't
2627 // remove/move anything.
2628 const BBState &RIPBBState = BBStates[RIP->getParent()];
2629 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2631 NewDelta -= PathCount;
2634 NewReleases.push_back(NewRetainRelease);
2639 if (NewReleases.empty()) break;
2641 // Back the other way.
2642 for (SmallVectorImpl<Instruction *>::const_iterator
2643 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2644 Instruction *NewRelease = *NI;
2645 DenseMap<Value *, RRInfo>::const_iterator It =
2646 Releases.find(NewRelease);
2647 assert(It != Releases.end());
2648 const RRInfo &NewReleaseRRI = It->second;
2649 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2650 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2651 for (SmallPtrSet<Instruction *, 2>::const_iterator
2652 LI = NewReleaseRRI.Calls.begin(),
2653 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2654 Instruction *NewReleaseRetain = *LI;
2655 MapVector<Value *, RRInfo>::const_iterator Jt =
2656 Retains.find(NewReleaseRetain);
2657 if (Jt == Retains.end())
2659 const RRInfo &NewReleaseRetainRRI = Jt->second;
2660 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2661 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2663 // If we overflow when we compute the path count, don't remove/move
2665 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2667 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2669 OldDelta += PathCount;
2670 OldCount += PathCount;
2672 // Collect the optimal insertion points.
2674 for (SmallPtrSet<Instruction *, 2>::const_iterator
2675 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2676 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2678 Instruction *RIP = *RI;
2679 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2680 // If we overflow when we compute the path count, don't
2681 // remove/move anything.
2682 const BBState &RIPBBState = BBStates[RIP->getParent()];
2683 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2685 NewDelta += PathCount;
2686 NewCount += PathCount;
2689 NewRetains.push_back(NewReleaseRetain);
2693 NewReleases.clear();
2694 if (NewRetains.empty()) break;
2697 // If the pointer is known incremented in 1 direction and we do not have
2698 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2699 // to be known safe in both directions.
2700 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2701 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2702 if (UnconditionallySafe) {
2703 RetainsToMove.ReverseInsertPts.clear();
2704 ReleasesToMove.ReverseInsertPts.clear();
2707 // Determine whether the new insertion points we computed preserve the
2708 // balance of retain and release calls through the program.
2709 // TODO: If the fully aggressive solution isn't valid, try to find a
2710 // less aggressive solution which is.
2714 // At this point, we are not going to remove any RR pairs, but we still are
2715 // able to move RR pairs. If one of our pointers is afflicted with
2716 // CFGHazards, we cannot perform such code motion so exit early.
2717 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2718 ReleasesToMove.ReverseInsertPts.size();
2719 if (CFGHazardAfflicted && WillPerformCodeMotion)
2723 // Determine whether the original call points are balanced in the retain and
2724 // release calls through the program. If not, conservatively don't touch
2726 // TODO: It's theoretically possible to do code motion in this case, as
2727 // long as the existing imbalances are maintained.
2731 #ifdef ARC_ANNOTATIONS
2732 // Do not move calls if ARC annotations are requested.
2733 if (EnableARCAnnotations)
2735 #endif // ARC_ANNOTATIONS
2738 assert(OldCount != 0 && "Unreachable code?");
2739 NumRRs += OldCount - NewCount;
2740 // Set to true if we completely removed any RR pairs.
2741 AnyPairsCompletelyEliminated = NewCount == 0;
2743 // We can move calls!
2747 /// Identify pairings between the retains and releases, and delete and/or move
2750 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2752 MapVector<Value *, RRInfo> &Retains,
2753 DenseMap<Value *, RRInfo> &Releases,
2755 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2757 bool AnyPairsCompletelyEliminated = false;
2758 RRInfo RetainsToMove;
2759 RRInfo ReleasesToMove;
2760 SmallVector<Instruction *, 4> NewRetains;
2761 SmallVector<Instruction *, 4> NewReleases;
2762 SmallVector<Instruction *, 8> DeadInsts;
2764 // Visit each retain.
2765 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2766 E = Retains.end(); I != E; ++I) {
2767 Value *V = I->first;
2768 if (!V) continue; // blotted
2770 Instruction *Retain = cast<Instruction>(V);
2772 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2774 Value *Arg = GetObjCArg(Retain);
2776 // If the object being released is in static or stack storage, we know it's
2777 // not being managed by ObjC reference counting, so we can delete pairs
2778 // regardless of what possible decrements or uses lie between them.
2779 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2781 // A constant pointer can't be pointing to an object on the heap. It may
2782 // be reference-counted, but it won't be deleted.
2783 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2784 if (const GlobalVariable *GV =
2785 dyn_cast<GlobalVariable>(
2786 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2787 if (GV->isConstant())
2790 // Connect the dots between the top-down-collected RetainsToMove and
2791 // bottom-up-collected ReleasesToMove to form sets of related calls.
2792 NewRetains.push_back(Retain);
2793 bool PerformMoveCalls =
2794 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2795 NewReleases, DeadInsts, RetainsToMove,
2796 ReleasesToMove, Arg, KnownSafe,
2797 AnyPairsCompletelyEliminated);
2799 if (PerformMoveCalls) {
2800 // Ok, everything checks out and we're all set. Let's move/delete some
2802 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2803 Retains, Releases, DeadInsts, M);
2806 // Clean up state for next retain.
2807 NewReleases.clear();
2809 RetainsToMove.clear();
2810 ReleasesToMove.clear();
2813 // Now that we're done moving everything, we can delete the newly dead
2814 // instructions, as we no longer need them as insert points.
2815 while (!DeadInsts.empty())
2816 EraseInstruction(DeadInsts.pop_back_val());
2818 return AnyPairsCompletelyEliminated;
2821 /// Weak pointer optimizations.
2822 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2823 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2825 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2826 // itself because it uses AliasAnalysis and we need to do provenance
2828 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2829 Instruction *Inst = &*I++;
2831 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2833 InstructionClass Class = GetBasicInstructionClass(Inst);
2834 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2837 // Delete objc_loadWeak calls with no users.
2838 if (Class == IC_LoadWeak && Inst->use_empty()) {
2839 Inst->eraseFromParent();
2843 // TODO: For now, just look for an earlier available version of this value
2844 // within the same block. Theoretically, we could do memdep-style non-local
2845 // analysis too, but that would want caching. A better approach would be to
2846 // use the technique that EarlyCSE uses.
2847 inst_iterator Current = llvm::prior(I);
2848 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2849 for (BasicBlock::iterator B = CurrentBB->begin(),
2850 J = Current.getInstructionIterator();
2852 Instruction *EarlierInst = &*llvm::prior(J);
2853 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2854 switch (EarlierClass) {
2856 case IC_LoadWeakRetained: {
2857 // If this is loading from the same pointer, replace this load's value
2859 CallInst *Call = cast<CallInst>(Inst);
2860 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2861 Value *Arg = Call->getArgOperand(0);
2862 Value *EarlierArg = EarlierCall->getArgOperand(0);
2863 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2864 case AliasAnalysis::MustAlias:
2866 // If the load has a builtin retain, insert a plain retain for it.
2867 if (Class == IC_LoadWeakRetained) {
2869 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2873 // Zap the fully redundant load.
2874 Call->replaceAllUsesWith(EarlierCall);
2875 Call->eraseFromParent();
2877 case AliasAnalysis::MayAlias:
2878 case AliasAnalysis::PartialAlias:
2880 case AliasAnalysis::NoAlias:
2887 // If this is storing to the same pointer and has the same size etc.
2888 // replace this load's value with the stored value.
2889 CallInst *Call = cast<CallInst>(Inst);
2890 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2891 Value *Arg = Call->getArgOperand(0);
2892 Value *EarlierArg = EarlierCall->getArgOperand(0);
2893 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2894 case AliasAnalysis::MustAlias:
2896 // If the load has a builtin retain, insert a plain retain for it.
2897 if (Class == IC_LoadWeakRetained) {
2899 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2903 // Zap the fully redundant load.
2904 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2905 Call->eraseFromParent();
2907 case AliasAnalysis::MayAlias:
2908 case AliasAnalysis::PartialAlias:
2910 case AliasAnalysis::NoAlias:
2917 // TOOD: Grab the copied value.
2919 case IC_AutoreleasepoolPush:
2921 case IC_IntrinsicUser:
2923 // Weak pointers are only modified through the weak entry points
2924 // (and arbitrary calls, which could call the weak entry points).
2927 // Anything else could modify the weak pointer.
2934 // Then, for each destroyWeak with an alloca operand, check to see if
2935 // the alloca and all its users can be zapped.
2936 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2937 Instruction *Inst = &*I++;
2938 InstructionClass Class = GetBasicInstructionClass(Inst);
2939 if (Class != IC_DestroyWeak)
2942 CallInst *Call = cast<CallInst>(Inst);
2943 Value *Arg = Call->getArgOperand(0);
2944 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2945 for (Value::use_iterator UI = Alloca->use_begin(),
2946 UE = Alloca->use_end(); UI != UE; ++UI) {
2947 const Instruction *UserInst = cast<Instruction>(*UI);
2948 switch (GetBasicInstructionClass(UserInst)) {
2951 case IC_DestroyWeak:
2958 for (Value::use_iterator UI = Alloca->use_begin(),
2959 UE = Alloca->use_end(); UI != UE; ) {
2960 CallInst *UserInst = cast<CallInst>(*UI++);
2961 switch (GetBasicInstructionClass(UserInst)) {
2964 // These functions return their second argument.
2965 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2967 case IC_DestroyWeak:
2971 llvm_unreachable("alloca really is used!");
2973 UserInst->eraseFromParent();
2975 Alloca->eraseFromParent();
2981 /// Identify program paths which execute sequences of retains and releases which
2982 /// can be eliminated.
2983 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2984 // Releases, Retains - These are used to store the results of the main flow
2985 // analysis. These use Value* as the key instead of Instruction* so that the
2986 // map stays valid when we get around to rewriting code and calls get
2987 // replaced by arguments.
2988 DenseMap<Value *, RRInfo> Releases;
2989 MapVector<Value *, RRInfo> Retains;
2991 // This is used during the traversal of the function to track the
2992 // states for each identified object at each block.
2993 DenseMap<const BasicBlock *, BBState> BBStates;
2995 // Analyze the CFG of the function, and all instructions.
2996 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2999 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
3004 MultiOwnersSet.clear();
3006 return AnyPairsCompletelyEliminated && NestingDetected;
3009 /// Check if there is a dependent call earlier that does not have anything in
3010 /// between the Retain and the call that can affect the reference count of their
3011 /// shared pointer argument. Note that Retain need not be in BB.
3013 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
3014 SmallPtrSet<Instruction *, 4> &DepInsts,
3015 SmallPtrSet<const BasicBlock *, 4> &Visited,
3016 ProvenanceAnalysis &PA) {
3017 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3018 DepInsts, Visited, PA);
3019 if (DepInsts.size() != 1)
3023 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3025 // Check that the pointer is the return value of the call.
3026 if (!Call || Arg != Call)
3029 // Check that the call is a regular call.
3030 InstructionClass Class = GetBasicInstructionClass(Call);
3031 if (Class != IC_CallOrUser && Class != IC_Call)
3037 /// Find a dependent retain that precedes the given autorelease for which there
3038 /// is nothing in between the two instructions that can affect the ref count of
3041 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3042 Instruction *Autorelease,
3043 SmallPtrSet<Instruction *, 4> &DepInsts,
3044 SmallPtrSet<const BasicBlock *, 4> &Visited,
3045 ProvenanceAnalysis &PA) {
3046 FindDependencies(CanChangeRetainCount, Arg,
3047 BB, Autorelease, DepInsts, Visited, PA);
3048 if (DepInsts.size() != 1)
3052 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3054 // Check that we found a retain with the same argument.
3056 !IsRetain(GetBasicInstructionClass(Retain)) ||
3057 GetObjCArg(Retain) != Arg) {
3064 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3065 /// no instructions dependent on Arg that need a positive ref count in between
3066 /// the autorelease and the ret.
3068 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3070 SmallPtrSet<Instruction *, 4> &DepInsts,
3071 SmallPtrSet<const BasicBlock *, 4> &V,
3072 ProvenanceAnalysis &PA) {
3073 FindDependencies(NeedsPositiveRetainCount, Arg,
3074 BB, Ret, DepInsts, V, PA);
3075 if (DepInsts.size() != 1)
3078 CallInst *Autorelease =
3079 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3082 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3083 if (!IsAutorelease(AutoreleaseClass))
3085 if (GetObjCArg(Autorelease) != Arg)
3091 /// Look for this pattern:
3093 /// %call = call i8* @something(...)
3094 /// %2 = call i8* @objc_retain(i8* %call)
3095 /// %3 = call i8* @objc_autorelease(i8* %2)
3098 /// And delete the retain and autorelease.
3099 void ObjCARCOpt::OptimizeReturns(Function &F) {
3100 if (!F.getReturnType()->isPointerTy())
3103 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3105 SmallPtrSet<Instruction *, 4> DependingInstructions;
3106 SmallPtrSet<const BasicBlock *, 4> Visited;
3107 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3108 BasicBlock *BB = FI;
3109 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3111 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3116 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3118 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3119 // dependent on Arg such that there are no instructions dependent on Arg
3120 // that need a positive ref count in between the autorelease and Ret.
3121 CallInst *Autorelease =
3122 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3123 DependingInstructions, Visited,
3125 DependingInstructions.clear();
3132 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3133 DependingInstructions, Visited, PA);
3134 DependingInstructions.clear();
3140 // Check that there is nothing that can affect the reference count
3141 // between the retain and the call. Note that Retain need not be in BB.
3142 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3143 DependingInstructions,
3145 DependingInstructions.clear();
3148 if (!HasSafePathToCall)
3151 // If so, we can zap the retain and autorelease.
3154 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3155 << *Autorelease << "\n");
3156 EraseInstruction(Retain);
3157 EraseInstruction(Autorelease);
3163 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3164 llvm::Statistic &NumRetains =
3165 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3166 llvm::Statistic &NumReleases =
3167 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3169 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3170 Instruction *Inst = &*I++;
3171 switch (GetBasicInstructionClass(Inst)) {
3185 bool ObjCARCOpt::doInitialization(Module &M) {
3189 // If nothing in the Module uses ARC, don't do anything.
3190 Run = ModuleHasARC(M);
3194 // Identify the imprecise release metadata kind.
3195 ImpreciseReleaseMDKind =
3196 M.getContext().getMDKindID("clang.imprecise_release");
3197 CopyOnEscapeMDKind =
3198 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3199 NoObjCARCExceptionsMDKind =
3200 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3201 #ifdef ARC_ANNOTATIONS
3202 ARCAnnotationBottomUpMDKind =
3203 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3204 ARCAnnotationTopDownMDKind =
3205 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3206 ARCAnnotationProvenanceSourceMDKind =
3207 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3208 #endif // ARC_ANNOTATIONS
3210 // Intuitively, objc_retain and others are nocapture, however in practice
3211 // they are not, because they return their argument value. And objc_release
3212 // calls finalizers which can have arbitrary side effects.
3214 // These are initialized lazily.
3215 AutoreleaseRVCallee = 0;
3218 RetainBlockCallee = 0;
3219 AutoreleaseCallee = 0;
3224 bool ObjCARCOpt::runOnFunction(Function &F) {
3228 // If nothing in the Module uses ARC, don't do anything.
3234 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3237 PA.setAA(&getAnalysis<AliasAnalysis>());
3240 if (AreStatisticsEnabled()) {
3241 GatherStatistics(F, false);
3245 // This pass performs several distinct transformations. As a compile-time aid
3246 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3247 // library functions aren't declared.
3249 // Preliminary optimizations. This also computes UsedInThisFunction.
3250 OptimizeIndividualCalls(F);
3252 // Optimizations for weak pointers.
3253 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3254 (1 << IC_LoadWeakRetained) |
3255 (1 << IC_StoreWeak) |
3256 (1 << IC_InitWeak) |
3257 (1 << IC_CopyWeak) |
3258 (1 << IC_MoveWeak) |
3259 (1 << IC_DestroyWeak)))
3260 OptimizeWeakCalls(F);
3262 // Optimizations for retain+release pairs.
3263 if (UsedInThisFunction & ((1 << IC_Retain) |
3264 (1 << IC_RetainRV) |
3265 (1 << IC_RetainBlock)))
3266 if (UsedInThisFunction & (1 << IC_Release))
3267 // Run OptimizeSequences until it either stops making changes or
3268 // no retain+release pair nesting is detected.
3269 while (OptimizeSequences(F)) {}
3271 // Optimizations if objc_autorelease is used.
3272 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3273 (1 << IC_AutoreleaseRV)))
3276 // Gather statistics after optimization.
3278 if (AreStatisticsEnabled()) {
3279 GatherStatistics(F, true);
3283 DEBUG(dbgs() << "\n");
3288 void ObjCARCOpt::releaseMemory() {