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 //===----------------------------------------------------------------------===//
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"
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");
30 class GCSE : public FunctionPass {
31 set<Instruction*> WorkList;
32 DominatorSet *DomSetInfo;
34 ImmediateDominators *ImmDominator;
38 virtual bool runOnFunction(Function &F);
41 bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
42 Instruction *EliminateCSE(Instruction *I, Instruction *Other);
43 void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
45 // This transformation requires dominator and immediate dominator info
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequired<DominatorSet>();
49 AU.addRequired<ImmediateDominators>();
50 AU.addRequired<ValueNumbering>();
54 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
57 // createGCSEPass - The public interface to this file...
58 Pass *createGCSEPass() { return new GCSE(); }
61 // GCSE::runOnFunction - This is the main transformation entry point for a
64 bool GCSE::runOnFunction(Function &F) {
67 // Get pointers to the analysis results that we will be using...
68 DomSetInfo = &getAnalysis<DominatorSet>();
70 ImmDominator = &getAnalysis<ImmediateDominators>();
72 VN = &getAnalysis<ValueNumbering>();
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.
78 WorkList.insert(inst_begin(F), inst_end(F));
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!
84 while (!WorkList.empty()) {
85 Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
86 WorkList.erase(WorkList.begin());
88 // If this instruction computes a value, try to fold together common
89 // instructions that compute it.
91 if (I.getType() != Type::VoidTy) {
92 std::vector<Value*> EqualValues;
93 VN->getEqualNumberNodes(&I, EqualValues);
95 if (!EqualValues.empty())
96 Changed |= EliminateRedundancies(&I, EqualValues);
100 // When the worklist is empty, return whether or not we changed anything...
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.
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
116 Value *Replacement = EqualValues[i];
118 // Make sure we get I as well...
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);
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
132 // Erase the instruction from the program.
133 I->getParent()->getInstList().erase(I);
139 // Remove duplicate entries from EqualValues...
140 std::sort(EqualValues.begin(), EqualValues.end());
141 EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
144 // From this point on, EqualValues is logically a vector of instructions.
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();
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
166 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
167 // uses of the instruction use First now instead.
169 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
170 Instruction &Second = *SI;
172 //cerr << "DEL " << (void*)Second << Second;
174 // Add the first instruction back to the worklist
175 WorkList.insert(First);
177 // Add all uses of the second instruction to the worklist
178 for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
180 WorkList.insert(cast<Instruction>(*UI));
182 // Make all users of 'Second' now use 'First'
183 Second.replaceAllUsesWith(First);
185 // Erase the second instruction from the program
186 Second.getParent()->getInstList().erase(SI);
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
195 Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
199 WorkList.erase(Other); // Other may not actually be on the worklist anymore...
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;
206 // Eliminate the second occuring instruction. Add all uses of the second
207 // instruction to the worklist.
209 // Scan the basic block looking for the "first" instruction
210 BasicBlock::iterator BI = BB1->begin();
211 while (&*BI != I && &*BI != Other) {
213 assert(BI != BB1->end() && "Instructions not found in parent BB!");
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
221 // Destroy Second, using First instead.
222 ReplaceInstWithInst(First, BI);
225 // Otherwise, the two instructions are in different basic blocks. If one
226 // dominates the other instruction, we can simply use it
228 } else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
229 ReplaceInstWithInst(I, Other);
231 } else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
232 ReplaceInstWithInst(Other, I);
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
241 // %Q = add int %X, %Y
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
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
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.
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];
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!");
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);
285 // Eliminate 'Other' now.
286 ReplaceInstWithInst(I, Other);
290 if (isa<LoadInst>(Ret))
291 ++NumLoadRemoved; // Keep track of loads eliminated
292 ++NumInstRemoved; // Keep track of number of instructions eliminated
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);