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/InstructionSimplify.h"
18#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/LoopPass.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/Dominators.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Target/TargetLibraryInfo.h"
25#include "llvm/Transforms/Utils/Local.h"
26using namespace llvm;
27
28#define DEBUG_TYPE "loop-instsimplify"
29
30STATISTIC(NumSimplified, "Number of redundant instructions simplified");
31
32namespace {
33  class LoopInstSimplify : public LoopPass {
34  public:
35    static char ID; // Pass ID, replacement for typeid
36    LoopInstSimplify() : LoopPass(ID) {
37      initializeLoopInstSimplifyPass(*PassRegistry::getPassRegistry());
38    }
39
40    bool runOnLoop(Loop*, LPPassManager&) override;
41
42    void getAnalysisUsage(AnalysisUsage &AU) const override {
43      AU.setPreservesCFG();
44      AU.addRequired<LoopInfo>();
45      AU.addRequiredID(LoopSimplifyID);
46      AU.addPreservedID(LoopSimplifyID);
47      AU.addPreservedID(LCSSAID);
48      AU.addPreserved("scalar-evolution");
49      AU.addRequired<TargetLibraryInfo>();
50    }
51  };
52}
53
54char LoopInstSimplify::ID = 0;
55INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
56                "Simplify instructions in loops", false, false)
57INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
58INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
59INITIALIZE_PASS_DEPENDENCY(LoopInfo)
60INITIALIZE_PASS_DEPENDENCY(LCSSA)
61INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
62                "Simplify instructions in loops", false, false)
63
64Pass *llvm::createLoopInstSimplifyPass() {
65  return new LoopInstSimplify();
66}
67
68bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
69  if (skipOptnoneFunction(L))
70    return false;
71
72  DominatorTreeWrapperPass *DTWP =
73      getAnalysisIfAvailable<DominatorTreeWrapperPass>();
74  DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
75  LoopInfo *LI = &getAnalysis<LoopInfo>();
76  DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
77  const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
78  const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
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
107      // Simplify instructions in the current basic block.
108      for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
109        Instruction *I = BI++;
110
111        // The first time through the loop ToSimplify is empty and we try to
112        // simplify all instructions. On later iterations ToSimplify is not
113        // empty and we only bother simplifying instructions that are in it.
114        if (!ToSimplify->empty() && !ToSimplify->count(I))
115          continue;
116
117        // Don't bother simplifying unused instructions.
118        if (!I->use_empty()) {
119          Value *V = SimplifyInstruction(I, DL, TLI, DT);
120          if (V && LI->replacementPreservesLCSSAForm(I, V)) {
121            // Mark all uses for resimplification next time round the loop.
122            for (User *U : I->users())
123              Next->insert(cast<Instruction>(U));
124
125            I->replaceAllUsesWith(V);
126            LocalChanged = true;
127            ++NumSimplified;
128          }
129        }
130        bool res = RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
131        if (res) {
132          // RecursivelyDeleteTriviallyDeadInstruction can remove
133          // more than one instruction, so simply incrementing the
134          // iterator does not work. When instructions get deleted
135          // re-iterate instead.
136          BI = BB->begin(); BE = BB->end();
137          LocalChanged |= res;
138        }
139
140        if (IsSubloopHeader && !isa<PHINode>(I))
141          break;
142      }
143
144      // Add all successors to the worklist, except for loop exit blocks and the
145      // bodies of subloops. We visit the headers of loops so that we can process
146      // their phis, but we contract the rest of the subloop body and only follow
147      // edges leading back to the original loop.
148      for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
149           ++SI) {
150        BasicBlock *SuccBB = *SI;
151        if (!Visited.insert(SuccBB))
152          continue;
153
154        const Loop *SuccLoop = LI->getLoopFor(SuccBB);
155        if (SuccLoop && SuccLoop->getHeader() == SuccBB
156                     && L->contains(SuccLoop)) {
157          VisitStack.push_back(WorklistItem(SuccBB, true));
158
159          SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
160          SuccLoop->getExitBlocks(SubLoopExitBlocks);
161
162          for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
163            BasicBlock *ExitBB = SubLoopExitBlocks[i];
164            if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB))
165              VisitStack.push_back(WorklistItem(ExitBB, false));
166          }
167
168          continue;
169        }
170
171        bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
172                                              ExitBlocks.end(), SuccBB);
173        if (IsExitBlock)
174          continue;
175
176        VisitStack.push_back(WorklistItem(SuccBB, false));
177      }
178    }
179
180    // Place the list of instructions to simplify on the next loop iteration
181    // into ToSimplify.
182    std::swap(ToSimplify, Next);
183    Next->clear();
184
185    Changed |= LocalChanged;
186  } while (LocalChanged);
187
188  return Changed;
189}
190