xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file defines ObjC ARC optimizations. ARC stands for Automatic
110b57cec5SDimitry Andric /// Reference Counting and is a system for managing reference counts for objects
120b57cec5SDimitry Andric /// in Objective C.
130b57cec5SDimitry Andric ///
140b57cec5SDimitry Andric /// The optimizations performed include elimination of redundant, partially
150b57cec5SDimitry Andric /// redundant, and inconsequential reference count operations, elimination of
160b57cec5SDimitry Andric /// redundant weak pointer operations, and numerous minor simplifications.
170b57cec5SDimitry Andric ///
180b57cec5SDimitry Andric /// WARNING: This file knows about certain library functions. It recognizes them
190b57cec5SDimitry Andric /// by name, and hardwires knowledge of their semantics.
200b57cec5SDimitry Andric ///
210b57cec5SDimitry Andric /// WARNING: This file knows about how certain Objective-C library functions are
220b57cec5SDimitry Andric /// used. Naive LLVM IR transformations which would otherwise be
230b57cec5SDimitry Andric /// behavior-preserving may break these assumptions.
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric #include "ARCRuntimeEntryPoints.h"
280b57cec5SDimitry Andric #include "BlotMapVector.h"
290b57cec5SDimitry Andric #include "DependencyAnalysis.h"
300b57cec5SDimitry Andric #include "ObjCARC.h"
310b57cec5SDimitry Andric #include "ProvenanceAnalysis.h"
320b57cec5SDimitry Andric #include "PtrState.h"
330b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
340b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
350b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
360b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
370b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
380b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
390b57cec5SDimitry Andric #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
400b57cec5SDimitry Andric #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
410b57cec5SDimitry Andric #include "llvm/Analysis/ObjCARCInstKind.h"
42fe6060f1SDimitry Andric #include "llvm/Analysis/ObjCARCUtil.h"
430b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
440b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
450b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
460b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
470b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
4806c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
490b57cec5SDimitry Andric #include "llvm/IR/Function.h"
500b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
510b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
520b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
530b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
540b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
550b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
560b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
570b57cec5SDimitry Andric #include "llvm/IR/Type.h"
580b57cec5SDimitry Andric #include "llvm/IR/User.h"
590b57cec5SDimitry Andric #include "llvm/IR/Value.h"
600b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
61480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
620b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
630b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
640b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
650b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
66e8d8bef9SDimitry Andric #include "llvm/Transforms/ObjCARC.h"
670b57cec5SDimitry Andric #include <cassert>
680b57cec5SDimitry Andric #include <iterator>
690b57cec5SDimitry Andric #include <utility>
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric using namespace llvm;
720b57cec5SDimitry Andric using namespace llvm::objcarc;
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric #define DEBUG_TYPE "objc-arc-opts"
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric static cl::opt<unsigned> MaxPtrStates("arc-opt-max-ptr-states",
770b57cec5SDimitry Andric     cl::Hidden,
780b57cec5SDimitry Andric     cl::desc("Maximum number of ptr states the optimizer keeps track of"),
790b57cec5SDimitry Andric     cl::init(4095));
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
820b57cec5SDimitry Andric /// @{
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric /// This is similar to GetRCIdentityRoot but it stops as soon
850b57cec5SDimitry Andric /// as it finds a value with multiple uses.
860b57cec5SDimitry Andric static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
870b57cec5SDimitry Andric   // ConstantData (like ConstantPointerNull and UndefValue) is used across
880b57cec5SDimitry Andric   // modules.  It's never a single-use value.
890b57cec5SDimitry Andric   if (isa<ConstantData>(Arg))
900b57cec5SDimitry Andric     return nullptr;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   if (Arg->hasOneUse()) {
930b57cec5SDimitry Andric     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
940b57cec5SDimitry Andric       return FindSingleUseIdentifiedObject(BC->getOperand(0));
950b57cec5SDimitry Andric     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
960b57cec5SDimitry Andric       if (GEP->hasAllZeroIndices())
970b57cec5SDimitry Andric         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
980b57cec5SDimitry Andric     if (IsForwarding(GetBasicARCInstKind(Arg)))
990b57cec5SDimitry Andric       return FindSingleUseIdentifiedObject(
1000b57cec5SDimitry Andric                cast<CallInst>(Arg)->getArgOperand(0));
1010b57cec5SDimitry Andric     if (!IsObjCIdentifiedObject(Arg))
1020b57cec5SDimitry Andric       return nullptr;
1030b57cec5SDimitry Andric     return Arg;
1040b57cec5SDimitry Andric   }
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   // If we found an identifiable object but it has multiple uses, but they are
1070b57cec5SDimitry Andric   // trivial uses, we can still consider this to be a single-use value.
1080b57cec5SDimitry Andric   if (IsObjCIdentifiedObject(Arg)) {
1090b57cec5SDimitry Andric     for (const User *U : Arg->users())
1100b57cec5SDimitry Andric       if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
1110b57cec5SDimitry Andric          return nullptr;
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric     return Arg;
1140b57cec5SDimitry Andric   }
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric   return nullptr;
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric /// @}
1200b57cec5SDimitry Andric ///
1210b57cec5SDimitry Andric /// \defgroup ARCOpt ARC Optimization.
1220b57cec5SDimitry Andric /// @{
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric // TODO: On code like this:
1250b57cec5SDimitry Andric //
1260b57cec5SDimitry Andric // objc_retain(%x)
1270b57cec5SDimitry Andric // stuff_that_cannot_release()
1280b57cec5SDimitry Andric // objc_autorelease(%x)
1290b57cec5SDimitry Andric // stuff_that_cannot_release()
1300b57cec5SDimitry Andric // objc_retain(%x)
1310b57cec5SDimitry Andric // stuff_that_cannot_release()
1320b57cec5SDimitry Andric // objc_autorelease(%x)
1330b57cec5SDimitry Andric //
1340b57cec5SDimitry Andric // The second retain and autorelease can be deleted.
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric // TODO: It should be possible to delete
1370b57cec5SDimitry Andric // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1380b57cec5SDimitry Andric // pairs if nothing is actually autoreleased between them. Also, autorelease
1390b57cec5SDimitry Andric // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1400b57cec5SDimitry Andric // after inlining) can be turned into plain release calls.
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric // TODO: Critical-edge splitting. If the optimial insertion point is
1430b57cec5SDimitry Andric // a critical edge, the current algorithm has to fail, because it doesn't
1440b57cec5SDimitry Andric // know how to split edges. It should be possible to make the optimizer
1450b57cec5SDimitry Andric // think in terms of edges, rather than blocks, and then split critical
1460b57cec5SDimitry Andric // edges on demand.
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric // TODO: OptimizeSequences could generalized to be Interprocedural.
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric // TODO: Recognize that a bunch of other objc runtime calls have
1510b57cec5SDimitry Andric // non-escaping arguments and non-releasing arguments, and may be
1520b57cec5SDimitry Andric // non-autoreleasing.
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric // TODO: Sink autorelease calls as far as possible. Unfortunately we
1550b57cec5SDimitry Andric // usually can't sink them past other calls, which would be the main
1560b57cec5SDimitry Andric // case where it would be useful.
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric // TODO: The pointer returned from objc_loadWeakRetained is retained.
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric // TODO: Delete release+retain pairs (rare).
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
1630b57cec5SDimitry Andric STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1640b57cec5SDimitry Andric STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1650b57cec5SDimitry Andric STATISTIC(NumRets,        "Number of return value forwarding "
1660b57cec5SDimitry Andric                           "retain+autoreleases eliminated");
1670b57cec5SDimitry Andric STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
1680b57cec5SDimitry Andric STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
1690b57cec5SDimitry Andric #ifndef NDEBUG
1700b57cec5SDimitry Andric STATISTIC(NumRetainsBeforeOpt,
1710b57cec5SDimitry Andric           "Number of retains before optimization");
1720b57cec5SDimitry Andric STATISTIC(NumReleasesBeforeOpt,
1730b57cec5SDimitry Andric           "Number of releases before optimization");
1740b57cec5SDimitry Andric STATISTIC(NumRetainsAfterOpt,
1750b57cec5SDimitry Andric           "Number of retains after optimization");
1760b57cec5SDimitry Andric STATISTIC(NumReleasesAfterOpt,
1770b57cec5SDimitry Andric           "Number of releases after optimization");
1780b57cec5SDimitry Andric #endif
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric namespace {
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   /// Per-BasicBlock state.
1830b57cec5SDimitry Andric   class BBState {
1840b57cec5SDimitry Andric     /// The number of unique control paths from the entry which can reach this
1850b57cec5SDimitry Andric     /// block.
1860b57cec5SDimitry Andric     unsigned TopDownPathCount = 0;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric     /// The number of unique control paths to exits from this block.
1890b57cec5SDimitry Andric     unsigned BottomUpPathCount = 0;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric     /// The top-down traversal uses this to record information known about a
1920b57cec5SDimitry Andric     /// pointer at the bottom of each block.
1930b57cec5SDimitry Andric     BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric     /// The bottom-up traversal uses this to record information known about a
1960b57cec5SDimitry Andric     /// pointer at the top of each block.
1970b57cec5SDimitry Andric     BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric     /// Effective predecessors of the current block ignoring ignorable edges and
2000b57cec5SDimitry Andric     /// ignored backedges.
2010b57cec5SDimitry Andric     SmallVector<BasicBlock *, 2> Preds;
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     /// Effective successors of the current block ignoring ignorable edges and
2040b57cec5SDimitry Andric     /// ignored backedges.
2050b57cec5SDimitry Andric     SmallVector<BasicBlock *, 2> Succs;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   public:
2080b57cec5SDimitry Andric     static const unsigned OverflowOccurredValue;
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric     BBState() = default;
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric     using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator;
2130b57cec5SDimitry Andric     using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric     top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
2160b57cec5SDimitry Andric     top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
2170b57cec5SDimitry Andric     const_top_down_ptr_iterator top_down_ptr_begin() const {
2180b57cec5SDimitry Andric       return PerPtrTopDown.begin();
2190b57cec5SDimitry Andric     }
2200b57cec5SDimitry Andric     const_top_down_ptr_iterator top_down_ptr_end() const {
2210b57cec5SDimitry Andric       return PerPtrTopDown.end();
2220b57cec5SDimitry Andric     }
2230b57cec5SDimitry Andric     bool hasTopDownPtrs() const {
2240b57cec5SDimitry Andric       return !PerPtrTopDown.empty();
2250b57cec5SDimitry Andric     }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     unsigned top_down_ptr_list_size() const {
2280b57cec5SDimitry Andric       return std::distance(top_down_ptr_begin(), top_down_ptr_end());
2290b57cec5SDimitry Andric     }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator;
2320b57cec5SDimitry Andric     using const_bottom_up_ptr_iterator =
2330b57cec5SDimitry Andric         decltype(PerPtrBottomUp)::const_iterator;
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     bottom_up_ptr_iterator bottom_up_ptr_begin() {
2360b57cec5SDimitry Andric       return PerPtrBottomUp.begin();
2370b57cec5SDimitry Andric     }
2380b57cec5SDimitry Andric     bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
2390b57cec5SDimitry Andric     const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
2400b57cec5SDimitry Andric       return PerPtrBottomUp.begin();
2410b57cec5SDimitry Andric     }
2420b57cec5SDimitry Andric     const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
2430b57cec5SDimitry Andric       return PerPtrBottomUp.end();
2440b57cec5SDimitry Andric     }
2450b57cec5SDimitry Andric     bool hasBottomUpPtrs() const {
2460b57cec5SDimitry Andric       return !PerPtrBottomUp.empty();
2470b57cec5SDimitry Andric     }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric     unsigned bottom_up_ptr_list_size() const {
2500b57cec5SDimitry Andric       return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end());
2510b57cec5SDimitry Andric     }
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric     /// Mark this block as being an entry block, which has one path from the
2540b57cec5SDimitry Andric     /// entry by definition.
2550b57cec5SDimitry Andric     void SetAsEntry() { TopDownPathCount = 1; }
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     /// Mark this block as being an exit block, which has one path to an exit by
2580b57cec5SDimitry Andric     /// definition.
2590b57cec5SDimitry Andric     void SetAsExit()  { BottomUpPathCount = 1; }
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric     /// Attempt to find the PtrState object describing the top down state for
2620b57cec5SDimitry Andric     /// pointer Arg. Return a new initialized PtrState describing the top down
2630b57cec5SDimitry Andric     /// state for Arg if we do not find one.
2640b57cec5SDimitry Andric     TopDownPtrState &getPtrTopDownState(const Value *Arg) {
2650b57cec5SDimitry Andric       return PerPtrTopDown[Arg];
2660b57cec5SDimitry Andric     }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric     /// Attempt to find the PtrState object describing the bottom up state for
2690b57cec5SDimitry Andric     /// pointer Arg. Return a new initialized PtrState describing the bottom up
2700b57cec5SDimitry Andric     /// state for Arg if we do not find one.
2710b57cec5SDimitry Andric     BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
2720b57cec5SDimitry Andric       return PerPtrBottomUp[Arg];
2730b57cec5SDimitry Andric     }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric     /// Attempt to find the PtrState object describing the bottom up state for
2760b57cec5SDimitry Andric     /// pointer Arg.
2770b57cec5SDimitry Andric     bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
2780b57cec5SDimitry Andric       return PerPtrBottomUp.find(Arg);
2790b57cec5SDimitry Andric     }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric     void clearBottomUpPointers() {
2820b57cec5SDimitry Andric       PerPtrBottomUp.clear();
2830b57cec5SDimitry Andric     }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric     void clearTopDownPointers() {
2860b57cec5SDimitry Andric       PerPtrTopDown.clear();
2870b57cec5SDimitry Andric     }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     void InitFromPred(const BBState &Other);
2900b57cec5SDimitry Andric     void InitFromSucc(const BBState &Other);
2910b57cec5SDimitry Andric     void MergePred(const BBState &Other);
2920b57cec5SDimitry Andric     void MergeSucc(const BBState &Other);
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric     /// Compute the number of possible unique paths from an entry to an exit
2950b57cec5SDimitry Andric     /// which pass through this block. This is only valid after both the
2960b57cec5SDimitry Andric     /// top-down and bottom-up traversals are complete.
2970b57cec5SDimitry Andric     ///
2980b57cec5SDimitry Andric     /// Returns true if overflow occurred. Returns false if overflow did not
2990b57cec5SDimitry Andric     /// occur.
3000b57cec5SDimitry Andric     bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
3010b57cec5SDimitry Andric       if (TopDownPathCount == OverflowOccurredValue ||
3020b57cec5SDimitry Andric           BottomUpPathCount == OverflowOccurredValue)
3030b57cec5SDimitry Andric         return true;
3040b57cec5SDimitry Andric       unsigned long long Product =
3050b57cec5SDimitry Andric         (unsigned long long)TopDownPathCount*BottomUpPathCount;
3060b57cec5SDimitry Andric       // Overflow occurred if any of the upper bits of Product are set or if all
3070b57cec5SDimitry Andric       // the lower bits of Product are all set.
3080b57cec5SDimitry Andric       return (Product >> 32) ||
3090b57cec5SDimitry Andric              ((PathCount = Product) == OverflowOccurredValue);
3100b57cec5SDimitry Andric     }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric     // Specialized CFG utilities.
3130b57cec5SDimitry Andric     using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator;
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric     edge_iterator pred_begin() const { return Preds.begin(); }
3160b57cec5SDimitry Andric     edge_iterator pred_end() const { return Preds.end(); }
3170b57cec5SDimitry Andric     edge_iterator succ_begin() const { return Succs.begin(); }
3180b57cec5SDimitry Andric     edge_iterator succ_end() const { return Succs.end(); }
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
3210b57cec5SDimitry Andric     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     bool isExit() const { return Succs.empty(); }
3240b57cec5SDimitry Andric   };
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric } // end anonymous namespace
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric const unsigned BBState::OverflowOccurredValue = 0xffffffff;
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric namespace llvm {
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS,
3330b57cec5SDimitry Andric                         BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric } // end namespace llvm
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric void BBState::InitFromPred(const BBState &Other) {
3380b57cec5SDimitry Andric   PerPtrTopDown = Other.PerPtrTopDown;
3390b57cec5SDimitry Andric   TopDownPathCount = Other.TopDownPathCount;
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric void BBState::InitFromSucc(const BBState &Other) {
3430b57cec5SDimitry Andric   PerPtrBottomUp = Other.PerPtrBottomUp;
3440b57cec5SDimitry Andric   BottomUpPathCount = Other.BottomUpPathCount;
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric /// The top-down traversal uses this to merge information about predecessors to
3480b57cec5SDimitry Andric /// form the initial state for a new block.
3490b57cec5SDimitry Andric void BBState::MergePred(const BBState &Other) {
3500b57cec5SDimitry Andric   if (TopDownPathCount == OverflowOccurredValue)
3510b57cec5SDimitry Andric     return;
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   // Other.TopDownPathCount can be 0, in which case it is either dead or a
3540b57cec5SDimitry Andric   // loop backedge. Loop backedges are special.
3550b57cec5SDimitry Andric   TopDownPathCount += Other.TopDownPathCount;
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   // In order to be consistent, we clear the top down pointers when by adding
3580b57cec5SDimitry Andric   // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
3590b57cec5SDimitry Andric   // has not occurred.
3600b57cec5SDimitry Andric   if (TopDownPathCount == OverflowOccurredValue) {
3610b57cec5SDimitry Andric     clearTopDownPointers();
3620b57cec5SDimitry Andric     return;
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   // Check for overflow. If we have overflow, fall back to conservative
3660b57cec5SDimitry Andric   // behavior.
3670b57cec5SDimitry Andric   if (TopDownPathCount < Other.TopDownPathCount) {
3680b57cec5SDimitry Andric     TopDownPathCount = OverflowOccurredValue;
3690b57cec5SDimitry Andric     clearTopDownPointers();
3700b57cec5SDimitry Andric     return;
3710b57cec5SDimitry Andric   }
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // For each entry in the other set, if our set has an entry with the same key,
3740b57cec5SDimitry Andric   // merge the entries. Otherwise, copy the entry and merge it with an empty
3750b57cec5SDimitry Andric   // entry.
3760b57cec5SDimitry Andric   for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
3770b57cec5SDimitry Andric        MI != ME; ++MI) {
3780b57cec5SDimitry Andric     auto Pair = PerPtrTopDown.insert(*MI);
3790b57cec5SDimitry Andric     Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
3800b57cec5SDimitry Andric                              /*TopDown=*/true);
3810b57cec5SDimitry Andric   }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   // For each entry in our set, if the other set doesn't have an entry with the
3840b57cec5SDimitry Andric   // same key, force it to merge with an empty entry.
3850b57cec5SDimitry Andric   for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
3860b57cec5SDimitry Andric     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
3870b57cec5SDimitry Andric       MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric /// The bottom-up traversal uses this to merge information about successors to
3910b57cec5SDimitry Andric /// form the initial state for a new block.
3920b57cec5SDimitry Andric void BBState::MergeSucc(const BBState &Other) {
3930b57cec5SDimitry Andric   if (BottomUpPathCount == OverflowOccurredValue)
3940b57cec5SDimitry Andric     return;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
3970b57cec5SDimitry Andric   // loop backedge. Loop backedges are special.
3980b57cec5SDimitry Andric   BottomUpPathCount += Other.BottomUpPathCount;
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   // In order to be consistent, we clear the top down pointers when by adding
4010b57cec5SDimitry Andric   // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
4020b57cec5SDimitry Andric   // has not occurred.
4030b57cec5SDimitry Andric   if (BottomUpPathCount == OverflowOccurredValue) {
4040b57cec5SDimitry Andric     clearBottomUpPointers();
4050b57cec5SDimitry Andric     return;
4060b57cec5SDimitry Andric   }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   // Check for overflow. If we have overflow, fall back to conservative
4090b57cec5SDimitry Andric   // behavior.
4100b57cec5SDimitry Andric   if (BottomUpPathCount < Other.BottomUpPathCount) {
4110b57cec5SDimitry Andric     BottomUpPathCount = OverflowOccurredValue;
4120b57cec5SDimitry Andric     clearBottomUpPointers();
4130b57cec5SDimitry Andric     return;
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   // For each entry in the other set, if our set has an entry with the
4170b57cec5SDimitry Andric   // same key, merge the entries. Otherwise, copy the entry and merge
4180b57cec5SDimitry Andric   // it with an empty entry.
4190b57cec5SDimitry Andric   for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
4200b57cec5SDimitry Andric        MI != ME; ++MI) {
4210b57cec5SDimitry Andric     auto Pair = PerPtrBottomUp.insert(*MI);
4220b57cec5SDimitry Andric     Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
4230b57cec5SDimitry Andric                              /*TopDown=*/false);
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // For each entry in our set, if the other set doesn't have an entry
4270b57cec5SDimitry Andric   // with the same key, force it to merge with an empty entry.
4280b57cec5SDimitry Andric   for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
4290b57cec5SDimitry Andric        ++MI)
4300b57cec5SDimitry Andric     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
4310b57cec5SDimitry Andric       MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
4320b57cec5SDimitry Andric }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
4350b57cec5SDimitry Andric   // Dump the pointers we are tracking.
4360b57cec5SDimitry Andric   OS << "    TopDown State:\n";
4370b57cec5SDimitry Andric   if (!BBInfo.hasTopDownPtrs()) {
4380b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "        NONE!\n");
4390b57cec5SDimitry Andric   } else {
4400b57cec5SDimitry Andric     for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
4410b57cec5SDimitry Andric          I != E; ++I) {
4420b57cec5SDimitry Andric       const PtrState &P = I->second;
4430b57cec5SDimitry Andric       OS << "        Ptr: " << *I->first
4440b57cec5SDimitry Andric          << "\n            KnownSafe:        " << (P.IsKnownSafe()?"true":"false")
4450b57cec5SDimitry Andric          << "\n            ImpreciseRelease: "
4460b57cec5SDimitry Andric            << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
4470b57cec5SDimitry Andric          << "            HasCFGHazards:    "
4480b57cec5SDimitry Andric            << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
4490b57cec5SDimitry Andric          << "            KnownPositive:    "
4500b57cec5SDimitry Andric            << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
4510b57cec5SDimitry Andric          << "            Seq:              "
4520b57cec5SDimitry Andric          << P.GetSeq() << "\n";
4530b57cec5SDimitry Andric     }
4540b57cec5SDimitry Andric   }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   OS << "    BottomUp State:\n";
4570b57cec5SDimitry Andric   if (!BBInfo.hasBottomUpPtrs()) {
4580b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "        NONE!\n");
4590b57cec5SDimitry Andric   } else {
4600b57cec5SDimitry Andric     for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
4610b57cec5SDimitry Andric          I != E; ++I) {
4620b57cec5SDimitry Andric       const PtrState &P = I->second;
4630b57cec5SDimitry Andric       OS << "        Ptr: " << *I->first
4640b57cec5SDimitry Andric          << "\n            KnownSafe:        " << (P.IsKnownSafe()?"true":"false")
4650b57cec5SDimitry Andric          << "\n            ImpreciseRelease: "
4660b57cec5SDimitry Andric            << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
4670b57cec5SDimitry Andric          << "            HasCFGHazards:    "
4680b57cec5SDimitry Andric            << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
4690b57cec5SDimitry Andric          << "            KnownPositive:    "
4700b57cec5SDimitry Andric            << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
4710b57cec5SDimitry Andric          << "            Seq:              "
4720b57cec5SDimitry Andric          << P.GetSeq() << "\n";
4730b57cec5SDimitry Andric     }
4740b57cec5SDimitry Andric   }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   return OS;
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric namespace {
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   /// The main ARC optimization pass.
482e8d8bef9SDimitry Andric class ObjCARCOpt {
483bdd1243dSDimitry Andric   bool Changed = false;
484bdd1243dSDimitry Andric   bool CFGChanged = false;
4850b57cec5SDimitry Andric   ProvenanceAnalysis PA;
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   /// A cache of references to runtime entry point constants.
4880b57cec5SDimitry Andric   ARCRuntimeEntryPoints EP;
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   /// A cache of MDKinds that can be passed into other functions to propagate
4910b57cec5SDimitry Andric   /// MDKind identifiers.
4920b57cec5SDimitry Andric   ARCMDKindCache MDKindCache;
4930b57cec5SDimitry Andric 
494fe6060f1SDimitry Andric   BundledRetainClaimRVs *BundledInsts = nullptr;
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   /// A flag indicating whether the optimization that removes or moves
4970b57cec5SDimitry Andric   /// retain/release pairs should be performed.
4980b57cec5SDimitry Andric   bool DisableRetainReleasePairing = false;
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   /// Flags which determine whether each of the interesting runtime functions
5010b57cec5SDimitry Andric   /// is in fact used in the current function.
5020b57cec5SDimitry Andric   unsigned UsedInThisFunction;
5030b57cec5SDimitry Andric 
504bdd1243dSDimitry Andric   DenseMap<BasicBlock *, ColorVector> BlockEHColors;
505bdd1243dSDimitry Andric 
5060b57cec5SDimitry Andric   bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
5070b57cec5SDimitry Andric   void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
5080b57cec5SDimitry Andric                                  ARCInstKind &Class);
5090b57cec5SDimitry Andric   void OptimizeIndividualCalls(Function &F);
5100b57cec5SDimitry Andric 
511480093f4SDimitry Andric   /// Optimize an individual call, optionally passing the
512480093f4SDimitry Andric   /// GetArgRCIdentityRoot if it has already been computed.
513bdd1243dSDimitry Andric   void OptimizeIndividualCallImpl(Function &F, Instruction *Inst,
514bdd1243dSDimitry Andric                                   ARCInstKind Class, const Value *Arg);
515480093f4SDimitry Andric 
51604eeddc0SDimitry Andric   /// Try to optimize an AutoreleaseRV with a RetainRV or UnsafeClaimRV.  If the
517480093f4SDimitry Andric   /// optimization occurs, returns true to indicate that the caller should
518480093f4SDimitry Andric   /// assume the instructions are dead.
519bdd1243dSDimitry Andric   bool OptimizeInlinedAutoreleaseRVCall(Function &F, Instruction *Inst,
520bdd1243dSDimitry Andric                                         const Value *&Arg, ARCInstKind Class,
521bdd1243dSDimitry Andric                                         Instruction *AutoreleaseRV,
522bdd1243dSDimitry Andric                                         const Value *&AutoreleaseRVArg);
523480093f4SDimitry Andric 
5240b57cec5SDimitry Andric   void CheckForCFGHazards(const BasicBlock *BB,
5250b57cec5SDimitry Andric                           DenseMap<const BasicBlock *, BBState> &BBStates,
5260b57cec5SDimitry Andric                           BBState &MyStates) const;
5270b57cec5SDimitry Andric   bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
5280b57cec5SDimitry Andric                                 BlotMapVector<Value *, RRInfo> &Retains,
5290b57cec5SDimitry Andric                                 BBState &MyStates);
5300b57cec5SDimitry Andric   bool VisitBottomUp(BasicBlock *BB,
5310b57cec5SDimitry Andric                      DenseMap<const BasicBlock *, BBState> &BBStates,
5320b57cec5SDimitry Andric                      BlotMapVector<Value *, RRInfo> &Retains);
533fe6060f1SDimitry Andric   bool VisitInstructionTopDown(
534fe6060f1SDimitry Andric       Instruction *Inst, DenseMap<Value *, RRInfo> &Releases, BBState &MyStates,
535fe6060f1SDimitry Andric       const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
536fe6060f1SDimitry Andric           &ReleaseInsertPtToRCIdentityRoots);
537fe6060f1SDimitry Andric   bool VisitTopDown(
538fe6060f1SDimitry Andric       BasicBlock *BB, DenseMap<const BasicBlock *, BBState> &BBStates,
5390b57cec5SDimitry Andric       DenseMap<Value *, RRInfo> &Releases,
540fe6060f1SDimitry Andric       const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
541fe6060f1SDimitry Andric           &ReleaseInsertPtToRCIdentityRoots);
5420b57cec5SDimitry Andric   bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
5430b57cec5SDimitry Andric              BlotMapVector<Value *, RRInfo> &Retains,
5440b57cec5SDimitry Andric              DenseMap<Value *, RRInfo> &Releases);
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
5470b57cec5SDimitry Andric                  BlotMapVector<Value *, RRInfo> &Retains,
5480b57cec5SDimitry Andric                  DenseMap<Value *, RRInfo> &Releases,
5490b57cec5SDimitry Andric                  SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
5500b57cec5SDimitry Andric 
551e8d8bef9SDimitry Andric   bool PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
5520b57cec5SDimitry Andric                                 BlotMapVector<Value *, RRInfo> &Retains,
5530b57cec5SDimitry Andric                                 DenseMap<Value *, RRInfo> &Releases, Module *M,
5540b57cec5SDimitry Andric                                 Instruction *Retain,
5550b57cec5SDimitry Andric                                 SmallVectorImpl<Instruction *> &DeadInsts,
5560b57cec5SDimitry Andric                                 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
5570b57cec5SDimitry Andric                                 Value *Arg, bool KnownSafe,
5580b57cec5SDimitry Andric                                 bool &AnyPairsCompletelyEliminated);
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
5610b57cec5SDimitry Andric                             BlotMapVector<Value *, RRInfo> &Retains,
5620b57cec5SDimitry Andric                             DenseMap<Value *, RRInfo> &Releases, Module *M);
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric   void OptimizeWeakCalls(Function &F);
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   bool OptimizeSequences(Function &F);
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   void OptimizeReturns(Function &F);
5690b57cec5SDimitry Andric 
570bdd1243dSDimitry Andric   template <typename PredicateT>
571bdd1243dSDimitry Andric   static void cloneOpBundlesIf(CallBase *CI,
572bdd1243dSDimitry Andric                                SmallVectorImpl<OperandBundleDef> &OpBundles,
573bdd1243dSDimitry Andric                                PredicateT Predicate) {
574bdd1243dSDimitry Andric     for (unsigned I = 0, E = CI->getNumOperandBundles(); I != E; ++I) {
575bdd1243dSDimitry Andric       OperandBundleUse B = CI->getOperandBundleAt(I);
576bdd1243dSDimitry Andric       if (Predicate(B))
577bdd1243dSDimitry Andric         OpBundles.emplace_back(B);
578bdd1243dSDimitry Andric     }
579bdd1243dSDimitry Andric   }
580bdd1243dSDimitry Andric 
581bdd1243dSDimitry Andric   void addOpBundleForFunclet(BasicBlock *BB,
582bdd1243dSDimitry Andric                              SmallVectorImpl<OperandBundleDef> &OpBundles) {
583bdd1243dSDimitry Andric     if (!BlockEHColors.empty()) {
584bdd1243dSDimitry Andric       const ColorVector &CV = BlockEHColors.find(BB)->second;
585bdd1243dSDimitry Andric       assert(CV.size() > 0 && "Uncolored block");
586bdd1243dSDimitry Andric       for (BasicBlock *EHPadBB : CV)
587bdd1243dSDimitry Andric         if (auto *EHPad = dyn_cast<FuncletPadInst>(EHPadBB->getFirstNonPHI())) {
588bdd1243dSDimitry Andric           OpBundles.emplace_back("funclet", EHPad);
589bdd1243dSDimitry Andric           return;
590bdd1243dSDimitry Andric         }
591bdd1243dSDimitry Andric     }
592bdd1243dSDimitry Andric   }
593bdd1243dSDimitry Andric 
5940b57cec5SDimitry Andric #ifndef NDEBUG
5950b57cec5SDimitry Andric   void GatherStatistics(Function &F, bool AfterOptimization = false);
5960b57cec5SDimitry Andric #endif
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric   public:
599bdd1243dSDimitry Andric     void init(Function &F);
600e8d8bef9SDimitry Andric     bool run(Function &F, AAResults &AA);
601fe6060f1SDimitry Andric     bool hasCFGChanged() const { return CFGChanged; }
6020b57cec5SDimitry Andric };
6030b57cec5SDimitry Andric } // end anonymous namespace
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
606480093f4SDimitry Andric /// not a return value.
6070b57cec5SDimitry Andric bool
6080b57cec5SDimitry Andric ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
6090b57cec5SDimitry Andric   // Check for the argument being from an immediately preceding call or invoke.
6100b57cec5SDimitry Andric   const Value *Arg = GetArgRCIdentityRoot(RetainRV);
6115ffd83dbSDimitry Andric   if (const Instruction *Call = dyn_cast<CallBase>(Arg)) {
6120b57cec5SDimitry Andric     if (Call->getParent() == RetainRV->getParent()) {
6130b57cec5SDimitry Andric       BasicBlock::const_iterator I(Call);
6140b57cec5SDimitry Andric       ++I;
6150b57cec5SDimitry Andric       while (IsNoopInstruction(&*I))
6160b57cec5SDimitry Andric         ++I;
6170b57cec5SDimitry Andric       if (&*I == RetainRV)
6180b57cec5SDimitry Andric         return false;
6190b57cec5SDimitry Andric     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
6200b57cec5SDimitry Andric       BasicBlock *RetainRVParent = RetainRV->getParent();
6210b57cec5SDimitry Andric       if (II->getNormalDest() == RetainRVParent) {
6220b57cec5SDimitry Andric         BasicBlock::const_iterator I = RetainRVParent->begin();
6230b57cec5SDimitry Andric         while (IsNoopInstruction(&*I))
6240b57cec5SDimitry Andric           ++I;
6250b57cec5SDimitry Andric         if (&*I == RetainRV)
6260b57cec5SDimitry Andric           return false;
6270b57cec5SDimitry Andric       }
6280b57cec5SDimitry Andric     }
6290b57cec5SDimitry Andric   }
6300b57cec5SDimitry Andric 
631fe6060f1SDimitry Andric   assert(!BundledInsts->contains(RetainRV) &&
632fe6060f1SDimitry Andric          "a bundled retainRV's argument should be a call");
633fe6060f1SDimitry Andric 
6340b57cec5SDimitry Andric   // Turn it to a plain objc_retain.
6350b57cec5SDimitry Andric   Changed = true;
6360b57cec5SDimitry Andric   ++NumPeeps;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
6390b57cec5SDimitry Andric                        "objc_retain since the operand is not a return value.\n"
6400b57cec5SDimitry Andric                        "Old = "
6410b57cec5SDimitry Andric                     << *RetainRV << "\n");
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
6440b57cec5SDimitry Andric   cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n");
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   return false;
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
651480093f4SDimitry Andric bool ObjCARCOpt::OptimizeInlinedAutoreleaseRVCall(
652bdd1243dSDimitry Andric     Function &F, Instruction *Inst, const Value *&Arg, ARCInstKind Class,
653480093f4SDimitry Andric     Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg) {
654fe6060f1SDimitry Andric   if (BundledInsts->contains(Inst))
655fe6060f1SDimitry Andric     return false;
656fe6060f1SDimitry Andric 
657480093f4SDimitry Andric   // Must be in the same basic block.
658480093f4SDimitry Andric   assert(Inst->getParent() == AutoreleaseRV->getParent());
659480093f4SDimitry Andric 
660480093f4SDimitry Andric   // Must operate on the same root.
661480093f4SDimitry Andric   Arg = GetArgRCIdentityRoot(Inst);
662480093f4SDimitry Andric   AutoreleaseRVArg = GetArgRCIdentityRoot(AutoreleaseRV);
663480093f4SDimitry Andric   if (Arg != AutoreleaseRVArg) {
664480093f4SDimitry Andric     // If there isn't an exact match, check if we have equivalent PHIs.
665480093f4SDimitry Andric     const PHINode *PN = dyn_cast<PHINode>(Arg);
666480093f4SDimitry Andric     if (!PN)
667480093f4SDimitry Andric       return false;
668480093f4SDimitry Andric 
669480093f4SDimitry Andric     SmallVector<const Value *, 4> ArgUsers;
670480093f4SDimitry Andric     getEquivalentPHIs(*PN, ArgUsers);
671e8d8bef9SDimitry Andric     if (!llvm::is_contained(ArgUsers, AutoreleaseRVArg))
672480093f4SDimitry Andric       return false;
673480093f4SDimitry Andric   }
674480093f4SDimitry Andric 
675480093f4SDimitry Andric   // Okay, this is a match.  Merge them.
676480093f4SDimitry Andric   ++NumPeeps;
677480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "Found inlined objc_autoreleaseReturnValue '"
678480093f4SDimitry Andric                     << *AutoreleaseRV << "' paired with '" << *Inst << "'\n");
679480093f4SDimitry Andric 
680480093f4SDimitry Andric   // Delete the RV pair, starting with the AutoreleaseRV.
681480093f4SDimitry Andric   AutoreleaseRV->replaceAllUsesWith(
682480093f4SDimitry Andric       cast<CallInst>(AutoreleaseRV)->getArgOperand(0));
6835ffd83dbSDimitry Andric   Changed = true;
684480093f4SDimitry Andric   EraseInstruction(AutoreleaseRV);
685480093f4SDimitry Andric   if (Class == ARCInstKind::RetainRV) {
686480093f4SDimitry Andric     // AutoreleaseRV and RetainRV cancel out.  Delete the RetainRV.
687480093f4SDimitry Andric     Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
688480093f4SDimitry Andric     EraseInstruction(Inst);
689480093f4SDimitry Andric     return true;
690480093f4SDimitry Andric   }
691480093f4SDimitry Andric 
69204eeddc0SDimitry Andric   // UnsafeClaimRV is a frontend peephole for RetainRV + Release.  Since the
69304eeddc0SDimitry Andric   // AutoreleaseRV and RetainRV cancel out, replace UnsafeClaimRV with Release.
69404eeddc0SDimitry Andric   assert(Class == ARCInstKind::UnsafeClaimRV);
695480093f4SDimitry Andric   Value *CallArg = cast<CallInst>(Inst)->getArgOperand(0);
696*0fca6ea1SDimitry Andric   CallInst *Release =
697*0fca6ea1SDimitry Andric       CallInst::Create(EP.get(ARCRuntimeEntryPointKind::Release), CallArg, "",
698*0fca6ea1SDimitry Andric                        Inst->getIterator());
69904eeddc0SDimitry Andric   assert(IsAlwaysTail(ARCInstKind::UnsafeClaimRV) &&
70004eeddc0SDimitry Andric          "Expected UnsafeClaimRV to be safe to tail call");
701480093f4SDimitry Andric   Release->setTailCall();
702480093f4SDimitry Andric   Inst->replaceAllUsesWith(CallArg);
703480093f4SDimitry Andric   EraseInstruction(Inst);
704480093f4SDimitry Andric 
705480093f4SDimitry Andric   // Run the normal optimizations on Release.
706bdd1243dSDimitry Andric   OptimizeIndividualCallImpl(F, Release, ARCInstKind::Release, Arg);
707480093f4SDimitry Andric   return true;
708480093f4SDimitry Andric }
709480093f4SDimitry Andric 
7100b57cec5SDimitry Andric /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
7110b57cec5SDimitry Andric /// used as a return value.
7120b57cec5SDimitry Andric void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
7130b57cec5SDimitry Andric                                            Instruction *AutoreleaseRV,
7140b57cec5SDimitry Andric                                            ARCInstKind &Class) {
7150b57cec5SDimitry Andric   // Check for a return of the pointer value.
7160b57cec5SDimitry Andric   const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   // If the argument is ConstantPointerNull or UndefValue, its other users
7190b57cec5SDimitry Andric   // aren't actually interesting to look at.
7200b57cec5SDimitry Andric   if (isa<ConstantData>(Ptr))
7210b57cec5SDimitry Andric     return;
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   SmallVector<const Value *, 2> Users;
7240b57cec5SDimitry Andric   Users.push_back(Ptr);
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   // Add PHIs that are equivalent to Ptr to Users.
7270b57cec5SDimitry Andric   if (const PHINode *PN = dyn_cast<PHINode>(Ptr))
7280b57cec5SDimitry Andric     getEquivalentPHIs(*PN, Users);
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   do {
7310b57cec5SDimitry Andric     Ptr = Users.pop_back_val();
7320b57cec5SDimitry Andric     for (const User *U : Ptr->users()) {
7330b57cec5SDimitry Andric       if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
7340b57cec5SDimitry Andric         return;
7350b57cec5SDimitry Andric       if (isa<BitCastInst>(U))
7360b57cec5SDimitry Andric         Users.push_back(U);
7370b57cec5SDimitry Andric     }
7380b57cec5SDimitry Andric   } while (!Users.empty());
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   Changed = true;
7410b57cec5SDimitry Andric   ++NumPeeps;
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   LLVM_DEBUG(
7440b57cec5SDimitry Andric       dbgs() << "Transforming objc_autoreleaseReturnValue => "
7450b57cec5SDimitry Andric                 "objc_autorelease since its operand is not used as a return "
7460b57cec5SDimitry Andric                 "value.\n"
7470b57cec5SDimitry Andric                 "Old = "
7480b57cec5SDimitry Andric              << *AutoreleaseRV << "\n");
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
7510b57cec5SDimitry Andric   Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
7520b57cec5SDimitry Andric   AutoreleaseRVCI->setCalledFunction(NewDecl);
7530b57cec5SDimitry Andric   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
7540b57cec5SDimitry Andric   Class = ARCInstKind::Autorelease;
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
7570b57cec5SDimitry Andric }
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric /// Visit each call, one at a time, and make simplifications without doing any
7600b57cec5SDimitry Andric /// additional analysis.
7610b57cec5SDimitry Andric void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
7620b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
7630b57cec5SDimitry Andric   // Reset all the flags in preparation for recomputing them.
7640b57cec5SDimitry Andric   UsedInThisFunction = 0;
7650b57cec5SDimitry Andric 
766480093f4SDimitry Andric   // Store any delayed AutoreleaseRV intrinsics, so they can be easily paired
76704eeddc0SDimitry Andric   // with RetainRV and UnsafeClaimRV.
768480093f4SDimitry Andric   Instruction *DelayedAutoreleaseRV = nullptr;
769480093f4SDimitry Andric   const Value *DelayedAutoreleaseRVArg = nullptr;
770480093f4SDimitry Andric   auto setDelayedAutoreleaseRV = [&](Instruction *AutoreleaseRV) {
771480093f4SDimitry Andric     assert(!DelayedAutoreleaseRV || !AutoreleaseRV);
772480093f4SDimitry Andric     DelayedAutoreleaseRV = AutoreleaseRV;
773480093f4SDimitry Andric     DelayedAutoreleaseRVArg = nullptr;
774480093f4SDimitry Andric   };
775480093f4SDimitry Andric   auto optimizeDelayedAutoreleaseRV = [&]() {
776480093f4SDimitry Andric     if (!DelayedAutoreleaseRV)
777480093f4SDimitry Andric       return;
778bdd1243dSDimitry Andric     OptimizeIndividualCallImpl(F, DelayedAutoreleaseRV,
779480093f4SDimitry Andric                                ARCInstKind::AutoreleaseRV,
780480093f4SDimitry Andric                                DelayedAutoreleaseRVArg);
781480093f4SDimitry Andric     setDelayedAutoreleaseRV(nullptr);
782480093f4SDimitry Andric   };
783480093f4SDimitry Andric   auto shouldDelayAutoreleaseRV = [&](Instruction *NonARCInst) {
784480093f4SDimitry Andric     // Nothing to delay, but we may as well skip the logic below.
785480093f4SDimitry Andric     if (!DelayedAutoreleaseRV)
786480093f4SDimitry Andric       return true;
787480093f4SDimitry Andric 
788480093f4SDimitry Andric     // If we hit the end of the basic block we're not going to find an RV-pair.
789480093f4SDimitry Andric     // Stop delaying.
790480093f4SDimitry Andric     if (NonARCInst->isTerminator())
791480093f4SDimitry Andric       return false;
792480093f4SDimitry Andric 
793480093f4SDimitry Andric     // Given the frontend rules for emitting AutoreleaseRV, RetainRV, and
79404eeddc0SDimitry Andric     // UnsafeClaimRV, it's probably safe to skip over even opaque function calls
795480093f4SDimitry Andric     // here since OptimizeInlinedAutoreleaseRVCall will confirm that they
796480093f4SDimitry Andric     // have the same RCIdentityRoot.  However, what really matters is
797480093f4SDimitry Andric     // skipping instructions or intrinsics that the inliner could leave behind;
798480093f4SDimitry Andric     // be conservative for now and don't skip over opaque calls, which could
799480093f4SDimitry Andric     // potentially include other ARC calls.
800480093f4SDimitry Andric     auto *CB = dyn_cast<CallBase>(NonARCInst);
801480093f4SDimitry Andric     if (!CB)
802480093f4SDimitry Andric       return true;
803480093f4SDimitry Andric     return CB->getIntrinsicID() != Intrinsic::not_intrinsic;
804480093f4SDimitry Andric   };
805480093f4SDimitry Andric 
8060b57cec5SDimitry Andric   // Visit all objc_* calls in F.
8070b57cec5SDimitry Andric   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
8080b57cec5SDimitry Andric     Instruction *Inst = &*I++;
8090b57cec5SDimitry Andric 
810fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(Inst))
811fe6060f1SDimitry Andric       if (objcarc::hasAttachedCallOpBundle(CI)) {
812*0fca6ea1SDimitry Andric         BundledInsts->insertRVCall(I->getIterator(), CI);
813fe6060f1SDimitry Andric         Changed = true;
814fe6060f1SDimitry Andric       }
815fe6060f1SDimitry Andric 
8160b57cec5SDimitry Andric     ARCInstKind Class = GetBasicARCInstKind(Inst);
8170b57cec5SDimitry Andric 
818480093f4SDimitry Andric     // Skip this loop if this instruction isn't itself an ARC intrinsic.
819480093f4SDimitry Andric     const Value *Arg = nullptr;
820480093f4SDimitry Andric     switch (Class) {
821480093f4SDimitry Andric     default:
822480093f4SDimitry Andric       optimizeDelayedAutoreleaseRV();
823480093f4SDimitry Andric       break;
824480093f4SDimitry Andric     case ARCInstKind::CallOrUser:
825480093f4SDimitry Andric     case ARCInstKind::User:
826480093f4SDimitry Andric     case ARCInstKind::None:
827480093f4SDimitry Andric       // This is a non-ARC instruction.  If we're delaying an AutoreleaseRV,
828480093f4SDimitry Andric       // check if it's safe to skip over it; if not, optimize the AutoreleaseRV
829480093f4SDimitry Andric       // now.
830480093f4SDimitry Andric       if (!shouldDelayAutoreleaseRV(Inst))
831480093f4SDimitry Andric         optimizeDelayedAutoreleaseRV();
832480093f4SDimitry Andric       continue;
833480093f4SDimitry Andric     case ARCInstKind::AutoreleaseRV:
834480093f4SDimitry Andric       optimizeDelayedAutoreleaseRV();
835480093f4SDimitry Andric       setDelayedAutoreleaseRV(Inst);
836480093f4SDimitry Andric       continue;
837480093f4SDimitry Andric     case ARCInstKind::RetainRV:
83804eeddc0SDimitry Andric     case ARCInstKind::UnsafeClaimRV:
839480093f4SDimitry Andric       if (DelayedAutoreleaseRV) {
840480093f4SDimitry Andric         // We have a potential RV pair.  Check if they cancel out.
841bdd1243dSDimitry Andric         if (OptimizeInlinedAutoreleaseRVCall(F, Inst, Arg, Class,
842480093f4SDimitry Andric                                              DelayedAutoreleaseRV,
843480093f4SDimitry Andric                                              DelayedAutoreleaseRVArg)) {
844480093f4SDimitry Andric           setDelayedAutoreleaseRV(nullptr);
845480093f4SDimitry Andric           continue;
846480093f4SDimitry Andric         }
847480093f4SDimitry Andric         optimizeDelayedAutoreleaseRV();
848480093f4SDimitry Andric       }
849480093f4SDimitry Andric       break;
850480093f4SDimitry Andric     }
851480093f4SDimitry Andric 
852bdd1243dSDimitry Andric     OptimizeIndividualCallImpl(F, Inst, Class, Arg);
853480093f4SDimitry Andric   }
854480093f4SDimitry Andric 
855480093f4SDimitry Andric   // Catch the final delayed AutoreleaseRV.
856480093f4SDimitry Andric   optimizeDelayedAutoreleaseRV();
857480093f4SDimitry Andric }
858480093f4SDimitry Andric 
8595ffd83dbSDimitry Andric /// This function returns true if the value is inert. An ObjC ARC runtime call
8605ffd83dbSDimitry Andric /// taking an inert operand can be safely deleted.
8615ffd83dbSDimitry Andric static bool isInertARCValue(Value *V, SmallPtrSet<Value *, 1> &VisitedPhis) {
8625ffd83dbSDimitry Andric   V = V->stripPointerCasts();
8635ffd83dbSDimitry Andric 
8645ffd83dbSDimitry Andric   if (IsNullOrUndef(V))
8655ffd83dbSDimitry Andric     return true;
8665ffd83dbSDimitry Andric 
8675ffd83dbSDimitry Andric   // See if this is a global attribute annotated with an 'objc_arc_inert'.
8685ffd83dbSDimitry Andric   if (auto *GV = dyn_cast<GlobalVariable>(V))
8695ffd83dbSDimitry Andric     if (GV->hasAttribute("objc_arc_inert"))
8705ffd83dbSDimitry Andric       return true;
8715ffd83dbSDimitry Andric 
8725ffd83dbSDimitry Andric   if (auto PN = dyn_cast<PHINode>(V)) {
8735ffd83dbSDimitry Andric     // Ignore this phi if it has already been discovered.
8745ffd83dbSDimitry Andric     if (!VisitedPhis.insert(PN).second)
8755ffd83dbSDimitry Andric       return true;
8765ffd83dbSDimitry Andric     // Look through phis's operands.
8775ffd83dbSDimitry Andric     for (Value *Opnd : PN->incoming_values())
8785ffd83dbSDimitry Andric       if (!isInertARCValue(Opnd, VisitedPhis))
8795ffd83dbSDimitry Andric         return false;
8805ffd83dbSDimitry Andric     return true;
8815ffd83dbSDimitry Andric   }
8825ffd83dbSDimitry Andric 
8835ffd83dbSDimitry Andric   return false;
8845ffd83dbSDimitry Andric }
8855ffd83dbSDimitry Andric 
886bdd1243dSDimitry Andric void ObjCARCOpt::OptimizeIndividualCallImpl(Function &F, Instruction *Inst,
887bdd1243dSDimitry Andric                                             ARCInstKind Class,
888bdd1243dSDimitry Andric                                             const Value *Arg) {
8890b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
8900b57cec5SDimitry Andric 
8915ffd83dbSDimitry Andric   // We can delete this call if it takes an inert value.
8925ffd83dbSDimitry Andric   SmallPtrSet<Value *, 1> VisitedPhis;
8935ffd83dbSDimitry Andric 
894fe6060f1SDimitry Andric   if (BundledInsts->contains(Inst)) {
895fe6060f1SDimitry Andric     UsedInThisFunction |= 1 << unsigned(Class);
896fe6060f1SDimitry Andric     return;
897fe6060f1SDimitry Andric   }
898fe6060f1SDimitry Andric 
8995ffd83dbSDimitry Andric   if (IsNoopOnGlobal(Class))
9005ffd83dbSDimitry Andric     if (isInertARCValue(Inst->getOperand(0), VisitedPhis)) {
9010b57cec5SDimitry Andric       if (!Inst->getType()->isVoidTy())
9025ffd83dbSDimitry Andric         Inst->replaceAllUsesWith(Inst->getOperand(0));
9030b57cec5SDimitry Andric       Inst->eraseFromParent();
9045ffd83dbSDimitry Andric       Changed = true;
905480093f4SDimitry Andric       return;
9060b57cec5SDimitry Andric     }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   switch (Class) {
909480093f4SDimitry Andric   default:
910480093f4SDimitry Andric     break;
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // Delete no-op casts. These function calls have special semantics, but
9130b57cec5SDimitry Andric   // the semantics are entirely implemented via lowering in the front-end,
9140b57cec5SDimitry Andric   // so by the time they reach the optimizer, they are just no-op calls
9150b57cec5SDimitry Andric   // which return their argument.
9160b57cec5SDimitry Andric   //
9170b57cec5SDimitry Andric   // There are gray areas here, as the ability to cast reference-counted
9180b57cec5SDimitry Andric   // pointers to raw void* and back allows code to break ARC assumptions,
9190b57cec5SDimitry Andric   // however these are currently considered to be unimportant.
9200b57cec5SDimitry Andric   case ARCInstKind::NoopCast:
9210b57cec5SDimitry Andric     Changed = true;
9220b57cec5SDimitry Andric     ++NumNoops;
9230b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
9240b57cec5SDimitry Andric     EraseInstruction(Inst);
925480093f4SDimitry Andric     return;
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   // If the pointer-to-weak-pointer is null, it's undefined behavior.
9280b57cec5SDimitry Andric   case ARCInstKind::StoreWeak:
9290b57cec5SDimitry Andric   case ARCInstKind::LoadWeak:
9300b57cec5SDimitry Andric   case ARCInstKind::LoadWeakRetained:
9310b57cec5SDimitry Andric   case ARCInstKind::InitWeak:
9320b57cec5SDimitry Andric   case ARCInstKind::DestroyWeak: {
9330b57cec5SDimitry Andric     CallInst *CI = cast<CallInst>(Inst);
9340b57cec5SDimitry Andric     if (IsNullOrUndef(CI->getArgOperand(0))) {
9350b57cec5SDimitry Andric       Changed = true;
93604eeddc0SDimitry Andric       new StoreInst(ConstantInt::getTrue(CI->getContext()),
9375f757f3fSDimitry Andric                     PoisonValue::get(PointerType::getUnqual(CI->getContext())),
938*0fca6ea1SDimitry Andric                     CI->getIterator());
93906c3fb27SDimitry Andric       Value *NewValue = PoisonValue::get(CI->getType());
9400b57cec5SDimitry Andric       LLVM_DEBUG(
9410b57cec5SDimitry Andric           dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
9420b57cec5SDimitry Andric                     "\nOld = "
9430b57cec5SDimitry Andric                  << *CI << "\nNew = " << *NewValue << "\n");
9440b57cec5SDimitry Andric       CI->replaceAllUsesWith(NewValue);
9450b57cec5SDimitry Andric       CI->eraseFromParent();
946480093f4SDimitry Andric       return;
9470b57cec5SDimitry Andric     }
9480b57cec5SDimitry Andric     break;
9490b57cec5SDimitry Andric   }
9500b57cec5SDimitry Andric   case ARCInstKind::CopyWeak:
9510b57cec5SDimitry Andric   case ARCInstKind::MoveWeak: {
9520b57cec5SDimitry Andric     CallInst *CI = cast<CallInst>(Inst);
9530b57cec5SDimitry Andric     if (IsNullOrUndef(CI->getArgOperand(0)) ||
9540b57cec5SDimitry Andric         IsNullOrUndef(CI->getArgOperand(1))) {
9550b57cec5SDimitry Andric       Changed = true;
95604eeddc0SDimitry Andric       new StoreInst(ConstantInt::getTrue(CI->getContext()),
9575f757f3fSDimitry Andric                     PoisonValue::get(PointerType::getUnqual(CI->getContext())),
958*0fca6ea1SDimitry Andric                     CI->getIterator());
9590b57cec5SDimitry Andric 
96006c3fb27SDimitry Andric       Value *NewValue = PoisonValue::get(CI->getType());
9610b57cec5SDimitry Andric       LLVM_DEBUG(
9620b57cec5SDimitry Andric           dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
9630b57cec5SDimitry Andric                     "\nOld = "
9640b57cec5SDimitry Andric                  << *CI << "\nNew = " << *NewValue << "\n");
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric       CI->replaceAllUsesWith(NewValue);
9670b57cec5SDimitry Andric       CI->eraseFromParent();
968480093f4SDimitry Andric       return;
9690b57cec5SDimitry Andric     }
9700b57cec5SDimitry Andric     break;
9710b57cec5SDimitry Andric   }
9720b57cec5SDimitry Andric   case ARCInstKind::RetainRV:
9730b57cec5SDimitry Andric     if (OptimizeRetainRVCall(F, Inst))
974480093f4SDimitry Andric       return;
9750b57cec5SDimitry Andric     break;
9760b57cec5SDimitry Andric   case ARCInstKind::AutoreleaseRV:
9770b57cec5SDimitry Andric     OptimizeAutoreleaseRVCall(F, Inst, Class);
9780b57cec5SDimitry Andric     break;
9790b57cec5SDimitry Andric   }
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
9820b57cec5SDimitry Andric   if (IsAutorelease(Class) && Inst->use_empty()) {
9830b57cec5SDimitry Andric     CallInst *Call = cast<CallInst>(Inst);
9840b57cec5SDimitry Andric     const Value *Arg = Call->getArgOperand(0);
9850b57cec5SDimitry Andric     Arg = FindSingleUseIdentifiedObject(Arg);
9860b57cec5SDimitry Andric     if (Arg) {
9870b57cec5SDimitry Andric       Changed = true;
9880b57cec5SDimitry Andric       ++NumAutoreleases;
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric       // Create the declaration lazily.
9910b57cec5SDimitry Andric       LLVMContext &C = Inst->getContext();
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric       Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
994*0fca6ea1SDimitry Andric       CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
995*0fca6ea1SDimitry Andric                                            Call->getIterator());
9960b57cec5SDimitry Andric       NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
997bdd1243dSDimitry Andric                            MDNode::get(C, std::nullopt));
9980b57cec5SDimitry Andric 
999480093f4SDimitry Andric       LLVM_DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
10000b57cec5SDimitry Andric                            "since x is otherwise unused.\nOld: "
10010b57cec5SDimitry Andric                         << *Call << "\nNew: " << *NewCall << "\n");
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric       EraseInstruction(Call);
10040b57cec5SDimitry Andric       Inst = NewCall;
10050b57cec5SDimitry Andric       Class = ARCInstKind::Release;
10060b57cec5SDimitry Andric     }
10070b57cec5SDimitry Andric   }
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   // For functions which can never be passed stack arguments, add
10100b57cec5SDimitry Andric   // a tail keyword.
10110b57cec5SDimitry Andric   if (IsAlwaysTail(Class) && !cast<CallInst>(Inst)->isNoTailCall()) {
10120b57cec5SDimitry Andric     Changed = true;
10130b57cec5SDimitry Andric     LLVM_DEBUG(
10140b57cec5SDimitry Andric         dbgs() << "Adding tail keyword to function since it can never be "
10150b57cec5SDimitry Andric                   "passed stack args: "
10160b57cec5SDimitry Andric                << *Inst << "\n");
10170b57cec5SDimitry Andric     cast<CallInst>(Inst)->setTailCall();
10180b57cec5SDimitry Andric   }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   // Ensure that functions that can never have a "tail" keyword due to the
10210b57cec5SDimitry Andric   // semantics of ARC truly do not do so.
10220b57cec5SDimitry Andric   if (IsNeverTail(Class)) {
10230b57cec5SDimitry Andric     Changed = true;
10240b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst
10250b57cec5SDimitry Andric                       << "\n");
10260b57cec5SDimitry Andric     cast<CallInst>(Inst)->setTailCall(false);
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   // Set nounwind as needed.
10300b57cec5SDimitry Andric   if (IsNoThrow(Class)) {
10310b57cec5SDimitry Andric     Changed = true;
1032480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1033480093f4SDimitry Andric                       << "\n");
10340b57cec5SDimitry Andric     cast<CallInst>(Inst)->setDoesNotThrow();
10350b57cec5SDimitry Andric   }
10360b57cec5SDimitry Andric 
1037480093f4SDimitry Andric   // Note: This catches instructions unrelated to ARC.
10380b57cec5SDimitry Andric   if (!IsNoopOnNull(Class)) {
10390b57cec5SDimitry Andric     UsedInThisFunction |= 1 << unsigned(Class);
1040480093f4SDimitry Andric     return;
10410b57cec5SDimitry Andric   }
10420b57cec5SDimitry Andric 
1043480093f4SDimitry Andric   // If we haven't already looked up the root, look it up now.
1044480093f4SDimitry Andric   if (!Arg)
1045480093f4SDimitry Andric     Arg = GetArgRCIdentityRoot(Inst);
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric   // ARC calls with null are no-ops. Delete them.
10480b57cec5SDimitry Andric   if (IsNullOrUndef(Arg)) {
10490b57cec5SDimitry Andric     Changed = true;
10500b57cec5SDimitry Andric     ++NumNoops;
10510b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "ARC calls with  null are no-ops. Erasing: " << *Inst
10520b57cec5SDimitry Andric                       << "\n");
10530b57cec5SDimitry Andric     EraseInstruction(Inst);
1054480093f4SDimitry Andric     return;
10550b57cec5SDimitry Andric   }
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   // Keep track of which of retain, release, autorelease, and retain_block
10580b57cec5SDimitry Andric   // are actually present in this function.
10590b57cec5SDimitry Andric   UsedInThisFunction |= 1 << unsigned(Class);
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   // If Arg is a PHI, and one or more incoming values to the
10620b57cec5SDimitry Andric   // PHI are null, and the call is control-equivalent to the PHI, and there
10630b57cec5SDimitry Andric   // are no relevant side effects between the PHI and the call, and the call
10640b57cec5SDimitry Andric   // is not a release that doesn't have the clang.imprecise_release tag, the
10650b57cec5SDimitry Andric   // call could be pushed up to just those paths with non-null incoming
10660b57cec5SDimitry Andric   // values. For now, don't bother splitting critical edges for this.
10670b57cec5SDimitry Andric   if (Class == ARCInstKind::Release &&
10680b57cec5SDimitry Andric       !Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease)))
1069480093f4SDimitry Andric     return;
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric   SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
10720b57cec5SDimitry Andric   Worklist.push_back(std::make_pair(Inst, Arg));
10730b57cec5SDimitry Andric   do {
10740b57cec5SDimitry Andric     std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
10750b57cec5SDimitry Andric     Inst = Pair.first;
10760b57cec5SDimitry Andric     Arg = Pair.second;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric     const PHINode *PN = dyn_cast<PHINode>(Arg);
1079480093f4SDimitry Andric     if (!PN)
1080480093f4SDimitry Andric       continue;
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric     // Determine if the PHI has any null operands, or any incoming
10830b57cec5SDimitry Andric     // critical edges.
10840b57cec5SDimitry Andric     bool HasNull = false;
10850b57cec5SDimitry Andric     bool HasCriticalEdges = false;
10860b57cec5SDimitry Andric     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1087480093f4SDimitry Andric       Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i));
10880b57cec5SDimitry Andric       if (IsNullOrUndef(Incoming))
10890b57cec5SDimitry Andric         HasNull = true;
10900b57cec5SDimitry Andric       else if (PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() !=
10910b57cec5SDimitry Andric                1) {
10920b57cec5SDimitry Andric         HasCriticalEdges = true;
10930b57cec5SDimitry Andric         break;
10940b57cec5SDimitry Andric       }
10950b57cec5SDimitry Andric     }
10960b57cec5SDimitry Andric     // If we have null operands and no critical edges, optimize.
1097480093f4SDimitry Andric     if (HasCriticalEdges)
1098480093f4SDimitry Andric       continue;
1099480093f4SDimitry Andric     if (!HasNull)
1100480093f4SDimitry Andric       continue;
1101480093f4SDimitry Andric 
1102e8d8bef9SDimitry Andric     Instruction *DepInst = nullptr;
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric     // Check that there is nothing that cares about the reference
11050b57cec5SDimitry Andric     // count between the call and the phi.
11060b57cec5SDimitry Andric     switch (Class) {
11070b57cec5SDimitry Andric     case ARCInstKind::Retain:
11080b57cec5SDimitry Andric     case ARCInstKind::RetainBlock:
11090b57cec5SDimitry Andric       // These can always be moved up.
11100b57cec5SDimitry Andric       break;
11110b57cec5SDimitry Andric     case ARCInstKind::Release:
11120b57cec5SDimitry Andric       // These can't be moved across things that care about the retain
11130b57cec5SDimitry Andric       // count.
1114e8d8bef9SDimitry Andric       DepInst = findSingleDependency(NeedsPositiveRetainCount, Arg,
1115e8d8bef9SDimitry Andric                                      Inst->getParent(), Inst, PA);
11160b57cec5SDimitry Andric       break;
11170b57cec5SDimitry Andric     case ARCInstKind::Autorelease:
11180b57cec5SDimitry Andric       // These can't be moved across autorelease pool scope boundaries.
1119e8d8bef9SDimitry Andric       DepInst = findSingleDependency(AutoreleasePoolBoundary, Arg,
1120e8d8bef9SDimitry Andric                                      Inst->getParent(), Inst, PA);
11210b57cec5SDimitry Andric       break;
112204eeddc0SDimitry Andric     case ARCInstKind::UnsafeClaimRV:
11230b57cec5SDimitry Andric     case ARCInstKind::RetainRV:
11240b57cec5SDimitry Andric     case ARCInstKind::AutoreleaseRV:
11250b57cec5SDimitry Andric       // Don't move these; the RV optimization depends on the autoreleaseRV
11260b57cec5SDimitry Andric       // being tail called, and the retainRV being immediately after a call
11270b57cec5SDimitry Andric       // (which might still happen if we get lucky with codegen layout, but
11280b57cec5SDimitry Andric       // it's not worth taking the chance).
11290b57cec5SDimitry Andric       continue;
11300b57cec5SDimitry Andric     default:
11310b57cec5SDimitry Andric       llvm_unreachable("Invalid dependence flavor");
11320b57cec5SDimitry Andric     }
11330b57cec5SDimitry Andric 
1134e8d8bef9SDimitry Andric     if (DepInst != PN)
1135480093f4SDimitry Andric       continue;
1136480093f4SDimitry Andric 
11370b57cec5SDimitry Andric     Changed = true;
11380b57cec5SDimitry Andric     ++NumPartialNoops;
11390b57cec5SDimitry Andric     // Clone the call into each predecessor that has a non-null value.
11400b57cec5SDimitry Andric     CallInst *CInst = cast<CallInst>(Inst);
11410b57cec5SDimitry Andric     Type *ParamTy = CInst->getArgOperand(0)->getType();
11420b57cec5SDimitry Andric     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1143480093f4SDimitry Andric       Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i));
1144480093f4SDimitry Andric       if (IsNullOrUndef(Incoming))
1145480093f4SDimitry Andric         continue;
11460b57cec5SDimitry Andric       Value *Op = PN->getIncomingValue(i);
1147*0fca6ea1SDimitry Andric       BasicBlock::iterator InsertPos =
1148*0fca6ea1SDimitry Andric           PN->getIncomingBlock(i)->back().getIterator();
1149bdd1243dSDimitry Andric       SmallVector<OperandBundleDef, 1> OpBundles;
1150bdd1243dSDimitry Andric       cloneOpBundlesIf(CInst, OpBundles, [](const OperandBundleUse &B) {
1151bdd1243dSDimitry Andric         return B.getTagID() != LLVMContext::OB_funclet;
1152bdd1243dSDimitry Andric       });
1153bdd1243dSDimitry Andric       addOpBundleForFunclet(InsertPos->getParent(), OpBundles);
1154bdd1243dSDimitry Andric       CallInst *Clone = CallInst::Create(CInst, OpBundles);
11550b57cec5SDimitry Andric       if (Op->getType() != ParamTy)
11560b57cec5SDimitry Andric         Op = new BitCastInst(Op, ParamTy, "", InsertPos);
11570b57cec5SDimitry Andric       Clone->setArgOperand(0, Op);
1158*0fca6ea1SDimitry Andric       Clone->insertBefore(*InsertPos->getParent(), InsertPos);
11590b57cec5SDimitry Andric 
1160480093f4SDimitry Andric       LLVM_DEBUG(dbgs() << "Cloning " << *CInst << "\n"
11610b57cec5SDimitry Andric                                                    "And inserting clone at "
11620b57cec5SDimitry Andric                         << *InsertPos << "\n");
11630b57cec5SDimitry Andric       Worklist.push_back(std::make_pair(Clone, Incoming));
11640b57cec5SDimitry Andric     }
11650b57cec5SDimitry Andric     // Erase the original call.
11660b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
11670b57cec5SDimitry Andric     EraseInstruction(CInst);
11680b57cec5SDimitry Andric   } while (!Worklist.empty());
11690b57cec5SDimitry Andric }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric /// If we have a top down pointer in the S_Use state, make sure that there are
11720b57cec5SDimitry Andric /// no CFG hazards by checking the states of various bottom up pointers.
11730b57cec5SDimitry Andric static void CheckForUseCFGHazard(const Sequence SuccSSeq,
11740b57cec5SDimitry Andric                                  const bool SuccSRRIKnownSafe,
11750b57cec5SDimitry Andric                                  TopDownPtrState &S,
11760b57cec5SDimitry Andric                                  bool &SomeSuccHasSame,
11770b57cec5SDimitry Andric                                  bool &AllSuccsHaveSame,
11780b57cec5SDimitry Andric                                  bool &NotAllSeqEqualButKnownSafe,
11790b57cec5SDimitry Andric                                  bool &ShouldContinue) {
11800b57cec5SDimitry Andric   switch (SuccSSeq) {
11810b57cec5SDimitry Andric   case S_CanRelease: {
11820b57cec5SDimitry Andric     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
11830b57cec5SDimitry Andric       S.ClearSequenceProgress();
11840b57cec5SDimitry Andric       break;
11850b57cec5SDimitry Andric     }
11860b57cec5SDimitry Andric     S.SetCFGHazardAfflicted(true);
11870b57cec5SDimitry Andric     ShouldContinue = true;
11880b57cec5SDimitry Andric     break;
11890b57cec5SDimitry Andric   }
11900b57cec5SDimitry Andric   case S_Use:
11910b57cec5SDimitry Andric     SomeSuccHasSame = true;
11920b57cec5SDimitry Andric     break;
11930b57cec5SDimitry Andric   case S_Stop:
11940b57cec5SDimitry Andric   case S_MovableRelease:
11950b57cec5SDimitry Andric     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
11960b57cec5SDimitry Andric       AllSuccsHaveSame = false;
11970b57cec5SDimitry Andric     else
11980b57cec5SDimitry Andric       NotAllSeqEqualButKnownSafe = true;
11990b57cec5SDimitry Andric     break;
12000b57cec5SDimitry Andric   case S_Retain:
12010b57cec5SDimitry Andric     llvm_unreachable("bottom-up pointer in retain state!");
12020b57cec5SDimitry Andric   case S_None:
12030b57cec5SDimitry Andric     llvm_unreachable("This should have been handled earlier.");
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric /// If we have a Top Down pointer in the S_CanRelease state, make sure that
12080b57cec5SDimitry Andric /// there are no CFG hazards by checking the states of various bottom up
12090b57cec5SDimitry Andric /// pointers.
12100b57cec5SDimitry Andric static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
12110b57cec5SDimitry Andric                                         const bool SuccSRRIKnownSafe,
12120b57cec5SDimitry Andric                                         TopDownPtrState &S,
12130b57cec5SDimitry Andric                                         bool &SomeSuccHasSame,
12140b57cec5SDimitry Andric                                         bool &AllSuccsHaveSame,
12150b57cec5SDimitry Andric                                         bool &NotAllSeqEqualButKnownSafe) {
12160b57cec5SDimitry Andric   switch (SuccSSeq) {
12170b57cec5SDimitry Andric   case S_CanRelease:
12180b57cec5SDimitry Andric     SomeSuccHasSame = true;
12190b57cec5SDimitry Andric     break;
12200b57cec5SDimitry Andric   case S_Stop:
12210b57cec5SDimitry Andric   case S_MovableRelease:
12220b57cec5SDimitry Andric   case S_Use:
12230b57cec5SDimitry Andric     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
12240b57cec5SDimitry Andric       AllSuccsHaveSame = false;
12250b57cec5SDimitry Andric     else
12260b57cec5SDimitry Andric       NotAllSeqEqualButKnownSafe = true;
12270b57cec5SDimitry Andric     break;
12280b57cec5SDimitry Andric   case S_Retain:
12290b57cec5SDimitry Andric     llvm_unreachable("bottom-up pointer in retain state!");
12300b57cec5SDimitry Andric   case S_None:
12310b57cec5SDimitry Andric     llvm_unreachable("This should have been handled earlier.");
12320b57cec5SDimitry Andric   }
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric /// Check for critical edges, loop boundaries, irreducible control flow, or
12360b57cec5SDimitry Andric /// other CFG structures where moving code across the edge would result in it
12370b57cec5SDimitry Andric /// being executed more.
12380b57cec5SDimitry Andric void
12390b57cec5SDimitry Andric ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
12400b57cec5SDimitry Andric                                DenseMap<const BasicBlock *, BBState> &BBStates,
12410b57cec5SDimitry Andric                                BBState &MyStates) const {
12420b57cec5SDimitry Andric   // If any top-down local-use or possible-dec has a succ which is earlier in
12430b57cec5SDimitry Andric   // the sequence, forget it.
12440b57cec5SDimitry Andric   for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
12450b57cec5SDimitry Andric        I != E; ++I) {
12460b57cec5SDimitry Andric     TopDownPtrState &S = I->second;
12470b57cec5SDimitry Andric     const Sequence Seq = I->second.GetSeq();
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric     // We only care about S_Retain, S_CanRelease, and S_Use.
12500b57cec5SDimitry Andric     if (Seq == S_None)
12510b57cec5SDimitry Andric       continue;
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric     // Make sure that if extra top down states are added in the future that this
12540b57cec5SDimitry Andric     // code is updated to handle it.
12550b57cec5SDimitry Andric     assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
12560b57cec5SDimitry Andric            "Unknown top down sequence state.");
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric     const Value *Arg = I->first;
12590b57cec5SDimitry Andric     bool SomeSuccHasSame = false;
12600b57cec5SDimitry Andric     bool AllSuccsHaveSame = true;
12610b57cec5SDimitry Andric     bool NotAllSeqEqualButKnownSafe = false;
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric     for (const BasicBlock *Succ : successors(BB)) {
12640b57cec5SDimitry Andric       // If VisitBottomUp has pointer information for this successor, take
12650b57cec5SDimitry Andric       // what we know about it.
12660b57cec5SDimitry Andric       const DenseMap<const BasicBlock *, BBState>::iterator BBI =
12670b57cec5SDimitry Andric           BBStates.find(Succ);
12680b57cec5SDimitry Andric       assert(BBI != BBStates.end());
12690b57cec5SDimitry Andric       const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
12700b57cec5SDimitry Andric       const Sequence SuccSSeq = SuccS.GetSeq();
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric       // If bottom up, the pointer is in an S_None state, clear the sequence
12730b57cec5SDimitry Andric       // progress since the sequence in the bottom up state finished
12740b57cec5SDimitry Andric       // suggesting a mismatch in between retains/releases. This is true for
12750b57cec5SDimitry Andric       // all three cases that we are handling here: S_Retain, S_Use, and
12760b57cec5SDimitry Andric       // S_CanRelease.
12770b57cec5SDimitry Andric       if (SuccSSeq == S_None) {
12780b57cec5SDimitry Andric         S.ClearSequenceProgress();
12790b57cec5SDimitry Andric         continue;
12800b57cec5SDimitry Andric       }
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric       // If we have S_Use or S_CanRelease, perform our check for cfg hazard
12830b57cec5SDimitry Andric       // checks.
12840b57cec5SDimitry Andric       const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric       // *NOTE* We do not use Seq from above here since we are allowing for
12870b57cec5SDimitry Andric       // S.GetSeq() to change while we are visiting basic blocks.
12880b57cec5SDimitry Andric       switch(S.GetSeq()) {
12890b57cec5SDimitry Andric       case S_Use: {
12900b57cec5SDimitry Andric         bool ShouldContinue = false;
12910b57cec5SDimitry Andric         CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
12920b57cec5SDimitry Andric                              AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
12930b57cec5SDimitry Andric                              ShouldContinue);
12940b57cec5SDimitry Andric         if (ShouldContinue)
12950b57cec5SDimitry Andric           continue;
12960b57cec5SDimitry Andric         break;
12970b57cec5SDimitry Andric       }
12980b57cec5SDimitry Andric       case S_CanRelease:
12990b57cec5SDimitry Andric         CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
13000b57cec5SDimitry Andric                                     SomeSuccHasSame, AllSuccsHaveSame,
13010b57cec5SDimitry Andric                                     NotAllSeqEqualButKnownSafe);
13020b57cec5SDimitry Andric         break;
13030b57cec5SDimitry Andric       case S_Retain:
13040b57cec5SDimitry Andric       case S_None:
13050b57cec5SDimitry Andric       case S_Stop:
13060b57cec5SDimitry Andric       case S_MovableRelease:
13070b57cec5SDimitry Andric         break;
13080b57cec5SDimitry Andric       }
13090b57cec5SDimitry Andric     }
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric     // If the state at the other end of any of the successor edges
13120b57cec5SDimitry Andric     // matches the current state, require all edges to match. This
13130b57cec5SDimitry Andric     // guards against loops in the middle of a sequence.
13140b57cec5SDimitry Andric     if (SomeSuccHasSame && !AllSuccsHaveSame) {
13150b57cec5SDimitry Andric       S.ClearSequenceProgress();
13160b57cec5SDimitry Andric     } else if (NotAllSeqEqualButKnownSafe) {
13170b57cec5SDimitry Andric       // If we would have cleared the state foregoing the fact that we are known
13180b57cec5SDimitry Andric       // safe, stop code motion. This is because whether or not it is safe to
13190b57cec5SDimitry Andric       // remove RR pairs via KnownSafe is an orthogonal concept to whether we
13200b57cec5SDimitry Andric       // are allowed to perform code motion.
13210b57cec5SDimitry Andric       S.SetCFGHazardAfflicted(true);
13220b57cec5SDimitry Andric     }
13230b57cec5SDimitry Andric   }
13240b57cec5SDimitry Andric }
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric bool ObjCARCOpt::VisitInstructionBottomUp(
13270b57cec5SDimitry Andric     Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
13280b57cec5SDimitry Andric     BBState &MyStates) {
13290b57cec5SDimitry Andric   bool NestingDetected = false;
13300b57cec5SDimitry Andric   ARCInstKind Class = GetARCInstKind(Inst);
13310b57cec5SDimitry Andric   const Value *Arg = nullptr;
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "        Class: " << Class << "\n");
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric   switch (Class) {
13360b57cec5SDimitry Andric   case ARCInstKind::Release: {
13370b57cec5SDimitry Andric     Arg = GetArgRCIdentityRoot(Inst);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric     BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
13400b57cec5SDimitry Andric     NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
13410b57cec5SDimitry Andric     break;
13420b57cec5SDimitry Andric   }
13430b57cec5SDimitry Andric   case ARCInstKind::RetainBlock:
13440b57cec5SDimitry Andric     // In OptimizeIndividualCalls, we have strength reduced all optimizable
13450b57cec5SDimitry Andric     // objc_retainBlocks to objc_retains. Thus at this point any
13460b57cec5SDimitry Andric     // objc_retainBlocks that we see are not optimizable.
13470b57cec5SDimitry Andric     break;
13480b57cec5SDimitry Andric   case ARCInstKind::Retain:
13490b57cec5SDimitry Andric   case ARCInstKind::RetainRV: {
13500b57cec5SDimitry Andric     Arg = GetArgRCIdentityRoot(Inst);
13510b57cec5SDimitry Andric     BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
13520b57cec5SDimitry Andric     if (S.MatchWithRetain()) {
13530b57cec5SDimitry Andric       // Don't do retain+release tracking for ARCInstKind::RetainRV, because
13540b57cec5SDimitry Andric       // it's better to let it remain as the first instruction after a call.
13550b57cec5SDimitry Andric       if (Class != ARCInstKind::RetainRV) {
13560b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "        Matching with: " << *Inst << "\n");
13570b57cec5SDimitry Andric         Retains[Inst] = S.GetRRInfo();
13580b57cec5SDimitry Andric       }
13590b57cec5SDimitry Andric       S.ClearSequenceProgress();
13600b57cec5SDimitry Andric     }
13610b57cec5SDimitry Andric     // A retain moving bottom up can be a use.
13620b57cec5SDimitry Andric     break;
13630b57cec5SDimitry Andric   }
13640b57cec5SDimitry Andric   case ARCInstKind::AutoreleasepoolPop:
13650b57cec5SDimitry Andric     // Conservatively, clear MyStates for all known pointers.
13660b57cec5SDimitry Andric     MyStates.clearBottomUpPointers();
13670b57cec5SDimitry Andric     return NestingDetected;
13680b57cec5SDimitry Andric   case ARCInstKind::AutoreleasepoolPush:
13690b57cec5SDimitry Andric   case ARCInstKind::None:
13700b57cec5SDimitry Andric     // These are irrelevant.
13710b57cec5SDimitry Andric     return NestingDetected;
13720b57cec5SDimitry Andric   default:
13730b57cec5SDimitry Andric     break;
13740b57cec5SDimitry Andric   }
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric   // Consider any other possible effects of this instruction on each
13770b57cec5SDimitry Andric   // pointer being tracked.
13780b57cec5SDimitry Andric   for (auto MI = MyStates.bottom_up_ptr_begin(),
13790b57cec5SDimitry Andric             ME = MyStates.bottom_up_ptr_end();
13800b57cec5SDimitry Andric        MI != ME; ++MI) {
13810b57cec5SDimitry Andric     const Value *Ptr = MI->first;
13820b57cec5SDimitry Andric     if (Ptr == Arg)
13830b57cec5SDimitry Andric       continue; // Handled above.
13840b57cec5SDimitry Andric     BottomUpPtrState &S = MI->second;
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric     if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
13870b57cec5SDimitry Andric       continue;
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric     S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
13900b57cec5SDimitry Andric   }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric   return NestingDetected;
13930b57cec5SDimitry Andric }
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
13960b57cec5SDimitry Andric                                DenseMap<const BasicBlock *, BBState> &BBStates,
13970b57cec5SDimitry Andric                                BlotMapVector<Value *, RRInfo> &Retains) {
13980b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   bool NestingDetected = false;
14010b57cec5SDimitry Andric   BBState &MyStates = BBStates[BB];
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // Merge the states from each successor to compute the initial state
14040b57cec5SDimitry Andric   // for the current block.
14050b57cec5SDimitry Andric   BBState::edge_iterator SI(MyStates.succ_begin()),
14060b57cec5SDimitry Andric                          SE(MyStates.succ_end());
14070b57cec5SDimitry Andric   if (SI != SE) {
14080b57cec5SDimitry Andric     const BasicBlock *Succ = *SI;
14090b57cec5SDimitry Andric     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
14100b57cec5SDimitry Andric     assert(I != BBStates.end());
14110b57cec5SDimitry Andric     MyStates.InitFromSucc(I->second);
14120b57cec5SDimitry Andric     ++SI;
14130b57cec5SDimitry Andric     for (; SI != SE; ++SI) {
14140b57cec5SDimitry Andric       Succ = *SI;
14150b57cec5SDimitry Andric       I = BBStates.find(Succ);
14160b57cec5SDimitry Andric       assert(I != BBStates.end());
14170b57cec5SDimitry Andric       MyStates.MergeSucc(I->second);
14180b57cec5SDimitry Andric     }
14190b57cec5SDimitry Andric   }
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Before:\n"
14220b57cec5SDimitry Andric                     << BBStates[BB] << "\n"
14230b57cec5SDimitry Andric                     << "Performing Dataflow:\n");
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric   // Visit all the instructions, bottom-up.
14260b57cec5SDimitry Andric   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
14270b57cec5SDimitry Andric     Instruction *Inst = &*std::prev(I);
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric     // Invoke instructions are visited as part of their successors (below).
14300b57cec5SDimitry Andric     if (isa<InvokeInst>(Inst))
14310b57cec5SDimitry Andric       continue;
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    Visiting " << *Inst << "\n");
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric     // Bail out if the number of pointers being tracked becomes too large so
14380b57cec5SDimitry Andric     // that this pass can complete in a reasonable amount of time.
14390b57cec5SDimitry Andric     if (MyStates.bottom_up_ptr_list_size() > MaxPtrStates) {
14400b57cec5SDimitry Andric       DisableRetainReleasePairing = true;
14410b57cec5SDimitry Andric       return false;
14420b57cec5SDimitry Andric     }
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   // If there's a predecessor with an invoke, visit the invoke as if it were
14460b57cec5SDimitry Andric   // part of this block, since we can't insert code after an invoke in its own
14470b57cec5SDimitry Andric   // block, and we don't want to split critical edges.
14480b57cec5SDimitry Andric   for (BBState::edge_iterator PI(MyStates.pred_begin()),
14490b57cec5SDimitry Andric        PE(MyStates.pred_end()); PI != PE; ++PI) {
14500b57cec5SDimitry Andric     BasicBlock *Pred = *PI;
14510b57cec5SDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
14520b57cec5SDimitry Andric       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
14530b57cec5SDimitry Andric   }
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   return NestingDetected;
14580b57cec5SDimitry Andric }
14590b57cec5SDimitry Andric 
1460fe6060f1SDimitry Andric // Fill ReleaseInsertPtToRCIdentityRoots, which is a map from insertion points
1461fe6060f1SDimitry Andric // to the set of RC identity roots that would be released by the release calls
1462fe6060f1SDimitry Andric // moved to the insertion points.
1463fe6060f1SDimitry Andric static void collectReleaseInsertPts(
1464fe6060f1SDimitry Andric     const BlotMapVector<Value *, RRInfo> &Retains,
1465fe6060f1SDimitry Andric     DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
1466fe6060f1SDimitry Andric         &ReleaseInsertPtToRCIdentityRoots) {
1467bdd1243dSDimitry Andric   for (const auto &P : Retains) {
1468fe6060f1SDimitry Andric     // Retains is a map from an objc_retain call to a RRInfo of the RC identity
1469fe6060f1SDimitry Andric     // root of the call. Get the RC identity root of the objc_retain call.
1470fe6060f1SDimitry Andric     Instruction *Retain = cast<Instruction>(P.first);
1471fe6060f1SDimitry Andric     Value *Root = GetRCIdentityRoot(Retain->getOperand(0));
1472fe6060f1SDimitry Andric     // Collect all the insertion points of the objc_release calls that release
1473fe6060f1SDimitry Andric     // the RC identity root of the objc_retain call.
1474fe6060f1SDimitry Andric     for (const Instruction *InsertPt : P.second.ReverseInsertPts)
1475fe6060f1SDimitry Andric       ReleaseInsertPtToRCIdentityRoots[InsertPt].insert(Root);
1476fe6060f1SDimitry Andric   }
1477fe6060f1SDimitry Andric }
1478fe6060f1SDimitry Andric 
1479fe6060f1SDimitry Andric // Get the RC identity roots from an insertion point of an objc_release call.
1480fe6060f1SDimitry Andric // Return nullptr if the passed instruction isn't an insertion point.
1481fe6060f1SDimitry Andric static const SmallPtrSet<const Value *, 2> *
1482fe6060f1SDimitry Andric getRCIdentityRootsFromReleaseInsertPt(
1483fe6060f1SDimitry Andric     const Instruction *InsertPt,
1484fe6060f1SDimitry Andric     const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
1485fe6060f1SDimitry Andric         &ReleaseInsertPtToRCIdentityRoots) {
1486fe6060f1SDimitry Andric   auto I = ReleaseInsertPtToRCIdentityRoots.find(InsertPt);
1487fe6060f1SDimitry Andric   if (I == ReleaseInsertPtToRCIdentityRoots.end())
1488fe6060f1SDimitry Andric     return nullptr;
1489fe6060f1SDimitry Andric   return &I->second;
1490fe6060f1SDimitry Andric }
1491fe6060f1SDimitry Andric 
1492fe6060f1SDimitry Andric bool ObjCARCOpt::VisitInstructionTopDown(
1493fe6060f1SDimitry Andric     Instruction *Inst, DenseMap<Value *, RRInfo> &Releases, BBState &MyStates,
1494fe6060f1SDimitry Andric     const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
1495fe6060f1SDimitry Andric         &ReleaseInsertPtToRCIdentityRoots) {
14960b57cec5SDimitry Andric   bool NestingDetected = false;
14970b57cec5SDimitry Andric   ARCInstKind Class = GetARCInstKind(Inst);
14980b57cec5SDimitry Andric   const Value *Arg = nullptr;
14990b57cec5SDimitry Andric 
1500fe6060f1SDimitry Andric   // Make sure a call to objc_retain isn't moved past insertion points of calls
1501fe6060f1SDimitry Andric   // to objc_release.
1502fe6060f1SDimitry Andric   if (const SmallPtrSet<const Value *, 2> *Roots =
1503fe6060f1SDimitry Andric           getRCIdentityRootsFromReleaseInsertPt(
1504fe6060f1SDimitry Andric               Inst, ReleaseInsertPtToRCIdentityRoots))
1505bdd1243dSDimitry Andric     for (const auto *Root : *Roots) {
1506fe6060f1SDimitry Andric       TopDownPtrState &S = MyStates.getPtrTopDownState(Root);
1507fe6060f1SDimitry Andric       // Disable code motion if the current position is S_Retain to prevent
1508fe6060f1SDimitry Andric       // moving the objc_retain call past objc_release calls. If it's
1509fe6060f1SDimitry Andric       // S_CanRelease or larger, it's not necessary to disable code motion as
1510fe6060f1SDimitry Andric       // the insertion points that prevent the objc_retain call from moving down
1511fe6060f1SDimitry Andric       // should have been set already.
1512fe6060f1SDimitry Andric       if (S.GetSeq() == S_Retain)
1513fe6060f1SDimitry Andric         S.SetCFGHazardAfflicted(true);
1514fe6060f1SDimitry Andric     }
1515fe6060f1SDimitry Andric 
15160b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "        Class: " << Class << "\n");
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric   switch (Class) {
15190b57cec5SDimitry Andric   case ARCInstKind::RetainBlock:
15200b57cec5SDimitry Andric     // In OptimizeIndividualCalls, we have strength reduced all optimizable
15210b57cec5SDimitry Andric     // objc_retainBlocks to objc_retains. Thus at this point any
15220b57cec5SDimitry Andric     // objc_retainBlocks that we see are not optimizable. We need to break since
15230b57cec5SDimitry Andric     // a retain can be a potential use.
15240b57cec5SDimitry Andric     break;
15250b57cec5SDimitry Andric   case ARCInstKind::Retain:
15260b57cec5SDimitry Andric   case ARCInstKind::RetainRV: {
15270b57cec5SDimitry Andric     Arg = GetArgRCIdentityRoot(Inst);
15280b57cec5SDimitry Andric     TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
15290b57cec5SDimitry Andric     NestingDetected |= S.InitTopDown(Class, Inst);
15300b57cec5SDimitry Andric     // A retain can be a potential use; proceed to the generic checking
15310b57cec5SDimitry Andric     // code below.
15320b57cec5SDimitry Andric     break;
15330b57cec5SDimitry Andric   }
15340b57cec5SDimitry Andric   case ARCInstKind::Release: {
15350b57cec5SDimitry Andric     Arg = GetArgRCIdentityRoot(Inst);
15360b57cec5SDimitry Andric     TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
15370b57cec5SDimitry Andric     // Try to form a tentative pair in between this release instruction and the
15380b57cec5SDimitry Andric     // top down pointers that we are tracking.
15390b57cec5SDimitry Andric     if (S.MatchWithRelease(MDKindCache, Inst)) {
15400b57cec5SDimitry Andric       // If we succeed, copy S's RRInfo into the Release -> {Retain Set
15410b57cec5SDimitry Andric       // Map}. Then we clear S.
15420b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "        Matching with: " << *Inst << "\n");
15430b57cec5SDimitry Andric       Releases[Inst] = S.GetRRInfo();
15440b57cec5SDimitry Andric       S.ClearSequenceProgress();
15450b57cec5SDimitry Andric     }
15460b57cec5SDimitry Andric     break;
15470b57cec5SDimitry Andric   }
15480b57cec5SDimitry Andric   case ARCInstKind::AutoreleasepoolPop:
15490b57cec5SDimitry Andric     // Conservatively, clear MyStates for all known pointers.
15500b57cec5SDimitry Andric     MyStates.clearTopDownPointers();
15510b57cec5SDimitry Andric     return false;
15520b57cec5SDimitry Andric   case ARCInstKind::AutoreleasepoolPush:
15530b57cec5SDimitry Andric   case ARCInstKind::None:
15540b57cec5SDimitry Andric     // These can not be uses of
15550b57cec5SDimitry Andric     return false;
15560b57cec5SDimitry Andric   default:
15570b57cec5SDimitry Andric     break;
15580b57cec5SDimitry Andric   }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric   // Consider any other possible effects of this instruction on each
15610b57cec5SDimitry Andric   // pointer being tracked.
15620b57cec5SDimitry Andric   for (auto MI = MyStates.top_down_ptr_begin(),
15630b57cec5SDimitry Andric             ME = MyStates.top_down_ptr_end();
15640b57cec5SDimitry Andric        MI != ME; ++MI) {
15650b57cec5SDimitry Andric     const Value *Ptr = MI->first;
15660b57cec5SDimitry Andric     if (Ptr == Arg)
15670b57cec5SDimitry Andric       continue; // Handled above.
15680b57cec5SDimitry Andric     TopDownPtrState &S = MI->second;
1569fe6060f1SDimitry Andric     if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class, *BundledInsts))
15700b57cec5SDimitry Andric       continue;
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric     S.HandlePotentialUse(Inst, Ptr, PA, Class);
15730b57cec5SDimitry Andric   }
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   return NestingDetected;
15760b57cec5SDimitry Andric }
15770b57cec5SDimitry Andric 
1578fe6060f1SDimitry Andric bool ObjCARCOpt::VisitTopDown(
1579fe6060f1SDimitry Andric     BasicBlock *BB, DenseMap<const BasicBlock *, BBState> &BBStates,
1580fe6060f1SDimitry Andric     DenseMap<Value *, RRInfo> &Releases,
1581fe6060f1SDimitry Andric     const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
1582fe6060f1SDimitry Andric         &ReleaseInsertPtToRCIdentityRoots) {
15830b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
15840b57cec5SDimitry Andric   bool NestingDetected = false;
15850b57cec5SDimitry Andric   BBState &MyStates = BBStates[BB];
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   // Merge the states from each predecessor to compute the initial state
15880b57cec5SDimitry Andric   // for the current block.
15890b57cec5SDimitry Andric   BBState::edge_iterator PI(MyStates.pred_begin()),
15900b57cec5SDimitry Andric                          PE(MyStates.pred_end());
15910b57cec5SDimitry Andric   if (PI != PE) {
15920b57cec5SDimitry Andric     const BasicBlock *Pred = *PI;
15930b57cec5SDimitry Andric     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
15940b57cec5SDimitry Andric     assert(I != BBStates.end());
15950b57cec5SDimitry Andric     MyStates.InitFromPred(I->second);
15960b57cec5SDimitry Andric     ++PI;
15970b57cec5SDimitry Andric     for (; PI != PE; ++PI) {
15980b57cec5SDimitry Andric       Pred = *PI;
15990b57cec5SDimitry Andric       I = BBStates.find(Pred);
16000b57cec5SDimitry Andric       assert(I != BBStates.end());
16010b57cec5SDimitry Andric       MyStates.MergePred(I->second);
16020b57cec5SDimitry Andric     }
16030b57cec5SDimitry Andric   }
16040b57cec5SDimitry Andric 
16055ffd83dbSDimitry Andric   // Check that BB and MyStates have the same number of predecessors. This
16065ffd83dbSDimitry Andric   // prevents retain calls that live outside a loop from being moved into the
16075ffd83dbSDimitry Andric   // loop.
16085ffd83dbSDimitry Andric   if (!BB->hasNPredecessors(MyStates.pred_end() - MyStates.pred_begin()))
16095ffd83dbSDimitry Andric     for (auto I = MyStates.top_down_ptr_begin(),
16105ffd83dbSDimitry Andric               E = MyStates.top_down_ptr_end();
16115ffd83dbSDimitry Andric          I != E; ++I)
16125ffd83dbSDimitry Andric       I->second.SetCFGHazardAfflicted(true);
16135ffd83dbSDimitry Andric 
16140b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Before:\n"
16150b57cec5SDimitry Andric                     << BBStates[BB] << "\n"
16160b57cec5SDimitry Andric                     << "Performing Dataflow:\n");
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric   // Visit all the instructions, top-down.
16190b57cec5SDimitry Andric   for (Instruction &Inst : *BB) {
16200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    Visiting " << Inst << "\n");
16210b57cec5SDimitry Andric 
1622fe6060f1SDimitry Andric     NestingDetected |= VisitInstructionTopDown(
1623fe6060f1SDimitry Andric         &Inst, Releases, MyStates, ReleaseInsertPtToRCIdentityRoots);
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric     // Bail out if the number of pointers being tracked becomes too large so
16260b57cec5SDimitry Andric     // that this pass can complete in a reasonable amount of time.
16270b57cec5SDimitry Andric     if (MyStates.top_down_ptr_list_size() > MaxPtrStates) {
16280b57cec5SDimitry Andric       DisableRetainReleasePairing = true;
16290b57cec5SDimitry Andric       return false;
16300b57cec5SDimitry Andric     }
16310b57cec5SDimitry Andric   }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nState Before Checking for CFG Hazards:\n"
16340b57cec5SDimitry Andric                     << BBStates[BB] << "\n\n");
16350b57cec5SDimitry Andric   CheckForCFGHazards(BB, BBStates, MyStates);
16360b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Final State:\n" << BBStates[BB] << "\n");
16370b57cec5SDimitry Andric   return NestingDetected;
16380b57cec5SDimitry Andric }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric static void
16410b57cec5SDimitry Andric ComputePostOrders(Function &F,
16420b57cec5SDimitry Andric                   SmallVectorImpl<BasicBlock *> &PostOrder,
16430b57cec5SDimitry Andric                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
16440b57cec5SDimitry Andric                   unsigned NoObjCARCExceptionsMDKind,
16450b57cec5SDimitry Andric                   DenseMap<const BasicBlock *, BBState> &BBStates) {
16460b57cec5SDimitry Andric   /// The visited set, for doing DFS walks.
16470b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Visited;
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   // Do DFS, computing the PostOrder.
16500b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> OnStack;
16510b57cec5SDimitry Andric   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   // Functions always have exactly one entry block, and we don't have
16540b57cec5SDimitry Andric   // any other block that we treat like an entry block.
16550b57cec5SDimitry Andric   BasicBlock *EntryBB = &F.getEntryBlock();
16560b57cec5SDimitry Andric   BBState &MyStates = BBStates[EntryBB];
16570b57cec5SDimitry Andric   MyStates.SetAsEntry();
16580b57cec5SDimitry Andric   Instruction *EntryTI = EntryBB->getTerminator();
16590b57cec5SDimitry Andric   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
16600b57cec5SDimitry Andric   Visited.insert(EntryBB);
16610b57cec5SDimitry Andric   OnStack.insert(EntryBB);
16620b57cec5SDimitry Andric   do {
16630b57cec5SDimitry Andric   dfs_next_succ:
16640b57cec5SDimitry Andric     BasicBlock *CurrBB = SuccStack.back().first;
16650b57cec5SDimitry Andric     succ_iterator SE(CurrBB->getTerminator(), false);
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric     while (SuccStack.back().second != SE) {
16680b57cec5SDimitry Andric       BasicBlock *SuccBB = *SuccStack.back().second++;
16690b57cec5SDimitry Andric       if (Visited.insert(SuccBB).second) {
16700b57cec5SDimitry Andric         SuccStack.push_back(
16710b57cec5SDimitry Andric             std::make_pair(SuccBB, succ_iterator(SuccBB->getTerminator())));
16720b57cec5SDimitry Andric         BBStates[CurrBB].addSucc(SuccBB);
16730b57cec5SDimitry Andric         BBState &SuccStates = BBStates[SuccBB];
16740b57cec5SDimitry Andric         SuccStates.addPred(CurrBB);
16750b57cec5SDimitry Andric         OnStack.insert(SuccBB);
16760b57cec5SDimitry Andric         goto dfs_next_succ;
16770b57cec5SDimitry Andric       }
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric       if (!OnStack.count(SuccBB)) {
16800b57cec5SDimitry Andric         BBStates[CurrBB].addSucc(SuccBB);
16810b57cec5SDimitry Andric         BBStates[SuccBB].addPred(CurrBB);
16820b57cec5SDimitry Andric       }
16830b57cec5SDimitry Andric     }
16840b57cec5SDimitry Andric     OnStack.erase(CurrBB);
16850b57cec5SDimitry Andric     PostOrder.push_back(CurrBB);
16860b57cec5SDimitry Andric     SuccStack.pop_back();
16870b57cec5SDimitry Andric   } while (!SuccStack.empty());
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric   Visited.clear();
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
16920b57cec5SDimitry Andric   // Functions may have many exits, and there also blocks which we treat
16930b57cec5SDimitry Andric   // as exits due to ignored edges.
16940b57cec5SDimitry Andric   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
16950b57cec5SDimitry Andric   for (BasicBlock &ExitBB : F) {
16960b57cec5SDimitry Andric     BBState &MyStates = BBStates[&ExitBB];
16970b57cec5SDimitry Andric     if (!MyStates.isExit())
16980b57cec5SDimitry Andric       continue;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric     MyStates.SetAsExit();
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric     PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
17030b57cec5SDimitry Andric     Visited.insert(&ExitBB);
17040b57cec5SDimitry Andric     while (!PredStack.empty()) {
17050b57cec5SDimitry Andric     reverse_dfs_next_succ:
17060b57cec5SDimitry Andric       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
17070b57cec5SDimitry Andric       while (PredStack.back().second != PE) {
17080b57cec5SDimitry Andric         BasicBlock *BB = *PredStack.back().second++;
17090b57cec5SDimitry Andric         if (Visited.insert(BB).second) {
17100b57cec5SDimitry Andric           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
17110b57cec5SDimitry Andric           goto reverse_dfs_next_succ;
17120b57cec5SDimitry Andric         }
17130b57cec5SDimitry Andric       }
17140b57cec5SDimitry Andric       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
17150b57cec5SDimitry Andric     }
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric }
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric // Visit the function both top-down and bottom-up.
17200b57cec5SDimitry Andric bool ObjCARCOpt::Visit(Function &F,
17210b57cec5SDimitry Andric                        DenseMap<const BasicBlock *, BBState> &BBStates,
17220b57cec5SDimitry Andric                        BlotMapVector<Value *, RRInfo> &Retains,
17230b57cec5SDimitry Andric                        DenseMap<Value *, RRInfo> &Releases) {
17240b57cec5SDimitry Andric   // Use reverse-postorder traversals, because we magically know that loops
17250b57cec5SDimitry Andric   // will be well behaved, i.e. they won't repeatedly call retain on a single
17260b57cec5SDimitry Andric   // pointer without doing a release. We can't use the ReversePostOrderTraversal
17270b57cec5SDimitry Andric   // class here because we want the reverse-CFG postorder to consider each
17280b57cec5SDimitry Andric   // function exit point, and we want to ignore selected cycle edges.
17290b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> PostOrder;
17300b57cec5SDimitry Andric   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
17310b57cec5SDimitry Andric   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
17320b57cec5SDimitry Andric                     MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
17330b57cec5SDimitry Andric                     BBStates);
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   // Use reverse-postorder on the reverse CFG for bottom-up.
17360b57cec5SDimitry Andric   bool BottomUpNestingDetected = false;
17370b57cec5SDimitry Andric   for (BasicBlock *BB : llvm::reverse(ReverseCFGPostOrder)) {
17380b57cec5SDimitry Andric     BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
17390b57cec5SDimitry Andric     if (DisableRetainReleasePairing)
17400b57cec5SDimitry Andric       return false;
17410b57cec5SDimitry Andric   }
17420b57cec5SDimitry Andric 
1743fe6060f1SDimitry Andric   DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
1744fe6060f1SDimitry Andric       ReleaseInsertPtToRCIdentityRoots;
1745fe6060f1SDimitry Andric   collectReleaseInsertPts(Retains, ReleaseInsertPtToRCIdentityRoots);
1746fe6060f1SDimitry Andric 
17470b57cec5SDimitry Andric   // Use reverse-postorder for top-down.
17480b57cec5SDimitry Andric   bool TopDownNestingDetected = false;
17490b57cec5SDimitry Andric   for (BasicBlock *BB : llvm::reverse(PostOrder)) {
1750fe6060f1SDimitry Andric     TopDownNestingDetected |=
1751fe6060f1SDimitry Andric         VisitTopDown(BB, BBStates, Releases, ReleaseInsertPtToRCIdentityRoots);
17520b57cec5SDimitry Andric     if (DisableRetainReleasePairing)
17530b57cec5SDimitry Andric       return false;
17540b57cec5SDimitry Andric   }
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   return TopDownNestingDetected && BottomUpNestingDetected;
17570b57cec5SDimitry Andric }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric /// Move the calls in RetainsToMove and ReleasesToMove.
17600b57cec5SDimitry Andric void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
17610b57cec5SDimitry Andric                            RRInfo &ReleasesToMove,
17620b57cec5SDimitry Andric                            BlotMapVector<Value *, RRInfo> &Retains,
17630b57cec5SDimitry Andric                            DenseMap<Value *, RRInfo> &Releases,
17640b57cec5SDimitry Andric                            SmallVectorImpl<Instruction *> &DeadInsts,
17650b57cec5SDimitry Andric                            Module *M) {
17660b57cec5SDimitry Andric   Type *ArgTy = Arg->getType();
17670b57cec5SDimitry Andric   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   // Insert the new retain and release calls.
17720b57cec5SDimitry Andric   for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
1773*0fca6ea1SDimitry Andric     Value *MyArg = ArgTy == ParamTy ? Arg
1774*0fca6ea1SDimitry Andric                                     : new BitCastInst(Arg, ParamTy, "",
1775*0fca6ea1SDimitry Andric                                                       InsertPt->getIterator());
17760b57cec5SDimitry Andric     Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1777bdd1243dSDimitry Andric     SmallVector<OperandBundleDef, 1> BundleList;
1778bdd1243dSDimitry Andric     addOpBundleForFunclet(InsertPt->getParent(), BundleList);
1779*0fca6ea1SDimitry Andric     CallInst *Call =
1780*0fca6ea1SDimitry Andric         CallInst::Create(Decl, MyArg, BundleList, "", InsertPt->getIterator());
17810b57cec5SDimitry Andric     Call->setDoesNotThrow();
17820b57cec5SDimitry Andric     Call->setTailCall();
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserting new Retain: " << *Call
17850b57cec5SDimitry Andric                       << "\n"
17860b57cec5SDimitry Andric                          "At insertion point: "
17870b57cec5SDimitry Andric                       << *InsertPt << "\n");
17880b57cec5SDimitry Andric   }
17890b57cec5SDimitry Andric   for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
1790*0fca6ea1SDimitry Andric     Value *MyArg = ArgTy == ParamTy ? Arg
1791*0fca6ea1SDimitry Andric                                     : new BitCastInst(Arg, ParamTy, "",
1792*0fca6ea1SDimitry Andric                                                       InsertPt->getIterator());
17930b57cec5SDimitry Andric     Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
1794bdd1243dSDimitry Andric     SmallVector<OperandBundleDef, 1> BundleList;
1795bdd1243dSDimitry Andric     addOpBundleForFunclet(InsertPt->getParent(), BundleList);
1796*0fca6ea1SDimitry Andric     CallInst *Call =
1797*0fca6ea1SDimitry Andric         CallInst::Create(Decl, MyArg, BundleList, "", InsertPt->getIterator());
17980b57cec5SDimitry Andric     // Attach a clang.imprecise_release metadata tag, if appropriate.
17990b57cec5SDimitry Andric     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
18000b57cec5SDimitry Andric       Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
18010b57cec5SDimitry Andric     Call->setDoesNotThrow();
18020b57cec5SDimitry Andric     if (ReleasesToMove.IsTailCallRelease)
18030b57cec5SDimitry Andric       Call->setTailCall();
18040b57cec5SDimitry Andric 
18050b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserting new Release: " << *Call
18060b57cec5SDimitry Andric                       << "\n"
18070b57cec5SDimitry Andric                          "At insertion point: "
18080b57cec5SDimitry Andric                       << *InsertPt << "\n");
18090b57cec5SDimitry Andric   }
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   // Delete the original retain and release calls.
18120b57cec5SDimitry Andric   for (Instruction *OrigRetain : RetainsToMove.Calls) {
18130b57cec5SDimitry Andric     Retains.blot(OrigRetain);
18140b57cec5SDimitry Andric     DeadInsts.push_back(OrigRetain);
18150b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
18160b57cec5SDimitry Andric   }
18170b57cec5SDimitry Andric   for (Instruction *OrigRelease : ReleasesToMove.Calls) {
18180b57cec5SDimitry Andric     Releases.erase(OrigRelease);
18190b57cec5SDimitry Andric     DeadInsts.push_back(OrigRelease);
18200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
18210b57cec5SDimitry Andric   }
18220b57cec5SDimitry Andric }
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric bool ObjCARCOpt::PairUpRetainsAndReleases(
18250b57cec5SDimitry Andric     DenseMap<const BasicBlock *, BBState> &BBStates,
18260b57cec5SDimitry Andric     BlotMapVector<Value *, RRInfo> &Retains,
18270b57cec5SDimitry Andric     DenseMap<Value *, RRInfo> &Releases, Module *M,
18280b57cec5SDimitry Andric     Instruction *Retain,
18290b57cec5SDimitry Andric     SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
18300b57cec5SDimitry Andric     RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
18310b57cec5SDimitry Andric     bool &AnyPairsCompletelyEliminated) {
18320b57cec5SDimitry Andric   // If a pair happens in a region where it is known that the reference count
18330b57cec5SDimitry Andric   // is already incremented, we can similarly ignore possible decrements unless
18340b57cec5SDimitry Andric   // we are dealing with a retainable object with multiple provenance sources.
18350b57cec5SDimitry Andric   bool KnownSafeTD = true, KnownSafeBU = true;
18360b57cec5SDimitry Andric   bool CFGHazardAfflicted = false;
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   // Connect the dots between the top-down-collected RetainsToMove and
18390b57cec5SDimitry Andric   // bottom-up-collected ReleasesToMove to form sets of related calls.
18400b57cec5SDimitry Andric   // This is an iterative process so that we connect multiple releases
18410b57cec5SDimitry Andric   // to multiple retains if needed.
18420b57cec5SDimitry Andric   unsigned OldDelta = 0;
18430b57cec5SDimitry Andric   unsigned NewDelta = 0;
18440b57cec5SDimitry Andric   unsigned OldCount = 0;
18450b57cec5SDimitry Andric   unsigned NewCount = 0;
18460b57cec5SDimitry Andric   bool FirstRelease = true;
18470b57cec5SDimitry Andric   for (SmallVector<Instruction *, 4> NewRetains{Retain};;) {
18480b57cec5SDimitry Andric     SmallVector<Instruction *, 4> NewReleases;
18490b57cec5SDimitry Andric     for (Instruction *NewRetain : NewRetains) {
18500b57cec5SDimitry Andric       auto It = Retains.find(NewRetain);
18510b57cec5SDimitry Andric       assert(It != Retains.end());
18520b57cec5SDimitry Andric       const RRInfo &NewRetainRRI = It->second;
18530b57cec5SDimitry Andric       KnownSafeTD &= NewRetainRRI.KnownSafe;
18540b57cec5SDimitry Andric       CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted;
18550b57cec5SDimitry Andric       for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
18560b57cec5SDimitry Andric         auto Jt = Releases.find(NewRetainRelease);
18570b57cec5SDimitry Andric         if (Jt == Releases.end())
18580b57cec5SDimitry Andric           return false;
18590b57cec5SDimitry Andric         const RRInfo &NewRetainReleaseRRI = Jt->second;
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric         // If the release does not have a reference to the retain as well,
18620b57cec5SDimitry Andric         // something happened which is unaccounted for. Do not do anything.
18630b57cec5SDimitry Andric         //
18640b57cec5SDimitry Andric         // This can happen if we catch an additive overflow during path count
18650b57cec5SDimitry Andric         // merging.
18660b57cec5SDimitry Andric         if (!NewRetainReleaseRRI.Calls.count(NewRetain))
18670b57cec5SDimitry Andric           return false;
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric         if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
18700b57cec5SDimitry Andric           // If we overflow when we compute the path count, don't remove/move
18710b57cec5SDimitry Andric           // anything.
18720b57cec5SDimitry Andric           const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
18730b57cec5SDimitry Andric           unsigned PathCount = BBState::OverflowOccurredValue;
18740b57cec5SDimitry Andric           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
18750b57cec5SDimitry Andric             return false;
18760b57cec5SDimitry Andric           assert(PathCount != BBState::OverflowOccurredValue &&
18770b57cec5SDimitry Andric                  "PathCount at this point can not be "
18780b57cec5SDimitry Andric                  "OverflowOccurredValue.");
18790b57cec5SDimitry Andric           OldDelta -= PathCount;
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric           // Merge the ReleaseMetadata and IsTailCallRelease values.
18820b57cec5SDimitry Andric           if (FirstRelease) {
18830b57cec5SDimitry Andric             ReleasesToMove.ReleaseMetadata =
18840b57cec5SDimitry Andric               NewRetainReleaseRRI.ReleaseMetadata;
18850b57cec5SDimitry Andric             ReleasesToMove.IsTailCallRelease =
18860b57cec5SDimitry Andric               NewRetainReleaseRRI.IsTailCallRelease;
18870b57cec5SDimitry Andric             FirstRelease = false;
18880b57cec5SDimitry Andric           } else {
18890b57cec5SDimitry Andric             if (ReleasesToMove.ReleaseMetadata !=
18900b57cec5SDimitry Andric                 NewRetainReleaseRRI.ReleaseMetadata)
18910b57cec5SDimitry Andric               ReleasesToMove.ReleaseMetadata = nullptr;
18920b57cec5SDimitry Andric             if (ReleasesToMove.IsTailCallRelease !=
18930b57cec5SDimitry Andric                 NewRetainReleaseRRI.IsTailCallRelease)
18940b57cec5SDimitry Andric               ReleasesToMove.IsTailCallRelease = false;
18950b57cec5SDimitry Andric           }
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric           // Collect the optimal insertion points.
18980b57cec5SDimitry Andric           if (!KnownSafe)
18990b57cec5SDimitry Andric             for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
19000b57cec5SDimitry Andric               if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
19010b57cec5SDimitry Andric                 // If we overflow when we compute the path count, don't
19020b57cec5SDimitry Andric                 // remove/move anything.
19030b57cec5SDimitry Andric                 const BBState &RIPBBState = BBStates[RIP->getParent()];
19040b57cec5SDimitry Andric                 PathCount = BBState::OverflowOccurredValue;
19050b57cec5SDimitry Andric                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
19060b57cec5SDimitry Andric                   return false;
19070b57cec5SDimitry Andric                 assert(PathCount != BBState::OverflowOccurredValue &&
19080b57cec5SDimitry Andric                        "PathCount at this point can not be "
19090b57cec5SDimitry Andric                        "OverflowOccurredValue.");
19100b57cec5SDimitry Andric                 NewDelta -= PathCount;
19110b57cec5SDimitry Andric               }
19120b57cec5SDimitry Andric             }
19130b57cec5SDimitry Andric           NewReleases.push_back(NewRetainRelease);
19140b57cec5SDimitry Andric         }
19150b57cec5SDimitry Andric       }
19160b57cec5SDimitry Andric     }
19170b57cec5SDimitry Andric     NewRetains.clear();
19180b57cec5SDimitry Andric     if (NewReleases.empty()) break;
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric     // Back the other way.
19210b57cec5SDimitry Andric     for (Instruction *NewRelease : NewReleases) {
19220b57cec5SDimitry Andric       auto It = Releases.find(NewRelease);
19230b57cec5SDimitry Andric       assert(It != Releases.end());
19240b57cec5SDimitry Andric       const RRInfo &NewReleaseRRI = It->second;
19250b57cec5SDimitry Andric       KnownSafeBU &= NewReleaseRRI.KnownSafe;
19260b57cec5SDimitry Andric       CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
19270b57cec5SDimitry Andric       for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
19280b57cec5SDimitry Andric         auto Jt = Retains.find(NewReleaseRetain);
19290b57cec5SDimitry Andric         if (Jt == Retains.end())
19300b57cec5SDimitry Andric           return false;
19310b57cec5SDimitry Andric         const RRInfo &NewReleaseRetainRRI = Jt->second;
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric         // If the retain does not have a reference to the release as well,
19340b57cec5SDimitry Andric         // something happened which is unaccounted for. Do not do anything.
19350b57cec5SDimitry Andric         //
19360b57cec5SDimitry Andric         // This can happen if we catch an additive overflow during path count
19370b57cec5SDimitry Andric         // merging.
19380b57cec5SDimitry Andric         if (!NewReleaseRetainRRI.Calls.count(NewRelease))
19390b57cec5SDimitry Andric           return false;
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric         if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
19420b57cec5SDimitry Andric           // If we overflow when we compute the path count, don't remove/move
19430b57cec5SDimitry Andric           // anything.
19440b57cec5SDimitry Andric           const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
19450b57cec5SDimitry Andric           unsigned PathCount = BBState::OverflowOccurredValue;
19460b57cec5SDimitry Andric           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
19470b57cec5SDimitry Andric             return false;
19480b57cec5SDimitry Andric           assert(PathCount != BBState::OverflowOccurredValue &&
19490b57cec5SDimitry Andric                  "PathCount at this point can not be "
19500b57cec5SDimitry Andric                  "OverflowOccurredValue.");
19510b57cec5SDimitry Andric           OldDelta += PathCount;
19520b57cec5SDimitry Andric           OldCount += PathCount;
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric           // Collect the optimal insertion points.
19550b57cec5SDimitry Andric           if (!KnownSafe)
19560b57cec5SDimitry Andric             for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
19570b57cec5SDimitry Andric               if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
19580b57cec5SDimitry Andric                 // If we overflow when we compute the path count, don't
19590b57cec5SDimitry Andric                 // remove/move anything.
19600b57cec5SDimitry Andric                 const BBState &RIPBBState = BBStates[RIP->getParent()];
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric                 PathCount = BBState::OverflowOccurredValue;
19630b57cec5SDimitry Andric                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
19640b57cec5SDimitry Andric                   return false;
19650b57cec5SDimitry Andric                 assert(PathCount != BBState::OverflowOccurredValue &&
19660b57cec5SDimitry Andric                        "PathCount at this point can not be "
19670b57cec5SDimitry Andric                        "OverflowOccurredValue.");
19680b57cec5SDimitry Andric                 NewDelta += PathCount;
19690b57cec5SDimitry Andric                 NewCount += PathCount;
19700b57cec5SDimitry Andric               }
19710b57cec5SDimitry Andric             }
19720b57cec5SDimitry Andric           NewRetains.push_back(NewReleaseRetain);
19730b57cec5SDimitry Andric         }
19740b57cec5SDimitry Andric       }
19750b57cec5SDimitry Andric     }
19760b57cec5SDimitry Andric     if (NewRetains.empty()) break;
19770b57cec5SDimitry Andric   }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric   // We can only remove pointers if we are known safe in both directions.
19800b57cec5SDimitry Andric   bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
19810b57cec5SDimitry Andric   if (UnconditionallySafe) {
19820b57cec5SDimitry Andric     RetainsToMove.ReverseInsertPts.clear();
19830b57cec5SDimitry Andric     ReleasesToMove.ReverseInsertPts.clear();
19840b57cec5SDimitry Andric     NewCount = 0;
19850b57cec5SDimitry Andric   } else {
19860b57cec5SDimitry Andric     // Determine whether the new insertion points we computed preserve the
19870b57cec5SDimitry Andric     // balance of retain and release calls through the program.
19880b57cec5SDimitry Andric     // TODO: If the fully aggressive solution isn't valid, try to find a
19890b57cec5SDimitry Andric     // less aggressive solution which is.
19900b57cec5SDimitry Andric     if (NewDelta != 0)
19910b57cec5SDimitry Andric       return false;
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric     // At this point, we are not going to remove any RR pairs, but we still are
19940b57cec5SDimitry Andric     // able to move RR pairs. If one of our pointers is afflicted with
19950b57cec5SDimitry Andric     // CFGHazards, we cannot perform such code motion so exit early.
19960b57cec5SDimitry Andric     const bool WillPerformCodeMotion =
19970b57cec5SDimitry Andric         !RetainsToMove.ReverseInsertPts.empty() ||
19980b57cec5SDimitry Andric         !ReleasesToMove.ReverseInsertPts.empty();
19990b57cec5SDimitry Andric     if (CFGHazardAfflicted && WillPerformCodeMotion)
20000b57cec5SDimitry Andric       return false;
20010b57cec5SDimitry Andric   }
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric   // Determine whether the original call points are balanced in the retain and
20040b57cec5SDimitry Andric   // release calls through the program. If not, conservatively don't touch
20050b57cec5SDimitry Andric   // them.
20060b57cec5SDimitry Andric   // TODO: It's theoretically possible to do code motion in this case, as
20070b57cec5SDimitry Andric   // long as the existing imbalances are maintained.
20080b57cec5SDimitry Andric   if (OldDelta != 0)
20090b57cec5SDimitry Andric     return false;
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   Changed = true;
20120b57cec5SDimitry Andric   assert(OldCount != 0 && "Unreachable code?");
20130b57cec5SDimitry Andric   NumRRs += OldCount - NewCount;
20140b57cec5SDimitry Andric   // Set to true if we completely removed any RR pairs.
20150b57cec5SDimitry Andric   AnyPairsCompletelyEliminated = NewCount == 0;
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric   // We can move calls!
20180b57cec5SDimitry Andric   return true;
20190b57cec5SDimitry Andric }
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric /// Identify pairings between the retains and releases, and delete and/or move
20220b57cec5SDimitry Andric /// them.
20230b57cec5SDimitry Andric bool ObjCARCOpt::PerformCodePlacement(
20240b57cec5SDimitry Andric     DenseMap<const BasicBlock *, BBState> &BBStates,
20250b57cec5SDimitry Andric     BlotMapVector<Value *, RRInfo> &Retains,
20260b57cec5SDimitry Andric     DenseMap<Value *, RRInfo> &Releases, Module *M) {
20270b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   bool AnyPairsCompletelyEliminated = false;
20300b57cec5SDimitry Andric   SmallVector<Instruction *, 8> DeadInsts;
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric   // Visit each retain.
20330b57cec5SDimitry Andric   for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
20340b57cec5SDimitry Andric                                                       E = Retains.end();
20350b57cec5SDimitry Andric        I != E; ++I) {
20360b57cec5SDimitry Andric     Value *V = I->first;
20370b57cec5SDimitry Andric     if (!V) continue; // blotted
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric     Instruction *Retain = cast<Instruction>(V);
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric     Value *Arg = GetArgRCIdentityRoot(Retain);
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric     // If the object being released is in static or stack storage, we know it's
20460b57cec5SDimitry Andric     // not being managed by ObjC reference counting, so we can delete pairs
20470b57cec5SDimitry Andric     // regardless of what possible decrements or uses lie between them.
20480b57cec5SDimitry Andric     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric     // A constant pointer can't be pointing to an object on the heap. It may
20510b57cec5SDimitry Andric     // be reference-counted, but it won't be deleted.
20520b57cec5SDimitry Andric     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
20530b57cec5SDimitry Andric       if (const GlobalVariable *GV =
20540b57cec5SDimitry Andric             dyn_cast<GlobalVariable>(
20550b57cec5SDimitry Andric               GetRCIdentityRoot(LI->getPointerOperand())))
20560b57cec5SDimitry Andric         if (GV->isConstant())
20570b57cec5SDimitry Andric           KnownSafe = true;
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric     // Connect the dots between the top-down-collected RetainsToMove and
20600b57cec5SDimitry Andric     // bottom-up-collected ReleasesToMove to form sets of related calls.
20610b57cec5SDimitry Andric     RRInfo RetainsToMove, ReleasesToMove;
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric     bool PerformMoveCalls = PairUpRetainsAndReleases(
20640b57cec5SDimitry Andric         BBStates, Retains, Releases, M, Retain, DeadInsts,
20650b57cec5SDimitry Andric         RetainsToMove, ReleasesToMove, Arg, KnownSafe,
20660b57cec5SDimitry Andric         AnyPairsCompletelyEliminated);
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric     if (PerformMoveCalls) {
20690b57cec5SDimitry Andric       // Ok, everything checks out and we're all set. Let's move/delete some
20700b57cec5SDimitry Andric       // code!
20710b57cec5SDimitry Andric       MoveCalls(Arg, RetainsToMove, ReleasesToMove,
20720b57cec5SDimitry Andric                 Retains, Releases, DeadInsts, M);
20730b57cec5SDimitry Andric     }
20740b57cec5SDimitry Andric   }
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   // Now that we're done moving everything, we can delete the newly dead
20770b57cec5SDimitry Andric   // instructions, as we no longer need them as insert points.
20780b57cec5SDimitry Andric   while (!DeadInsts.empty())
20790b57cec5SDimitry Andric     EraseInstruction(DeadInsts.pop_back_val());
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric   return AnyPairsCompletelyEliminated;
20820b57cec5SDimitry Andric }
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric /// Weak pointer optimizations.
20850b57cec5SDimitry Andric void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
20860b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
20890b57cec5SDimitry Andric   // itself because it uses AliasAnalysis and we need to do provenance
20900b57cec5SDimitry Andric   // queries instead.
20910b57cec5SDimitry Andric   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
20920b57cec5SDimitry Andric     Instruction *Inst = &*I++;
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric     ARCInstKind Class = GetBasicARCInstKind(Inst);
20970b57cec5SDimitry Andric     if (Class != ARCInstKind::LoadWeak &&
20980b57cec5SDimitry Andric         Class != ARCInstKind::LoadWeakRetained)
20990b57cec5SDimitry Andric       continue;
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric     // Delete objc_loadWeak calls with no users.
21020b57cec5SDimitry Andric     if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
21030b57cec5SDimitry Andric       Inst->eraseFromParent();
21045ffd83dbSDimitry Andric       Changed = true;
21050b57cec5SDimitry Andric       continue;
21060b57cec5SDimitry Andric     }
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric     // TODO: For now, just look for an earlier available version of this value
21090b57cec5SDimitry Andric     // within the same block. Theoretically, we could do memdep-style non-local
21100b57cec5SDimitry Andric     // analysis too, but that would want caching. A better approach would be to
21110b57cec5SDimitry Andric     // use the technique that EarlyCSE uses.
21120b57cec5SDimitry Andric     inst_iterator Current = std::prev(I);
21130b57cec5SDimitry Andric     BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
21140b57cec5SDimitry Andric     for (BasicBlock::iterator B = CurrentBB->begin(),
21150b57cec5SDimitry Andric                               J = Current.getInstructionIterator();
21160b57cec5SDimitry Andric          J != B; --J) {
21170b57cec5SDimitry Andric       Instruction *EarlierInst = &*std::prev(J);
21180b57cec5SDimitry Andric       ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
21190b57cec5SDimitry Andric       switch (EarlierClass) {
21200b57cec5SDimitry Andric       case ARCInstKind::LoadWeak:
21210b57cec5SDimitry Andric       case ARCInstKind::LoadWeakRetained: {
21220b57cec5SDimitry Andric         // If this is loading from the same pointer, replace this load's value
21230b57cec5SDimitry Andric         // with that one.
21240b57cec5SDimitry Andric         CallInst *Call = cast<CallInst>(Inst);
21250b57cec5SDimitry Andric         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
21260b57cec5SDimitry Andric         Value *Arg = Call->getArgOperand(0);
21270b57cec5SDimitry Andric         Value *EarlierArg = EarlierCall->getArgOperand(0);
21280b57cec5SDimitry Andric         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2129fe6060f1SDimitry Andric         case AliasResult::MustAlias:
21300b57cec5SDimitry Andric           Changed = true;
21310b57cec5SDimitry Andric           // If the load has a builtin retain, insert a plain retain for it.
21320b57cec5SDimitry Andric           if (Class == ARCInstKind::LoadWeakRetained) {
21330b57cec5SDimitry Andric             Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
2134*0fca6ea1SDimitry Andric             CallInst *CI =
2135*0fca6ea1SDimitry Andric                 CallInst::Create(Decl, EarlierCall, "", Call->getIterator());
21360b57cec5SDimitry Andric             CI->setTailCall();
21370b57cec5SDimitry Andric           }
21380b57cec5SDimitry Andric           // Zap the fully redundant load.
21390b57cec5SDimitry Andric           Call->replaceAllUsesWith(EarlierCall);
21400b57cec5SDimitry Andric           Call->eraseFromParent();
21410b57cec5SDimitry Andric           goto clobbered;
2142fe6060f1SDimitry Andric         case AliasResult::MayAlias:
2143fe6060f1SDimitry Andric         case AliasResult::PartialAlias:
21440b57cec5SDimitry Andric           goto clobbered;
2145fe6060f1SDimitry Andric         case AliasResult::NoAlias:
21460b57cec5SDimitry Andric           break;
21470b57cec5SDimitry Andric         }
21480b57cec5SDimitry Andric         break;
21490b57cec5SDimitry Andric       }
21500b57cec5SDimitry Andric       case ARCInstKind::StoreWeak:
21510b57cec5SDimitry Andric       case ARCInstKind::InitWeak: {
21520b57cec5SDimitry Andric         // If this is storing to the same pointer and has the same size etc.
21530b57cec5SDimitry Andric         // replace this load's value with the stored value.
21540b57cec5SDimitry Andric         CallInst *Call = cast<CallInst>(Inst);
21550b57cec5SDimitry Andric         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
21560b57cec5SDimitry Andric         Value *Arg = Call->getArgOperand(0);
21570b57cec5SDimitry Andric         Value *EarlierArg = EarlierCall->getArgOperand(0);
21580b57cec5SDimitry Andric         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2159fe6060f1SDimitry Andric         case AliasResult::MustAlias:
21600b57cec5SDimitry Andric           Changed = true;
21610b57cec5SDimitry Andric           // If the load has a builtin retain, insert a plain retain for it.
21620b57cec5SDimitry Andric           if (Class == ARCInstKind::LoadWeakRetained) {
21630b57cec5SDimitry Andric             Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
2164*0fca6ea1SDimitry Andric             CallInst *CI =
2165*0fca6ea1SDimitry Andric                 CallInst::Create(Decl, EarlierCall, "", Call->getIterator());
21660b57cec5SDimitry Andric             CI->setTailCall();
21670b57cec5SDimitry Andric           }
21680b57cec5SDimitry Andric           // Zap the fully redundant load.
21690b57cec5SDimitry Andric           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
21700b57cec5SDimitry Andric           Call->eraseFromParent();
21710b57cec5SDimitry Andric           goto clobbered;
2172fe6060f1SDimitry Andric         case AliasResult::MayAlias:
2173fe6060f1SDimitry Andric         case AliasResult::PartialAlias:
21740b57cec5SDimitry Andric           goto clobbered;
2175fe6060f1SDimitry Andric         case AliasResult::NoAlias:
21760b57cec5SDimitry Andric           break;
21770b57cec5SDimitry Andric         }
21780b57cec5SDimitry Andric         break;
21790b57cec5SDimitry Andric       }
21800b57cec5SDimitry Andric       case ARCInstKind::MoveWeak:
21810b57cec5SDimitry Andric       case ARCInstKind::CopyWeak:
21820b57cec5SDimitry Andric         // TOOD: Grab the copied value.
21830b57cec5SDimitry Andric         goto clobbered;
21840b57cec5SDimitry Andric       case ARCInstKind::AutoreleasepoolPush:
21850b57cec5SDimitry Andric       case ARCInstKind::None:
21860b57cec5SDimitry Andric       case ARCInstKind::IntrinsicUser:
21870b57cec5SDimitry Andric       case ARCInstKind::User:
21880b57cec5SDimitry Andric         // Weak pointers are only modified through the weak entry points
21890b57cec5SDimitry Andric         // (and arbitrary calls, which could call the weak entry points).
21900b57cec5SDimitry Andric         break;
21910b57cec5SDimitry Andric       default:
21920b57cec5SDimitry Andric         // Anything else could modify the weak pointer.
21930b57cec5SDimitry Andric         goto clobbered;
21940b57cec5SDimitry Andric       }
21950b57cec5SDimitry Andric     }
21960b57cec5SDimitry Andric   clobbered:;
21970b57cec5SDimitry Andric   }
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric   // Then, for each destroyWeak with an alloca operand, check to see if
22000b57cec5SDimitry Andric   // the alloca and all its users can be zapped.
2201349cc55cSDimitry Andric   for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
2202349cc55cSDimitry Andric     ARCInstKind Class = GetBasicARCInstKind(&Inst);
22030b57cec5SDimitry Andric     if (Class != ARCInstKind::DestroyWeak)
22040b57cec5SDimitry Andric       continue;
22050b57cec5SDimitry Andric 
2206349cc55cSDimitry Andric     CallInst *Call = cast<CallInst>(&Inst);
22070b57cec5SDimitry Andric     Value *Arg = Call->getArgOperand(0);
22080b57cec5SDimitry Andric     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
22090b57cec5SDimitry Andric       for (User *U : Alloca->users()) {
22100b57cec5SDimitry Andric         const Instruction *UserInst = cast<Instruction>(U);
22110b57cec5SDimitry Andric         switch (GetBasicARCInstKind(UserInst)) {
22120b57cec5SDimitry Andric         case ARCInstKind::InitWeak:
22130b57cec5SDimitry Andric         case ARCInstKind::StoreWeak:
22140b57cec5SDimitry Andric         case ARCInstKind::DestroyWeak:
22150b57cec5SDimitry Andric           continue;
22160b57cec5SDimitry Andric         default:
22170b57cec5SDimitry Andric           goto done;
22180b57cec5SDimitry Andric         }
22190b57cec5SDimitry Andric       }
22200b57cec5SDimitry Andric       Changed = true;
2221349cc55cSDimitry Andric       for (User *U : llvm::make_early_inc_range(Alloca->users())) {
2222349cc55cSDimitry Andric         CallInst *UserInst = cast<CallInst>(U);
22230b57cec5SDimitry Andric         switch (GetBasicARCInstKind(UserInst)) {
22240b57cec5SDimitry Andric         case ARCInstKind::InitWeak:
22250b57cec5SDimitry Andric         case ARCInstKind::StoreWeak:
22260b57cec5SDimitry Andric           // These functions return their second argument.
22270b57cec5SDimitry Andric           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
22280b57cec5SDimitry Andric           break;
22290b57cec5SDimitry Andric         case ARCInstKind::DestroyWeak:
22300b57cec5SDimitry Andric           // No return value.
22310b57cec5SDimitry Andric           break;
22320b57cec5SDimitry Andric         default:
22330b57cec5SDimitry Andric           llvm_unreachable("alloca really is used!");
22340b57cec5SDimitry Andric         }
22350b57cec5SDimitry Andric         UserInst->eraseFromParent();
22360b57cec5SDimitry Andric       }
22370b57cec5SDimitry Andric       Alloca->eraseFromParent();
22380b57cec5SDimitry Andric     done:;
22390b57cec5SDimitry Andric     }
22400b57cec5SDimitry Andric   }
22410b57cec5SDimitry Andric }
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric /// Identify program paths which execute sequences of retains and releases which
22440b57cec5SDimitry Andric /// can be eliminated.
22450b57cec5SDimitry Andric bool ObjCARCOpt::OptimizeSequences(Function &F) {
22460b57cec5SDimitry Andric   // Releases, Retains - These are used to store the results of the main flow
22470b57cec5SDimitry Andric   // analysis. These use Value* as the key instead of Instruction* so that the
22480b57cec5SDimitry Andric   // map stays valid when we get around to rewriting code and calls get
22490b57cec5SDimitry Andric   // replaced by arguments.
22500b57cec5SDimitry Andric   DenseMap<Value *, RRInfo> Releases;
22510b57cec5SDimitry Andric   BlotMapVector<Value *, RRInfo> Retains;
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric   // This is used during the traversal of the function to track the
22540b57cec5SDimitry Andric   // states for each identified object at each block.
22550b57cec5SDimitry Andric   DenseMap<const BasicBlock *, BBState> BBStates;
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric   // Analyze the CFG of the function, and all instructions.
22580b57cec5SDimitry Andric   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric   if (DisableRetainReleasePairing)
22610b57cec5SDimitry Andric     return false;
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   // Transform.
22640b57cec5SDimitry Andric   bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
22650b57cec5SDimitry Andric                                                            Releases,
22660b57cec5SDimitry Andric                                                            F.getParent());
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric   return AnyPairsCompletelyEliminated && NestingDetected;
22690b57cec5SDimitry Andric }
22700b57cec5SDimitry Andric 
22710b57cec5SDimitry Andric /// Check if there is a dependent call earlier that does not have anything in
22720b57cec5SDimitry Andric /// between the Retain and the call that can affect the reference count of their
22730b57cec5SDimitry Andric /// shared pointer argument. Note that Retain need not be in BB.
2274e8d8bef9SDimitry Andric static CallInst *HasSafePathToPredecessorCall(const Value *Arg,
2275e8d8bef9SDimitry Andric                                               Instruction *Retain,
22760b57cec5SDimitry Andric                                               ProvenanceAnalysis &PA) {
2277e8d8bef9SDimitry Andric   auto *Call = dyn_cast_or_null<CallInst>(findSingleDependency(
2278e8d8bef9SDimitry Andric       CanChangeRetainCount, Arg, Retain->getParent(), Retain, PA));
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric   // Check that the pointer is the return value of the call.
22810b57cec5SDimitry Andric   if (!Call || Arg != Call)
2282e8d8bef9SDimitry Andric     return nullptr;
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   // Check that the call is a regular call.
22850b57cec5SDimitry Andric   ARCInstKind Class = GetBasicARCInstKind(Call);
2286e8d8bef9SDimitry Andric   return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call
2287e8d8bef9SDimitry Andric              ? Call
2288e8d8bef9SDimitry Andric              : nullptr;
22890b57cec5SDimitry Andric }
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric /// Find a dependent retain that precedes the given autorelease for which there
22920b57cec5SDimitry Andric /// is nothing in between the two instructions that can affect the ref count of
22930b57cec5SDimitry Andric /// Arg.
22940b57cec5SDimitry Andric static CallInst *
22950b57cec5SDimitry Andric FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
22960b57cec5SDimitry Andric                                   Instruction *Autorelease,
22970b57cec5SDimitry Andric                                   ProvenanceAnalysis &PA) {
2298e8d8bef9SDimitry Andric   auto *Retain = dyn_cast_or_null<CallInst>(
2299e8d8bef9SDimitry Andric       findSingleDependency(CanChangeRetainCount, Arg, BB, Autorelease, PA));
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric   // Check that we found a retain with the same argument.
23020b57cec5SDimitry Andric   if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
23030b57cec5SDimitry Andric       GetArgRCIdentityRoot(Retain) != Arg) {
23040b57cec5SDimitry Andric     return nullptr;
23050b57cec5SDimitry Andric   }
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric   return Retain;
23080b57cec5SDimitry Andric }
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric /// Look for an ``autorelease'' instruction dependent on Arg such that there are
23110b57cec5SDimitry Andric /// no instructions dependent on Arg that need a positive ref count in between
23120b57cec5SDimitry Andric /// the autorelease and the ret.
23130b57cec5SDimitry Andric static CallInst *
23140b57cec5SDimitry Andric FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
23150b57cec5SDimitry Andric                                        ReturnInst *Ret,
23160b57cec5SDimitry Andric                                        ProvenanceAnalysis &PA) {
2317e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 4> DepInsts;
2318e8d8bef9SDimitry Andric   auto *Autorelease = dyn_cast_or_null<CallInst>(
2319e8d8bef9SDimitry Andric       findSingleDependency(NeedsPositiveRetainCount, Arg, BB, Ret, PA));
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric   if (!Autorelease)
23220b57cec5SDimitry Andric     return nullptr;
23230b57cec5SDimitry Andric   ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
23240b57cec5SDimitry Andric   if (!IsAutorelease(AutoreleaseClass))
23250b57cec5SDimitry Andric     return nullptr;
23260b57cec5SDimitry Andric   if (GetArgRCIdentityRoot(Autorelease) != Arg)
23270b57cec5SDimitry Andric     return nullptr;
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   return Autorelease;
23300b57cec5SDimitry Andric }
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric /// Look for this pattern:
23330b57cec5SDimitry Andric /// \code
23340b57cec5SDimitry Andric ///    %call = call i8* @something(...)
23350b57cec5SDimitry Andric ///    %2 = call i8* @objc_retain(i8* %call)
23360b57cec5SDimitry Andric ///    %3 = call i8* @objc_autorelease(i8* %2)
23370b57cec5SDimitry Andric ///    ret i8* %3
23380b57cec5SDimitry Andric /// \endcode
23390b57cec5SDimitry Andric /// And delete the retain and autorelease.
23400b57cec5SDimitry Andric void ObjCARCOpt::OptimizeReturns(Function &F) {
23410b57cec5SDimitry Andric   if (!F.getReturnType()->isPointerTy())
23420b57cec5SDimitry Andric     return;
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric   for (BasicBlock &BB: F) {
23470b57cec5SDimitry Andric     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
23480b57cec5SDimitry Andric     if (!Ret)
23490b57cec5SDimitry Andric       continue;
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric     const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric     // Look for an ``autorelease'' instruction that is a predecessor of Ret and
23560b57cec5SDimitry Andric     // dependent on Arg such that there are no instructions dependent on Arg
23570b57cec5SDimitry Andric     // that need a positive ref count in between the autorelease and Ret.
2358e8d8bef9SDimitry Andric     CallInst *Autorelease =
2359e8d8bef9SDimitry Andric         FindPredecessorAutoreleaseWithSafePath(Arg, &BB, Ret, PA);
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric     if (!Autorelease)
23620b57cec5SDimitry Andric       continue;
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric     CallInst *Retain = FindPredecessorRetainWithSafePath(
2365e8d8bef9SDimitry Andric         Arg, Autorelease->getParent(), Autorelease, PA);
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric     if (!Retain)
23680b57cec5SDimitry Andric       continue;
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric     // Check that there is nothing that can affect the reference count
23710b57cec5SDimitry Andric     // between the retain and the call.  Note that Retain need not be in BB.
2372e8d8bef9SDimitry Andric     CallInst *Call = HasSafePathToPredecessorCall(Arg, Retain, PA);
23735ffd83dbSDimitry Andric 
23745ffd83dbSDimitry Andric     // Don't remove retainRV/autoreleaseRV pairs if the call isn't a tail call.
2375e8d8bef9SDimitry Andric     if (!Call ||
2376e8d8bef9SDimitry Andric         (!Call->isTailCall() &&
23775ffd83dbSDimitry Andric          GetBasicARCInstKind(Retain) == ARCInstKind::RetainRV &&
2378e8d8bef9SDimitry Andric          GetBasicARCInstKind(Autorelease) == ARCInstKind::AutoreleaseRV))
23790b57cec5SDimitry Andric       continue;
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric     // If so, we can zap the retain and autorelease.
23820b57cec5SDimitry Andric     Changed = true;
23830b57cec5SDimitry Andric     ++NumRets;
23840b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " << *Autorelease
23850b57cec5SDimitry Andric                       << "\n");
2386fe6060f1SDimitry Andric     BundledInsts->eraseInst(Retain);
23870b57cec5SDimitry Andric     EraseInstruction(Autorelease);
23880b57cec5SDimitry Andric   }
23890b57cec5SDimitry Andric }
23900b57cec5SDimitry Andric 
23910b57cec5SDimitry Andric #ifndef NDEBUG
23920b57cec5SDimitry Andric void
23930b57cec5SDimitry Andric ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
23940b57cec5SDimitry Andric   Statistic &NumRetains =
23950b57cec5SDimitry Andric       AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt;
23960b57cec5SDimitry Andric   Statistic &NumReleases =
23970b57cec5SDimitry Andric       AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt;
23980b57cec5SDimitry Andric 
23990b57cec5SDimitry Andric   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
24000b57cec5SDimitry Andric     Instruction *Inst = &*I++;
24010b57cec5SDimitry Andric     switch (GetBasicARCInstKind(Inst)) {
24020b57cec5SDimitry Andric     default:
24030b57cec5SDimitry Andric       break;
24040b57cec5SDimitry Andric     case ARCInstKind::Retain:
24050b57cec5SDimitry Andric       ++NumRetains;
24060b57cec5SDimitry Andric       break;
24070b57cec5SDimitry Andric     case ARCInstKind::Release:
24080b57cec5SDimitry Andric       ++NumReleases;
24090b57cec5SDimitry Andric       break;
24100b57cec5SDimitry Andric     }
24110b57cec5SDimitry Andric   }
24120b57cec5SDimitry Andric }
24130b57cec5SDimitry Andric #endif
24140b57cec5SDimitry Andric 
2415bdd1243dSDimitry Andric void ObjCARCOpt::init(Function &F) {
24160b57cec5SDimitry Andric   if (!EnableARCOpts)
2417e8d8bef9SDimitry Andric     return;
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   // Intuitively, objc_retain and others are nocapture, however in practice
24200b57cec5SDimitry Andric   // they are not, because they return their argument value. And objc_release
24210b57cec5SDimitry Andric   // calls finalizers which can have arbitrary side effects.
2422bdd1243dSDimitry Andric   MDKindCache.init(F.getParent());
24230b57cec5SDimitry Andric 
24240b57cec5SDimitry Andric   // Initialize our runtime entry point cache.
2425bdd1243dSDimitry Andric   EP.init(F.getParent());
2426bdd1243dSDimitry Andric 
2427bdd1243dSDimitry Andric   // Compute which blocks are in which funclet.
2428bdd1243dSDimitry Andric   if (F.hasPersonalityFn() &&
2429bdd1243dSDimitry Andric       isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
2430bdd1243dSDimitry Andric     BlockEHColors = colorEHFunclets(F);
24310b57cec5SDimitry Andric }
24320b57cec5SDimitry Andric 
2433e8d8bef9SDimitry Andric bool ObjCARCOpt::run(Function &F, AAResults &AA) {
24340b57cec5SDimitry Andric   if (!EnableARCOpts)
24350b57cec5SDimitry Andric     return false;
24360b57cec5SDimitry Andric 
2437fe6060f1SDimitry Andric   Changed = CFGChanged = false;
24381fd87a68SDimitry Andric   BundledRetainClaimRVs BRV(/*ContractPass=*/false);
2439fe6060f1SDimitry Andric   BundledInsts = &BRV;
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName()
24420b57cec5SDimitry Andric                     << " >>>"
24430b57cec5SDimitry Andric                        "\n");
24440b57cec5SDimitry Andric 
2445fe6060f1SDimitry Andric   std::pair<bool, bool> R = BundledInsts->insertAfterInvokes(F, nullptr);
2446fe6060f1SDimitry Andric   Changed |= R.first;
2447fe6060f1SDimitry Andric   CFGChanged |= R.second;
2448fe6060f1SDimitry Andric 
2449e8d8bef9SDimitry Andric   PA.setAA(&AA);
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric #ifndef NDEBUG
24520b57cec5SDimitry Andric   if (AreStatisticsEnabled()) {
24530b57cec5SDimitry Andric     GatherStatistics(F, false);
24540b57cec5SDimitry Andric   }
24550b57cec5SDimitry Andric #endif
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   // This pass performs several distinct transformations. As a compile-time aid
24580b57cec5SDimitry Andric   // when compiling code that isn't ObjC, skip these if the relevant ObjC
24590b57cec5SDimitry Andric   // library functions aren't declared.
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric   // Preliminary optimizations. This also computes UsedInThisFunction.
24620b57cec5SDimitry Andric   OptimizeIndividualCalls(F);
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric   // Optimizations for weak pointers.
24650b57cec5SDimitry Andric   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
24660b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
24670b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::StoreWeak)) |
24680b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::InitWeak)) |
24690b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::CopyWeak)) |
24700b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::MoveWeak)) |
24710b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::DestroyWeak))))
24720b57cec5SDimitry Andric     OptimizeWeakCalls(F);
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric   // Optimizations for retain+release pairs.
24750b57cec5SDimitry Andric   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
24760b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::RetainRV)) |
24770b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::RetainBlock))))
24780b57cec5SDimitry Andric     if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
24790b57cec5SDimitry Andric       // Run OptimizeSequences until it either stops making changes or
24800b57cec5SDimitry Andric       // no retain+release pair nesting is detected.
24810b57cec5SDimitry Andric       while (OptimizeSequences(F)) {}
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric   // Optimizations if objc_autorelease is used.
24840b57cec5SDimitry Andric   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
24850b57cec5SDimitry Andric                             (1 << unsigned(ARCInstKind::AutoreleaseRV))))
24860b57cec5SDimitry Andric     OptimizeReturns(F);
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric   // Gather statistics after optimization.
24890b57cec5SDimitry Andric #ifndef NDEBUG
24900b57cec5SDimitry Andric   if (AreStatisticsEnabled()) {
24910b57cec5SDimitry Andric     GatherStatistics(F, true);
24920b57cec5SDimitry Andric   }
24930b57cec5SDimitry Andric #endif
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n");
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric   return Changed;
24980b57cec5SDimitry Andric }
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric /// @}
25010b57cec5SDimitry Andric ///
2502e8d8bef9SDimitry Andric 
2503e8d8bef9SDimitry Andric PreservedAnalyses ObjCARCOptPass::run(Function &F,
2504e8d8bef9SDimitry Andric                                       FunctionAnalysisManager &AM) {
2505e8d8bef9SDimitry Andric   ObjCARCOpt OCAO;
2506bdd1243dSDimitry Andric   OCAO.init(F);
2507e8d8bef9SDimitry Andric 
2508e8d8bef9SDimitry Andric   bool Changed = OCAO.run(F, AM.getResult<AAManager>(F));
2509fe6060f1SDimitry Andric   bool CFGChanged = OCAO.hasCFGChanged();
2510e8d8bef9SDimitry Andric   if (Changed) {
2511e8d8bef9SDimitry Andric     PreservedAnalyses PA;
2512fe6060f1SDimitry Andric     if (!CFGChanged)
2513e8d8bef9SDimitry Andric       PA.preserveSet<CFGAnalyses>();
2514e8d8bef9SDimitry Andric     return PA;
2515e8d8bef9SDimitry Andric   }
2516e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
2517e8d8bef9SDimitry Andric }
2518