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