Implement PR1786 by iterating between dead cycle elimination
[oota-llvm.git] / lib / Transforms / Scalar / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements dead code elimination and basic block merging.
11 // Specifically:
12 //
13 //   * Removes basic blocks with no predecessors.
14 //   * Merges a basic block into its predecessor if there is only one and the
15 //     predecessor only has one successor.
16 //   * Eliminates PHI nodes for basic blocks with a single predecessor.
17 //   * Eliminates a basic block that only contains an unconditional branch.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "simplifycfg"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Pass.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 using namespace llvm;
34
35 STATISTIC(NumSimpl, "Number of blocks simplified");
36
37 namespace {
38   struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass {
39     static char ID; // Pass identification, replacement for typeid
40     CFGSimplifyPass() : FunctionPass((intptr_t)&ID) {}
41
42     virtual bool runOnFunction(Function &F);
43   };
44   char CFGSimplifyPass::ID = 0;
45   RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
46 }
47
48 // Public interface to the CFGSimplification pass
49 FunctionPass *llvm::createCFGSimplificationPass() {
50   return new CFGSimplifyPass();
51 }
52
53 static bool MarkAliveBlocks(BasicBlock *BB,
54                             SmallPtrSet<BasicBlock*, 128> &Reachable) {
55   
56   SmallVector<BasicBlock*, 128> Worklist;
57   Worklist.push_back(BB);
58   bool Changed = false;
59   while (!Worklist.empty()) {
60     BB = Worklist.back();
61     Worklist.pop_back();
62     
63     if (!Reachable.insert(BB))
64       continue;
65
66     // Do a quick scan of the basic block, turning any obviously unreachable
67     // instructions into LLVM unreachable insts.  The instruction combining pass
68     // canonnicalizes unreachable insts into stores to null or undef.
69     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ++BBI)
70       if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
71         if (isa<ConstantPointerNull>(SI->getOperand(1)) ||
72             isa<UndefValue>(SI->getOperand(1))) {
73           // Loop over all of the successors, removing BB's entry from any PHI
74           // nodes.
75           for (succ_iterator I = succ_begin(BB), SE = succ_end(BB); I != SE;++I)
76             (*I)->removePredecessor(BB);
77
78           new UnreachableInst(SI);
79
80           // All instructions after this are dead.
81           while (BBI != E) {
82             if (!BBI->use_empty())
83               BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
84             BB->getInstList().erase(BBI++);
85           }
86           break;
87         }
88
89
90     Changed |= ConstantFoldTerminator(BB);
91     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
92       Worklist.push_back(*SI);
93   }
94   return Changed;
95 }
96
97 /// RemoveUnreachableBlocks - Remove blocks that are not reachable, even if they
98 /// are in a dead cycle.  Return true if a change was made, false otherwise.
99 static bool RemoveUnreachableBlocks(Function &F) {
100   SmallPtrSet<BasicBlock*, 128> Reachable;
101   bool Changed = MarkAliveBlocks(F.begin(), Reachable);
102   
103   // If there are unreachable blocks in the CFG...
104   if (Reachable.size() == F.size())
105     return Changed;
106   
107   assert(Reachable.size() < F.size());
108   NumSimpl += F.size()-Reachable.size();
109   
110   // Loop over all of the basic blocks that are not reachable, dropping all of
111   // their internal references...
112   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
113     if (!Reachable.count(BB)) {
114       for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
115         if (Reachable.count(*SI))
116           (*SI)->removePredecessor(BB);
117       BB->dropAllReferences();
118     }
119   
120   for (Function::iterator I = ++F.begin(); I != F.end();)
121     if (!Reachable.count(I))
122       I = F.getBasicBlockList().erase(I);
123     else
124       ++I;
125   
126   return true;
127 }
128
129 /// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function,
130 /// iterating until no more changes are made.
131 static bool IterativeSimplifyCFG(Function &F) {
132   bool Changed = false;
133   bool LocalChange = true;
134   while (LocalChange) {
135     LocalChange = false;
136     
137     // Loop over all of the basic blocks (except the first one) and remove them
138     // if they are unneeded...
139     //
140     for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
141       if (SimplifyCFG(BBIt++)) {
142         LocalChange = true;
143         ++NumSimpl;
144       }
145     }
146     Changed |= LocalChange;
147   }
148   return Changed;
149 }
150
151 // It is possible that we may require multiple passes over the code to fully
152 // simplify the CFG.
153 //
154 bool CFGSimplifyPass::runOnFunction(Function &F) {
155   bool EverChanged = RemoveUnreachableBlocks(F);
156   EverChanged |= IterativeSimplifyCFG(F);
157   
158   // If neither pass changed anything, we're done.
159   if (!EverChanged) return false;
160
161   // IterativeSimplifyCFG can (rarely) make some loops dead.  If this happens,
162   // RemoveUnreachableBlocks is needed to nuke them, which means we should
163   // iterate between the two optimizations.  We structure the code like this to
164   // avoid reruning IterativeSimplifyCFG if the second pass of 
165   // RemoveUnreachableBlocks doesn't do anything.
166   if (!RemoveUnreachableBlocks(F))
167     return true;
168   
169   do {
170     EverChanged = IterativeSimplifyCFG(F);
171     EverChanged |= RemoveUnreachableBlocks(F);
172   } while (EverChanged);
173   
174   return true;
175 }