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