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 bool IsTrackingImpreciseReleases() {
469 return ReleaseMetadata != 0;
474 void RRInfo::clear() {
476 IsTailCallRelease = false;
479 ReverseInsertPts.clear();
480 CFGHazardAfflicted = false;
484 /// \brief This class summarizes several per-pointer runtime properties which
485 /// are propogated through the flow graph.
487 /// True if the reference count is known to be incremented.
488 bool KnownPositiveRefCount;
490 /// True if we've seen an opportunity for partial RR elimination, such as
491 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
494 /// The current position in the sequence.
498 /// Unidirectional information about the current sequence.
500 /// TODO: Encapsulate this better.
503 PtrState() : KnownPositiveRefCount(false), Partial(false),
506 void SetKnownPositiveRefCount() {
507 DEBUG(dbgs() << "Setting Known Positive.\n");
508 KnownPositiveRefCount = true;
511 void ClearKnownPositiveRefCount() {
512 DEBUG(dbgs() << "Clearing Known Positive.\n");
513 KnownPositiveRefCount = false;
516 bool HasKnownPositiveRefCount() const {
517 return KnownPositiveRefCount;
520 void SetSeq(Sequence NewSeq) {
521 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
525 Sequence GetSeq() const {
529 void ClearSequenceProgress() {
530 ResetSequenceProgress(S_None);
533 void ResetSequenceProgress(Sequence NewSeq) {
534 DEBUG(dbgs() << "Resetting sequence progress.\n");
540 void Merge(const PtrState &Other, bool TopDown);
545 PtrState::Merge(const PtrState &Other, bool TopDown) {
546 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
547 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
549 // If we're not in a sequence (anymore), drop all associated state.
553 } else if (Partial || Other.Partial) {
554 // If we're doing a merge on a path that's previously seen a partial
555 // merge, conservatively drop the sequence, to avoid doing partial
556 // RR elimination. If the branch predicates for the two merge differ,
557 // mixing them is unsafe.
558 ClearSequenceProgress();
560 // Conservatively merge the ReleaseMetadata information.
561 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
562 RRI.ReleaseMetadata = 0;
564 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
565 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
566 Other.RRI.IsTailCallRelease;
567 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
568 RRI.CFGHazardAfflicted |= Other.RRI.CFGHazardAfflicted;
570 // Merge the insert point sets. If there are any differences,
571 // that makes this a partial merge.
572 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
573 for (SmallPtrSet<Instruction *, 2>::const_iterator
574 I = Other.RRI.ReverseInsertPts.begin(),
575 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
576 Partial |= RRI.ReverseInsertPts.insert(*I);
581 /// \brief Per-BasicBlock state.
583 /// The number of unique control paths from the entry which can reach this
585 unsigned TopDownPathCount;
587 /// The number of unique control paths to exits from this block.
588 unsigned BottomUpPathCount;
590 /// A type for PerPtrTopDown and PerPtrBottomUp.
591 typedef MapVector<const Value *, PtrState> MapTy;
593 /// The top-down traversal uses this to record information known about a
594 /// pointer at the bottom of each block.
597 /// The bottom-up traversal uses this to record information known about a
598 /// pointer at the top of each block.
599 MapTy PerPtrBottomUp;
601 /// Effective predecessors of the current block ignoring ignorable edges and
602 /// ignored backedges.
603 SmallVector<BasicBlock *, 2> Preds;
604 /// Effective successors of the current block ignoring ignorable edges and
605 /// ignored backedges.
606 SmallVector<BasicBlock *, 2> Succs;
609 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
611 typedef MapTy::iterator ptr_iterator;
612 typedef MapTy::const_iterator ptr_const_iterator;
614 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
615 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
616 ptr_const_iterator top_down_ptr_begin() const {
617 return PerPtrTopDown.begin();
619 ptr_const_iterator top_down_ptr_end() const {
620 return PerPtrTopDown.end();
623 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
624 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
625 ptr_const_iterator bottom_up_ptr_begin() const {
626 return PerPtrBottomUp.begin();
628 ptr_const_iterator bottom_up_ptr_end() const {
629 return PerPtrBottomUp.end();
632 /// Mark this block as being an entry block, which has one path from the
633 /// entry by definition.
634 void SetAsEntry() { TopDownPathCount = 1; }
636 /// Mark this block as being an exit block, which has one path to an exit by
638 void SetAsExit() { BottomUpPathCount = 1; }
640 /// Attempt to find the PtrState object describing the top down state for
641 /// pointer Arg. Return a new initialized PtrState describing the top down
642 /// state for Arg if we do not find one.
643 PtrState &getPtrTopDownState(const Value *Arg) {
644 return PerPtrTopDown[Arg];
647 /// Attempt to find the PtrState object describing the bottom up state for
648 /// pointer Arg. Return a new initialized PtrState describing the bottom up
649 /// state for Arg if we do not find one.
650 PtrState &getPtrBottomUpState(const Value *Arg) {
651 return PerPtrBottomUp[Arg];
654 /// Attempt to find the PtrState object describing the bottom up state for
656 ptr_iterator findPtrBottomUpState(const Value *Arg) {
657 return PerPtrBottomUp.find(Arg);
660 void clearBottomUpPointers() {
661 PerPtrBottomUp.clear();
664 void clearTopDownPointers() {
665 PerPtrTopDown.clear();
668 void InitFromPred(const BBState &Other);
669 void InitFromSucc(const BBState &Other);
670 void MergePred(const BBState &Other);
671 void MergeSucc(const BBState &Other);
673 /// Return the number of possible unique paths from an entry to an exit
674 /// which pass through this block. This is only valid after both the
675 /// top-down and bottom-up traversals are complete.
676 unsigned GetAllPathCount() const {
677 assert(TopDownPathCount != 0);
678 assert(BottomUpPathCount != 0);
679 return TopDownPathCount * BottomUpPathCount;
682 // Specialized CFG utilities.
683 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
684 edge_iterator pred_begin() { return Preds.begin(); }
685 edge_iterator pred_end() { return Preds.end(); }
686 edge_iterator succ_begin() { return Succs.begin(); }
687 edge_iterator succ_end() { return Succs.end(); }
689 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
690 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
692 bool isExit() const { return Succs.empty(); }
696 void BBState::InitFromPred(const BBState &Other) {
697 PerPtrTopDown = Other.PerPtrTopDown;
698 TopDownPathCount = Other.TopDownPathCount;
701 void BBState::InitFromSucc(const BBState &Other) {
702 PerPtrBottomUp = Other.PerPtrBottomUp;
703 BottomUpPathCount = Other.BottomUpPathCount;
706 /// The top-down traversal uses this to merge information about predecessors to
707 /// form the initial state for a new block.
708 void BBState::MergePred(const BBState &Other) {
709 // Other.TopDownPathCount can be 0, in which case it is either dead or a
710 // loop backedge. Loop backedges are special.
711 TopDownPathCount += Other.TopDownPathCount;
713 // Check for overflow. If we have overflow, fall back to conservative
715 if (TopDownPathCount < Other.TopDownPathCount) {
716 clearTopDownPointers();
720 // For each entry in the other set, if our set has an entry with the same key,
721 // merge the entries. Otherwise, copy the entry and merge it with an empty
723 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
724 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
725 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
726 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
730 // For each entry in our set, if the other set doesn't have an entry with the
731 // same key, force it to merge with an empty entry.
732 for (ptr_iterator MI = top_down_ptr_begin(),
733 ME = top_down_ptr_end(); MI != ME; ++MI)
734 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
735 MI->second.Merge(PtrState(), /*TopDown=*/true);
738 /// The bottom-up traversal uses this to merge information about successors to
739 /// form the initial state for a new block.
740 void BBState::MergeSucc(const BBState &Other) {
741 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
742 // loop backedge. Loop backedges are special.
743 BottomUpPathCount += Other.BottomUpPathCount;
745 // Check for overflow. If we have overflow, fall back to conservative
747 if (BottomUpPathCount < Other.BottomUpPathCount) {
748 clearBottomUpPointers();
752 // For each entry in the other set, if our set has an entry with the
753 // same key, merge the entries. Otherwise, copy the entry and merge
754 // it with an empty entry.
755 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
756 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
757 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
758 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
762 // For each entry in our set, if the other set doesn't have an entry
763 // with the same key, force it to merge with an empty entry.
764 for (ptr_iterator MI = bottom_up_ptr_begin(),
765 ME = bottom_up_ptr_end(); MI != ME; ++MI)
766 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
767 MI->second.Merge(PtrState(), /*TopDown=*/false);
770 // Only enable ARC Annotations if we are building a debug version of
773 #define ARC_ANNOTATIONS
776 // Define some macros along the lines of DEBUG and some helper functions to make
777 // it cleaner to create annotations in the source code and to no-op when not
778 // building in debug mode.
779 #ifdef ARC_ANNOTATIONS
781 #include "llvm/Support/CommandLine.h"
783 /// Enable/disable ARC sequence annotations.
785 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
786 cl::desc("Enable emission of arc data flow analysis "
789 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
790 cl::desc("Disable check for cfg hazards when "
792 static cl::opt<std::string>
793 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
795 cl::desc("filter out all data flow annotations "
796 "but those that apply to the given "
797 "target llvm identifier."));
799 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
800 /// instruction so that we can track backwards when post processing via the llvm
801 /// arc annotation processor tool. If the function is an
802 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
806 // If pointer is a result of an instruction and it does not have a source
807 // MDNode it, attach a new MDNode onto it. If pointer is a result of
808 // an instruction and does have a source MDNode attached to it, return a
809 // reference to said Node. Otherwise just return 0.
810 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
812 if (!(Node = Inst->getMetadata(NodeId))) {
813 // We do not have any node. Generate and attatch the hash MDString to the
816 // We just use an MDString to ensure that this metadata gets written out
817 // of line at the module level and to provide a very simple format
818 // encoding the information herein. Both of these makes it simpler to
819 // parse the annotations by a simple external program.
821 raw_string_ostream os(Str);
822 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
823 << Inst->getName() << ")";
825 Hash = MDString::get(Inst->getContext(), os.str());
826 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
828 // We have a node. Grab its hash and return it.
829 assert(Node->getNumOperands() == 1 &&
830 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
831 Hash = cast<MDString>(Node->getOperand(0));
833 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
835 raw_string_ostream os(str);
836 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
838 Hash = MDString::get(Arg->getContext(), os.str());
844 static std::string SequenceToString(Sequence A) {
846 raw_string_ostream os(str);
851 /// Helper function to change a Sequence into a String object using our overload
852 /// for raw_ostream so we only have printing code in one location.
853 static MDString *SequenceToMDString(LLVMContext &Context,
855 return MDString::get(Context, SequenceToString(A));
858 /// A simple function to generate a MDNode which describes the change in state
859 /// for Value *Ptr caused by Instruction *Inst.
860 static void AppendMDNodeToInstForPtr(unsigned NodeId,
863 MDString *PtrSourceMDNodeID,
867 Value *tmp[3] = {PtrSourceMDNodeID,
868 SequenceToMDString(Inst->getContext(),
870 SequenceToMDString(Inst->getContext(),
872 Node = MDNode::get(Inst->getContext(),
873 ArrayRef<Value*>(tmp, 3));
875 Inst->setMetadata(NodeId, Node);
878 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
879 /// state of a pointer at the entrance to a basic block.
880 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
881 Value *Ptr, Sequence Seq) {
882 // If we have a target identifier, make sure that we match it before
884 if(!ARCAnnotationTargetIdentifier.empty() &&
885 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
888 Module *M = BB->getParent()->getParent();
889 LLVMContext &C = M->getContext();
890 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
891 Type *I8XX = PointerType::getUnqual(I8X);
892 Type *Params[] = {I8XX, I8XX};
893 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
894 ArrayRef<Type*>(Params, 2),
896 Constant *Callee = M->getOrInsertFunction(Name, FTy);
898 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
901 StringRef Tmp = Ptr->getName();
902 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
903 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
905 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
906 cast<Constant>(ActualPtrName), Tmp);
910 std::string SeqStr = SequenceToString(Seq);
911 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
912 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
914 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
915 cast<Constant>(ActualPtrName), SeqStr);
918 Builder.CreateCall2(Callee, PtrName, S);
921 /// Add to the end of the basic block llvm.ptr.annotations which show the state
922 /// of the pointer at the bottom of the basic block.
923 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
924 Value *Ptr, Sequence Seq) {
925 // If we have a target identifier, make sure that we match it before emitting
927 if(!ARCAnnotationTargetIdentifier.empty() &&
928 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
931 Module *M = BB->getParent()->getParent();
932 LLVMContext &C = M->getContext();
933 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
934 Type *I8XX = PointerType::getUnqual(I8X);
935 Type *Params[] = {I8XX, I8XX};
936 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
937 ArrayRef<Type*>(Params, 2),
939 Constant *Callee = M->getOrInsertFunction(Name, FTy);
941 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
944 StringRef Tmp = Ptr->getName();
945 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
946 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
948 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
949 cast<Constant>(ActualPtrName), Tmp);
953 std::string SeqStr = SequenceToString(Seq);
954 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
955 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
957 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
958 cast<Constant>(ActualPtrName), SeqStr);
960 Builder.CreateCall2(Callee, PtrName, S);
963 /// Adds a source annotation to pointer and a state change annotation to Inst
964 /// referencing the source annotation and the old/new state of pointer.
965 static void GenerateARCAnnotation(unsigned InstMDId,
971 if (EnableARCAnnotations) {
972 // If we have a target identifier, make sure that we match it before
973 // emitting an annotation.
974 if(!ARCAnnotationTargetIdentifier.empty() &&
975 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
978 // First generate the source annotation on our pointer. This will return an
979 // MDString* if Ptr actually comes from an instruction implying we can put
980 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
981 // then we know that our pointer is from an Argument so we put a reference
982 // to the argument number.
984 // The point of this is to make it easy for the
985 // llvm-arc-annotation-processor tool to cross reference where the source
986 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
987 // information via debug info for backends to use (since why would anyone
988 // need such a thing from LLVM IR besides in non standard cases
990 MDString *SourcePtrMDNode =
991 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
992 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
997 // The actual interface for accessing the above functionality is defined via
998 // some simple macros which are defined below. We do this so that the user does
999 // not need to pass in what metadata id is needed resulting in cleaner code and
1000 // additionally since it provides an easy way to conditionally no-op all
1001 // annotation support in a non-debug build.
1003 /// Use this macro to annotate a sequence state change when processing
1004 /// instructions bottom up,
1005 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1006 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1007 ARCAnnotationProvenanceSourceMDKind, (inst), \
1008 const_cast<Value*>(ptr), (old), (new))
1009 /// Use this macro to annotate a sequence state change when processing
1010 /// instructions top down.
1011 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1012 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1013 ARCAnnotationProvenanceSourceMDKind, (inst), \
1014 const_cast<Value*>(ptr), (old), (new))
1016 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1018 if (EnableARCAnnotations) { \
1019 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1020 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1021 Value *Ptr = const_cast<Value*>(I->first); \
1022 Sequence Seq = I->second.GetSeq(); \
1023 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1028 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1029 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1030 Entrance, bottom_up)
1031 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1032 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1033 Terminator, bottom_up)
1034 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1035 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1037 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1038 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1039 Terminator, top_down)
1041 #else // !ARC_ANNOTATION
1042 // If annotations are off, noop.
1043 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1044 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1045 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1046 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1047 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1048 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1049 #endif // !ARC_ANNOTATION
1052 /// \brief The main ARC optimization pass.
1053 class ObjCARCOpt : public FunctionPass {
1055 ProvenanceAnalysis PA;
1057 // This is used to track if a pointer is stored into an alloca.
1058 DenseSet<const Value *> MultiOwnersSet;
1060 /// A flag indicating whether this optimization pass should run.
1063 /// Declarations for ObjC runtime functions, for use in creating calls to
1064 /// them. These are initialized lazily to avoid cluttering up the Module
1065 /// with unused declarations.
1067 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1068 Constant *AutoreleaseRVCallee;
1069 /// Declaration for ObjC runtime function objc_release.
1070 Constant *ReleaseCallee;
1071 /// Declaration for ObjC runtime function objc_retain.
1072 Constant *RetainCallee;
1073 /// Declaration for ObjC runtime function objc_retainBlock.
1074 Constant *RetainBlockCallee;
1075 /// Declaration for ObjC runtime function objc_autorelease.
1076 Constant *AutoreleaseCallee;
1078 /// Flags which determine whether each of the interesting runtine functions
1079 /// is in fact used in the current function.
1080 unsigned UsedInThisFunction;
1082 /// The Metadata Kind for clang.imprecise_release metadata.
1083 unsigned ImpreciseReleaseMDKind;
1085 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1086 unsigned CopyOnEscapeMDKind;
1088 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1089 unsigned NoObjCARCExceptionsMDKind;
1091 #ifdef ARC_ANNOTATIONS
1092 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1093 unsigned ARCAnnotationBottomUpMDKind;
1094 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1095 unsigned ARCAnnotationTopDownMDKind;
1096 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1097 unsigned ARCAnnotationProvenanceSourceMDKind;
1098 #endif // ARC_ANNOATIONS
1100 Constant *getAutoreleaseRVCallee(Module *M);
1101 Constant *getReleaseCallee(Module *M);
1102 Constant *getRetainCallee(Module *M);
1103 Constant *getRetainBlockCallee(Module *M);
1104 Constant *getAutoreleaseCallee(Module *M);
1106 bool IsRetainBlockOptimizable(const Instruction *Inst);
1108 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1109 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1110 InstructionClass &Class);
1111 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1112 InstructionClass &Class);
1113 void OptimizeIndividualCalls(Function &F);
1115 void CheckForCFGHazards(const BasicBlock *BB,
1116 DenseMap<const BasicBlock *, BBState> &BBStates,
1117 BBState &MyStates) const;
1118 bool VisitInstructionBottomUp(Instruction *Inst,
1120 MapVector<Value *, RRInfo> &Retains,
1122 bool VisitBottomUp(BasicBlock *BB,
1123 DenseMap<const BasicBlock *, BBState> &BBStates,
1124 MapVector<Value *, RRInfo> &Retains);
1125 bool VisitInstructionTopDown(Instruction *Inst,
1126 DenseMap<Value *, RRInfo> &Releases,
1128 bool VisitTopDown(BasicBlock *BB,
1129 DenseMap<const BasicBlock *, BBState> &BBStates,
1130 DenseMap<Value *, RRInfo> &Releases);
1131 bool Visit(Function &F,
1132 DenseMap<const BasicBlock *, BBState> &BBStates,
1133 MapVector<Value *, RRInfo> &Retains,
1134 DenseMap<Value *, RRInfo> &Releases);
1136 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1137 MapVector<Value *, RRInfo> &Retains,
1138 DenseMap<Value *, RRInfo> &Releases,
1139 SmallVectorImpl<Instruction *> &DeadInsts,
1142 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1143 MapVector<Value *, RRInfo> &Retains,
1144 DenseMap<Value *, RRInfo> &Releases,
1146 SmallVector<Instruction *, 4> &NewRetains,
1147 SmallVector<Instruction *, 4> &NewReleases,
1148 SmallVector<Instruction *, 8> &DeadInsts,
1149 RRInfo &RetainsToMove,
1150 RRInfo &ReleasesToMove,
1153 bool &AnyPairsCompletelyEliminated);
1155 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1156 MapVector<Value *, RRInfo> &Retains,
1157 DenseMap<Value *, RRInfo> &Releases,
1160 void OptimizeWeakCalls(Function &F);
1162 bool OptimizeSequences(Function &F);
1164 void OptimizeReturns(Function &F);
1167 void GatherStatistics(Function &F, bool AfterOptimization = false);
1170 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1171 virtual bool doInitialization(Module &M);
1172 virtual bool runOnFunction(Function &F);
1173 virtual void releaseMemory();
1177 ObjCARCOpt() : FunctionPass(ID) {
1178 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1183 char ObjCARCOpt::ID = 0;
1184 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1185 "objc-arc", "ObjC ARC optimization", false, false)
1186 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1187 INITIALIZE_PASS_END(ObjCARCOpt,
1188 "objc-arc", "ObjC ARC optimization", false, false)
1190 Pass *llvm::createObjCARCOptPass() {
1191 return new ObjCARCOpt();
1194 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1195 AU.addRequired<ObjCARCAliasAnalysis>();
1196 AU.addRequired<AliasAnalysis>();
1197 // ARC optimization doesn't currently split critical edges.
1198 AU.setPreservesCFG();
1201 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1202 // Without the magic metadata tag, we have to assume this might be an
1203 // objc_retainBlock call inserted to convert a block pointer to an id,
1204 // in which case it really is needed.
1205 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1208 // If the pointer "escapes" (not including being used in a call),
1209 // the copy may be needed.
1210 if (DoesRetainableObjPtrEscape(Inst))
1213 // Otherwise, it's not needed.
1217 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1218 if (!AutoreleaseRVCallee) {
1219 LLVMContext &C = M->getContext();
1220 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1221 Type *Params[] = { I8X };
1222 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1223 AttributeSet Attribute =
1224 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1225 Attribute::NoUnwind);
1226 AutoreleaseRVCallee =
1227 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1230 return AutoreleaseRVCallee;
1233 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1234 if (!ReleaseCallee) {
1235 LLVMContext &C = M->getContext();
1236 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1237 AttributeSet Attribute =
1238 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1239 Attribute::NoUnwind);
1241 M->getOrInsertFunction(
1243 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1246 return ReleaseCallee;
1249 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1250 if (!RetainCallee) {
1251 LLVMContext &C = M->getContext();
1252 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1253 AttributeSet Attribute =
1254 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1255 Attribute::NoUnwind);
1257 M->getOrInsertFunction(
1259 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1262 return RetainCallee;
1265 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1266 if (!RetainBlockCallee) {
1267 LLVMContext &C = M->getContext();
1268 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1269 // objc_retainBlock is not nounwind because it calls user copy constructors
1270 // which could theoretically throw.
1272 M->getOrInsertFunction(
1274 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1277 return RetainBlockCallee;
1280 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1281 if (!AutoreleaseCallee) {
1282 LLVMContext &C = M->getContext();
1283 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1284 AttributeSet Attribute =
1285 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1286 Attribute::NoUnwind);
1288 M->getOrInsertFunction(
1290 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1293 return AutoreleaseCallee;
1296 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1297 /// not a return value. Or, if it can be paired with an
1298 /// objc_autoreleaseReturnValue, delete the pair and return true.
1300 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1301 // Check for the argument being from an immediately preceding call or invoke.
1302 const Value *Arg = GetObjCArg(RetainRV);
1303 ImmutableCallSite CS(Arg);
1304 if (const Instruction *Call = CS.getInstruction()) {
1305 if (Call->getParent() == RetainRV->getParent()) {
1306 BasicBlock::const_iterator I = Call;
1308 while (IsNoopInstruction(I)) ++I;
1309 if (&*I == RetainRV)
1311 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1312 BasicBlock *RetainRVParent = RetainRV->getParent();
1313 if (II->getNormalDest() == RetainRVParent) {
1314 BasicBlock::const_iterator I = RetainRVParent->begin();
1315 while (IsNoopInstruction(I)) ++I;
1316 if (&*I == RetainRV)
1322 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1323 // pointer. In this case, we can delete the pair.
1324 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1326 do --I; while (I != Begin && IsNoopInstruction(I));
1327 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1328 GetObjCArg(I) == Arg) {
1332 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1333 << "Erasing " << *RetainRV << "\n");
1335 EraseInstruction(I);
1336 EraseInstruction(RetainRV);
1341 // Turn it to a plain objc_retain.
1345 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1346 "objc_retain since the operand is not a return value.\n"
1347 "Old = " << *RetainRV << "\n");
1349 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1351 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1356 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1357 /// used as a return value.
1359 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1360 InstructionClass &Class) {
1361 // Check for a return of the pointer value.
1362 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1363 SmallVector<const Value *, 2> Users;
1364 Users.push_back(Ptr);
1366 Ptr = Users.pop_back_val();
1367 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1369 const User *I = *UI;
1370 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1372 if (isa<BitCastInst>(I))
1375 } while (!Users.empty());
1380 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1381 "objc_autorelease since its operand is not used as a return "
1383 "Old = " << *AutoreleaseRV << "\n");
1385 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1387 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1388 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1389 Class = IC_Autorelease;
1391 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1395 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1398 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1399 // does not escape (following the rules of block escaping), strength reduce the
1400 // objc_retainBlock to an objc_retain.
1402 // TODO: If an objc_retainBlock call is dominated period by a previous
1403 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1406 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1407 InstructionClass &Class) {
1408 assert(GetBasicInstructionClass(Inst) == Class);
1409 assert(IC_RetainBlock == Class);
1411 // If we can not optimize Inst, return false.
1412 if (!IsRetainBlockOptimizable(Inst))
1418 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1419 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1420 CallInst *RetainBlock = cast<CallInst>(Inst);
1421 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1422 // Remove copy_on_escape metadata.
1423 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1425 DEBUG(dbgs() << "New: " << *Inst << "\n");
1429 /// Visit each call, one at a time, and make simplifications without doing any
1430 /// additional analysis.
1431 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1432 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1433 // Reset all the flags in preparation for recomputing them.
1434 UsedInThisFunction = 0;
1436 // Visit all objc_* calls in F.
1437 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1438 Instruction *Inst = &*I++;
1440 InstructionClass Class = GetBasicInstructionClass(Inst);
1442 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1447 // Delete no-op casts. These function calls have special semantics, but
1448 // the semantics are entirely implemented via lowering in the front-end,
1449 // so by the time they reach the optimizer, they are just no-op calls
1450 // which return their argument.
1452 // There are gray areas here, as the ability to cast reference-counted
1453 // pointers to raw void* and back allows code to break ARC assumptions,
1454 // however these are currently considered to be unimportant.
1458 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1459 EraseInstruction(Inst);
1462 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1465 case IC_LoadWeakRetained:
1467 case IC_DestroyWeak: {
1468 CallInst *CI = cast<CallInst>(Inst);
1469 if (IsNullOrUndef(CI->getArgOperand(0))) {
1471 Type *Ty = CI->getArgOperand(0)->getType();
1472 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1473 Constant::getNullValue(Ty),
1475 llvm::Value *NewValue = UndefValue::get(CI->getType());
1476 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1477 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1478 CI->replaceAllUsesWith(NewValue);
1479 CI->eraseFromParent();
1486 CallInst *CI = cast<CallInst>(Inst);
1487 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1488 IsNullOrUndef(CI->getArgOperand(1))) {
1490 Type *Ty = CI->getArgOperand(0)->getType();
1491 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1492 Constant::getNullValue(Ty),
1495 llvm::Value *NewValue = UndefValue::get(CI->getType());
1496 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1497 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1499 CI->replaceAllUsesWith(NewValue);
1500 CI->eraseFromParent();
1505 case IC_RetainBlock:
1506 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1507 // onto the objc_retain peephole optimizations. Otherwise break.
1508 OptimizeRetainBlockCall(F, Inst, Class);
1511 if (OptimizeRetainRVCall(F, Inst))
1514 case IC_AutoreleaseRV:
1515 OptimizeAutoreleaseRVCall(F, Inst, Class);
1519 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1520 if (IsAutorelease(Class) && Inst->use_empty()) {
1521 CallInst *Call = cast<CallInst>(Inst);
1522 const Value *Arg = Call->getArgOperand(0);
1523 Arg = FindSingleUseIdentifiedObject(Arg);
1528 // Create the declaration lazily.
1529 LLVMContext &C = Inst->getContext();
1531 CallInst::Create(getReleaseCallee(F.getParent()),
1532 Call->getArgOperand(0), "", Call);
1533 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1535 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1536 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1537 << *NewCall << "\n");
1539 EraseInstruction(Call);
1545 // For functions which can never be passed stack arguments, add
1547 if (IsAlwaysTail(Class)) {
1549 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1550 "passed stack args: " << *Inst << "\n");
1551 cast<CallInst>(Inst)->setTailCall();
1554 // Ensure that functions that can never have a "tail" keyword due to the
1555 // semantics of ARC truly do not do so.
1556 if (IsNeverTail(Class)) {
1558 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1560 cast<CallInst>(Inst)->setTailCall(false);
1563 // Set nounwind as needed.
1564 if (IsNoThrow(Class)) {
1566 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1568 cast<CallInst>(Inst)->setDoesNotThrow();
1571 if (!IsNoopOnNull(Class)) {
1572 UsedInThisFunction |= 1 << Class;
1576 const Value *Arg = GetObjCArg(Inst);
1578 // ARC calls with null are no-ops. Delete them.
1579 if (IsNullOrUndef(Arg)) {
1582 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1584 EraseInstruction(Inst);
1588 // Keep track of which of retain, release, autorelease, and retain_block
1589 // are actually present in this function.
1590 UsedInThisFunction |= 1 << Class;
1592 // If Arg is a PHI, and one or more incoming values to the
1593 // PHI are null, and the call is control-equivalent to the PHI, and there
1594 // are no relevant side effects between the PHI and the call, the call
1595 // could be pushed up to just those paths with non-null incoming values.
1596 // For now, don't bother splitting critical edges for this.
1597 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1598 Worklist.push_back(std::make_pair(Inst, Arg));
1600 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1604 const PHINode *PN = dyn_cast<PHINode>(Arg);
1607 // Determine if the PHI has any null operands, or any incoming
1609 bool HasNull = false;
1610 bool HasCriticalEdges = false;
1611 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1613 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1614 if (IsNullOrUndef(Incoming))
1616 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1617 .getNumSuccessors() != 1) {
1618 HasCriticalEdges = true;
1622 // If we have null operands and no critical edges, optimize.
1623 if (!HasCriticalEdges && HasNull) {
1624 SmallPtrSet<Instruction *, 4> DependingInstructions;
1625 SmallPtrSet<const BasicBlock *, 4> Visited;
1627 // Check that there is nothing that cares about the reference
1628 // count between the call and the phi.
1631 case IC_RetainBlock:
1632 // These can always be moved up.
1635 // These can't be moved across things that care about the retain
1637 FindDependencies(NeedsPositiveRetainCount, Arg,
1638 Inst->getParent(), Inst,
1639 DependingInstructions, Visited, PA);
1641 case IC_Autorelease:
1642 // These can't be moved across autorelease pool scope boundaries.
1643 FindDependencies(AutoreleasePoolBoundary, Arg,
1644 Inst->getParent(), Inst,
1645 DependingInstructions, Visited, PA);
1648 case IC_AutoreleaseRV:
1649 // Don't move these; the RV optimization depends on the autoreleaseRV
1650 // being tail called, and the retainRV being immediately after a call
1651 // (which might still happen if we get lucky with codegen layout, but
1652 // it's not worth taking the chance).
1655 llvm_unreachable("Invalid dependence flavor");
1658 if (DependingInstructions.size() == 1 &&
1659 *DependingInstructions.begin() == PN) {
1662 // Clone the call into each predecessor that has a non-null value.
1663 CallInst *CInst = cast<CallInst>(Inst);
1664 Type *ParamTy = CInst->getArgOperand(0)->getType();
1665 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1667 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1668 if (!IsNullOrUndef(Incoming)) {
1669 CallInst *Clone = cast<CallInst>(CInst->clone());
1670 Value *Op = PN->getIncomingValue(i);
1671 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1672 if (Op->getType() != ParamTy)
1673 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1674 Clone->setArgOperand(0, Op);
1675 Clone->insertBefore(InsertPos);
1677 DEBUG(dbgs() << "Cloning "
1679 "And inserting clone at " << *InsertPos << "\n");
1680 Worklist.push_back(std::make_pair(Clone, Incoming));
1683 // Erase the original call.
1684 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1685 EraseInstruction(CInst);
1689 } while (!Worklist.empty());
1693 /// If we have a top down pointer in the S_Use state, make sure that there are
1694 /// no CFG hazards by checking the states of various bottom up pointers.
1695 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1696 const bool SuccSRRIKnownSafe,
1698 bool &SomeSuccHasSame,
1699 bool &AllSuccsHaveSame,
1700 bool &NotAllSeqEqualButKnownSafe,
1701 bool &ShouldContinue) {
1703 case S_CanRelease: {
1704 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1705 S.ClearSequenceProgress();
1708 S.RRI.CFGHazardAfflicted = true;
1709 ShouldContinue = true;
1713 SomeSuccHasSame = true;
1717 case S_MovableRelease:
1718 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1719 AllSuccsHaveSame = false;
1721 NotAllSeqEqualButKnownSafe = true;
1724 llvm_unreachable("bottom-up pointer in retain state!");
1726 llvm_unreachable("This should have been handled earlier.");
1730 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1731 /// there are no CFG hazards by checking the states of various bottom up
1733 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1734 const bool SuccSRRIKnownSafe,
1736 bool &SomeSuccHasSame,
1737 bool &AllSuccsHaveSame,
1738 bool &NotAllSeqEqualButKnownSafe) {
1741 SomeSuccHasSame = true;
1745 case S_MovableRelease:
1747 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1748 AllSuccsHaveSame = false;
1750 NotAllSeqEqualButKnownSafe = true;
1753 llvm_unreachable("bottom-up pointer in retain state!");
1755 llvm_unreachable("This should have been handled earlier.");
1759 /// Check for critical edges, loop boundaries, irreducible control flow, or
1760 /// other CFG structures where moving code across the edge would result in it
1761 /// being executed more.
1763 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1764 DenseMap<const BasicBlock *, BBState> &BBStates,
1765 BBState &MyStates) const {
1766 // If any top-down local-use or possible-dec has a succ which is earlier in
1767 // the sequence, forget it.
1768 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1769 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1770 PtrState &S = I->second;
1771 const Sequence Seq = I->second.GetSeq();
1773 // We only care about S_Retain, S_CanRelease, and S_Use.
1777 // Make sure that if extra top down states are added in the future that this
1778 // code is updated to handle it.
1779 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1780 "Unknown top down sequence state.");
1782 const Value *Arg = I->first;
1783 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1784 bool SomeSuccHasSame = false;
1785 bool AllSuccsHaveSame = true;
1786 bool NotAllSeqEqualButKnownSafe = false;
1788 succ_const_iterator SI(TI), SE(TI, false);
1790 for (; SI != SE; ++SI) {
1791 // If VisitBottomUp has pointer information for this successor, take
1792 // what we know about it.
1793 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1795 assert(BBI != BBStates.end());
1796 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1797 const Sequence SuccSSeq = SuccS.GetSeq();
1799 // If bottom up, the pointer is in an S_None state, clear the sequence
1800 // progress since the sequence in the bottom up state finished
1801 // suggesting a mismatch in between retains/releases. This is true for
1802 // all three cases that we are handling here: S_Retain, S_Use, and
1804 if (SuccSSeq == S_None) {
1805 S.ClearSequenceProgress();
1809 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1811 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1813 // *NOTE* We do not use Seq from above here since we are allowing for
1814 // S.GetSeq() to change while we are visiting basic blocks.
1815 switch(S.GetSeq()) {
1817 bool ShouldContinue = false;
1818 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1819 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1825 case S_CanRelease: {
1826 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1827 SomeSuccHasSame, AllSuccsHaveSame,
1828 NotAllSeqEqualButKnownSafe);
1835 case S_MovableRelease:
1840 // If the state at the other end of any of the successor edges
1841 // matches the current state, require all edges to match. This
1842 // guards against loops in the middle of a sequence.
1843 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1844 S.ClearSequenceProgress();
1845 } else if (NotAllSeqEqualButKnownSafe) {
1846 // If we would have cleared the state foregoing the fact that we are known
1847 // safe, stop code motion. This is because whether or not it is safe to
1848 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1849 // are allowed to perform code motion.
1850 S.RRI.CFGHazardAfflicted = true;
1856 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1858 MapVector<Value *, RRInfo> &Retains,
1859 BBState &MyStates) {
1860 bool NestingDetected = false;
1861 InstructionClass Class = GetInstructionClass(Inst);
1862 const Value *Arg = 0;
1864 DEBUG(dbgs() << "Class: " << Class << "\n");
1868 Arg = GetObjCArg(Inst);
1870 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1872 // If we see two releases in a row on the same pointer. If so, make
1873 // a note, and we'll cicle back to revisit it after we've
1874 // hopefully eliminated the second release, which may allow us to
1875 // eliminate the first release too.
1876 // Theoretically we could implement removal of nested retain+release
1877 // pairs by making PtrState hold a stack of states, but this is
1878 // simple and avoids adding overhead for the non-nested case.
1879 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1880 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1881 NestingDetected = true;
1884 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1885 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1886 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1887 S.ResetSequenceProgress(NewSeq);
1888 S.RRI.ReleaseMetadata = ReleaseMetadata;
1889 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1890 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1891 S.RRI.Calls.insert(Inst);
1892 S.SetKnownPositiveRefCount();
1895 case IC_RetainBlock:
1896 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1897 // objc_retainBlocks to objc_retains. Thus at this point any
1898 // objc_retainBlocks that we see are not optimizable.
1902 Arg = GetObjCArg(Inst);
1904 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1905 S.SetKnownPositiveRefCount();
1907 Sequence OldSeq = S.GetSeq();
1911 case S_MovableRelease:
1913 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1914 // imprecise release, clear our reverse insertion points.
1915 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1916 S.RRI.ReverseInsertPts.clear();
1919 // Don't do retain+release tracking for IC_RetainRV, because it's
1920 // better to let it remain as the first instruction after a call.
1921 if (Class != IC_RetainRV)
1922 Retains[Inst] = S.RRI;
1923 S.ClearSequenceProgress();
1928 llvm_unreachable("bottom-up pointer in retain state!");
1930 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1931 // A retain moving bottom up can be a use.
1934 case IC_AutoreleasepoolPop:
1935 // Conservatively, clear MyStates for all known pointers.
1936 MyStates.clearBottomUpPointers();
1937 return NestingDetected;
1938 case IC_AutoreleasepoolPush:
1940 // These are irrelevant.
1941 return NestingDetected;
1943 // If we have a store into an alloca of a pointer we are tracking, the
1944 // pointer has multiple owners implying that we must be more conservative.
1946 // This comes up in the context of a pointer being ``KnownSafe''. In the
1947 // presense of a block being initialized, the frontend will emit the
1948 // objc_retain on the original pointer and the release on the pointer loaded
1949 // from the alloca. The optimizer will through the provenance analysis
1950 // realize that the two are related, but since we only require KnownSafe in
1951 // one direction, will match the inner retain on the original pointer with
1952 // the guard release on the original pointer. This is fixed by ensuring that
1953 // in the presense of allocas we only unconditionally remove pointers if
1954 // both our retain and our release are KnownSafe.
1955 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1956 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1957 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1958 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1959 if (I != MyStates.bottom_up_ptr_end())
1960 MultiOwnersSet.insert(I->first);
1968 // Consider any other possible effects of this instruction on each
1969 // pointer being tracked.
1970 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1971 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1972 const Value *Ptr = MI->first;
1974 continue; // Handled above.
1975 PtrState &S = MI->second;
1976 Sequence Seq = S.GetSeq();
1978 // Check for possible releases.
1979 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1980 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1982 S.ClearKnownPositiveRefCount();
1985 S.SetSeq(S_CanRelease);
1986 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1990 case S_MovableRelease:
1995 llvm_unreachable("bottom-up pointer in retain state!");
1999 // Check for possible direct uses.
2002 case S_MovableRelease:
2003 if (CanUse(Inst, Ptr, PA, Class)) {
2004 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2006 assert(S.RRI.ReverseInsertPts.empty());
2007 // If this is an invoke instruction, we're scanning it as part of
2008 // one of its successor blocks, since we can't insert code after it
2009 // in its own block, and we don't want to split critical edges.
2010 if (isa<InvokeInst>(Inst))
2011 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2013 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2015 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2016 } else if (Seq == S_Release && IsUser(Class)) {
2017 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2019 // Non-movable releases depend on any possible objc pointer use.
2021 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2022 assert(S.RRI.ReverseInsertPts.empty());
2023 // As above; handle invoke specially.
2024 if (isa<InvokeInst>(Inst))
2025 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2027 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2031 if (CanUse(Inst, Ptr, PA, Class)) {
2032 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2035 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2043 llvm_unreachable("bottom-up pointer in retain state!");
2047 return NestingDetected;
2051 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2052 DenseMap<const BasicBlock *, BBState> &BBStates,
2053 MapVector<Value *, RRInfo> &Retains) {
2055 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2057 bool NestingDetected = false;
2058 BBState &MyStates = BBStates[BB];
2060 // Merge the states from each successor to compute the initial state
2061 // for the current block.
2062 BBState::edge_iterator SI(MyStates.succ_begin()),
2063 SE(MyStates.succ_end());
2065 const BasicBlock *Succ = *SI;
2066 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2067 assert(I != BBStates.end());
2068 MyStates.InitFromSucc(I->second);
2070 for (; SI != SE; ++SI) {
2072 I = BBStates.find(Succ);
2073 assert(I != BBStates.end());
2074 MyStates.MergeSucc(I->second);
2078 // If ARC Annotations are enabled, output the current state of pointers at the
2079 // bottom of the basic block.
2080 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2082 // Visit all the instructions, bottom-up.
2083 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2084 Instruction *Inst = llvm::prior(I);
2086 // Invoke instructions are visited as part of their successors (below).
2087 if (isa<InvokeInst>(Inst))
2090 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2092 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2095 // If there's a predecessor with an invoke, visit the invoke as if it were
2096 // part of this block, since we can't insert code after an invoke in its own
2097 // block, and we don't want to split critical edges.
2098 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2099 PE(MyStates.pred_end()); PI != PE; ++PI) {
2100 BasicBlock *Pred = *PI;
2101 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2102 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2105 // If ARC Annotations are enabled, output the current state of pointers at the
2106 // top of the basic block.
2107 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2109 return NestingDetected;
2113 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2114 DenseMap<Value *, RRInfo> &Releases,
2115 BBState &MyStates) {
2116 bool NestingDetected = false;
2117 InstructionClass Class = GetInstructionClass(Inst);
2118 const Value *Arg = 0;
2121 case IC_RetainBlock:
2122 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2123 // objc_retainBlocks to objc_retains. Thus at this point any
2124 // objc_retainBlocks that we see are not optimizable.
2128 Arg = GetObjCArg(Inst);
2130 PtrState &S = MyStates.getPtrTopDownState(Arg);
2132 // Don't do retain+release tracking for IC_RetainRV, because it's
2133 // better to let it remain as the first instruction after a call.
2134 if (Class != IC_RetainRV) {
2135 // If we see two retains in a row on the same pointer. If so, make
2136 // a note, and we'll cicle back to revisit it after we've
2137 // hopefully eliminated the second retain, which may allow us to
2138 // eliminate the first retain too.
2139 // Theoretically we could implement removal of nested retain+release
2140 // pairs by making PtrState hold a stack of states, but this is
2141 // simple and avoids adding overhead for the non-nested case.
2142 if (S.GetSeq() == S_Retain)
2143 NestingDetected = true;
2145 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2146 S.ResetSequenceProgress(S_Retain);
2147 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2148 S.RRI.Calls.insert(Inst);
2151 S.SetKnownPositiveRefCount();
2153 // A retain can be a potential use; procede to the generic checking
2158 Arg = GetObjCArg(Inst);
2160 PtrState &S = MyStates.getPtrTopDownState(Arg);
2161 S.ClearKnownPositiveRefCount();
2163 Sequence OldSeq = S.GetSeq();
2165 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2170 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2171 S.RRI.ReverseInsertPts.clear();
2174 S.RRI.ReleaseMetadata = ReleaseMetadata;
2175 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2176 Releases[Inst] = S.RRI;
2177 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2178 S.ClearSequenceProgress();
2184 case S_MovableRelease:
2185 llvm_unreachable("top-down pointer in release state!");
2189 case IC_AutoreleasepoolPop:
2190 // Conservatively, clear MyStates for all known pointers.
2191 MyStates.clearTopDownPointers();
2192 return NestingDetected;
2193 case IC_AutoreleasepoolPush:
2195 // These are irrelevant.
2196 return NestingDetected;
2201 // Consider any other possible effects of this instruction on each
2202 // pointer being tracked.
2203 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2204 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2205 const Value *Ptr = MI->first;
2207 continue; // Handled above.
2208 PtrState &S = MI->second;
2209 Sequence Seq = S.GetSeq();
2211 // Check for possible releases.
2212 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2213 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2215 S.ClearKnownPositiveRefCount();
2218 S.SetSeq(S_CanRelease);
2219 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2220 assert(S.RRI.ReverseInsertPts.empty());
2221 S.RRI.ReverseInsertPts.insert(Inst);
2223 // One call can't cause a transition from S_Retain to S_CanRelease
2224 // and S_CanRelease to S_Use. If we've made the first transition,
2233 case S_MovableRelease:
2234 llvm_unreachable("top-down pointer in release state!");
2238 // Check for possible direct uses.
2241 if (CanUse(Inst, Ptr, PA, Class)) {
2242 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2245 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2254 case S_MovableRelease:
2255 llvm_unreachable("top-down pointer in release state!");
2259 return NestingDetected;
2263 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2264 DenseMap<const BasicBlock *, BBState> &BBStates,
2265 DenseMap<Value *, RRInfo> &Releases) {
2266 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2267 bool NestingDetected = false;
2268 BBState &MyStates = BBStates[BB];
2270 // Merge the states from each predecessor to compute the initial state
2271 // for the current block.
2272 BBState::edge_iterator PI(MyStates.pred_begin()),
2273 PE(MyStates.pred_end());
2275 const BasicBlock *Pred = *PI;
2276 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2277 assert(I != BBStates.end());
2278 MyStates.InitFromPred(I->second);
2280 for (; PI != PE; ++PI) {
2282 I = BBStates.find(Pred);
2283 assert(I != BBStates.end());
2284 MyStates.MergePred(I->second);
2288 // If ARC Annotations are enabled, output the current state of pointers at the
2289 // top of the basic block.
2290 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2292 // Visit all the instructions, top-down.
2293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2294 Instruction *Inst = I;
2296 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2298 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2301 // If ARC Annotations are enabled, output the current state of pointers at the
2302 // bottom of the basic block.
2303 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2305 #ifdef ARC_ANNOTATIONS
2306 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2308 CheckForCFGHazards(BB, BBStates, MyStates);
2309 return NestingDetected;
2313 ComputePostOrders(Function &F,
2314 SmallVectorImpl<BasicBlock *> &PostOrder,
2315 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2316 unsigned NoObjCARCExceptionsMDKind,
2317 DenseMap<const BasicBlock *, BBState> &BBStates) {
2318 /// The visited set, for doing DFS walks.
2319 SmallPtrSet<BasicBlock *, 16> Visited;
2321 // Do DFS, computing the PostOrder.
2322 SmallPtrSet<BasicBlock *, 16> OnStack;
2323 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2325 // Functions always have exactly one entry block, and we don't have
2326 // any other block that we treat like an entry block.
2327 BasicBlock *EntryBB = &F.getEntryBlock();
2328 BBState &MyStates = BBStates[EntryBB];
2329 MyStates.SetAsEntry();
2330 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2331 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2332 Visited.insert(EntryBB);
2333 OnStack.insert(EntryBB);
2336 BasicBlock *CurrBB = SuccStack.back().first;
2337 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2338 succ_iterator SE(TI, false);
2340 while (SuccStack.back().second != SE) {
2341 BasicBlock *SuccBB = *SuccStack.back().second++;
2342 if (Visited.insert(SuccBB)) {
2343 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2344 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2345 BBStates[CurrBB].addSucc(SuccBB);
2346 BBState &SuccStates = BBStates[SuccBB];
2347 SuccStates.addPred(CurrBB);
2348 OnStack.insert(SuccBB);
2352 if (!OnStack.count(SuccBB)) {
2353 BBStates[CurrBB].addSucc(SuccBB);
2354 BBStates[SuccBB].addPred(CurrBB);
2357 OnStack.erase(CurrBB);
2358 PostOrder.push_back(CurrBB);
2359 SuccStack.pop_back();
2360 } while (!SuccStack.empty());
2364 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2365 // Functions may have many exits, and there also blocks which we treat
2366 // as exits due to ignored edges.
2367 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2368 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2369 BasicBlock *ExitBB = I;
2370 BBState &MyStates = BBStates[ExitBB];
2371 if (!MyStates.isExit())
2374 MyStates.SetAsExit();
2376 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2377 Visited.insert(ExitBB);
2378 while (!PredStack.empty()) {
2379 reverse_dfs_next_succ:
2380 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2381 while (PredStack.back().second != PE) {
2382 BasicBlock *BB = *PredStack.back().second++;
2383 if (Visited.insert(BB)) {
2384 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2385 goto reverse_dfs_next_succ;
2388 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2393 // Visit the function both top-down and bottom-up.
2395 ObjCARCOpt::Visit(Function &F,
2396 DenseMap<const BasicBlock *, BBState> &BBStates,
2397 MapVector<Value *, RRInfo> &Retains,
2398 DenseMap<Value *, RRInfo> &Releases) {
2400 // Use reverse-postorder traversals, because we magically know that loops
2401 // will be well behaved, i.e. they won't repeatedly call retain on a single
2402 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2403 // class here because we want the reverse-CFG postorder to consider each
2404 // function exit point, and we want to ignore selected cycle edges.
2405 SmallVector<BasicBlock *, 16> PostOrder;
2406 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2407 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2408 NoObjCARCExceptionsMDKind,
2411 // Use reverse-postorder on the reverse CFG for bottom-up.
2412 bool BottomUpNestingDetected = false;
2413 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2414 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2416 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2418 // Use reverse-postorder for top-down.
2419 bool TopDownNestingDetected = false;
2420 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2421 PostOrder.rbegin(), E = PostOrder.rend();
2423 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2425 return TopDownNestingDetected && BottomUpNestingDetected;
2428 /// Move the calls in RetainsToMove and ReleasesToMove.
2429 void ObjCARCOpt::MoveCalls(Value *Arg,
2430 RRInfo &RetainsToMove,
2431 RRInfo &ReleasesToMove,
2432 MapVector<Value *, RRInfo> &Retains,
2433 DenseMap<Value *, RRInfo> &Releases,
2434 SmallVectorImpl<Instruction *> &DeadInsts,
2436 Type *ArgTy = Arg->getType();
2437 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2439 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2441 // Insert the new retain and release calls.
2442 for (SmallPtrSet<Instruction *, 2>::const_iterator
2443 PI = ReleasesToMove.ReverseInsertPts.begin(),
2444 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2445 Instruction *InsertPt = *PI;
2446 Value *MyArg = ArgTy == ParamTy ? Arg :
2447 new BitCastInst(Arg, ParamTy, "", InsertPt);
2449 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2450 Call->setDoesNotThrow();
2451 Call->setTailCall();
2453 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2454 "At insertion point: " << *InsertPt << "\n");
2456 for (SmallPtrSet<Instruction *, 2>::const_iterator
2457 PI = RetainsToMove.ReverseInsertPts.begin(),
2458 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2459 Instruction *InsertPt = *PI;
2460 Value *MyArg = ArgTy == ParamTy ? Arg :
2461 new BitCastInst(Arg, ParamTy, "", InsertPt);
2462 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2464 // Attach a clang.imprecise_release metadata tag, if appropriate.
2465 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2466 Call->setMetadata(ImpreciseReleaseMDKind, M);
2467 Call->setDoesNotThrow();
2468 if (ReleasesToMove.IsTailCallRelease)
2469 Call->setTailCall();
2471 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2472 "At insertion point: " << *InsertPt << "\n");
2475 // Delete the original retain and release calls.
2476 for (SmallPtrSet<Instruction *, 2>::const_iterator
2477 AI = RetainsToMove.Calls.begin(),
2478 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2479 Instruction *OrigRetain = *AI;
2480 Retains.blot(OrigRetain);
2481 DeadInsts.push_back(OrigRetain);
2482 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2484 for (SmallPtrSet<Instruction *, 2>::const_iterator
2485 AI = ReleasesToMove.Calls.begin(),
2486 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2487 Instruction *OrigRelease = *AI;
2488 Releases.erase(OrigRelease);
2489 DeadInsts.push_back(OrigRelease);
2490 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2496 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2498 MapVector<Value *, RRInfo> &Retains,
2499 DenseMap<Value *, RRInfo> &Releases,
2501 SmallVector<Instruction *, 4> &NewRetains,
2502 SmallVector<Instruction *, 4> &NewReleases,
2503 SmallVector<Instruction *, 8> &DeadInsts,
2504 RRInfo &RetainsToMove,
2505 RRInfo &ReleasesToMove,
2508 bool &AnyPairsCompletelyEliminated) {
2509 // If a pair happens in a region where it is known that the reference count
2510 // is already incremented, we can similarly ignore possible decrements unless
2511 // we are dealing with a retainable object with multiple provenance sources.
2512 bool KnownSafeTD = true, KnownSafeBU = true;
2513 bool MultipleOwners = false;
2514 bool CFGHazardAfflicted = false;
2516 // Connect the dots between the top-down-collected RetainsToMove and
2517 // bottom-up-collected ReleasesToMove to form sets of related calls.
2518 // This is an iterative process so that we connect multiple releases
2519 // to multiple retains if needed.
2520 unsigned OldDelta = 0;
2521 unsigned NewDelta = 0;
2522 unsigned OldCount = 0;
2523 unsigned NewCount = 0;
2524 bool FirstRelease = true;
2526 for (SmallVectorImpl<Instruction *>::const_iterator
2527 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2528 Instruction *NewRetain = *NI;
2529 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2530 assert(It != Retains.end());
2531 const RRInfo &NewRetainRRI = It->second;
2532 KnownSafeTD &= NewRetainRRI.KnownSafe;
2534 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2535 for (SmallPtrSet<Instruction *, 2>::const_iterator
2536 LI = NewRetainRRI.Calls.begin(),
2537 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2538 Instruction *NewRetainRelease = *LI;
2539 DenseMap<Value *, RRInfo>::const_iterator Jt =
2540 Releases.find(NewRetainRelease);
2541 if (Jt == Releases.end())
2543 const RRInfo &NewRetainReleaseRRI = Jt->second;
2544 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2545 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2547 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2549 // Merge the ReleaseMetadata and IsTailCallRelease values.
2551 ReleasesToMove.ReleaseMetadata =
2552 NewRetainReleaseRRI.ReleaseMetadata;
2553 ReleasesToMove.IsTailCallRelease =
2554 NewRetainReleaseRRI.IsTailCallRelease;
2555 FirstRelease = false;
2557 if (ReleasesToMove.ReleaseMetadata !=
2558 NewRetainReleaseRRI.ReleaseMetadata)
2559 ReleasesToMove.ReleaseMetadata = 0;
2560 if (ReleasesToMove.IsTailCallRelease !=
2561 NewRetainReleaseRRI.IsTailCallRelease)
2562 ReleasesToMove.IsTailCallRelease = false;
2565 // Collect the optimal insertion points.
2567 for (SmallPtrSet<Instruction *, 2>::const_iterator
2568 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2569 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2571 Instruction *RIP = *RI;
2572 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2573 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2575 NewReleases.push_back(NewRetainRelease);
2580 if (NewReleases.empty()) break;
2582 // Back the other way.
2583 for (SmallVectorImpl<Instruction *>::const_iterator
2584 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2585 Instruction *NewRelease = *NI;
2586 DenseMap<Value *, RRInfo>::const_iterator It =
2587 Releases.find(NewRelease);
2588 assert(It != Releases.end());
2589 const RRInfo &NewReleaseRRI = It->second;
2590 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2591 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2592 for (SmallPtrSet<Instruction *, 2>::const_iterator
2593 LI = NewReleaseRRI.Calls.begin(),
2594 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2595 Instruction *NewReleaseRetain = *LI;
2596 MapVector<Value *, RRInfo>::const_iterator Jt =
2597 Retains.find(NewReleaseRetain);
2598 if (Jt == Retains.end())
2600 const RRInfo &NewReleaseRetainRRI = Jt->second;
2601 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2602 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2603 unsigned PathCount =
2604 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2605 OldDelta += PathCount;
2606 OldCount += PathCount;
2608 // Collect the optimal insertion points.
2610 for (SmallPtrSet<Instruction *, 2>::const_iterator
2611 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2612 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2614 Instruction *RIP = *RI;
2615 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2616 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2617 NewDelta += PathCount;
2618 NewCount += PathCount;
2621 NewRetains.push_back(NewReleaseRetain);
2625 NewReleases.clear();
2626 if (NewRetains.empty()) break;
2629 // If the pointer is known incremented in 1 direction and we do not have
2630 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2631 // to be known safe in both directions.
2632 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2633 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2634 if (UnconditionallySafe) {
2635 RetainsToMove.ReverseInsertPts.clear();
2636 ReleasesToMove.ReverseInsertPts.clear();
2639 // Determine whether the new insertion points we computed preserve the
2640 // balance of retain and release calls through the program.
2641 // TODO: If the fully aggressive solution isn't valid, try to find a
2642 // less aggressive solution which is.
2646 // At this point, we are not going to remove any RR pairs, but we still are
2647 // able to move RR pairs. If one of our pointers is afflicted with
2648 // CFGHazards, we cannot perform such code motion so exit early.
2649 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2650 ReleasesToMove.ReverseInsertPts.size();
2651 if (CFGHazardAfflicted && WillPerformCodeMotion)
2655 // Determine whether the original call points are balanced in the retain and
2656 // release calls through the program. If not, conservatively don't touch
2658 // TODO: It's theoretically possible to do code motion in this case, as
2659 // long as the existing imbalances are maintained.
2663 #ifdef ARC_ANNOTATIONS
2664 // Do not move calls if ARC annotations are requested.
2665 if (EnableARCAnnotations)
2667 #endif // ARC_ANNOTATIONS
2670 assert(OldCount != 0 && "Unreachable code?");
2671 NumRRs += OldCount - NewCount;
2672 // Set to true if we completely removed any RR pairs.
2673 AnyPairsCompletelyEliminated = NewCount == 0;
2675 // We can move calls!
2679 /// Identify pairings between the retains and releases, and delete and/or move
2682 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2684 MapVector<Value *, RRInfo> &Retains,
2685 DenseMap<Value *, RRInfo> &Releases,
2687 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2689 bool AnyPairsCompletelyEliminated = false;
2690 RRInfo RetainsToMove;
2691 RRInfo ReleasesToMove;
2692 SmallVector<Instruction *, 4> NewRetains;
2693 SmallVector<Instruction *, 4> NewReleases;
2694 SmallVector<Instruction *, 8> DeadInsts;
2696 // Visit each retain.
2697 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2698 E = Retains.end(); I != E; ++I) {
2699 Value *V = I->first;
2700 if (!V) continue; // blotted
2702 Instruction *Retain = cast<Instruction>(V);
2704 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2706 Value *Arg = GetObjCArg(Retain);
2708 // If the object being released is in static or stack storage, we know it's
2709 // not being managed by ObjC reference counting, so we can delete pairs
2710 // regardless of what possible decrements or uses lie between them.
2711 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2713 // A constant pointer can't be pointing to an object on the heap. It may
2714 // be reference-counted, but it won't be deleted.
2715 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2716 if (const GlobalVariable *GV =
2717 dyn_cast<GlobalVariable>(
2718 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2719 if (GV->isConstant())
2722 // Connect the dots between the top-down-collected RetainsToMove and
2723 // bottom-up-collected ReleasesToMove to form sets of related calls.
2724 NewRetains.push_back(Retain);
2725 bool PerformMoveCalls =
2726 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2727 NewReleases, DeadInsts, RetainsToMove,
2728 ReleasesToMove, Arg, KnownSafe,
2729 AnyPairsCompletelyEliminated);
2731 if (PerformMoveCalls) {
2732 // Ok, everything checks out and we're all set. Let's move/delete some
2734 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2735 Retains, Releases, DeadInsts, M);
2738 // Clean up state for next retain.
2739 NewReleases.clear();
2741 RetainsToMove.clear();
2742 ReleasesToMove.clear();
2745 // Now that we're done moving everything, we can delete the newly dead
2746 // instructions, as we no longer need them as insert points.
2747 while (!DeadInsts.empty())
2748 EraseInstruction(DeadInsts.pop_back_val());
2750 return AnyPairsCompletelyEliminated;
2753 /// Weak pointer optimizations.
2754 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2755 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2757 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2758 // itself because it uses AliasAnalysis and we need to do provenance
2760 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2761 Instruction *Inst = &*I++;
2763 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2765 InstructionClass Class = GetBasicInstructionClass(Inst);
2766 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2769 // Delete objc_loadWeak calls with no users.
2770 if (Class == IC_LoadWeak && Inst->use_empty()) {
2771 Inst->eraseFromParent();
2775 // TODO: For now, just look for an earlier available version of this value
2776 // within the same block. Theoretically, we could do memdep-style non-local
2777 // analysis too, but that would want caching. A better approach would be to
2778 // use the technique that EarlyCSE uses.
2779 inst_iterator Current = llvm::prior(I);
2780 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2781 for (BasicBlock::iterator B = CurrentBB->begin(),
2782 J = Current.getInstructionIterator();
2784 Instruction *EarlierInst = &*llvm::prior(J);
2785 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2786 switch (EarlierClass) {
2788 case IC_LoadWeakRetained: {
2789 // If this is loading from the same pointer, replace this load's value
2791 CallInst *Call = cast<CallInst>(Inst);
2792 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2793 Value *Arg = Call->getArgOperand(0);
2794 Value *EarlierArg = EarlierCall->getArgOperand(0);
2795 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2796 case AliasAnalysis::MustAlias:
2798 // If the load has a builtin retain, insert a plain retain for it.
2799 if (Class == IC_LoadWeakRetained) {
2801 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2805 // Zap the fully redundant load.
2806 Call->replaceAllUsesWith(EarlierCall);
2807 Call->eraseFromParent();
2809 case AliasAnalysis::MayAlias:
2810 case AliasAnalysis::PartialAlias:
2812 case AliasAnalysis::NoAlias:
2819 // If this is storing to the same pointer and has the same size etc.
2820 // replace this load's value with the stored value.
2821 CallInst *Call = cast<CallInst>(Inst);
2822 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2823 Value *Arg = Call->getArgOperand(0);
2824 Value *EarlierArg = EarlierCall->getArgOperand(0);
2825 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2826 case AliasAnalysis::MustAlias:
2828 // If the load has a builtin retain, insert a plain retain for it.
2829 if (Class == IC_LoadWeakRetained) {
2831 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2835 // Zap the fully redundant load.
2836 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2837 Call->eraseFromParent();
2839 case AliasAnalysis::MayAlias:
2840 case AliasAnalysis::PartialAlias:
2842 case AliasAnalysis::NoAlias:
2849 // TOOD: Grab the copied value.
2851 case IC_AutoreleasepoolPush:
2853 case IC_IntrinsicUser:
2855 // Weak pointers are only modified through the weak entry points
2856 // (and arbitrary calls, which could call the weak entry points).
2859 // Anything else could modify the weak pointer.
2866 // Then, for each destroyWeak with an alloca operand, check to see if
2867 // the alloca and all its users can be zapped.
2868 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2869 Instruction *Inst = &*I++;
2870 InstructionClass Class = GetBasicInstructionClass(Inst);
2871 if (Class != IC_DestroyWeak)
2874 CallInst *Call = cast<CallInst>(Inst);
2875 Value *Arg = Call->getArgOperand(0);
2876 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2877 for (Value::use_iterator UI = Alloca->use_begin(),
2878 UE = Alloca->use_end(); UI != UE; ++UI) {
2879 const Instruction *UserInst = cast<Instruction>(*UI);
2880 switch (GetBasicInstructionClass(UserInst)) {
2883 case IC_DestroyWeak:
2890 for (Value::use_iterator UI = Alloca->use_begin(),
2891 UE = Alloca->use_end(); UI != UE; ) {
2892 CallInst *UserInst = cast<CallInst>(*UI++);
2893 switch (GetBasicInstructionClass(UserInst)) {
2896 // These functions return their second argument.
2897 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2899 case IC_DestroyWeak:
2903 llvm_unreachable("alloca really is used!");
2905 UserInst->eraseFromParent();
2907 Alloca->eraseFromParent();
2913 /// Identify program paths which execute sequences of retains and releases which
2914 /// can be eliminated.
2915 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2916 // Releases, Retains - These are used to store the results of the main flow
2917 // analysis. These use Value* as the key instead of Instruction* so that the
2918 // map stays valid when we get around to rewriting code and calls get
2919 // replaced by arguments.
2920 DenseMap<Value *, RRInfo> Releases;
2921 MapVector<Value *, RRInfo> Retains;
2923 // This is used during the traversal of the function to track the
2924 // states for each identified object at each block.
2925 DenseMap<const BasicBlock *, BBState> BBStates;
2927 // Analyze the CFG of the function, and all instructions.
2928 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2931 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2936 MultiOwnersSet.clear();
2938 return AnyPairsCompletelyEliminated && NestingDetected;
2941 /// Check if there is a dependent call earlier that does not have anything in
2942 /// between the Retain and the call that can affect the reference count of their
2943 /// shared pointer argument. Note that Retain need not be in BB.
2945 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2946 SmallPtrSet<Instruction *, 4> &DepInsts,
2947 SmallPtrSet<const BasicBlock *, 4> &Visited,
2948 ProvenanceAnalysis &PA) {
2949 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2950 DepInsts, Visited, PA);
2951 if (DepInsts.size() != 1)
2955 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2957 // Check that the pointer is the return value of the call.
2958 if (!Call || Arg != Call)
2961 // Check that the call is a regular call.
2962 InstructionClass Class = GetBasicInstructionClass(Call);
2963 if (Class != IC_CallOrUser && Class != IC_Call)
2969 /// Find a dependent retain that precedes the given autorelease for which there
2970 /// is nothing in between the two instructions that can affect the ref count of
2973 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2974 Instruction *Autorelease,
2975 SmallPtrSet<Instruction *, 4> &DepInsts,
2976 SmallPtrSet<const BasicBlock *, 4> &Visited,
2977 ProvenanceAnalysis &PA) {
2978 FindDependencies(CanChangeRetainCount, Arg,
2979 BB, Autorelease, DepInsts, Visited, PA);
2980 if (DepInsts.size() != 1)
2984 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2986 // Check that we found a retain with the same argument.
2988 !IsRetain(GetBasicInstructionClass(Retain)) ||
2989 GetObjCArg(Retain) != Arg) {
2996 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
2997 /// no instructions dependent on Arg that need a positive ref count in between
2998 /// the autorelease and the ret.
3000 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3002 SmallPtrSet<Instruction *, 4> &DepInsts,
3003 SmallPtrSet<const BasicBlock *, 4> &V,
3004 ProvenanceAnalysis &PA) {
3005 FindDependencies(NeedsPositiveRetainCount, Arg,
3006 BB, Ret, DepInsts, V, PA);
3007 if (DepInsts.size() != 1)
3010 CallInst *Autorelease =
3011 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3014 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3015 if (!IsAutorelease(AutoreleaseClass))
3017 if (GetObjCArg(Autorelease) != Arg)
3023 /// Look for this pattern:
3025 /// %call = call i8* @something(...)
3026 /// %2 = call i8* @objc_retain(i8* %call)
3027 /// %3 = call i8* @objc_autorelease(i8* %2)
3030 /// And delete the retain and autorelease.
3031 void ObjCARCOpt::OptimizeReturns(Function &F) {
3032 if (!F.getReturnType()->isPointerTy())
3035 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3037 SmallPtrSet<Instruction *, 4> DependingInstructions;
3038 SmallPtrSet<const BasicBlock *, 4> Visited;
3039 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3040 BasicBlock *BB = FI;
3041 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3043 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3048 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3050 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3051 // dependent on Arg such that there are no instructions dependent on Arg
3052 // that need a positive ref count in between the autorelease and Ret.
3053 CallInst *Autorelease =
3054 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3055 DependingInstructions, Visited,
3057 DependingInstructions.clear();
3064 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3065 DependingInstructions, Visited, PA);
3066 DependingInstructions.clear();
3072 // Check that there is nothing that can affect the reference count
3073 // between the retain and the call. Note that Retain need not be in BB.
3074 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3075 DependingInstructions,
3077 DependingInstructions.clear();
3080 if (!HasSafePathToCall)
3083 // If so, we can zap the retain and autorelease.
3086 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3087 << *Autorelease << "\n");
3088 EraseInstruction(Retain);
3089 EraseInstruction(Autorelease);
3095 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3096 llvm::Statistic &NumRetains =
3097 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3098 llvm::Statistic &NumReleases =
3099 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3101 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3102 Instruction *Inst = &*I++;
3103 switch (GetBasicInstructionClass(Inst)) {
3117 bool ObjCARCOpt::doInitialization(Module &M) {
3121 // If nothing in the Module uses ARC, don't do anything.
3122 Run = ModuleHasARC(M);
3126 // Identify the imprecise release metadata kind.
3127 ImpreciseReleaseMDKind =
3128 M.getContext().getMDKindID("clang.imprecise_release");
3129 CopyOnEscapeMDKind =
3130 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3131 NoObjCARCExceptionsMDKind =
3132 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3133 #ifdef ARC_ANNOTATIONS
3134 ARCAnnotationBottomUpMDKind =
3135 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3136 ARCAnnotationTopDownMDKind =
3137 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3138 ARCAnnotationProvenanceSourceMDKind =
3139 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3140 #endif // ARC_ANNOTATIONS
3142 // Intuitively, objc_retain and others are nocapture, however in practice
3143 // they are not, because they return their argument value. And objc_release
3144 // calls finalizers which can have arbitrary side effects.
3146 // These are initialized lazily.
3147 AutoreleaseRVCallee = 0;
3150 RetainBlockCallee = 0;
3151 AutoreleaseCallee = 0;
3156 bool ObjCARCOpt::runOnFunction(Function &F) {
3160 // If nothing in the Module uses ARC, don't do anything.
3166 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3169 PA.setAA(&getAnalysis<AliasAnalysis>());
3172 if (AreStatisticsEnabled()) {
3173 GatherStatistics(F, false);
3177 // This pass performs several distinct transformations. As a compile-time aid
3178 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3179 // library functions aren't declared.
3181 // Preliminary optimizations. This also computes UsedInThisFunction.
3182 OptimizeIndividualCalls(F);
3184 // Optimizations for weak pointers.
3185 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3186 (1 << IC_LoadWeakRetained) |
3187 (1 << IC_StoreWeak) |
3188 (1 << IC_InitWeak) |
3189 (1 << IC_CopyWeak) |
3190 (1 << IC_MoveWeak) |
3191 (1 << IC_DestroyWeak)))
3192 OptimizeWeakCalls(F);
3194 // Optimizations for retain+release pairs.
3195 if (UsedInThisFunction & ((1 << IC_Retain) |
3196 (1 << IC_RetainRV) |
3197 (1 << IC_RetainBlock)))
3198 if (UsedInThisFunction & (1 << IC_Release))
3199 // Run OptimizeSequences until it either stops making changes or
3200 // no retain+release pair nesting is detected.
3201 while (OptimizeSequences(F)) {}
3203 // Optimizations if objc_autorelease is used.
3204 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3205 (1 << IC_AutoreleaseRV)))
3208 // Gather statistics after optimization.
3210 if (AreStatisticsEnabled()) {
3211 GatherStatistics(F, true);
3215 DEBUG(dbgs() << "\n");
3220 void ObjCARCOpt::releaseMemory() {