Remove an unused method.
[oota-llvm.git] / lib / Transforms / Scalar / GVNPRE.cpp
1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs a hybrid of global value numbering and partial redundancy
11 // elimination, known as GVN-PRE.  It performs partial redundancy elimination on
12 // values, rather than lexical expressions, allowing a more comprehensive view 
13 // the optimization.  It replaces redundant values with uses of earlier 
14 // occurences of the same value.  While this is beneficial in that it eliminates
15 // unneeded computation, it also increases register pressure by creating large
16 // live ranges, and should be used with caution on platforms that a very 
17 // sensitive to register pressure.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "gvnpre"
22 #include "llvm/Value.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Function.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm/Analysis/PostDominators.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include <algorithm>
33 #include <deque>
34 #include <map>
35 #include <vector>
36 #include <set>
37 using namespace llvm;
38
39 struct ExprLT {
40   bool operator()(Value* left, Value* right) {
41     if (!isa<BinaryOperator>(left) || !isa<BinaryOperator>(right))
42       return left < right;
43     
44     BinaryOperator* BO1 = cast<BinaryOperator>(left);
45     BinaryOperator* BO2 = cast<BinaryOperator>(right);
46     
47     if ((*this)(BO1->getOperand(0), BO2->getOperand(0)))
48       return true;
49     else if ((*this)(BO2->getOperand(0), BO1->getOperand(0)))
50       return false;
51     else
52       return (*this)(BO1->getOperand(1), BO2->getOperand(1));
53   }
54 };
55
56 namespace {
57
58   class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
59     bool runOnFunction(Function &F);
60   public:
61     static char ID; // Pass identification, replacement for typeid
62     GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; }
63
64   private:
65     uint32_t nextValueNumber;
66     typedef std::map<Value*, uint32_t, ExprLT> ValueTable;
67     
68     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69       AU.setPreservesCFG();
70       AU.addRequired<DominatorTree>();
71       AU.addRequired<PostDominatorTree>();
72     }
73   
74     // Helper fuctions
75     // FIXME: eliminate or document these better
76     void dump(ValueTable& VN, std::set<Value*, ExprLT>& s);
77     void clean(ValueTable VN, std::set<Value*, ExprLT>& set);
78     bool add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V);
79     Value* find_leader(ValueTable VN, std::set<Value*, ExprLT>& vals, uint32_t v);
80     void phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
81                        std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
82                        std::set<Value*, ExprLT>& out);
83     
84     void topo_sort(ValueTable& VN, std::set<Value*, ExprLT>& set,
85                    std::vector<Value*>& vec);
86     
87     // For a given block, calculate the generated expressions, temporaries,
88     // and the AVAIL_OUT set
89     void CalculateAvailOut(ValueTable& VN, std::set<Value*, ExprLT>& MS,
90                        DominatorTree::Node* DI,
91                        std::set<Value*, ExprLT>& currExps,
92                        std::set<PHINode*>& currPhis,
93                        std::set<Value*, ExprLT>& currTemps,
94                        std::set<Value*, ExprLT>& currAvail,
95                        std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
96   
97   };
98   
99   char GVNPRE::ID = 0;
100   
101 }
102
103 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
104
105 RegisterPass<GVNPRE> X("gvnpre",
106                        "Global Value Numbering/Partial Redundancy Elimination");
107
108
109
110 bool GVNPRE::add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V) {
111   std::pair<ValueTable::iterator, bool> ret = VN.insert(std::make_pair(V, nextValueNumber));
112   if (ret.second)
113     nextValueNumber++;
114   if (isa<BinaryOperator>(V) || isa<PHINode>(V))
115     MS.insert(V);
116   return ret.second;
117 }
118
119 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
120                            std::set<Value*, ExprLT>& vals,
121                            uint32_t v) {
122   for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
123        I != E; ++I)
124     if (VN[*I] == v)
125       return *I;
126   
127   return 0;
128 }
129
130 void GVNPRE::phi_translate(GVNPRE::ValueTable& VN,
131                            std::set<Value*, ExprLT>& MS,
132                            std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
133                            std::set<Value*, ExprLT>& out) {
134   BasicBlock* succ = B->getTerminator()->getSuccessor(0);
135   
136   for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(), E = anticIn.end();
137        I != E; ++I) {
138     if (!isa<BinaryOperator>(*I)) {
139       if (PHINode* p = dyn_cast<PHINode>(*I)) {
140         if (p->getParent() == succ)
141           out.insert(p);
142       } else {
143         out.insert(*I);
144       }
145     } else {
146       BinaryOperator* BO = cast<BinaryOperator>(*I);
147       Value* lhs = find_leader(VN, anticIn, VN[BO->getOperand(0)]);
148       if (lhs == 0)
149         continue;
150       
151       if (PHINode* p = dyn_cast<PHINode>(lhs))
152         if (p->getParent() == succ) {
153           lhs = p->getIncomingValueForBlock(B);
154           out.insert(lhs);
155         }
156       
157       Value* rhs = find_leader(VN, anticIn, VN[BO->getOperand(1)]);
158       if (rhs == 0)
159         continue;
160       
161       if (PHINode* p = dyn_cast<PHINode>(rhs))
162         if (p->getParent() == succ) {
163           rhs = p->getIncomingValueForBlock(B);
164           out.insert(rhs);
165         }
166       
167       if (lhs != BO->getOperand(0) || rhs != BO->getOperand(1)) {
168         BO = BinaryOperator::create(BO->getOpcode(), lhs, rhs, BO->getName()+".gvnpre");
169         if (VN.insert(std::make_pair(BO, nextValueNumber)).second)
170           nextValueNumber++;
171         MS.insert(BO);
172       }
173       
174       out.insert(BO);
175       
176     }
177   }
178 }
179
180 // Remove all expressions whose operands are not themselves in the set
181 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
182   std::vector<Value*> worklist;
183   topo_sort(VN, set, worklist);
184   
185   while (!worklist.empty()) {
186     Value* v = worklist.back();
187     worklist.pop_back();
188     
189     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {   
190       bool lhsValid = false;
191       for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
192            I != E; ++I)
193         if (VN[*I] == VN[BO->getOperand(0)]);
194           lhsValid = true;
195     
196       bool rhsValid = false;
197       for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
198            I != E; ++I)
199         if (VN[*I] == VN[BO->getOperand(1)]);
200           rhsValid = true;
201       
202       if (!lhsValid || !rhsValid)
203         set.erase(BO);
204     }
205   }
206 }
207
208 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
209                        std::set<Value*, ExprLT>& set,
210                        std::vector<Value*>& vec) {
211   std::set<Value*, ExprLT> toErase;               
212   for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
213        I != E; ++I) {
214     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
215       for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
216         if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
217           toErase.insert(BO);
218         }
219     }
220   }
221   
222   std::vector<Value*> Q;
223   std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
224   std::set_difference(set.begin(), set.end(),
225                      toErase.begin(), toErase.end(),
226                      q_ins, ExprLT());
227   
228   std::set<Value*, ExprLT> visited;
229   while (!Q.empty()) {
230     Value* e = Q.back();
231   
232     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
233       Value* l = find_leader(VN, set, VN[BO->getOperand(0)]);
234       Value* r = find_leader(VN, set, VN[BO->getOperand(1)]);
235       
236       if (l != 0 && visited.find(l) == visited.end())
237         Q.push_back(l);
238       else if (r != 0 && visited.find(r) == visited.end())
239         Q.push_back(r);
240       else {
241         vec.push_back(e);
242         visited.insert(e);
243         Q.pop_back();
244       }
245     } else {
246       visited.insert(e);
247       vec.push_back(e);
248       Q.pop_back();
249     }
250   }
251 }
252
253 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
254   std::vector<Value*> sorted;
255   topo_sort(VN, s, sorted);
256   DOUT << "{ ";
257   for (std::vector<Value*>::iterator I = sorted.begin(), E = sorted.end();
258        I != E; ++I) {
259     DEBUG((*I)->dump());
260   }
261   DOUT << "}\n\n";
262 }
263
264 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
265                        DominatorTree::Node* DI,
266                        std::set<Value*, ExprLT>& currExps,
267                        std::set<PHINode*>& currPhis,
268                        std::set<Value*, ExprLT>& currTemps,
269                        std::set<Value*, ExprLT>& currAvail,
270                        std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
271   
272   BasicBlock* BB = DI->getBlock();
273   
274   // A block inherits AVAIL_OUT from its dominator
275   if (DI->getIDom() != 0)
276   currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
277                    availOut[DI->getIDom()->getBlock()].end());
278     
279     
280  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
281       BI != BE; ++BI) {
282        
283     // Handle PHI nodes...
284     if (PHINode* p = dyn_cast<PHINode>(BI)) {
285       add(VN, MS, p);
286       currPhis.insert(p);
287     
288     // Handle binary ops...
289     } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
290       Value* leftValue = BO->getOperand(0);
291       Value* rightValue = BO->getOperand(1);
292       
293       add(VN, MS, BO);
294       
295       currExps.insert(leftValue);
296       currExps.insert(rightValue);
297       currExps.insert(BO);
298       
299       currTemps.insert(BO);
300         
301     // Handle unsupported ops
302     } else if (!BI->isTerminator()){
303       add(VN, MS, BI);
304       currTemps.insert(BI);
305     }
306     
307     if (!BI->isTerminator())
308       currAvail.insert(BI);
309   }
310 }
311
312 bool GVNPRE::runOnFunction(Function &F) {
313   ValueTable VN;
314   std::set<Value*, ExprLT> maximalSet;
315
316   std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
317   std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
318   std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedTemporaries;
319   std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
320   std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
321   
322   DominatorTree &DT = getAnalysis<DominatorTree>();   
323   
324   // First Phase of BuildSets - calculate AVAIL_OUT
325   
326   // Top-down walk of the dominator tree
327   for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
328          E = df_end(DT.getRootNode()); DI != E; ++DI) {
329     
330     // Get the sets to update for this block
331     std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
332     std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
333     std::set<Value*, ExprLT>& currTemps = generatedTemporaries[DI->getBlock()];
334     std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];     
335     
336     CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
337                       currTemps, currAvail, availableOut);
338   }
339   
340   PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
341   
342   // Second Phase of BuildSets - calculate ANTIC_IN
343   
344   std::set<BasicBlock*> visited;
345   
346   bool changed = true;
347   unsigned iterations = 0;
348   while (changed) {
349     changed = false;
350     std::set<Value*, ExprLT> anticOut;
351     
352     // Top-down walk of the postdominator tree
353     for (df_iterator<PostDominatorTree::Node*> PDI = 
354          df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
355          PDI != E; ++PDI) {
356       BasicBlock* BB = PDI->getBlock();
357       
358       visited.insert(BB);
359       
360       std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
361       std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
362       
363       if (BB->getTerminator()->getNumSuccessors() == 1) {
364          if (visited.find(BB) == visited.end())
365            phi_translate(VN, maximalSet, anticIn, BB, anticOut);
366          else
367            phi_translate(VN, anticIn, anticIn, BB, anticOut);
368       } else if (BB->getTerminator()->getNumSuccessors() > 1) {
369         for (unsigned i = 0; i < BB->getTerminator()->getNumSuccessors(); ++i) {
370           BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
371           std::set<Value*, ExprLT> temp;
372           if (visited.find(currSucc) == visited.end())
373             temp.insert(maximalSet.begin(), maximalSet.end());
374           else
375             temp.insert(anticIn.begin(), anticIn.end());
376        
377           anticIn.clear();
378           std::insert_iterator<std::set<Value*, ExprLT> >  ai_ins(anticIn,
379                                                        anticIn.begin());
380                                                        
381           std::set_difference(anticipatedIn[currSucc].begin(),
382                               anticipatedIn[currSucc].end(),
383                               temp.begin(),
384                               temp.end(),
385                               ai_ins,
386                               ExprLT());
387         }
388       }
389       
390       std::set<Value*, ExprLT> S;
391       std::insert_iterator<std::set<Value*, ExprLT> >  s_ins(S, S.begin());
392       std::set_union(anticOut.begin(), anticOut.end(),
393                      generatedExpressions[BB].begin(),
394                      generatedExpressions[BB].end(),
395                      s_ins, ExprLT());
396       
397       anticIn.clear();
398       std::insert_iterator<std::set<Value*, ExprLT> >  antic_ins(anticIn, 
399                                                              anticIn.begin());
400       std::set_difference(S.begin(), S.end(),
401                           generatedTemporaries[BB].begin(),
402                           generatedTemporaries[BB].end(),
403                           antic_ins,
404                           ExprLT());
405       
406       clean(VN, anticIn);
407       
408       if (old != anticIn)
409         changed = true;
410       
411       anticOut.clear();
412     }
413     iterations++;
414   }
415   
416   DOUT << "Iterations: " << iterations << "\n";
417   
418   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
419     DOUT << "Name: " << I->getName().c_str() << "\n";
420     
421     DOUT << "TMP_GEN: ";
422     dump(VN, generatedTemporaries[I]);
423     DOUT << "\n";
424     
425     DOUT << "EXP_GEN: ";
426     dump(VN, generatedExpressions[I]);
427     DOUT << "\n";
428     
429     DOUT << "ANTIC_IN: ";
430     dump(VN, anticipatedIn[I]);
431     DOUT << "\n";
432     
433     DOUT << "AVAIL_OUT: ";
434     dump(VN, availableOut[I]);
435     DOUT << "\n";
436   }
437   
438   return false;
439 }