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#define DEBUG_TYPE "loop-instsimplify"
15#include "llvm/Instructions.h"
16#include "llvm/Analysis/Dominators.h"
17#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/Target/TargetLibraryInfo.h"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Transforms/Utils/Local.h"
25#include "llvm/ADT/Statistic.h"
26using namespace llvm;
27
28STATISTIC(NumSimplified, "Number of redundant instructions simplified");
29
30namespace {
31  class LoopInstSimplify : public LoopPass {
32  public:
33    static char ID; // Pass ID, replacement for typeid
34    LoopInstSimplify() : LoopPass(ID) {
35      initializeLoopInstSimplifyPass(*PassRegistry::getPassRegistry());
36    }
37
38    bool runOnLoop(Loop*, LPPassManager&);
39
40    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41      AU.setPreservesCFG();
42      AU.addRequired<LoopInfo>();
43      AU.addRequiredID(LoopSimplifyID);
44      AU.addPreservedID(LoopSimplifyID);
45      AU.addPreservedID(LCSSAID);
46      AU.addPreserved("scalar-evolution");
47      AU.addRequired<TargetLibraryInfo>();
48    }
49  };
50}
51
52char LoopInstSimplify::ID = 0;
53INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
54                "Simplify instructions in loops", false, false)
55INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
56INITIALIZE_PASS_DEPENDENCY(DominatorTree)
57INITIALIZE_PASS_DEPENDENCY(LoopInfo)
58INITIALIZE_PASS_DEPENDENCY(LCSSA)
59INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
60                "Simplify instructions in loops", false, false)
61
62Pass *llvm::createLoopInstSimplifyPass() {
63  return new LoopInstSimplify();
64}
65
66bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
67  DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>();
68  LoopInfo *LI = &getAnalysis<LoopInfo>();
69  const TargetData *TD = getAnalysisIfAvailable<TargetData>();
70  const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
71
72  SmallVector<BasicBlock*, 8> ExitBlocks;
73  L->getUniqueExitBlocks(ExitBlocks);
74  array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
75
76  SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
77
78  // The bit we are stealing from the pointer represents whether this basic
79  // block is the header of a subloop, in which case we only process its phis.
80  typedef PointerIntPair<BasicBlock*, 1> WorklistItem;
81  SmallVector<WorklistItem, 16> VisitStack;
82  SmallPtrSet<BasicBlock*, 32> Visited;
83
84  bool Changed = false;
85  bool LocalChanged;
86  do {
87    LocalChanged = false;
88
89    VisitStack.clear();
90    Visited.clear();
91
92    VisitStack.push_back(WorklistItem(L->getHeader(), false));
93
94    while (!VisitStack.empty()) {
95      WorklistItem Item = VisitStack.pop_back_val();
96      BasicBlock *BB = Item.getPointer();
97      bool IsSubloopHeader = Item.getInt();
98
99      // Simplify instructions in the current basic block.
100      for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
101        Instruction *I = BI++;
102
103        // The first time through the loop ToSimplify is empty and we try to
104        // simplify all instructions. On later iterations ToSimplify is not
105        // empty and we only bother simplifying instructions that are in it.
106        if (!ToSimplify->empty() && !ToSimplify->count(I))
107          continue;
108
109        // Don't bother simplifying unused instructions.
110        if (!I->use_empty()) {
111          Value *V = SimplifyInstruction(I, TD, TLI, DT);
112          if (V && LI->replacementPreservesLCSSAForm(I, V)) {
113            // Mark all uses for resimplification next time round the loop.
114            for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
115                 UI != UE; ++UI)
116              Next->insert(cast<Instruction>(*UI));
117
118            I->replaceAllUsesWith(V);
119            LocalChanged = true;
120            ++NumSimplified;
121          }
122        }
123        LocalChanged |= RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
124
125        if (IsSubloopHeader && !isa<PHINode>(I))
126          break;
127      }
128
129      // Add all successors to the worklist, except for loop exit blocks and the
130      // bodies of subloops. We visit the headers of loops so that we can process
131      // their phis, but we contract the rest of the subloop body and only follow
132      // edges leading back to the original loop.
133      for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
134           ++SI) {
135        BasicBlock *SuccBB = *SI;
136        if (!Visited.insert(SuccBB))
137          continue;
138
139        const Loop *SuccLoop = LI->getLoopFor(SuccBB);
140        if (SuccLoop && SuccLoop->getHeader() == SuccBB
141                     && L->contains(SuccLoop)) {
142          VisitStack.push_back(WorklistItem(SuccBB, true));
143
144          SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
145          SuccLoop->getExitBlocks(SubLoopExitBlocks);
146
147          for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
148            BasicBlock *ExitBB = SubLoopExitBlocks[i];
149            if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB))
150              VisitStack.push_back(WorklistItem(ExitBB, false));
151          }
152
153          continue;
154        }
155
156        bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
157                                              ExitBlocks.end(), SuccBB);
158        if (IsExitBlock)
159          continue;
160
161        VisitStack.push_back(WorklistItem(SuccBB, false));
162      }
163    }
164
165    // Place the list of instructions to simplify on the next loop iteration
166    // into ToSimplify.
167    std::swap(ToSimplify, Next);
168    Next->clear();
169
170    Changed |= LocalChanged;
171  } while (LocalChanged);
172
173  return Changed;
174}
175