1 //===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
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.
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).
12 // This pass does not attempt to CSE load instructions, because it does not use
13 // pointer analysis to determine when it is safe.
15 //===----------------------------------------------------------------------===//
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"
29 class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
30 set<Instruction*> WorkList;
31 DominatorSet *DomSetInfo;
32 ImmediateDominators *ImmDominator;
34 virtual bool runOnFunction(Function *F);
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.
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);
47 bool visitInstruction(Instruction *) { return false; }
50 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
51 void CommonSubExpressionFound(Instruction *I, Instruction *Other);
53 // This transformation requires dominator and immediate dominator info
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired(DominatorSet::ID);
57 AU.addRequired(ImmediateDominators::ID);
62 // createGCSEPass - The public interface to this file...
63 Pass *createGCSEPass() { return new GCSE(); }
66 // GCSE::runOnFunction - This is the main transformation entry point for a
69 bool GCSE::runOnFunction(Function *F) {
72 DomSetInfo = &getAnalysis<DominatorSet>();
73 ImmDominator = &getAnalysis<ImmediateDominators>();
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.
79 WorkList.insert(inst_begin(F), inst_end(F));
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!
85 while (!WorkList.empty()) {
86 Instruction *I = *WorkList.begin(); // Get an instruction from the worklist
87 WorkList.erase(WorkList.begin());
89 // Visit the instruction, dispatching to the correct visit function based on
90 // the instruction type. This does the checking.
95 // When the worklist is empty, return whether or not we changed anything...
100 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
101 // uses of the instruction use First now instead.
103 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
104 Instruction *Second = *SI;
106 // Add the first instruction back to the worklist
107 WorkList.insert(First);
109 // Add all uses of the second instruction to the worklist
110 for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
112 WorkList.insert(cast<Instruction>(*UI));
114 // Make all users of 'Second' now use 'First'
115 Second->replaceAllUsesWith(First);
117 // Erase the second instruction from the program
118 delete Second->getParent()->getInstList().remove(SI);
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.
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);
131 // Handle the easy case, where both instructions are in the same basic block
132 BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
134 // Eliminate the second occuring instruction. Add all uses of the second
135 // instruction to the worklist.
137 // Scan the basic block looking for the "first" instruction
138 BasicBlock::iterator BI = BB1->begin();
139 while (*BI != I && *BI != Other) {
141 assert(BI != BB1->end() && "Instructions not found in parent BB!");
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!");
150 // Destroy Second, using First instead.
151 ReplaceInstWithInst(First, BI);
153 // Otherwise, the two instructions are in different basic blocks. If one
154 // dominates the other instruction, we can simply use it
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);
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.
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];
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!");
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);
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);
193 //===----------------------------------------------------------------------===//
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.
198 //===----------------------------------------------------------------------===//
200 bool GCSE::visitUnaryOperator(Instruction *I) {
201 Value *Op = I->getOperand(0);
202 Function *F = I->getParent()->getParent();
204 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
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 &&
214 // Check that the types are the same, since this code handles casts...
215 Other->getType() == I->getType()) {
217 // These instructions are identical. Handle the situation.
218 CommonSubExpressionFound(I, Other);
219 return true; // One instruction eliminated!
225 bool GCSE::visitBinaryOperator(Instruction *I) {
226 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
227 Function *F = I->getParent()->getParent();
229 for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
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) {
240 // These instructions are identical. Handle the situation.
241 CommonSubExpressionFound(I, Other);
242 return true; // One instruction eliminated!
248 bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
249 Value *Op = I->getOperand(0);
250 Function *F = I->getParent()->getParent();
252 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
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()) {
259 // Check to see that all operators past the 0th are the same...
260 unsigned i = 1, e = I->getNumOperands();
262 if (I->getOperand(i) != Other->getOperand(i)) break;
265 // These instructions are identical. Handle the situation.
266 CommonSubExpressionFound(I, Other);
267 return true; // One instruction eliminated!