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