1 //===- LoopInstSimplify.cpp - Loop Instruction Simplification Pass --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs lightweight instruction simplification on loop bodies.
12 //===----------------------------------------------------------------------===//
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"
28 #define DEBUG_TYPE "loop-instsimplify"
30 STATISTIC(NumSimplified, "Number of redundant instructions simplified");
33 class LoopInstSimplify : public LoopPass {
35 static char ID; // Pass ID, replacement for typeid
36 LoopInstSimplify() : LoopPass(ID) {
37 initializeLoopInstSimplifyPass(*PassRegistry::getPassRegistry());
40 bool runOnLoop(Loop*, LPPassManager&) override;
42 void getAnalysisUsage(AnalysisUsage &AU) const override {
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>();
54 char LoopInstSimplify::ID = 0;
55 INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
56 "Simplify instructions in loops", false, false)
57 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
58 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
59 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
60 INITIALIZE_PASS_DEPENDENCY(LCSSA)
61 INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
62 "Simplify instructions in loops", false, false)
64 Pass *llvm::createLoopInstSimplifyPass() {
65 return new LoopInstSimplify();
68 bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
69 if (skipOptnoneFunction(L))
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>();
80 SmallVector<BasicBlock*, 8> ExitBlocks;
81 L->getUniqueExitBlocks(ExitBlocks);
82 array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
84 SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
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;
100 VisitStack.push_back(WorklistItem(L->getHeader(), false));
102 while (!VisitStack.empty()) {
103 WorklistItem Item = VisitStack.pop_back_val();
104 BasicBlock *BB = Item.getPointer();
105 bool IsSubloopHeader = Item.getInt();
107 // Simplify instructions in the current basic block.
108 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
109 Instruction *I = BI++;
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))
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));
125 I->replaceAllUsesWith(V);
130 bool res = RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
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();
140 if (IsSubloopHeader && !isa<PHINode>(I))
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;
150 BasicBlock *SuccBB = *SI;
151 if (!Visited.insert(SuccBB))
154 const Loop *SuccLoop = LI->getLoopFor(SuccBB);
155 if (SuccLoop && SuccLoop->getHeader() == SuccBB
156 && L->contains(SuccLoop)) {
157 VisitStack.push_back(WorklistItem(SuccBB, true));
159 SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
160 SuccLoop->getExitBlocks(SubLoopExitBlocks);
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));
171 bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
172 ExitBlocks.end(), SuccBB);
176 VisitStack.push_back(WorklistItem(SuccBB, false));
180 // Place the list of instructions to simplify on the next loop iteration
182 std::swap(ToSimplify, Next);
185 Changed |= LocalChanged;
186 } while (LocalChanged);