Expand the scope to include global values because they are now constants
[oota-llvm.git] / lib / Transforms / Scalar / GCSE.cpp
1 //===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
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 pass is designed to be a very quick global transformation that
11 // eliminates global common subexpressions from a function.  It does this by
12 // using an existing value numbering implementation to identify the common
13 // subexpressions, eliminating them when possible.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constant.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Type.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/ValueNumbering.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "Support/DepthFirstIterator.h"
26 #include "Support/Statistic.h"
27 #include <algorithm>
28 using namespace llvm;
29
30 namespace {
31   Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
32   Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
33   Statistic<> NumCallRemoved("gcse", "Number of calls removed");
34   Statistic<> NumNonInsts   ("gcse", "Number of instructions removed due "
35                              "to non-instruction values");
36   Statistic<> NumArgsRepl   ("gcse", "Number of function arguments replaced "
37                              "with constant values");
38
39   struct GCSE : public FunctionPass {
40     virtual bool runOnFunction(Function &F);
41
42   private:
43     void ReplaceInstructionWith(Instruction *I, Value *V);
44
45     // This transformation requires dominator and immediate dominator info
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.setPreservesCFG();
48       AU.addRequired<DominatorSet>();
49       AU.addRequired<DominatorTree>();
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 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
59
60 // GCSE::runOnFunction - This is the main transformation entry point for a
61 // function.
62 //
63 bool GCSE::runOnFunction(Function &F) {
64   bool Changed = false;
65
66   // Get pointers to the analysis results that we will be using...
67   DominatorSet &DS = getAnalysis<DominatorSet>();
68   ValueNumbering &VN = getAnalysis<ValueNumbering>();
69   DominatorTree &DT = getAnalysis<DominatorTree>();
70
71   std::vector<Value*> EqualValues;
72
73   // Check for value numbers of arguments.  If the value numbering
74   // implementation can prove that an incoming argument is a constant or global
75   // value address, substitute it, making the argument dead.
76   for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
77     if (!AI->use_empty()) {
78       VN.getEqualNumberNodes(AI, EqualValues);
79       if (!EqualValues.empty()) {
80         for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
81           if (isa<Constant>(EqualValues[i])) {
82             AI->replaceAllUsesWith(EqualValues[i]);
83             ++NumArgsRepl;
84             Changed = true;
85             break;
86           }
87         EqualValues.clear();
88       }
89     }
90
91   // Traverse the CFG of the function in dominator order, so that we see each
92   // instruction after we see its operands.
93   for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
94          E = df_end(DT.getRootNode()); DI != E; ++DI) {
95     BasicBlock *BB = DI->getBlock();
96
97     // Remember which instructions we've seen in this basic block as we scan.
98     std::set<Instruction*> BlockInsts;
99
100     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
101       Instruction *Inst = I++;
102
103       // If this instruction computes a value, try to fold together common
104       // instructions that compute it.
105       //
106       if (Inst->getType() != Type::VoidTy) {
107         VN.getEqualNumberNodes(Inst, EqualValues);
108
109         // If this instruction computes a value that is already computed
110         // elsewhere, try to recycle the old value.
111         if (!EqualValues.empty()) {
112           if (Inst == &*BB->begin())
113             I = BB->end();
114           else {
115             I = Inst; --I;
116           }
117           
118           // First check to see if we were able to value number this instruction
119           // to a non-instruction value.  If so, prefer that value over other
120           // instructions which may compute the same thing.
121           for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
122             if (!isa<Instruction>(EqualValues[i])) {
123               ++NumNonInsts;      // Keep track of # of insts repl with values
124
125               // Change all users of Inst to use the replacement and remove it
126               // from the program.
127               ReplaceInstructionWith(Inst, EqualValues[i]);
128               Inst = 0;
129               EqualValues.clear();  // don't enter the next loop
130               break;
131             }
132
133           // If there were no non-instruction values that this instruction
134           // produces, find a dominating instruction that produces the same
135           // value.  If we find one, use it's value instead of ours.
136           for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
137             Instruction *OtherI = cast<Instruction>(EqualValues[i]);
138             bool Dominates = false;
139             if (OtherI->getParent() == BB)
140               Dominates = BlockInsts.count(OtherI);
141             else
142               Dominates = DS.dominates(OtherI->getParent(), BB);
143
144             if (Dominates) {
145               // Okay, we found an instruction with the same value as this one
146               // and that dominates this one.  Replace this instruction with the
147               // specified one.
148               ReplaceInstructionWith(Inst, OtherI);
149               Inst = 0;
150               break;
151             }
152           }
153
154           EqualValues.clear();
155
156           if (Inst) {
157             I = Inst; ++I;             // Deleted no instructions
158           } else if (I == BB->end()) { // Deleted first instruction
159             I = BB->begin();
160           } else {                     // Deleted inst in middle of block.
161             ++I;
162           }
163         }
164
165         if (Inst)
166           BlockInsts.insert(Inst);
167       }
168     }
169   }
170
171   // When the worklist is empty, return whether or not we changed anything...
172   return Changed;
173 }
174
175
176 void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
177   if (isa<LoadInst>(I))
178     ++NumLoadRemoved; // Keep track of loads eliminated
179   if (isa<CallInst>(I))
180     ++NumCallRemoved; // Keep track of calls eliminated
181   ++NumInstRemoved;   // Keep track of number of insts eliminated
182
183   // Update value numbering
184   getAnalysis<ValueNumbering>().deleteValue(I);
185
186   // If we are not replacing the instruction with a constant, we cannot do
187   // anything special.
188   if (!isa<Constant>(V)) {
189     I->replaceAllUsesWith(V);
190
191     if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
192       // Removing an invoke instruction requires adding a branch to the normal
193       // destination and removing PHI node entries in the exception destination.
194       new BranchInst(II->getNormalDest(), II);
195       II->getUnwindDest()->removePredecessor(II->getParent());
196     }
197     
198     // Erase the instruction from the program.
199     I->getParent()->getInstList().erase(I);
200     return;
201   }
202
203   Constant *C = cast<Constant>(V);
204   std::vector<User*> Users(I->use_begin(), I->use_end());
205
206   // Perform the replacement.
207   I->replaceAllUsesWith(C);
208
209   if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
210     // Removing an invoke instruction requires adding a branch to the normal
211     // destination and removing PHI node entries in the exception destination.
212     new BranchInst(II->getNormalDest(), II);
213     II->getUnwindDest()->removePredecessor(II->getParent());
214   }
215
216   // Erase the instruction from the program.
217   I->getParent()->getInstList().erase(I);
218   
219   // Check each user to see if we can constant fold it.
220   while (!Users.empty()) {
221     Instruction *U = cast<Instruction>(Users.back());
222     Users.pop_back();
223
224     if (Constant *C = ConstantFoldInstruction(U)) {
225       ReplaceInstructionWith(U, C);
226
227       // If the instruction used I more than once, it could be on the user list
228       // multiple times.  Make sure we don't reprocess it.
229       std::vector<User*>::iterator It = std::find(Users.begin(), Users.end(),U);
230       while (It != Users.end()) {
231         Users.erase(It);
232         It = std::find(Users.begin(), Users.end(), U);
233       }
234     }
235   }
236 }