- GCSE now no longer counts instructions not removed (due to no common
[oota-llvm.git] / lib / Transforms / Scalar / GCSE.cpp
1 //===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
2 //
3 // This pass is designed to be a very quick global transformation that
4 // eliminates global common subexpressions from a function.  It does this by
5 // examining the SSA value graph of the function, instead of doing slow, dense,
6 // bit-vector computations.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/InstrTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/Analysis/ValueNumbering.h"
15 #include "llvm/Support/InstIterator.h"
16 #include "llvm/Support/CFG.h"
17 #include "llvm/Type.h"
18 #include "Support/StatisticReporter.h"
19 #include <algorithm>
20 using std::set;
21 using std::map;
22
23
24 namespace {
25   Statistic<> NumInstRemoved("gcse\t\t- Number of instructions removed");
26   Statistic<> NumLoadRemoved("gcse\t\t- Number of loads removed");
27   Statistic<> NumNonInsts   ("gcse\t\t- Number of instructions removed due "
28                              "to non-instruction values");
29
30   class GCSE : public FunctionPass {
31     set<Instruction*>       WorkList;
32     DominatorSet           *DomSetInfo;
33 #if 0
34     ImmediateDominators    *ImmDominator;
35 #endif
36     ValueNumbering         *VN;
37   public:
38     virtual bool runOnFunction(Function &F);
39
40   private:
41     bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
42     Instruction *EliminateCSE(Instruction *I, Instruction *Other);
43     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
44
45     // This transformation requires dominator and immediate dominator info
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.preservesCFG();
48       AU.addRequired<DominatorSet>();
49       AU.addRequired<ImmediateDominators>();
50       AU.addRequired<ValueNumbering>();
51     }
52   };
53
54   RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
55 }
56
57 // createGCSEPass - The public interface to this file...
58 Pass *createGCSEPass() { return new GCSE(); }
59
60
61 // GCSE::runOnFunction - This is the main transformation entry point for a
62 // function.
63 //
64 bool GCSE::runOnFunction(Function &F) {
65   bool Changed = false;
66
67   // Get pointers to the analysis results that we will be using...
68   DomSetInfo = &getAnalysis<DominatorSet>();
69 #if 0
70   ImmDominator = &getAnalysis<ImmediateDominators>();
71 #endif
72   VN = &getAnalysis<ValueNumbering>();
73
74   // Step #1: Add all instructions in the function to the worklist for
75   // processing.  All of the instructions are considered to be our
76   // subexpressions to eliminate if possible.
77   //
78   WorkList.insert(inst_begin(F), inst_end(F));
79
80   // Step #2: WorkList processing.  Iterate through all of the instructions,
81   // checking to see if there are any additionally defined subexpressions in the
82   // program.  If so, eliminate them!
83   //
84   while (!WorkList.empty()) {
85     Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
86     WorkList.erase(WorkList.begin());
87
88     // If this instruction computes a value, try to fold together common
89     // instructions that compute it.
90     //
91     if (I.getType() != Type::VoidTy) {
92       std::vector<Value*> EqualValues;
93       VN->getEqualNumberNodes(&I, EqualValues);
94
95       if (!EqualValues.empty())
96         Changed |= EliminateRedundancies(&I, EqualValues);
97     }
98   }
99
100   // When the worklist is empty, return whether or not we changed anything...
101   return Changed;
102 }
103
104 bool GCSE::EliminateRedundancies(Instruction *I,
105                                  std::vector<Value*> &EqualValues) {
106   // If the EqualValues set contains any non-instruction values, then we know
107   // that all of the instructions can be replaced with the non-instruction value
108   // because it is guaranteed to dominate all of the instructions in the
109   // function.  We only have to do hard work if all we have are instructions.
110   //
111   for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
112     if (!isa<Instruction>(EqualValues[i])) {
113       // Found a non-instruction.  Replace all instructions with the
114       // non-instruction.
115       //
116       Value *Replacement = EqualValues[i];
117
118       // Make sure we get I as well...
119       EqualValues[i] = I;
120
121       // Replace all instructions with the Replacement value.
122       for (i = 0; i != e; ++i)
123         if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
124           // Change all users of I to use Replacement.
125           I->replaceAllUsesWith(Replacement);
126
127           if (isa<LoadInst>(I))
128             ++NumLoadRemoved; // Keep track of loads eliminated
129           ++NumInstRemoved;   // Keep track of number of instructions eliminated
130           ++NumNonInsts;      // Keep track of number of insts repl with values
131
132           // Erase the instruction from the program.
133           I->getParent()->getInstList().erase(I);
134         }
135       
136       return true;
137     }
138   
139   // Remove duplicate entries from EqualValues...
140   std::sort(EqualValues.begin(), EqualValues.end());
141   EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
142                     EqualValues.end());
143
144   // From this point on, EqualValues is logically a vector of instructions.
145   //
146   bool Changed = false;
147   EqualValues.push_back(I); // Make sure I is included...
148   while (EqualValues.size() > 1) {
149     // FIXME, this could be done better than simple iteration!
150     Instruction *Test = cast<Instruction>(EqualValues.back());
151     EqualValues.pop_back();
152     
153     for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
154       if (Instruction *Ret = EliminateCSE(Test,
155                                           cast<Instruction>(EqualValues[i]))) {
156         if (Ret == Test)          // Eliminated EqualValues[i]
157           EqualValues[i] = Test;  // Make sure that we reprocess I at some point
158         Changed = true;
159         break;
160       }
161   }
162   return Changed;
163 }
164
165
166 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
167 // uses of the instruction use First now instead.
168 //
169 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
170   Instruction &Second = *SI;
171   
172   //cerr << "DEL " << (void*)Second << Second;
173
174   // Add the first instruction back to the worklist
175   WorkList.insert(First);
176
177   // Add all uses of the second instruction to the worklist
178   for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
179        UI != UE; ++UI)
180     WorkList.insert(cast<Instruction>(*UI));
181     
182   // Make all users of 'Second' now use 'First'
183   Second.replaceAllUsesWith(First);
184
185   // Erase the second instruction from the program
186   Second.getParent()->getInstList().erase(SI);
187 }
188
189 // EliminateCSE - The two instruction I & Other have been found to be common
190 // subexpressions.  This function is responsible for eliminating one of them,
191 // and for fixing the worklist to be correct.  The instruction that is preserved
192 // is returned from the function if the other is eliminated, otherwise null is
193 // returned.
194 //
195 Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
196   assert(I != Other);
197
198   WorkList.erase(I);
199   WorkList.erase(Other); // Other may not actually be on the worklist anymore...
200
201   // Handle the easy case, where both instructions are in the same basic block
202   BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
203   Instruction *Ret = 0;
204
205   if (BB1 == BB2) {
206     // Eliminate the second occuring instruction.  Add all uses of the second
207     // instruction to the worklist.
208     //
209     // Scan the basic block looking for the "first" instruction
210     BasicBlock::iterator BI = BB1->begin();
211     while (&*BI != I && &*BI != Other) {
212       ++BI;
213       assert(BI != BB1->end() && "Instructions not found in parent BB!");
214     }
215
216     // Keep track of which instructions occurred first & second
217     Instruction *First = BI;
218     Instruction *Second = I != First ? I : Other; // Get iterator to second inst
219     BI = Second;
220
221     // Destroy Second, using First instead.
222     ReplaceInstWithInst(First, BI);
223     Ret = First;
224
225     // Otherwise, the two instructions are in different basic blocks.  If one
226     // dominates the other instruction, we can simply use it
227     //
228   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
229     ReplaceInstWithInst(I, Other);
230     Ret = I;
231   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
232     ReplaceInstWithInst(Other, I);
233     Ret = Other;
234   } else {
235     // This code is disabled because it has several problems:
236     // One, the actual assumption is wrong, as shown by this code:
237     // int "test"(int %X, int %Y) {
238     //         %Z = add int %X, %Y
239     //         ret int %Z
240     // Unreachable:
241     //         %Q = add int %X, %Y
242     //         ret int %Q
243     // }
244     //
245     // Here there are no shared dominators.  Additionally, this had the habit of
246     // moving computations where they were not always computed.  For example, in
247     // a cast like this:
248     //  if (c) {
249     //    if (d)  ...
250     //    else ... X+Y ...
251     //  } else {
252     //    ... X+Y ...
253     //  }
254     // 
255     // In thiscase, the expression would be hoisted to outside the 'if' stmt,
256     // causing the expression to be evaluated, even for the if (d) path, which
257     // could cause problems, if, for example, it caused a divide by zero.  In
258     // general the problem this case is trying to solve is better addressed with
259     // PRE than GCSE.
260     //
261     return 0;
262
263 #if 0
264     // Handle the most general case now.  In this case, neither I dom Other nor
265     // Other dom I.  Because we are in SSA form, we are guaranteed that the
266     // operands of the two instructions both dominate the uses, so we _know_
267     // that there must exist a block that dominates both instructions (if the
268     // operands of the instructions are globals or constants, worst case we
269     // would get the entry node of the function).  Search for this block now.
270     //
271
272     // Search up the immediate dominator chain of BB1 for the shared dominator
273     BasicBlock *SharedDom = (*ImmDominator)[BB1];
274     while (!DomSetInfo->dominates(SharedDom, BB2))
275       SharedDom = (*ImmDominator)[SharedDom];
276
277     // At this point, shared dom must dominate BOTH BB1 and BB2...
278     assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
279            DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
280
281     // Rip 'I' out of BB1, and move it to the end of SharedDom.
282     BB1->getInstList().remove(I);
283     SharedDom->getInstList().insert(--SharedDom->end(), I);
284
285     // Eliminate 'Other' now.
286     ReplaceInstWithInst(I, Other);
287 #endif
288   }
289
290   if (isa<LoadInst>(Ret))
291     ++NumLoadRemoved;  // Keep track of loads eliminated
292   ++NumInstRemoved;   // Keep track of number of instructions eliminated
293
294   // Add all users of Ret to the worklist...
295   for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
296     if (Instruction *Inst = dyn_cast<Instruction>(*I))
297       WorkList.insert(Inst);
298
299   return Ret;
300 }