1//===- LoopInstSimplify.cpp - Loop Instruction Simplification Pass --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs lightweight instruction simplification on loop bodies.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Scalar.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/AssumptionCache.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/LoopInfo.h"
20#include "llvm/Analysis/LoopPass.h"
21#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Transforms/Utils/Local.h"
28#include "llvm/Transforms/Utils/LoopUtils.h"
29using namespace llvm;
30
31#define DEBUG_TYPE "loop-instsimplify"
32
33STATISTIC(NumSimplified, "Number of redundant instructions simplified");
34
35namespace {
36  class LoopInstSimplify : public LoopPass {
37  public:
38    static char ID; // Pass ID, replacement for typeid
39    LoopInstSimplify() : LoopPass(ID) {
40      initializeLoopInstSimplifyPass(*PassRegistry::getPassRegistry());
41    }
42
43    bool runOnLoop(Loop*, LPPassManager&) override;
44
45    void getAnalysisUsage(AnalysisUsage &AU) const override {
46      AU.addRequired<AssumptionCacheTracker>();
47      AU.addRequired<TargetLibraryInfoWrapperPass>();
48      AU.setPreservesCFG();
49      getLoopAnalysisUsage(AU);
50    }
51  };
52}
53
54char LoopInstSimplify::ID = 0;
55INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
56                "Simplify instructions in loops", false, false)
57INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
58INITIALIZE_PASS_DEPENDENCY(LoopPass)
59INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
60INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
61                "Simplify instructions in loops", false, false)
62
63Pass *llvm::createLoopInstSimplifyPass() {
64  return new LoopInstSimplify();
65}
66
67bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
68  if (skipLoop(L))
69    return false;
70
71  DominatorTreeWrapperPass *DTWP =
72      getAnalysisIfAvailable<DominatorTreeWrapperPass>();
73  DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
74  LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
75  const TargetLibraryInfo *TLI =
76      &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
77  auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
78      *L->getHeader()->getParent());
79
80  SmallVector<BasicBlock*, 8> ExitBlocks;
81  L->getUniqueExitBlocks(ExitBlocks);
82  array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
83
84  SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
85
86  // The bit we are stealing from the pointer represents whether this basic
87  // block is the header of a subloop, in which case we only process its phis.
88  typedef PointerIntPair<BasicBlock*, 1> WorklistItem;
89  SmallVector<WorklistItem, 16> VisitStack;
90  SmallPtrSet<BasicBlock*, 32> Visited;
91
92  bool Changed = false;
93  bool LocalChanged;
94  do {
95    LocalChanged = false;
96
97    VisitStack.clear();
98    Visited.clear();
99
100    VisitStack.push_back(WorklistItem(L->getHeader(), false));
101
102    while (!VisitStack.empty()) {
103      WorklistItem Item = VisitStack.pop_back_val();
104      BasicBlock *BB = Item.getPointer();
105      bool IsSubloopHeader = Item.getInt();
106      const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
107
108      // Simplify instructions in the current basic block.
109      for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
110        Instruction *I = &*BI++;
111
112        // The first time through the loop ToSimplify is empty and we try to
113        // simplify all instructions. On later iterations ToSimplify is not
114        // empty and we only bother simplifying instructions that are in it.
115        if (!ToSimplify->empty() && !ToSimplify->count(I))
116          continue;
117
118        // Don't bother simplifying unused instructions.
119        if (!I->use_empty()) {
120          Value *V = SimplifyInstruction(I, DL, TLI, DT, &AC);
121          if (V && LI->replacementPreservesLCSSAForm(I, V)) {
122            // Mark all uses for resimplification next time round the loop.
123            for (User *U : I->users())
124              Next->insert(cast<Instruction>(U));
125
126            I->replaceAllUsesWith(V);
127            LocalChanged = true;
128            ++NumSimplified;
129          }
130        }
131        if (RecursivelyDeleteTriviallyDeadInstructions(I, TLI)) {
132          // RecursivelyDeleteTriviallyDeadInstruction can remove more than one
133          // instruction, so simply incrementing the iterator does not work.
134          // When instructions get deleted re-iterate instead.
135          BI = BB->begin(); BE = BB->end();
136          LocalChanged = true;
137        }
138
139        if (IsSubloopHeader && !isa<PHINode>(I))
140          break;
141      }
142
143      // Add all successors to the worklist, except for loop exit blocks and the
144      // bodies of subloops. We visit the headers of loops so that we can process
145      // their phis, but we contract the rest of the subloop body and only follow
146      // edges leading back to the original loop.
147      for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
148           ++SI) {
149        BasicBlock *SuccBB = *SI;
150        if (!Visited.insert(SuccBB).second)
151          continue;
152
153        const Loop *SuccLoop = LI->getLoopFor(SuccBB);
154        if (SuccLoop && SuccLoop->getHeader() == SuccBB
155                     && L->contains(SuccLoop)) {
156          VisitStack.push_back(WorklistItem(SuccBB, true));
157
158          SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
159          SuccLoop->getExitBlocks(SubLoopExitBlocks);
160
161          for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
162            BasicBlock *ExitBB = SubLoopExitBlocks[i];
163            if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB).second)
164              VisitStack.push_back(WorklistItem(ExitBB, false));
165          }
166
167          continue;
168        }
169
170        bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
171                                              ExitBlocks.end(), SuccBB);
172        if (IsExitBlock)
173          continue;
174
175        VisitStack.push_back(WorklistItem(SuccBB, false));
176      }
177    }
178
179    // Place the list of instructions to simplify on the next loop iteration
180    // into ToSimplify.
181    std::swap(ToSimplify, Next);
182    Next->clear();
183
184    Changed |= LocalChanged;
185  } while (LocalChanged);
186
187  return Changed;
188}
189