Initial checkin of simple&fast SSA based GCSE algorithm
[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 // This pass works best if it is proceeded with a simple constant propogation
9 // pass and an instruction combination pass because this pass does not do any
10 // value numbering (in order to be speedy).
11 //
12 // This pass does not attempt to CSE load instructions, because it does not use
13 // pointer analysis to determine when it is safe.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Scalar/GCSE.h"
18 #include "llvm/Pass.h"
19 #include "llvm/InstrTypes.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Support/InstIterator.h"
24 #include <set>
25 #include <algorithm>
26 using namespace cfg;
27
28 namespace {
29   class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
30     set<Instruction*> WorkList;
31     DominatorSet        *DomSetInfo;
32     ImmediateDominators *ImmDominator;
33   public:
34     virtual bool runOnFunction(Function *F);
35
36     // Visitation methods, these are invoked depending on the type of
37     // instruction being checked.  They should return true if a common
38     // subexpression was folded.
39     //
40     bool visitUnaryOperator(Instruction *I);
41     bool visitBinaryOperator(Instruction *I);
42     bool visitGetElementPtrInst(GetElementPtrInst *I);
43     bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
44     bool visitShiftInst(ShiftInst *I) {
45       return visitBinaryOperator((Instruction*)I);
46     }
47     bool visitInstruction(Instruction *) { return false; }
48
49   private:
50     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
51     void CommonSubExpressionFound(Instruction *I, Instruction *Other);
52
53     // This transformation requires dominator and immediate dominator info
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       //preservesCFG(AU);
56       AU.addRequired(DominatorSet::ID);
57       AU.addRequired(ImmediateDominators::ID); 
58     }
59   };
60 }
61
62 // createGCSEPass - The public interface to this file...
63 Pass *createGCSEPass() { return new GCSE(); }
64
65
66 // GCSE::runOnFunction - This is the main transformation entry point for a
67 // function.
68 //
69 bool GCSE::runOnFunction(Function *F) {
70   bool Changed = false;
71
72   DomSetInfo = &getAnalysis<DominatorSet>();
73   ImmDominator = &getAnalysis<ImmediateDominators>();
74
75   // Step #1: Add all instructions in the function to the worklist for
76   // processing.  All of the instructions are considered to be our
77   // subexpressions to eliminate if possible.
78   //
79   WorkList.insert(inst_begin(F), inst_end(F));
80
81   // Step #2: WorkList processing.  Iterate through all of the instructions,
82   // checking to see if there are any additionally defined subexpressions in the
83   // program.  If so, eliminate them!
84   //
85   while (!WorkList.empty()) {
86     Instruction *I = *WorkList.begin();  // Get an instruction from the worklist
87     WorkList.erase(WorkList.begin());
88
89     // Visit the instruction, dispatching to the correct visit function based on
90     // the instruction type.  This does the checking.
91     //
92     Changed |= visit(I);
93   }
94   
95   // When the worklist is empty, return whether or not we changed anything...
96   return Changed;
97 }
98
99
100 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
101 // uses of the instruction use First now instead.
102 //
103 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
104   Instruction *Second = *SI;
105
106   // Add the first instruction back to the worklist
107   WorkList.insert(First);
108
109   // Add all uses of the second instruction to the worklist
110   for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
111        UI != UE; ++UI)
112     WorkList.insert(cast<Instruction>(*UI));
113     
114   // Make all users of 'Second' now use 'First'
115   Second->replaceAllUsesWith(First);
116
117   // Erase the second instruction from the program
118   delete Second->getParent()->getInstList().remove(SI);
119 }
120
121 // CommonSubExpressionFound - The two instruction I & Other have been found to
122 // be common subexpressions.  This function is responsible for eliminating one
123 // of them, and for fixing the worklist to be correct.
124 //
125 void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
126   // I has already been removed from the worklist, Other needs to be.
127   assert(WorkList.count(I) == 0 && WorkList.count(Other) &&
128          "I in worklist or Other not!");
129   WorkList.erase(Other);
130
131   // Handle the easy case, where both instructions are in the same basic block
132   BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
133   if (BB1 == BB2) {
134     // Eliminate the second occuring instruction.  Add all uses of the second
135     // instruction to the worklist.
136     //
137     // Scan the basic block looking for the "first" instruction
138     BasicBlock::iterator BI = BB1->begin();
139     while (*BI != I && *BI != Other) {
140       ++BI;
141       assert(BI != BB1->end() && "Instructions not found in parent BB!");
142     }
143
144     // Keep track of which instructions occurred first & second
145     Instruction *First = *BI;
146     Instruction *Second = I != First ? I : Other; // Get iterator to second inst
147     BI = find(BI, BB1->end(), Second);
148     assert(BI != BB1->end() && "Second instruction not found in parent block!");
149
150     // Destroy Second, using First instead.
151     ReplaceInstWithInst(First, BI);    
152
153     // Otherwise, the two instructions are in different basic blocks.  If one
154     // dominates the other instruction, we can simply use it
155     //
156   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
157     BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
158     assert(BI != BB2->end() && "Other not in parent basic block!");
159     ReplaceInstWithInst(I, BI);    
160   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
161     BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
162     assert(BI != BB1->end() && "I not in parent basic block!");
163     ReplaceInstWithInst(Other, BI);
164   } else {
165     // Handle the most general case now.  In this case, neither I dom Other nor
166     // Other dom I.  Because we are in SSA form, we are guaranteed that the
167     // operands of the two instructions both dominate the uses, so we _know_
168     // that there must exist a block that dominates both instructions (if the
169     // operands of the instructions are globals or constants, worst case we
170     // would get the entry node of the function).  Search for this block now.
171     //
172
173     // Search up the immediate dominator chain of BB1 for the shared dominator
174     BasicBlock *SharedDom = (*ImmDominator)[BB1];
175     while (!DomSetInfo->dominates(SharedDom, BB2))
176       SharedDom = (*ImmDominator)[SharedDom];
177
178     // At this point, shared dom must dominate BOTH BB1 and BB2...
179     assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
180            DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
181
182     // Rip 'I' out of BB1, and move it to the end of SharedDom.
183     BB1->getInstList().remove(I);
184     SharedDom->getInstList().insert(SharedDom->end()-1, I);
185
186     // Eliminate 'Other' now.
187     BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
188     assert(BI != BB2->end() && "I not in parent basic block!");
189     ReplaceInstWithInst(I, BI);
190   }
191 }
192
193 //===----------------------------------------------------------------------===//
194 //
195 // Visitation methods, these are invoked depending on the type of instruction
196 // being checked.  They should return true if a common subexpression was folded.
197 //
198 //===----------------------------------------------------------------------===//
199
200 bool GCSE::visitUnaryOperator(Instruction *I) {
201   Value *Op = I->getOperand(0);
202   Function *F = I->getParent()->getParent();
203   
204   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
205        UI != UE; ++UI)
206     if (Instruction *Other = dyn_cast<Instruction>(*UI))
207       // Check to see if this new binary operator is not I, but same operand...
208       if (Other != I && Other->getOpcode() == I->getOpcode() &&
209           Other->getOperand(0) == Op &&     // Is the operand the same?
210           // Is it embeded in the same function?  (This could be false if LHS
211           // is a constant or global!)
212           Other->getParent()->getParent() == F &&
213
214           // Check that the types are the same, since this code handles casts...
215           Other->getType() == I->getType()) {
216         
217         // These instructions are identical.  Handle the situation.
218         CommonSubExpressionFound(I, Other);
219         return true;   // One instruction eliminated!
220       }
221   
222   return false;
223 }
224
225 bool GCSE::visitBinaryOperator(Instruction *I) {
226   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
227   Function *F = I->getParent()->getParent();
228   
229   for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
230        UI != UE; ++UI)
231     if (Instruction *Other = dyn_cast<Instruction>(*UI))
232       // Check to see if this new binary operator is not I, but same operand...
233       if (Other != I && Other->getOpcode() == I->getOpcode() &&
234           // Are the LHS and RHS the same?
235           Other->getOperand(0) == LHS && Other->getOperand(1) == RHS &&
236           // Is it embeded in the same function?  (This could be false if LHS
237           // is a constant or global!)
238           Other->getParent()->getParent() == F) {
239         
240         // These instructions are identical.  Handle the situation.
241         CommonSubExpressionFound(I, Other);
242         return true;   // One instruction eliminated!
243       }
244   
245   return false;
246 }
247
248 bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
249   Value *Op = I->getOperand(0);
250   Function *F = I->getParent()->getParent();
251   
252   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
253        UI != UE; ++UI)
254     if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
255       // Check to see if this new binary operator is not I, but same operand...
256       if (Other != I && Other->getParent()->getParent() == F &&
257           Other->getType() == I->getType()) {
258
259         // Check to see that all operators past the 0th are the same...
260         unsigned i = 1, e = I->getNumOperands();
261         for (; i != e; ++i)
262           if (I->getOperand(i) != Other->getOperand(i)) break;
263         
264         if (i == e) {
265           // These instructions are identical.  Handle the situation.
266           CommonSubExpressionFound(I, Other);
267           return true;   // One instruction eliminated!
268         }
269       }
270   
271   return false;
272 }