Fix a small bug, some 80 cols violations, and add some more debugging output.
[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*>& s);
77     void dump_unique(ValueTable& VN, std::set<Value*, ExprLT>& s);
78     void clean(ValueTable VN, std::set<Value*, ExprLT>& set);
79     bool add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V);
80     Value* find_leader(ValueTable VN, std::set<Value*, ExprLT>& vals, uint32_t v);
81     Value* phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
82                          std::set<Value*, ExprLT>& set,
83                          Value* V, BasicBlock* pred);
84     void phi_translate_set(ValueTable& VN, std::set<Value*, ExprLT>& MS,
85                        std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
86                        std::set<Value*, ExprLT>& out);
87     
88     void topo_sort(ValueTable& VN, std::set<Value*, ExprLT>& set,
89                    std::vector<Value*>& vec);
90     
91     // For a given block, calculate the generated expressions, temporaries,
92     // and the AVAIL_OUT set
93     void CalculateAvailOut(ValueTable& VN, std::set<Value*, ExprLT>& MS,
94                        DomTreeNode* DI,
95                        std::set<Value*, ExprLT>& currExps,
96                        std::set<PHINode*>& currPhis,
97                        std::set<Value*>& currTemps,
98                        std::set<Value*, ExprLT>& currAvail,
99                        std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
100   
101   };
102   
103   char GVNPRE::ID = 0;
104   
105 }
106
107 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
108
109 RegisterPass<GVNPRE> X("gvnpre",
110                        "Global Value Numbering/Partial Redundancy Elimination");
111
112
113
114 bool GVNPRE::add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V) {
115   std::pair<ValueTable::iterator, bool> ret = VN.insert(std::make_pair(V, nextValueNumber));
116   if (ret.second)
117     nextValueNumber++;
118   if (isa<BinaryOperator>(V) || isa<PHINode>(V))
119     MS.insert(V);
120   return ret.second;
121 }
122
123 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
124                            std::set<Value*, ExprLT>& vals,
125                            uint32_t v) {
126   for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
127        I != E; ++I)
128     if (VN[*I] == v)
129       return *I;
130   
131   return 0;
132 }
133
134 Value* GVNPRE::phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
135                              std::set<Value*, ExprLT>& set,
136                              Value* V, BasicBlock* pred) {
137   if (V == 0)
138     return 0;
139   
140   if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
141     Value* newOp1 = isa<Instruction>(BO->getOperand(0))
142                                 ? phi_translate(VN, MS, set,
143                                   find_leader(VN, set, VN[BO->getOperand(0)]),
144                                   pred)
145                                 : BO->getOperand(0);
146     if (newOp1 == 0)
147       return 0;
148     
149     Value* newOp2 = isa<Instruction>(BO->getOperand(1))
150                                 ? phi_translate(VN, MS, set,
151                                   find_leader(VN, set, VN[BO->getOperand(0)]),
152                                   pred)
153                                 : BO->getOperand(1);
154     if (newOp2 == 0)
155       return 0;
156     
157     if (newOp1 != BO->getOperand(0) || newOp2 != BO->getOperand(1)) {
158       Value* newVal = BinaryOperator::create(BO->getOpcode(),
159                                              newOp1, newOp2,
160                                              BO->getName()+".gvnpre");
161       add(VN, MS, newVal);
162       if (!find_leader(VN, set, VN[newVal]))
163         return newVal;
164       else
165         return 0;
166     }
167   } else if (PHINode* P = dyn_cast<PHINode>(V)) {
168     if (P->getParent() == pred->getTerminator()->getSuccessor(0))
169       return P->getIncomingValueForBlock(pred);
170   }
171   
172   return V;
173 }
174
175 void GVNPRE::phi_translate_set(GVNPRE::ValueTable& VN,
176                            std::set<Value*, ExprLT>& MS,
177                            std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
178                            std::set<Value*, ExprLT>& out) {
179   for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(),
180        E = anticIn.end(); I != E; ++I) {
181     Value* V = phi_translate(VN, MS, anticIn, *I, B);
182     if (V != 0)
183       out.insert(V);
184   }
185 }
186
187 // Remove all expressions whose operands are not themselves in the set
188 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
189   std::vector<Value*> worklist;
190   topo_sort(VN, set, worklist);
191   
192   while (!worklist.empty()) {
193     Value* v = worklist.back();
194     worklist.pop_back();
195     
196     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {   
197       bool lhsValid = false;
198       for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
199            I != E; ++I)
200         if (VN[*I] == VN[BO->getOperand(0)]);
201           lhsValid = true;
202     
203       bool rhsValid = false;
204       for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
205            I != E; ++I)
206         if (VN[*I] == VN[BO->getOperand(1)]);
207           rhsValid = true;
208       
209       if (!lhsValid || !rhsValid)
210         set.erase(BO);
211     }
212   }
213 }
214
215 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
216                        std::set<Value*, ExprLT>& set,
217                        std::vector<Value*>& vec) {
218   std::set<Value*, ExprLT> toErase;               
219   for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
220        I != E; ++I) {
221     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
222       for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
223         if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
224           toErase.insert(BO);
225         }
226     }
227   }
228   
229   std::vector<Value*> Q;
230   std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
231   std::set_difference(set.begin(), set.end(),
232                      toErase.begin(), toErase.end(),
233                      q_ins, ExprLT());
234   
235   std::set<Value*, ExprLT> visited;
236   while (!Q.empty()) {
237     Value* e = Q.back();
238   
239     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
240       Value* l = find_leader(VN, set, VN[BO->getOperand(0)]);
241       Value* r = find_leader(VN, set, VN[BO->getOperand(1)]);
242       
243       if (l != 0 && visited.find(l) == visited.end())
244         Q.push_back(l);
245       else if (r != 0 && visited.find(r) == visited.end())
246         Q.push_back(r);
247       else {
248         vec.push_back(e);
249         visited.insert(e);
250         Q.pop_back();
251       }
252     } else {
253       visited.insert(e);
254       vec.push_back(e);
255       Q.pop_back();
256     }
257   }
258 }
259
260
261 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*>& s) {
262   DOUT << "{ ";
263   for (std::set<Value*>::iterator I = s.begin(), E = s.end();
264        I != E; ++I) {
265     DEBUG((*I)->dump());
266   }
267   DOUT << "}\n\n";
268 }
269
270 void GVNPRE::dump_unique(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
271   DOUT << "{ ";
272   for (std::set<Value*>::iterator I = s.begin(), E = s.end();
273        I != E; ++I) {
274     DEBUG((*I)->dump());
275   }
276   DOUT << "}\n\n";
277 }
278
279 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
280                        DomTreeNode* DI,
281                        std::set<Value*, ExprLT>& currExps,
282                        std::set<PHINode*>& currPhis,
283                        std::set<Value*>& currTemps,
284                        std::set<Value*, ExprLT>& currAvail,
285                        std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
286   
287   BasicBlock* BB = DI->getBlock();
288   
289   // A block inherits AVAIL_OUT from its dominator
290   if (DI->getIDom() != 0)
291   currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
292                    availOut[DI->getIDom()->getBlock()].end());
293     
294     
295  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
296       BI != BE; ++BI) {
297        
298     // Handle PHI nodes...
299     if (PHINode* p = dyn_cast<PHINode>(BI)) {
300       add(VN, MS, p);
301       currPhis.insert(p);
302     
303     // Handle binary ops...
304     } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
305       Value* leftValue = BO->getOperand(0);
306       Value* rightValue = BO->getOperand(1);
307       
308       add(VN, MS, BO);
309       
310       if (isa<Instruction>(leftValue))
311         currExps.insert(leftValue);
312       if (isa<Instruction>(rightValue))
313         currExps.insert(rightValue);
314       currExps.insert(BO);
315       
316       currTemps.insert(BO);
317       
318     // Handle unsupported ops
319     } else if (!BI->isTerminator()){
320       add(VN, MS, BI);
321       currTemps.insert(BI);
322     }
323     
324     if (!BI->isTerminator())
325       currAvail.insert(BI);
326   }
327 }
328
329 bool GVNPRE::runOnFunction(Function &F) {
330   ValueTable VN;
331   std::set<Value*, ExprLT> maximalSet;
332
333   std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
334   std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
335   std::map<BasicBlock*, std::set<Value*> > generatedTemporaries;
336   std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
337   std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
338   
339   DominatorTree &DT = getAnalysis<DominatorTree>();   
340   
341   // First Phase of BuildSets - calculate AVAIL_OUT
342   
343   // Top-down walk of the dominator tree
344   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
345          E = df_end(DT.getRootNode()); DI != E; ++DI) {
346     
347     // Get the sets to update for this block
348     std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
349     std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
350     std::set<Value*>& currTemps = generatedTemporaries[DI->getBlock()];
351     std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];     
352     
353     CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
354                       currTemps, currAvail, availableOut);
355   }
356   
357   DOUT << "Maximal Set: ";
358   dump_unique(VN, maximalSet);
359   DOUT << "\n";
360   
361   PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
362   
363   // Second Phase of BuildSets - calculate ANTIC_IN
364   
365   std::set<BasicBlock*> visited;
366   
367   bool changed = true;
368   unsigned iterations = 0;
369   while (changed) {
370     changed = false;
371     std::set<Value*, ExprLT> anticOut;
372     
373     // Top-down walk of the postdominator tree
374     for (df_iterator<DomTreeNode*> PDI = 
375          df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
376          PDI != E; ++PDI) {
377       BasicBlock* BB = PDI->getBlock();
378       DOUT << "Block: " << BB->getName() << "\n";
379       DOUT << "TMP_GEN: ";
380       dump(VN, generatedTemporaries[BB]);
381       DOUT << "\n";
382     
383       DOUT << "EXP_GEN: ";
384       dump_unique(VN, generatedExpressions[BB]);
385       visited.insert(BB);
386       
387       std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
388       std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
389       
390       if (BB->getTerminator()->getNumSuccessors() == 1) {
391          if (visited.find(BB->getTerminator()->getSuccessor(0)) == 
392              visited.end())
393            phi_translate_set(VN, maximalSet, maximalSet, BB, anticOut);
394          else
395            phi_translate_set(VN, maximalSet, 
396              anticipatedIn[BB->getTerminator()->getSuccessor(0)], BB, anticOut);
397       } else if (BB->getTerminator()->getNumSuccessors() > 1) {
398         BasicBlock* first = BB->getTerminator()->getSuccessor(0);
399         anticOut.insert(anticipatedIn[first].begin(),
400                         anticipatedIn[first].end());
401         for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
402           BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
403           std::set<Value*, ExprLT>& succAnticIn = anticipatedIn[currSucc];
404           
405           std::set<Value*, ExprLT> temp;
406           std::insert_iterator<std::set<Value*, ExprLT> >  temp_ins(temp, 
407                                                                   temp.begin());
408           std::set_intersection(anticOut.begin(), anticOut.end(),
409                                 succAnticIn.begin(), succAnticIn.end(),
410                                 temp_ins, ExprLT());
411           
412           anticOut.clear();
413           anticOut.insert(temp.begin(), temp.end());
414         }
415       }
416       
417       DOUT << "ANTIC_OUT: ";
418       dump_unique(VN, anticOut);
419       DOUT << "\n";
420       
421       std::set<Value*, ExprLT> S;
422       std::insert_iterator<std::set<Value*, ExprLT> >  s_ins(S, S.begin());
423       std::set_union(anticOut.begin(), anticOut.end(),
424                      generatedExpressions[BB].begin(),
425                      generatedExpressions[BB].end(),
426                      s_ins, ExprLT());
427       
428       anticIn.clear();
429       
430       for (std::set<Value*, ExprLT>::iterator I = S.begin(), E = S.end();
431            I != E; ++I) {
432         if (generatedTemporaries[BB].find(*I) == generatedTemporaries[BB].end())
433           anticIn.insert(*I);
434       }
435       
436       clean(VN, anticIn);
437       
438       DOUT << "ANTIC_IN: ";
439       dump_unique(VN, anticIn);
440       DOUT << "\n";
441       
442       if (old != anticIn)
443         changed = true;
444       
445       anticOut.clear();
446     }
447     
448     iterations++;
449   }
450   
451   DOUT << "Iterations: " << iterations << "\n";
452   
453   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
454     DOUT << "Name: " << I->getName().c_str() << "\n";
455     
456     DOUT << "TMP_GEN: ";
457     dump(VN, generatedTemporaries[I]);
458     DOUT << "\n";
459     
460     DOUT << "EXP_GEN: ";
461     dump_unique(VN, generatedExpressions[I]);
462     DOUT << "\n";
463     
464     DOUT << "ANTIC_IN: ";
465     dump_unique(VN, anticipatedIn[I]);
466     DOUT << "\n";
467     
468     DOUT << "AVAIL_OUT: ";
469     dump_unique(VN, availableOut[I]);
470     DOUT << "\n";
471   }
472   
473   return false;
474 }