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),
533 void SetKnownPositiveRefCount() {
534 DEBUG(dbgs() << "Setting Known Positive.\n");
535 KnownPositiveRefCount = true;
538 void ClearKnownPositiveRefCount() {
539 DEBUG(dbgs() << "Clearing Known Positive.\n");
540 KnownPositiveRefCount = false;
543 bool HasKnownPositiveRefCount() const {
544 return KnownPositiveRefCount;
547 void SetSeq(Sequence NewSeq) {
548 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
552 Sequence GetSeq() const {
556 void ClearSequenceProgress() {
557 ResetSequenceProgress(S_None);
560 void ResetSequenceProgress(Sequence NewSeq) {
561 DEBUG(dbgs() << "Resetting sequence progress.\n");
567 void Merge(const PtrState &Other, bool TopDown);
572 PtrState::Merge(const PtrState &Other, bool TopDown) {
573 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
574 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
576 // If we're not in a sequence (anymore), drop all associated state.
580 } else if (Partial || Other.Partial) {
581 // If we're doing a merge on a path that's previously seen a partial
582 // merge, conservatively drop the sequence, to avoid doing partial
583 // RR elimination. If the branch predicates for the two merge differ,
584 // mixing them is unsafe.
585 ClearSequenceProgress();
587 Partial = RRI.Merge(Other.RRI);
592 /// \brief Per-BasicBlock state.
594 /// The number of unique control paths from the entry which can reach this
596 unsigned TopDownPathCount;
598 /// The number of unique control paths to exits from this block.
599 unsigned BottomUpPathCount;
601 /// A type for PerPtrTopDown and PerPtrBottomUp.
602 typedef MapVector<const Value *, PtrState> MapTy;
604 /// The top-down traversal uses this to record information known about a
605 /// pointer at the bottom of each block.
608 /// The bottom-up traversal uses this to record information known about a
609 /// pointer at the top of each block.
610 MapTy PerPtrBottomUp;
612 /// Effective predecessors of the current block ignoring ignorable edges and
613 /// ignored backedges.
614 SmallVector<BasicBlock *, 2> Preds;
615 /// Effective successors of the current block ignoring ignorable edges and
616 /// ignored backedges.
617 SmallVector<BasicBlock *, 2> Succs;
620 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
622 typedef MapTy::iterator ptr_iterator;
623 typedef MapTy::const_iterator ptr_const_iterator;
625 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
626 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
627 ptr_const_iterator top_down_ptr_begin() const {
628 return PerPtrTopDown.begin();
630 ptr_const_iterator top_down_ptr_end() const {
631 return PerPtrTopDown.end();
634 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
635 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
636 ptr_const_iterator bottom_up_ptr_begin() const {
637 return PerPtrBottomUp.begin();
639 ptr_const_iterator bottom_up_ptr_end() const {
640 return PerPtrBottomUp.end();
643 /// Mark this block as being an entry block, which has one path from the
644 /// entry by definition.
645 void SetAsEntry() { TopDownPathCount = 1; }
647 /// Mark this block as being an exit block, which has one path to an exit by
649 void SetAsExit() { BottomUpPathCount = 1; }
651 /// Attempt to find the PtrState object describing the top down state for
652 /// pointer Arg. Return a new initialized PtrState describing the top down
653 /// state for Arg if we do not find one.
654 PtrState &getPtrTopDownState(const Value *Arg) {
655 return PerPtrTopDown[Arg];
658 /// Attempt to find the PtrState object describing the bottom up state for
659 /// pointer Arg. Return a new initialized PtrState describing the bottom up
660 /// state for Arg if we do not find one.
661 PtrState &getPtrBottomUpState(const Value *Arg) {
662 return PerPtrBottomUp[Arg];
665 /// Attempt to find the PtrState object describing the bottom up state for
667 ptr_iterator findPtrBottomUpState(const Value *Arg) {
668 return PerPtrBottomUp.find(Arg);
671 void clearBottomUpPointers() {
672 PerPtrBottomUp.clear();
675 void clearTopDownPointers() {
676 PerPtrTopDown.clear();
679 void InitFromPred(const BBState &Other);
680 void InitFromSucc(const BBState &Other);
681 void MergePred(const BBState &Other);
682 void MergeSucc(const BBState &Other);
684 /// Compute the number of possible unique paths from an entry to an exit
685 /// which pass through this block. This is only valid after both the
686 /// top-down and bottom-up traversals are complete.
688 /// Returns true if overflow occured. Returns false if overflow did not
690 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
691 assert(TopDownPathCount != 0);
692 assert(BottomUpPathCount != 0);
693 unsigned long long Product =
694 (unsigned long long)TopDownPathCount*BottomUpPathCount;
696 // Overflow occured if any of the upper bits of Product are set.
697 return Product >> 32;
700 // Specialized CFG utilities.
701 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
702 edge_iterator pred_begin() { return Preds.begin(); }
703 edge_iterator pred_end() { return Preds.end(); }
704 edge_iterator succ_begin() { return Succs.begin(); }
705 edge_iterator succ_end() { return Succs.end(); }
707 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
708 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
710 bool isExit() const { return Succs.empty(); }
714 void BBState::InitFromPred(const BBState &Other) {
715 PerPtrTopDown = Other.PerPtrTopDown;
716 TopDownPathCount = Other.TopDownPathCount;
719 void BBState::InitFromSucc(const BBState &Other) {
720 PerPtrBottomUp = Other.PerPtrBottomUp;
721 BottomUpPathCount = Other.BottomUpPathCount;
724 /// The top-down traversal uses this to merge information about predecessors to
725 /// form the initial state for a new block.
726 void BBState::MergePred(const BBState &Other) {
727 // Other.TopDownPathCount can be 0, in which case it is either dead or a
728 // loop backedge. Loop backedges are special.
729 TopDownPathCount += Other.TopDownPathCount;
731 // Check for overflow. If we have overflow, fall back to conservative
733 if (TopDownPathCount < Other.TopDownPathCount) {
734 clearTopDownPointers();
738 // For each entry in the other set, if our set has an entry with the same key,
739 // merge the entries. Otherwise, copy the entry and merge it with an empty
741 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
742 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
743 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
744 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
748 // For each entry in our set, if the other set doesn't have an entry with the
749 // same key, force it to merge with an empty entry.
750 for (ptr_iterator MI = top_down_ptr_begin(),
751 ME = top_down_ptr_end(); MI != ME; ++MI)
752 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
753 MI->second.Merge(PtrState(), /*TopDown=*/true);
756 /// The bottom-up traversal uses this to merge information about successors to
757 /// form the initial state for a new block.
758 void BBState::MergeSucc(const BBState &Other) {
759 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
760 // loop backedge. Loop backedges are special.
761 BottomUpPathCount += Other.BottomUpPathCount;
763 // Check for overflow. If we have overflow, fall back to conservative
765 if (BottomUpPathCount < Other.BottomUpPathCount) {
766 clearBottomUpPointers();
770 // For each entry in the other set, if our set has an entry with the
771 // same key, merge the entries. Otherwise, copy the entry and merge
772 // it with an empty entry.
773 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
774 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
775 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
776 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
780 // For each entry in our set, if the other set doesn't have an entry
781 // with the same key, force it to merge with an empty entry.
782 for (ptr_iterator MI = bottom_up_ptr_begin(),
783 ME = bottom_up_ptr_end(); MI != ME; ++MI)
784 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
785 MI->second.Merge(PtrState(), /*TopDown=*/false);
788 // Only enable ARC Annotations if we are building a debug version of
791 #define ARC_ANNOTATIONS
794 // Define some macros along the lines of DEBUG and some helper functions to make
795 // it cleaner to create annotations in the source code and to no-op when not
796 // building in debug mode.
797 #ifdef ARC_ANNOTATIONS
799 #include "llvm/Support/CommandLine.h"
801 /// Enable/disable ARC sequence annotations.
803 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
804 cl::desc("Enable emission of arc data flow analysis "
807 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
808 cl::desc("Disable check for cfg hazards when "
810 static cl::opt<std::string>
811 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
813 cl::desc("filter out all data flow annotations "
814 "but those that apply to the given "
815 "target llvm identifier."));
817 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
818 /// instruction so that we can track backwards when post processing via the llvm
819 /// arc annotation processor tool. If the function is an
820 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
824 // If pointer is a result of an instruction and it does not have a source
825 // MDNode it, attach a new MDNode onto it. If pointer is a result of
826 // an instruction and does have a source MDNode attached to it, return a
827 // reference to said Node. Otherwise just return 0.
828 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
830 if (!(Node = Inst->getMetadata(NodeId))) {
831 // We do not have any node. Generate and attatch the hash MDString to the
834 // We just use an MDString to ensure that this metadata gets written out
835 // of line at the module level and to provide a very simple format
836 // encoding the information herein. Both of these makes it simpler to
837 // parse the annotations by a simple external program.
839 raw_string_ostream os(Str);
840 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
841 << Inst->getName() << ")";
843 Hash = MDString::get(Inst->getContext(), os.str());
844 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
846 // We have a node. Grab its hash and return it.
847 assert(Node->getNumOperands() == 1 &&
848 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
849 Hash = cast<MDString>(Node->getOperand(0));
851 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
853 raw_string_ostream os(str);
854 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
856 Hash = MDString::get(Arg->getContext(), os.str());
862 static std::string SequenceToString(Sequence A) {
864 raw_string_ostream os(str);
869 /// Helper function to change a Sequence into a String object using our overload
870 /// for raw_ostream so we only have printing code in one location.
871 static MDString *SequenceToMDString(LLVMContext &Context,
873 return MDString::get(Context, SequenceToString(A));
876 /// A simple function to generate a MDNode which describes the change in state
877 /// for Value *Ptr caused by Instruction *Inst.
878 static void AppendMDNodeToInstForPtr(unsigned NodeId,
881 MDString *PtrSourceMDNodeID,
885 Value *tmp[3] = {PtrSourceMDNodeID,
886 SequenceToMDString(Inst->getContext(),
888 SequenceToMDString(Inst->getContext(),
890 Node = MDNode::get(Inst->getContext(),
891 ArrayRef<Value*>(tmp, 3));
893 Inst->setMetadata(NodeId, Node);
896 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
897 /// state of a pointer at the entrance to a basic block.
898 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
899 Value *Ptr, Sequence Seq) {
900 // If we have a target identifier, make sure that we match it before
902 if(!ARCAnnotationTargetIdentifier.empty() &&
903 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
906 Module *M = BB->getParent()->getParent();
907 LLVMContext &C = M->getContext();
908 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
909 Type *I8XX = PointerType::getUnqual(I8X);
910 Type *Params[] = {I8XX, I8XX};
911 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
912 ArrayRef<Type*>(Params, 2),
914 Constant *Callee = M->getOrInsertFunction(Name, FTy);
916 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
919 StringRef Tmp = Ptr->getName();
920 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
921 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
923 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
924 cast<Constant>(ActualPtrName), Tmp);
928 std::string SeqStr = SequenceToString(Seq);
929 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
930 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
932 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
933 cast<Constant>(ActualPtrName), SeqStr);
936 Builder.CreateCall2(Callee, PtrName, S);
939 /// Add to the end of the basic block llvm.ptr.annotations which show the state
940 /// of the pointer at the bottom of the basic block.
941 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
942 Value *Ptr, Sequence Seq) {
943 // If we have a target identifier, make sure that we match it before emitting
945 if(!ARCAnnotationTargetIdentifier.empty() &&
946 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
949 Module *M = BB->getParent()->getParent();
950 LLVMContext &C = M->getContext();
951 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
952 Type *I8XX = PointerType::getUnqual(I8X);
953 Type *Params[] = {I8XX, I8XX};
954 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
955 ArrayRef<Type*>(Params, 2),
957 Constant *Callee = M->getOrInsertFunction(Name, FTy);
959 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
962 StringRef Tmp = Ptr->getName();
963 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
964 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
966 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
967 cast<Constant>(ActualPtrName), Tmp);
971 std::string SeqStr = SequenceToString(Seq);
972 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
973 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
975 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
976 cast<Constant>(ActualPtrName), SeqStr);
978 Builder.CreateCall2(Callee, PtrName, S);
981 /// Adds a source annotation to pointer and a state change annotation to Inst
982 /// referencing the source annotation and the old/new state of pointer.
983 static void GenerateARCAnnotation(unsigned InstMDId,
989 if (EnableARCAnnotations) {
990 // If we have a target identifier, make sure that we match it before
991 // emitting an annotation.
992 if(!ARCAnnotationTargetIdentifier.empty() &&
993 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
996 // First generate the source annotation on our pointer. This will return an
997 // MDString* if Ptr actually comes from an instruction implying we can put
998 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
999 // then we know that our pointer is from an Argument so we put a reference
1000 // to the argument number.
1002 // The point of this is to make it easy for the
1003 // llvm-arc-annotation-processor tool to cross reference where the source
1004 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1005 // information via debug info for backends to use (since why would anyone
1006 // need such a thing from LLVM IR besides in non standard cases
1008 MDString *SourcePtrMDNode =
1009 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1010 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1015 // The actual interface for accessing the above functionality is defined via
1016 // some simple macros which are defined below. We do this so that the user does
1017 // not need to pass in what metadata id is needed resulting in cleaner code and
1018 // additionally since it provides an easy way to conditionally no-op all
1019 // annotation support in a non-debug build.
1021 /// Use this macro to annotate a sequence state change when processing
1022 /// instructions bottom up,
1023 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1024 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1025 ARCAnnotationProvenanceSourceMDKind, (inst), \
1026 const_cast<Value*>(ptr), (old), (new))
1027 /// Use this macro to annotate a sequence state change when processing
1028 /// instructions top down.
1029 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1030 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1031 ARCAnnotationProvenanceSourceMDKind, (inst), \
1032 const_cast<Value*>(ptr), (old), (new))
1034 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1036 if (EnableARCAnnotations) { \
1037 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1038 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1039 Value *Ptr = const_cast<Value*>(I->first); \
1040 Sequence Seq = I->second.GetSeq(); \
1041 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1046 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1047 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1048 Entrance, bottom_up)
1049 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1050 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1051 Terminator, bottom_up)
1052 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1053 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1055 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1056 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1057 Terminator, top_down)
1059 #else // !ARC_ANNOTATION
1060 // If annotations are off, noop.
1061 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1062 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1063 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1064 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1065 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1066 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1067 #endif // !ARC_ANNOTATION
1070 /// \brief The main ARC optimization pass.
1071 class ObjCARCOpt : public FunctionPass {
1073 ProvenanceAnalysis PA;
1075 // This is used to track if a pointer is stored into an alloca.
1076 DenseSet<const Value *> MultiOwnersSet;
1078 /// A flag indicating whether this optimization pass should run.
1081 /// Declarations for ObjC runtime functions, for use in creating calls to
1082 /// them. These are initialized lazily to avoid cluttering up the Module
1083 /// with unused declarations.
1085 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1086 Constant *AutoreleaseRVCallee;
1087 /// Declaration for ObjC runtime function objc_release.
1088 Constant *ReleaseCallee;
1089 /// Declaration for ObjC runtime function objc_retain.
1090 Constant *RetainCallee;
1091 /// Declaration for ObjC runtime function objc_retainBlock.
1092 Constant *RetainBlockCallee;
1093 /// Declaration for ObjC runtime function objc_autorelease.
1094 Constant *AutoreleaseCallee;
1096 /// Flags which determine whether each of the interesting runtine functions
1097 /// is in fact used in the current function.
1098 unsigned UsedInThisFunction;
1100 /// The Metadata Kind for clang.imprecise_release metadata.
1101 unsigned ImpreciseReleaseMDKind;
1103 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1104 unsigned CopyOnEscapeMDKind;
1106 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1107 unsigned NoObjCARCExceptionsMDKind;
1109 #ifdef ARC_ANNOTATIONS
1110 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1111 unsigned ARCAnnotationBottomUpMDKind;
1112 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1113 unsigned ARCAnnotationTopDownMDKind;
1114 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1115 unsigned ARCAnnotationProvenanceSourceMDKind;
1116 #endif // ARC_ANNOATIONS
1118 Constant *getAutoreleaseRVCallee(Module *M);
1119 Constant *getReleaseCallee(Module *M);
1120 Constant *getRetainCallee(Module *M);
1121 Constant *getRetainBlockCallee(Module *M);
1122 Constant *getAutoreleaseCallee(Module *M);
1124 bool IsRetainBlockOptimizable(const Instruction *Inst);
1126 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1127 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1128 InstructionClass &Class);
1129 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1130 InstructionClass &Class);
1131 void OptimizeIndividualCalls(Function &F);
1133 void CheckForCFGHazards(const BasicBlock *BB,
1134 DenseMap<const BasicBlock *, BBState> &BBStates,
1135 BBState &MyStates) const;
1136 bool VisitInstructionBottomUp(Instruction *Inst,
1138 MapVector<Value *, RRInfo> &Retains,
1140 bool VisitBottomUp(BasicBlock *BB,
1141 DenseMap<const BasicBlock *, BBState> &BBStates,
1142 MapVector<Value *, RRInfo> &Retains);
1143 bool VisitInstructionTopDown(Instruction *Inst,
1144 DenseMap<Value *, RRInfo> &Releases,
1146 bool VisitTopDown(BasicBlock *BB,
1147 DenseMap<const BasicBlock *, BBState> &BBStates,
1148 DenseMap<Value *, RRInfo> &Releases);
1149 bool Visit(Function &F,
1150 DenseMap<const BasicBlock *, BBState> &BBStates,
1151 MapVector<Value *, RRInfo> &Retains,
1152 DenseMap<Value *, RRInfo> &Releases);
1154 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1155 MapVector<Value *, RRInfo> &Retains,
1156 DenseMap<Value *, RRInfo> &Releases,
1157 SmallVectorImpl<Instruction *> &DeadInsts,
1160 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1161 MapVector<Value *, RRInfo> &Retains,
1162 DenseMap<Value *, RRInfo> &Releases,
1164 SmallVector<Instruction *, 4> &NewRetains,
1165 SmallVector<Instruction *, 4> &NewReleases,
1166 SmallVector<Instruction *, 8> &DeadInsts,
1167 RRInfo &RetainsToMove,
1168 RRInfo &ReleasesToMove,
1171 bool &AnyPairsCompletelyEliminated);
1173 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1174 MapVector<Value *, RRInfo> &Retains,
1175 DenseMap<Value *, RRInfo> &Releases,
1178 void OptimizeWeakCalls(Function &F);
1180 bool OptimizeSequences(Function &F);
1182 void OptimizeReturns(Function &F);
1185 void GatherStatistics(Function &F, bool AfterOptimization = false);
1188 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1189 virtual bool doInitialization(Module &M);
1190 virtual bool runOnFunction(Function &F);
1191 virtual void releaseMemory();
1195 ObjCARCOpt() : FunctionPass(ID) {
1196 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1201 char ObjCARCOpt::ID = 0;
1202 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1203 "objc-arc", "ObjC ARC optimization", false, false)
1204 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1205 INITIALIZE_PASS_END(ObjCARCOpt,
1206 "objc-arc", "ObjC ARC optimization", false, false)
1208 Pass *llvm::createObjCARCOptPass() {
1209 return new ObjCARCOpt();
1212 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1213 AU.addRequired<ObjCARCAliasAnalysis>();
1214 AU.addRequired<AliasAnalysis>();
1215 // ARC optimization doesn't currently split critical edges.
1216 AU.setPreservesCFG();
1219 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1220 // Without the magic metadata tag, we have to assume this might be an
1221 // objc_retainBlock call inserted to convert a block pointer to an id,
1222 // in which case it really is needed.
1223 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1226 // If the pointer "escapes" (not including being used in a call),
1227 // the copy may be needed.
1228 if (DoesRetainableObjPtrEscape(Inst))
1231 // Otherwise, it's not needed.
1235 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1236 if (!AutoreleaseRVCallee) {
1237 LLVMContext &C = M->getContext();
1238 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1239 Type *Params[] = { I8X };
1240 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1241 AttributeSet Attribute =
1242 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1243 Attribute::NoUnwind);
1244 AutoreleaseRVCallee =
1245 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1248 return AutoreleaseRVCallee;
1251 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1252 if (!ReleaseCallee) {
1253 LLVMContext &C = M->getContext();
1254 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1255 AttributeSet Attribute =
1256 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1257 Attribute::NoUnwind);
1259 M->getOrInsertFunction(
1261 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1264 return ReleaseCallee;
1267 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1268 if (!RetainCallee) {
1269 LLVMContext &C = M->getContext();
1270 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1271 AttributeSet Attribute =
1272 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1273 Attribute::NoUnwind);
1275 M->getOrInsertFunction(
1277 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1280 return RetainCallee;
1283 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1284 if (!RetainBlockCallee) {
1285 LLVMContext &C = M->getContext();
1286 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1287 // objc_retainBlock is not nounwind because it calls user copy constructors
1288 // which could theoretically throw.
1290 M->getOrInsertFunction(
1292 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1295 return RetainBlockCallee;
1298 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1299 if (!AutoreleaseCallee) {
1300 LLVMContext &C = M->getContext();
1301 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1302 AttributeSet Attribute =
1303 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1304 Attribute::NoUnwind);
1306 M->getOrInsertFunction(
1308 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1311 return AutoreleaseCallee;
1314 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1315 /// not a return value. Or, if it can be paired with an
1316 /// objc_autoreleaseReturnValue, delete the pair and return true.
1318 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1319 // Check for the argument being from an immediately preceding call or invoke.
1320 const Value *Arg = GetObjCArg(RetainRV);
1321 ImmutableCallSite CS(Arg);
1322 if (const Instruction *Call = CS.getInstruction()) {
1323 if (Call->getParent() == RetainRV->getParent()) {
1324 BasicBlock::const_iterator I = Call;
1326 while (IsNoopInstruction(I)) ++I;
1327 if (&*I == RetainRV)
1329 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1330 BasicBlock *RetainRVParent = RetainRV->getParent();
1331 if (II->getNormalDest() == RetainRVParent) {
1332 BasicBlock::const_iterator I = RetainRVParent->begin();
1333 while (IsNoopInstruction(I)) ++I;
1334 if (&*I == RetainRV)
1340 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1341 // pointer. In this case, we can delete the pair.
1342 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1344 do --I; while (I != Begin && IsNoopInstruction(I));
1345 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1346 GetObjCArg(I) == Arg) {
1350 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1351 << "Erasing " << *RetainRV << "\n");
1353 EraseInstruction(I);
1354 EraseInstruction(RetainRV);
1359 // Turn it to a plain objc_retain.
1363 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1364 "objc_retain since the operand is not a return value.\n"
1365 "Old = " << *RetainRV << "\n");
1367 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1369 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1374 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1375 /// used as a return value.
1377 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1378 InstructionClass &Class) {
1379 // Check for a return of the pointer value.
1380 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1381 SmallVector<const Value *, 2> Users;
1382 Users.push_back(Ptr);
1384 Ptr = Users.pop_back_val();
1385 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1387 const User *I = *UI;
1388 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1390 if (isa<BitCastInst>(I))
1393 } while (!Users.empty());
1398 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1399 "objc_autorelease since its operand is not used as a return "
1401 "Old = " << *AutoreleaseRV << "\n");
1403 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1405 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1406 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1407 Class = IC_Autorelease;
1409 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1413 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1416 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1417 // does not escape (following the rules of block escaping), strength reduce the
1418 // objc_retainBlock to an objc_retain.
1420 // TODO: If an objc_retainBlock call is dominated period by a previous
1421 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1424 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1425 InstructionClass &Class) {
1426 assert(GetBasicInstructionClass(Inst) == Class);
1427 assert(IC_RetainBlock == Class);
1429 // If we can not optimize Inst, return false.
1430 if (!IsRetainBlockOptimizable(Inst))
1436 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1437 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1438 CallInst *RetainBlock = cast<CallInst>(Inst);
1439 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1440 // Remove copy_on_escape metadata.
1441 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1443 DEBUG(dbgs() << "New: " << *Inst << "\n");
1447 /// Visit each call, one at a time, and make simplifications without doing any
1448 /// additional analysis.
1449 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1450 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1451 // Reset all the flags in preparation for recomputing them.
1452 UsedInThisFunction = 0;
1454 // Visit all objc_* calls in F.
1455 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1456 Instruction *Inst = &*I++;
1458 InstructionClass Class = GetBasicInstructionClass(Inst);
1460 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1465 // Delete no-op casts. These function calls have special semantics, but
1466 // the semantics are entirely implemented via lowering in the front-end,
1467 // so by the time they reach the optimizer, they are just no-op calls
1468 // which return their argument.
1470 // There are gray areas here, as the ability to cast reference-counted
1471 // pointers to raw void* and back allows code to break ARC assumptions,
1472 // however these are currently considered to be unimportant.
1476 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1477 EraseInstruction(Inst);
1480 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1483 case IC_LoadWeakRetained:
1485 case IC_DestroyWeak: {
1486 CallInst *CI = cast<CallInst>(Inst);
1487 if (IsNullOrUndef(CI->getArgOperand(0))) {
1489 Type *Ty = CI->getArgOperand(0)->getType();
1490 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1491 Constant::getNullValue(Ty),
1493 llvm::Value *NewValue = UndefValue::get(CI->getType());
1494 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1495 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1496 CI->replaceAllUsesWith(NewValue);
1497 CI->eraseFromParent();
1504 CallInst *CI = cast<CallInst>(Inst);
1505 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1506 IsNullOrUndef(CI->getArgOperand(1))) {
1508 Type *Ty = CI->getArgOperand(0)->getType();
1509 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1510 Constant::getNullValue(Ty),
1513 llvm::Value *NewValue = UndefValue::get(CI->getType());
1514 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1515 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1517 CI->replaceAllUsesWith(NewValue);
1518 CI->eraseFromParent();
1523 case IC_RetainBlock:
1524 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1525 // onto the objc_retain peephole optimizations. Otherwise break.
1526 OptimizeRetainBlockCall(F, Inst, Class);
1529 if (OptimizeRetainRVCall(F, Inst))
1532 case IC_AutoreleaseRV:
1533 OptimizeAutoreleaseRVCall(F, Inst, Class);
1537 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1538 if (IsAutorelease(Class) && Inst->use_empty()) {
1539 CallInst *Call = cast<CallInst>(Inst);
1540 const Value *Arg = Call->getArgOperand(0);
1541 Arg = FindSingleUseIdentifiedObject(Arg);
1546 // Create the declaration lazily.
1547 LLVMContext &C = Inst->getContext();
1549 CallInst::Create(getReleaseCallee(F.getParent()),
1550 Call->getArgOperand(0), "", Call);
1551 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1553 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1554 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1555 << *NewCall << "\n");
1557 EraseInstruction(Call);
1563 // For functions which can never be passed stack arguments, add
1565 if (IsAlwaysTail(Class)) {
1567 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1568 "passed stack args: " << *Inst << "\n");
1569 cast<CallInst>(Inst)->setTailCall();
1572 // Ensure that functions that can never have a "tail" keyword due to the
1573 // semantics of ARC truly do not do so.
1574 if (IsNeverTail(Class)) {
1576 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1578 cast<CallInst>(Inst)->setTailCall(false);
1581 // Set nounwind as needed.
1582 if (IsNoThrow(Class)) {
1584 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1586 cast<CallInst>(Inst)->setDoesNotThrow();
1589 if (!IsNoopOnNull(Class)) {
1590 UsedInThisFunction |= 1 << Class;
1594 const Value *Arg = GetObjCArg(Inst);
1596 // ARC calls with null are no-ops. Delete them.
1597 if (IsNullOrUndef(Arg)) {
1600 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1602 EraseInstruction(Inst);
1606 // Keep track of which of retain, release, autorelease, and retain_block
1607 // are actually present in this function.
1608 UsedInThisFunction |= 1 << Class;
1610 // If Arg is a PHI, and one or more incoming values to the
1611 // PHI are null, and the call is control-equivalent to the PHI, and there
1612 // are no relevant side effects between the PHI and the call, the call
1613 // could be pushed up to just those paths with non-null incoming values.
1614 // For now, don't bother splitting critical edges for this.
1615 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1616 Worklist.push_back(std::make_pair(Inst, Arg));
1618 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1622 const PHINode *PN = dyn_cast<PHINode>(Arg);
1625 // Determine if the PHI has any null operands, or any incoming
1627 bool HasNull = false;
1628 bool HasCriticalEdges = false;
1629 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1631 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1632 if (IsNullOrUndef(Incoming))
1634 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1635 .getNumSuccessors() != 1) {
1636 HasCriticalEdges = true;
1640 // If we have null operands and no critical edges, optimize.
1641 if (!HasCriticalEdges && HasNull) {
1642 SmallPtrSet<Instruction *, 4> DependingInstructions;
1643 SmallPtrSet<const BasicBlock *, 4> Visited;
1645 // Check that there is nothing that cares about the reference
1646 // count between the call and the phi.
1649 case IC_RetainBlock:
1650 // These can always be moved up.
1653 // These can't be moved across things that care about the retain
1655 FindDependencies(NeedsPositiveRetainCount, Arg,
1656 Inst->getParent(), Inst,
1657 DependingInstructions, Visited, PA);
1659 case IC_Autorelease:
1660 // These can't be moved across autorelease pool scope boundaries.
1661 FindDependencies(AutoreleasePoolBoundary, Arg,
1662 Inst->getParent(), Inst,
1663 DependingInstructions, Visited, PA);
1666 case IC_AutoreleaseRV:
1667 // Don't move these; the RV optimization depends on the autoreleaseRV
1668 // being tail called, and the retainRV being immediately after a call
1669 // (which might still happen if we get lucky with codegen layout, but
1670 // it's not worth taking the chance).
1673 llvm_unreachable("Invalid dependence flavor");
1676 if (DependingInstructions.size() == 1 &&
1677 *DependingInstructions.begin() == PN) {
1680 // Clone the call into each predecessor that has a non-null value.
1681 CallInst *CInst = cast<CallInst>(Inst);
1682 Type *ParamTy = CInst->getArgOperand(0)->getType();
1683 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1685 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1686 if (!IsNullOrUndef(Incoming)) {
1687 CallInst *Clone = cast<CallInst>(CInst->clone());
1688 Value *Op = PN->getIncomingValue(i);
1689 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1690 if (Op->getType() != ParamTy)
1691 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1692 Clone->setArgOperand(0, Op);
1693 Clone->insertBefore(InsertPos);
1695 DEBUG(dbgs() << "Cloning "
1697 "And inserting clone at " << *InsertPos << "\n");
1698 Worklist.push_back(std::make_pair(Clone, Incoming));
1701 // Erase the original call.
1702 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1703 EraseInstruction(CInst);
1707 } while (!Worklist.empty());
1711 /// If we have a top down pointer in the S_Use state, make sure that there are
1712 /// no CFG hazards by checking the states of various bottom up pointers.
1713 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1714 const bool SuccSRRIKnownSafe,
1716 bool &SomeSuccHasSame,
1717 bool &AllSuccsHaveSame,
1718 bool &NotAllSeqEqualButKnownSafe,
1719 bool &ShouldContinue) {
1721 case S_CanRelease: {
1722 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1723 S.ClearSequenceProgress();
1726 S.RRI.CFGHazardAfflicted = true;
1727 ShouldContinue = true;
1731 SomeSuccHasSame = true;
1735 case S_MovableRelease:
1736 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1737 AllSuccsHaveSame = false;
1739 NotAllSeqEqualButKnownSafe = true;
1742 llvm_unreachable("bottom-up pointer in retain state!");
1744 llvm_unreachable("This should have been handled earlier.");
1748 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1749 /// there are no CFG hazards by checking the states of various bottom up
1751 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1752 const bool SuccSRRIKnownSafe,
1754 bool &SomeSuccHasSame,
1755 bool &AllSuccsHaveSame,
1756 bool &NotAllSeqEqualButKnownSafe) {
1759 SomeSuccHasSame = true;
1763 case S_MovableRelease:
1765 if (!S.RRI.KnownSafe && !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 /// Check for critical edges, loop boundaries, irreducible control flow, or
1778 /// other CFG structures where moving code across the edge would result in it
1779 /// being executed more.
1781 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1782 DenseMap<const BasicBlock *, BBState> &BBStates,
1783 BBState &MyStates) const {
1784 // If any top-down local-use or possible-dec has a succ which is earlier in
1785 // the sequence, forget it.
1786 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1787 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1788 PtrState &S = I->second;
1789 const Sequence Seq = I->second.GetSeq();
1791 // We only care about S_Retain, S_CanRelease, and S_Use.
1795 // Make sure that if extra top down states are added in the future that this
1796 // code is updated to handle it.
1797 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1798 "Unknown top down sequence state.");
1800 const Value *Arg = I->first;
1801 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1802 bool SomeSuccHasSame = false;
1803 bool AllSuccsHaveSame = true;
1804 bool NotAllSeqEqualButKnownSafe = false;
1806 succ_const_iterator SI(TI), SE(TI, false);
1808 for (; SI != SE; ++SI) {
1809 // If VisitBottomUp has pointer information for this successor, take
1810 // what we know about it.
1811 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1813 assert(BBI != BBStates.end());
1814 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1815 const Sequence SuccSSeq = SuccS.GetSeq();
1817 // If bottom up, the pointer is in an S_None state, clear the sequence
1818 // progress since the sequence in the bottom up state finished
1819 // suggesting a mismatch in between retains/releases. This is true for
1820 // all three cases that we are handling here: S_Retain, S_Use, and
1822 if (SuccSSeq == S_None) {
1823 S.ClearSequenceProgress();
1827 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1829 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1831 // *NOTE* We do not use Seq from above here since we are allowing for
1832 // S.GetSeq() to change while we are visiting basic blocks.
1833 switch(S.GetSeq()) {
1835 bool ShouldContinue = false;
1836 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1837 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1843 case S_CanRelease: {
1844 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1845 SomeSuccHasSame, AllSuccsHaveSame,
1846 NotAllSeqEqualButKnownSafe);
1853 case S_MovableRelease:
1858 // If the state at the other end of any of the successor edges
1859 // matches the current state, require all edges to match. This
1860 // guards against loops in the middle of a sequence.
1861 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1862 S.ClearSequenceProgress();
1863 } else if (NotAllSeqEqualButKnownSafe) {
1864 // If we would have cleared the state foregoing the fact that we are known
1865 // safe, stop code motion. This is because whether or not it is safe to
1866 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1867 // are allowed to perform code motion.
1868 S.RRI.CFGHazardAfflicted = true;
1874 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1876 MapVector<Value *, RRInfo> &Retains,
1877 BBState &MyStates) {
1878 bool NestingDetected = false;
1879 InstructionClass Class = GetInstructionClass(Inst);
1880 const Value *Arg = 0;
1882 DEBUG(dbgs() << "Class: " << Class << "\n");
1886 Arg = GetObjCArg(Inst);
1888 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1890 // If we see two releases in a row on the same pointer. If so, make
1891 // a note, and we'll cicle back to revisit it after we've
1892 // hopefully eliminated the second release, which may allow us to
1893 // eliminate the first release too.
1894 // Theoretically we could implement removal of nested retain+release
1895 // pairs by making PtrState hold a stack of states, but this is
1896 // simple and avoids adding overhead for the non-nested case.
1897 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1898 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1899 NestingDetected = true;
1902 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1903 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1904 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1905 S.ResetSequenceProgress(NewSeq);
1906 S.RRI.ReleaseMetadata = ReleaseMetadata;
1907 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1908 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1909 S.RRI.Calls.insert(Inst);
1910 S.SetKnownPositiveRefCount();
1913 case IC_RetainBlock:
1914 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1915 // objc_retainBlocks to objc_retains. Thus at this point any
1916 // objc_retainBlocks that we see are not optimizable.
1920 Arg = GetObjCArg(Inst);
1922 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1923 S.SetKnownPositiveRefCount();
1925 Sequence OldSeq = S.GetSeq();
1929 case S_MovableRelease:
1931 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1932 // imprecise release, clear our reverse insertion points.
1933 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1934 S.RRI.ReverseInsertPts.clear();
1937 // Don't do retain+release tracking for IC_RetainRV, because it's
1938 // better to let it remain as the first instruction after a call.
1939 if (Class != IC_RetainRV)
1940 Retains[Inst] = S.RRI;
1941 S.ClearSequenceProgress();
1946 llvm_unreachable("bottom-up pointer in retain state!");
1948 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1949 // A retain moving bottom up can be a use.
1952 case IC_AutoreleasepoolPop:
1953 // Conservatively, clear MyStates for all known pointers.
1954 MyStates.clearBottomUpPointers();
1955 return NestingDetected;
1956 case IC_AutoreleasepoolPush:
1958 // These are irrelevant.
1959 return NestingDetected;
1961 // If we have a store into an alloca of a pointer we are tracking, the
1962 // pointer has multiple owners implying that we must be more conservative.
1964 // This comes up in the context of a pointer being ``KnownSafe''. In the
1965 // presense of a block being initialized, the frontend will emit the
1966 // objc_retain on the original pointer and the release on the pointer loaded
1967 // from the alloca. The optimizer will through the provenance analysis
1968 // realize that the two are related, but since we only require KnownSafe in
1969 // one direction, will match the inner retain on the original pointer with
1970 // the guard release on the original pointer. This is fixed by ensuring that
1971 // in the presense of allocas we only unconditionally remove pointers if
1972 // both our retain and our release are KnownSafe.
1973 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1974 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1975 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1976 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1977 if (I != MyStates.bottom_up_ptr_end())
1978 MultiOwnersSet.insert(I->first);
1986 // Consider any other possible effects of this instruction on each
1987 // pointer being tracked.
1988 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1989 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1990 const Value *Ptr = MI->first;
1992 continue; // Handled above.
1993 PtrState &S = MI->second;
1994 Sequence Seq = S.GetSeq();
1996 // Check for possible releases.
1997 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1998 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2000 S.ClearKnownPositiveRefCount();
2003 S.SetSeq(S_CanRelease);
2004 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
2008 case S_MovableRelease:
2013 llvm_unreachable("bottom-up pointer in retain state!");
2017 // Check for possible direct uses.
2020 case S_MovableRelease:
2021 if (CanUse(Inst, Ptr, PA, Class)) {
2022 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2024 assert(S.RRI.ReverseInsertPts.empty());
2025 // If this is an invoke instruction, we're scanning it as part of
2026 // one of its successor blocks, since we can't insert code after it
2027 // in its own block, and we don't want to split critical edges.
2028 if (isa<InvokeInst>(Inst))
2029 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2031 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2033 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2034 } else if (Seq == S_Release && IsUser(Class)) {
2035 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2037 // Non-movable releases depend on any possible objc pointer use.
2039 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2040 assert(S.RRI.ReverseInsertPts.empty());
2041 // As above; handle invoke specially.
2042 if (isa<InvokeInst>(Inst))
2043 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2045 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2049 if (CanUse(Inst, Ptr, PA, Class)) {
2050 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2053 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2061 llvm_unreachable("bottom-up pointer in retain state!");
2065 return NestingDetected;
2069 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2070 DenseMap<const BasicBlock *, BBState> &BBStates,
2071 MapVector<Value *, RRInfo> &Retains) {
2073 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2075 bool NestingDetected = false;
2076 BBState &MyStates = BBStates[BB];
2078 // Merge the states from each successor to compute the initial state
2079 // for the current block.
2080 BBState::edge_iterator SI(MyStates.succ_begin()),
2081 SE(MyStates.succ_end());
2083 const BasicBlock *Succ = *SI;
2084 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2085 assert(I != BBStates.end());
2086 MyStates.InitFromSucc(I->second);
2088 for (; SI != SE; ++SI) {
2090 I = BBStates.find(Succ);
2091 assert(I != BBStates.end());
2092 MyStates.MergeSucc(I->second);
2096 // If ARC Annotations are enabled, output the current state of pointers at the
2097 // bottom of the basic block.
2098 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2100 // Visit all the instructions, bottom-up.
2101 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2102 Instruction *Inst = llvm::prior(I);
2104 // Invoke instructions are visited as part of their successors (below).
2105 if (isa<InvokeInst>(Inst))
2108 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2110 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2113 // If there's a predecessor with an invoke, visit the invoke as if it were
2114 // part of this block, since we can't insert code after an invoke in its own
2115 // block, and we don't want to split critical edges.
2116 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2117 PE(MyStates.pred_end()); PI != PE; ++PI) {
2118 BasicBlock *Pred = *PI;
2119 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2120 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2123 // If ARC Annotations are enabled, output the current state of pointers at the
2124 // top of the basic block.
2125 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2127 return NestingDetected;
2131 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2132 DenseMap<Value *, RRInfo> &Releases,
2133 BBState &MyStates) {
2134 bool NestingDetected = false;
2135 InstructionClass Class = GetInstructionClass(Inst);
2136 const Value *Arg = 0;
2139 case IC_RetainBlock:
2140 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2141 // objc_retainBlocks to objc_retains. Thus at this point any
2142 // objc_retainBlocks that we see are not optimizable.
2146 Arg = GetObjCArg(Inst);
2148 PtrState &S = MyStates.getPtrTopDownState(Arg);
2150 // Don't do retain+release tracking for IC_RetainRV, because it's
2151 // better to let it remain as the first instruction after a call.
2152 if (Class != IC_RetainRV) {
2153 // If we see two retains in a row on the same pointer. If so, make
2154 // a note, and we'll cicle back to revisit it after we've
2155 // hopefully eliminated the second retain, which may allow us to
2156 // eliminate the first retain too.
2157 // Theoretically we could implement removal of nested retain+release
2158 // pairs by making PtrState hold a stack of states, but this is
2159 // simple and avoids adding overhead for the non-nested case.
2160 if (S.GetSeq() == S_Retain)
2161 NestingDetected = true;
2163 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2164 S.ResetSequenceProgress(S_Retain);
2165 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2166 S.RRI.Calls.insert(Inst);
2169 S.SetKnownPositiveRefCount();
2171 // A retain can be a potential use; procede to the generic checking
2176 Arg = GetObjCArg(Inst);
2178 PtrState &S = MyStates.getPtrTopDownState(Arg);
2179 S.ClearKnownPositiveRefCount();
2181 Sequence OldSeq = S.GetSeq();
2183 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2188 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2189 S.RRI.ReverseInsertPts.clear();
2192 S.RRI.ReleaseMetadata = ReleaseMetadata;
2193 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2194 Releases[Inst] = S.RRI;
2195 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2196 S.ClearSequenceProgress();
2202 case S_MovableRelease:
2203 llvm_unreachable("top-down pointer in release state!");
2207 case IC_AutoreleasepoolPop:
2208 // Conservatively, clear MyStates for all known pointers.
2209 MyStates.clearTopDownPointers();
2210 return NestingDetected;
2211 case IC_AutoreleasepoolPush:
2213 // These are irrelevant.
2214 return NestingDetected;
2219 // Consider any other possible effects of this instruction on each
2220 // pointer being tracked.
2221 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2222 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2223 const Value *Ptr = MI->first;
2225 continue; // Handled above.
2226 PtrState &S = MI->second;
2227 Sequence Seq = S.GetSeq();
2229 // Check for possible releases.
2230 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2231 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2233 S.ClearKnownPositiveRefCount();
2236 S.SetSeq(S_CanRelease);
2237 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2238 assert(S.RRI.ReverseInsertPts.empty());
2239 S.RRI.ReverseInsertPts.insert(Inst);
2241 // One call can't cause a transition from S_Retain to S_CanRelease
2242 // and S_CanRelease to S_Use. If we've made the first transition,
2251 case S_MovableRelease:
2252 llvm_unreachable("top-down pointer in release state!");
2256 // Check for possible direct uses.
2259 if (CanUse(Inst, Ptr, PA, Class)) {
2260 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2263 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2272 case S_MovableRelease:
2273 llvm_unreachable("top-down pointer in release state!");
2277 return NestingDetected;
2281 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2282 DenseMap<const BasicBlock *, BBState> &BBStates,
2283 DenseMap<Value *, RRInfo> &Releases) {
2284 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2285 bool NestingDetected = false;
2286 BBState &MyStates = BBStates[BB];
2288 // Merge the states from each predecessor to compute the initial state
2289 // for the current block.
2290 BBState::edge_iterator PI(MyStates.pred_begin()),
2291 PE(MyStates.pred_end());
2293 const BasicBlock *Pred = *PI;
2294 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2295 assert(I != BBStates.end());
2296 MyStates.InitFromPred(I->second);
2298 for (; PI != PE; ++PI) {
2300 I = BBStates.find(Pred);
2301 assert(I != BBStates.end());
2302 MyStates.MergePred(I->second);
2306 // If ARC Annotations are enabled, output the current state of pointers at the
2307 // top of the basic block.
2308 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2310 // Visit all the instructions, top-down.
2311 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2312 Instruction *Inst = I;
2314 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2316 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2319 // If ARC Annotations are enabled, output the current state of pointers at the
2320 // bottom of the basic block.
2321 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2323 #ifdef ARC_ANNOTATIONS
2324 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2326 CheckForCFGHazards(BB, BBStates, MyStates);
2327 return NestingDetected;
2331 ComputePostOrders(Function &F,
2332 SmallVectorImpl<BasicBlock *> &PostOrder,
2333 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2334 unsigned NoObjCARCExceptionsMDKind,
2335 DenseMap<const BasicBlock *, BBState> &BBStates) {
2336 /// The visited set, for doing DFS walks.
2337 SmallPtrSet<BasicBlock *, 16> Visited;
2339 // Do DFS, computing the PostOrder.
2340 SmallPtrSet<BasicBlock *, 16> OnStack;
2341 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2343 // Functions always have exactly one entry block, and we don't have
2344 // any other block that we treat like an entry block.
2345 BasicBlock *EntryBB = &F.getEntryBlock();
2346 BBState &MyStates = BBStates[EntryBB];
2347 MyStates.SetAsEntry();
2348 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2349 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2350 Visited.insert(EntryBB);
2351 OnStack.insert(EntryBB);
2354 BasicBlock *CurrBB = SuccStack.back().first;
2355 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2356 succ_iterator SE(TI, false);
2358 while (SuccStack.back().second != SE) {
2359 BasicBlock *SuccBB = *SuccStack.back().second++;
2360 if (Visited.insert(SuccBB)) {
2361 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2362 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2363 BBStates[CurrBB].addSucc(SuccBB);
2364 BBState &SuccStates = BBStates[SuccBB];
2365 SuccStates.addPred(CurrBB);
2366 OnStack.insert(SuccBB);
2370 if (!OnStack.count(SuccBB)) {
2371 BBStates[CurrBB].addSucc(SuccBB);
2372 BBStates[SuccBB].addPred(CurrBB);
2375 OnStack.erase(CurrBB);
2376 PostOrder.push_back(CurrBB);
2377 SuccStack.pop_back();
2378 } while (!SuccStack.empty());
2382 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2383 // Functions may have many exits, and there also blocks which we treat
2384 // as exits due to ignored edges.
2385 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2386 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2387 BasicBlock *ExitBB = I;
2388 BBState &MyStates = BBStates[ExitBB];
2389 if (!MyStates.isExit())
2392 MyStates.SetAsExit();
2394 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2395 Visited.insert(ExitBB);
2396 while (!PredStack.empty()) {
2397 reverse_dfs_next_succ:
2398 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2399 while (PredStack.back().second != PE) {
2400 BasicBlock *BB = *PredStack.back().second++;
2401 if (Visited.insert(BB)) {
2402 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2403 goto reverse_dfs_next_succ;
2406 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2411 // Visit the function both top-down and bottom-up.
2413 ObjCARCOpt::Visit(Function &F,
2414 DenseMap<const BasicBlock *, BBState> &BBStates,
2415 MapVector<Value *, RRInfo> &Retains,
2416 DenseMap<Value *, RRInfo> &Releases) {
2418 // Use reverse-postorder traversals, because we magically know that loops
2419 // will be well behaved, i.e. they won't repeatedly call retain on a single
2420 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2421 // class here because we want the reverse-CFG postorder to consider each
2422 // function exit point, and we want to ignore selected cycle edges.
2423 SmallVector<BasicBlock *, 16> PostOrder;
2424 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2425 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2426 NoObjCARCExceptionsMDKind,
2429 // Use reverse-postorder on the reverse CFG for bottom-up.
2430 bool BottomUpNestingDetected = false;
2431 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2432 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2434 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2436 // Use reverse-postorder for top-down.
2437 bool TopDownNestingDetected = false;
2438 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2439 PostOrder.rbegin(), E = PostOrder.rend();
2441 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2443 return TopDownNestingDetected && BottomUpNestingDetected;
2446 /// Move the calls in RetainsToMove and ReleasesToMove.
2447 void ObjCARCOpt::MoveCalls(Value *Arg,
2448 RRInfo &RetainsToMove,
2449 RRInfo &ReleasesToMove,
2450 MapVector<Value *, RRInfo> &Retains,
2451 DenseMap<Value *, RRInfo> &Releases,
2452 SmallVectorImpl<Instruction *> &DeadInsts,
2454 Type *ArgTy = Arg->getType();
2455 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2457 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2459 // Insert the new retain and release calls.
2460 for (SmallPtrSet<Instruction *, 2>::const_iterator
2461 PI = ReleasesToMove.ReverseInsertPts.begin(),
2462 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2463 Instruction *InsertPt = *PI;
2464 Value *MyArg = ArgTy == ParamTy ? Arg :
2465 new BitCastInst(Arg, ParamTy, "", InsertPt);
2467 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2468 Call->setDoesNotThrow();
2469 Call->setTailCall();
2471 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2472 "At insertion point: " << *InsertPt << "\n");
2474 for (SmallPtrSet<Instruction *, 2>::const_iterator
2475 PI = RetainsToMove.ReverseInsertPts.begin(),
2476 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2477 Instruction *InsertPt = *PI;
2478 Value *MyArg = ArgTy == ParamTy ? Arg :
2479 new BitCastInst(Arg, ParamTy, "", InsertPt);
2480 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2482 // Attach a clang.imprecise_release metadata tag, if appropriate.
2483 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2484 Call->setMetadata(ImpreciseReleaseMDKind, M);
2485 Call->setDoesNotThrow();
2486 if (ReleasesToMove.IsTailCallRelease)
2487 Call->setTailCall();
2489 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2490 "At insertion point: " << *InsertPt << "\n");
2493 // Delete the original retain and release calls.
2494 for (SmallPtrSet<Instruction *, 2>::const_iterator
2495 AI = RetainsToMove.Calls.begin(),
2496 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2497 Instruction *OrigRetain = *AI;
2498 Retains.blot(OrigRetain);
2499 DeadInsts.push_back(OrigRetain);
2500 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2502 for (SmallPtrSet<Instruction *, 2>::const_iterator
2503 AI = ReleasesToMove.Calls.begin(),
2504 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2505 Instruction *OrigRelease = *AI;
2506 Releases.erase(OrigRelease);
2507 DeadInsts.push_back(OrigRelease);
2508 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2514 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2516 MapVector<Value *, RRInfo> &Retains,
2517 DenseMap<Value *, RRInfo> &Releases,
2519 SmallVector<Instruction *, 4> &NewRetains,
2520 SmallVector<Instruction *, 4> &NewReleases,
2521 SmallVector<Instruction *, 8> &DeadInsts,
2522 RRInfo &RetainsToMove,
2523 RRInfo &ReleasesToMove,
2526 bool &AnyPairsCompletelyEliminated) {
2527 // If a pair happens in a region where it is known that the reference count
2528 // is already incremented, we can similarly ignore possible decrements unless
2529 // we are dealing with a retainable object with multiple provenance sources.
2530 bool KnownSafeTD = true, KnownSafeBU = true;
2531 bool MultipleOwners = false;
2532 bool CFGHazardAfflicted = false;
2534 // Connect the dots between the top-down-collected RetainsToMove and
2535 // bottom-up-collected ReleasesToMove to form sets of related calls.
2536 // This is an iterative process so that we connect multiple releases
2537 // to multiple retains if needed.
2538 unsigned OldDelta = 0;
2539 unsigned NewDelta = 0;
2540 unsigned OldCount = 0;
2541 unsigned NewCount = 0;
2542 bool FirstRelease = true;
2544 for (SmallVectorImpl<Instruction *>::const_iterator
2545 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2546 Instruction *NewRetain = *NI;
2547 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2548 assert(It != Retains.end());
2549 const RRInfo &NewRetainRRI = It->second;
2550 KnownSafeTD &= NewRetainRRI.KnownSafe;
2552 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2553 for (SmallPtrSet<Instruction *, 2>::const_iterator
2554 LI = NewRetainRRI.Calls.begin(),
2555 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2556 Instruction *NewRetainRelease = *LI;
2557 DenseMap<Value *, RRInfo>::const_iterator Jt =
2558 Releases.find(NewRetainRelease);
2559 if (Jt == Releases.end())
2561 const RRInfo &NewRetainReleaseRRI = Jt->second;
2562 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2563 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2565 // If we overflow when we compute the path count, don't remove/move
2567 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2569 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2571 OldDelta -= PathCount;
2573 // Merge the ReleaseMetadata and IsTailCallRelease values.
2575 ReleasesToMove.ReleaseMetadata =
2576 NewRetainReleaseRRI.ReleaseMetadata;
2577 ReleasesToMove.IsTailCallRelease =
2578 NewRetainReleaseRRI.IsTailCallRelease;
2579 FirstRelease = false;
2581 if (ReleasesToMove.ReleaseMetadata !=
2582 NewRetainReleaseRRI.ReleaseMetadata)
2583 ReleasesToMove.ReleaseMetadata = 0;
2584 if (ReleasesToMove.IsTailCallRelease !=
2585 NewRetainReleaseRRI.IsTailCallRelease)
2586 ReleasesToMove.IsTailCallRelease = false;
2589 // Collect the optimal insertion points.
2591 for (SmallPtrSet<Instruction *, 2>::const_iterator
2592 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2593 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2595 Instruction *RIP = *RI;
2596 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2597 // If we overflow when we compute the path count, don't
2598 // remove/move anything.
2599 const BBState &RIPBBState = BBStates[RIP->getParent()];
2600 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2602 NewDelta -= PathCount;
2605 NewReleases.push_back(NewRetainRelease);
2610 if (NewReleases.empty()) break;
2612 // Back the other way.
2613 for (SmallVectorImpl<Instruction *>::const_iterator
2614 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2615 Instruction *NewRelease = *NI;
2616 DenseMap<Value *, RRInfo>::const_iterator It =
2617 Releases.find(NewRelease);
2618 assert(It != Releases.end());
2619 const RRInfo &NewReleaseRRI = It->second;
2620 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2621 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2622 for (SmallPtrSet<Instruction *, 2>::const_iterator
2623 LI = NewReleaseRRI.Calls.begin(),
2624 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2625 Instruction *NewReleaseRetain = *LI;
2626 MapVector<Value *, RRInfo>::const_iterator Jt =
2627 Retains.find(NewReleaseRetain);
2628 if (Jt == Retains.end())
2630 const RRInfo &NewReleaseRetainRRI = Jt->second;
2631 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2632 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2634 // If we overflow when we compute the path count, don't remove/move
2636 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2638 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2640 OldDelta += PathCount;
2641 OldCount += PathCount;
2643 // Collect the optimal insertion points.
2645 for (SmallPtrSet<Instruction *, 2>::const_iterator
2646 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2647 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2649 Instruction *RIP = *RI;
2650 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2651 // If we overflow when we compute the path count, don't
2652 // remove/move anything.
2653 const BBState &RIPBBState = BBStates[RIP->getParent()];
2654 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2656 NewDelta += PathCount;
2657 NewCount += PathCount;
2660 NewRetains.push_back(NewReleaseRetain);
2664 NewReleases.clear();
2665 if (NewRetains.empty()) break;
2668 // If the pointer is known incremented in 1 direction and we do not have
2669 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2670 // to be known safe in both directions.
2671 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2672 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2673 if (UnconditionallySafe) {
2674 RetainsToMove.ReverseInsertPts.clear();
2675 ReleasesToMove.ReverseInsertPts.clear();
2678 // Determine whether the new insertion points we computed preserve the
2679 // balance of retain and release calls through the program.
2680 // TODO: If the fully aggressive solution isn't valid, try to find a
2681 // less aggressive solution which is.
2685 // At this point, we are not going to remove any RR pairs, but we still are
2686 // able to move RR pairs. If one of our pointers is afflicted with
2687 // CFGHazards, we cannot perform such code motion so exit early.
2688 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2689 ReleasesToMove.ReverseInsertPts.size();
2690 if (CFGHazardAfflicted && WillPerformCodeMotion)
2694 // Determine whether the original call points are balanced in the retain and
2695 // release calls through the program. If not, conservatively don't touch
2697 // TODO: It's theoretically possible to do code motion in this case, as
2698 // long as the existing imbalances are maintained.
2702 #ifdef ARC_ANNOTATIONS
2703 // Do not move calls if ARC annotations are requested.
2704 if (EnableARCAnnotations)
2706 #endif // ARC_ANNOTATIONS
2709 assert(OldCount != 0 && "Unreachable code?");
2710 NumRRs += OldCount - NewCount;
2711 // Set to true if we completely removed any RR pairs.
2712 AnyPairsCompletelyEliminated = NewCount == 0;
2714 // We can move calls!
2718 /// Identify pairings between the retains and releases, and delete and/or move
2721 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2723 MapVector<Value *, RRInfo> &Retains,
2724 DenseMap<Value *, RRInfo> &Releases,
2726 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2728 bool AnyPairsCompletelyEliminated = false;
2729 RRInfo RetainsToMove;
2730 RRInfo ReleasesToMove;
2731 SmallVector<Instruction *, 4> NewRetains;
2732 SmallVector<Instruction *, 4> NewReleases;
2733 SmallVector<Instruction *, 8> DeadInsts;
2735 // Visit each retain.
2736 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2737 E = Retains.end(); I != E; ++I) {
2738 Value *V = I->first;
2739 if (!V) continue; // blotted
2741 Instruction *Retain = cast<Instruction>(V);
2743 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2745 Value *Arg = GetObjCArg(Retain);
2747 // If the object being released is in static or stack storage, we know it's
2748 // not being managed by ObjC reference counting, so we can delete pairs
2749 // regardless of what possible decrements or uses lie between them.
2750 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2752 // A constant pointer can't be pointing to an object on the heap. It may
2753 // be reference-counted, but it won't be deleted.
2754 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2755 if (const GlobalVariable *GV =
2756 dyn_cast<GlobalVariable>(
2757 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2758 if (GV->isConstant())
2761 // Connect the dots between the top-down-collected RetainsToMove and
2762 // bottom-up-collected ReleasesToMove to form sets of related calls.
2763 NewRetains.push_back(Retain);
2764 bool PerformMoveCalls =
2765 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2766 NewReleases, DeadInsts, RetainsToMove,
2767 ReleasesToMove, Arg, KnownSafe,
2768 AnyPairsCompletelyEliminated);
2770 if (PerformMoveCalls) {
2771 // Ok, everything checks out and we're all set. Let's move/delete some
2773 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2774 Retains, Releases, DeadInsts, M);
2777 // Clean up state for next retain.
2778 NewReleases.clear();
2780 RetainsToMove.clear();
2781 ReleasesToMove.clear();
2784 // Now that we're done moving everything, we can delete the newly dead
2785 // instructions, as we no longer need them as insert points.
2786 while (!DeadInsts.empty())
2787 EraseInstruction(DeadInsts.pop_back_val());
2789 return AnyPairsCompletelyEliminated;
2792 /// Weak pointer optimizations.
2793 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2794 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2796 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2797 // itself because it uses AliasAnalysis and we need to do provenance
2799 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2800 Instruction *Inst = &*I++;
2802 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2804 InstructionClass Class = GetBasicInstructionClass(Inst);
2805 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2808 // Delete objc_loadWeak calls with no users.
2809 if (Class == IC_LoadWeak && Inst->use_empty()) {
2810 Inst->eraseFromParent();
2814 // TODO: For now, just look for an earlier available version of this value
2815 // within the same block. Theoretically, we could do memdep-style non-local
2816 // analysis too, but that would want caching. A better approach would be to
2817 // use the technique that EarlyCSE uses.
2818 inst_iterator Current = llvm::prior(I);
2819 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2820 for (BasicBlock::iterator B = CurrentBB->begin(),
2821 J = Current.getInstructionIterator();
2823 Instruction *EarlierInst = &*llvm::prior(J);
2824 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2825 switch (EarlierClass) {
2827 case IC_LoadWeakRetained: {
2828 // If this is loading from the same pointer, replace this load's value
2830 CallInst *Call = cast<CallInst>(Inst);
2831 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2832 Value *Arg = Call->getArgOperand(0);
2833 Value *EarlierArg = EarlierCall->getArgOperand(0);
2834 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2835 case AliasAnalysis::MustAlias:
2837 // If the load has a builtin retain, insert a plain retain for it.
2838 if (Class == IC_LoadWeakRetained) {
2840 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2844 // Zap the fully redundant load.
2845 Call->replaceAllUsesWith(EarlierCall);
2846 Call->eraseFromParent();
2848 case AliasAnalysis::MayAlias:
2849 case AliasAnalysis::PartialAlias:
2851 case AliasAnalysis::NoAlias:
2858 // If this is storing to the same pointer and has the same size etc.
2859 // replace this load's value with the stored value.
2860 CallInst *Call = cast<CallInst>(Inst);
2861 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2862 Value *Arg = Call->getArgOperand(0);
2863 Value *EarlierArg = EarlierCall->getArgOperand(0);
2864 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2865 case AliasAnalysis::MustAlias:
2867 // If the load has a builtin retain, insert a plain retain for it.
2868 if (Class == IC_LoadWeakRetained) {
2870 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2874 // Zap the fully redundant load.
2875 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2876 Call->eraseFromParent();
2878 case AliasAnalysis::MayAlias:
2879 case AliasAnalysis::PartialAlias:
2881 case AliasAnalysis::NoAlias:
2888 // TOOD: Grab the copied value.
2890 case IC_AutoreleasepoolPush:
2892 case IC_IntrinsicUser:
2894 // Weak pointers are only modified through the weak entry points
2895 // (and arbitrary calls, which could call the weak entry points).
2898 // Anything else could modify the weak pointer.
2905 // Then, for each destroyWeak with an alloca operand, check to see if
2906 // the alloca and all its users can be zapped.
2907 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2908 Instruction *Inst = &*I++;
2909 InstructionClass Class = GetBasicInstructionClass(Inst);
2910 if (Class != IC_DestroyWeak)
2913 CallInst *Call = cast<CallInst>(Inst);
2914 Value *Arg = Call->getArgOperand(0);
2915 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2916 for (Value::use_iterator UI = Alloca->use_begin(),
2917 UE = Alloca->use_end(); UI != UE; ++UI) {
2918 const Instruction *UserInst = cast<Instruction>(*UI);
2919 switch (GetBasicInstructionClass(UserInst)) {
2922 case IC_DestroyWeak:
2929 for (Value::use_iterator UI = Alloca->use_begin(),
2930 UE = Alloca->use_end(); UI != UE; ) {
2931 CallInst *UserInst = cast<CallInst>(*UI++);
2932 switch (GetBasicInstructionClass(UserInst)) {
2935 // These functions return their second argument.
2936 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2938 case IC_DestroyWeak:
2942 llvm_unreachable("alloca really is used!");
2944 UserInst->eraseFromParent();
2946 Alloca->eraseFromParent();
2952 /// Identify program paths which execute sequences of retains and releases which
2953 /// can be eliminated.
2954 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2955 // Releases, Retains - These are used to store the results of the main flow
2956 // analysis. These use Value* as the key instead of Instruction* so that the
2957 // map stays valid when we get around to rewriting code and calls get
2958 // replaced by arguments.
2959 DenseMap<Value *, RRInfo> Releases;
2960 MapVector<Value *, RRInfo> Retains;
2962 // This is used during the traversal of the function to track the
2963 // states for each identified object at each block.
2964 DenseMap<const BasicBlock *, BBState> BBStates;
2966 // Analyze the CFG of the function, and all instructions.
2967 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2970 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2975 MultiOwnersSet.clear();
2977 return AnyPairsCompletelyEliminated && NestingDetected;
2980 /// Check if there is a dependent call earlier that does not have anything in
2981 /// between the Retain and the call that can affect the reference count of their
2982 /// shared pointer argument. Note that Retain need not be in BB.
2984 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2985 SmallPtrSet<Instruction *, 4> &DepInsts,
2986 SmallPtrSet<const BasicBlock *, 4> &Visited,
2987 ProvenanceAnalysis &PA) {
2988 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2989 DepInsts, Visited, PA);
2990 if (DepInsts.size() != 1)
2994 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2996 // Check that the pointer is the return value of the call.
2997 if (!Call || Arg != Call)
3000 // Check that the call is a regular call.
3001 InstructionClass Class = GetBasicInstructionClass(Call);
3002 if (Class != IC_CallOrUser && Class != IC_Call)
3008 /// Find a dependent retain that precedes the given autorelease for which there
3009 /// is nothing in between the two instructions that can affect the ref count of
3012 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3013 Instruction *Autorelease,
3014 SmallPtrSet<Instruction *, 4> &DepInsts,
3015 SmallPtrSet<const BasicBlock *, 4> &Visited,
3016 ProvenanceAnalysis &PA) {
3017 FindDependencies(CanChangeRetainCount, Arg,
3018 BB, Autorelease, DepInsts, Visited, PA);
3019 if (DepInsts.size() != 1)
3023 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3025 // Check that we found a retain with the same argument.
3027 !IsRetain(GetBasicInstructionClass(Retain)) ||
3028 GetObjCArg(Retain) != Arg) {
3035 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3036 /// no instructions dependent on Arg that need a positive ref count in between
3037 /// the autorelease and the ret.
3039 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3041 SmallPtrSet<Instruction *, 4> &DepInsts,
3042 SmallPtrSet<const BasicBlock *, 4> &V,
3043 ProvenanceAnalysis &PA) {
3044 FindDependencies(NeedsPositiveRetainCount, Arg,
3045 BB, Ret, DepInsts, V, PA);
3046 if (DepInsts.size() != 1)
3049 CallInst *Autorelease =
3050 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3053 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3054 if (!IsAutorelease(AutoreleaseClass))
3056 if (GetObjCArg(Autorelease) != Arg)
3062 /// Look for this pattern:
3064 /// %call = call i8* @something(...)
3065 /// %2 = call i8* @objc_retain(i8* %call)
3066 /// %3 = call i8* @objc_autorelease(i8* %2)
3069 /// And delete the retain and autorelease.
3070 void ObjCARCOpt::OptimizeReturns(Function &F) {
3071 if (!F.getReturnType()->isPointerTy())
3074 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3076 SmallPtrSet<Instruction *, 4> DependingInstructions;
3077 SmallPtrSet<const BasicBlock *, 4> Visited;
3078 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3079 BasicBlock *BB = FI;
3080 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3082 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3087 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3089 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3090 // dependent on Arg such that there are no instructions dependent on Arg
3091 // that need a positive ref count in between the autorelease and Ret.
3092 CallInst *Autorelease =
3093 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3094 DependingInstructions, Visited,
3096 DependingInstructions.clear();
3103 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3104 DependingInstructions, Visited, PA);
3105 DependingInstructions.clear();
3111 // Check that there is nothing that can affect the reference count
3112 // between the retain and the call. Note that Retain need not be in BB.
3113 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3114 DependingInstructions,
3116 DependingInstructions.clear();
3119 if (!HasSafePathToCall)
3122 // If so, we can zap the retain and autorelease.
3125 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3126 << *Autorelease << "\n");
3127 EraseInstruction(Retain);
3128 EraseInstruction(Autorelease);
3134 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3135 llvm::Statistic &NumRetains =
3136 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3137 llvm::Statistic &NumReleases =
3138 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3140 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3141 Instruction *Inst = &*I++;
3142 switch (GetBasicInstructionClass(Inst)) {
3156 bool ObjCARCOpt::doInitialization(Module &M) {
3160 // If nothing in the Module uses ARC, don't do anything.
3161 Run = ModuleHasARC(M);
3165 // Identify the imprecise release metadata kind.
3166 ImpreciseReleaseMDKind =
3167 M.getContext().getMDKindID("clang.imprecise_release");
3168 CopyOnEscapeMDKind =
3169 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3170 NoObjCARCExceptionsMDKind =
3171 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3172 #ifdef ARC_ANNOTATIONS
3173 ARCAnnotationBottomUpMDKind =
3174 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3175 ARCAnnotationTopDownMDKind =
3176 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3177 ARCAnnotationProvenanceSourceMDKind =
3178 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3179 #endif // ARC_ANNOTATIONS
3181 // Intuitively, objc_retain and others are nocapture, however in practice
3182 // they are not, because they return their argument value. And objc_release
3183 // calls finalizers which can have arbitrary side effects.
3185 // These are initialized lazily.
3186 AutoreleaseRVCallee = 0;
3189 RetainBlockCallee = 0;
3190 AutoreleaseCallee = 0;
3195 bool ObjCARCOpt::runOnFunction(Function &F) {
3199 // If nothing in the Module uses ARC, don't do anything.
3205 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3208 PA.setAA(&getAnalysis<AliasAnalysis>());
3211 if (AreStatisticsEnabled()) {
3212 GatherStatistics(F, false);
3216 // This pass performs several distinct transformations. As a compile-time aid
3217 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3218 // library functions aren't declared.
3220 // Preliminary optimizations. This also computes UsedInThisFunction.
3221 OptimizeIndividualCalls(F);
3223 // Optimizations for weak pointers.
3224 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3225 (1 << IC_LoadWeakRetained) |
3226 (1 << IC_StoreWeak) |
3227 (1 << IC_InitWeak) |
3228 (1 << IC_CopyWeak) |
3229 (1 << IC_MoveWeak) |
3230 (1 << IC_DestroyWeak)))
3231 OptimizeWeakCalls(F);
3233 // Optimizations for retain+release pairs.
3234 if (UsedInThisFunction & ((1 << IC_Retain) |
3235 (1 << IC_RetainRV) |
3236 (1 << IC_RetainBlock)))
3237 if (UsedInThisFunction & (1 << IC_Release))
3238 // Run OptimizeSequences until it either stops making changes or
3239 // no retain+release pair nesting is detected.
3240 while (OptimizeSequences(F)) {}
3242 // Optimizations if objc_autorelease is used.
3243 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3244 (1 << IC_AutoreleaseRV)))
3247 // Gather statistics after optimization.
3249 if (AreStatisticsEnabled()) {
3250 GatherStatistics(F, true);
3254 DEBUG(dbgs() << "\n");
3259 void ObjCARCOpt::releaseMemory() {