Add functionality to value number GEP instructions. This also provides the infrastru...
[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 are 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/DerivedTypes.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include <algorithm>
38 #include <deque>
39 #include <map>
40 #include <vector>
41 #include <set>
42 using namespace llvm;
43
44 //===----------------------------------------------------------------------===//
45 //                         ValueTable Class
46 //===----------------------------------------------------------------------===//
47
48 /// This class holds the mapping between values and value numbers.  It is used
49 /// as an efficient mechanism to determine the expression-wise equivalence of
50 /// two values.
51
52 namespace {
53   class VISIBILITY_HIDDEN ValueTable {
54     public:
55       struct Expression {
56         enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
57                               FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
58                               ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
59                               ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
60                               FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
61                               FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
62                               FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
63                               SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
64                               FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
65                               PTRTOINT, INTTOPTR, BITCAST, GEP};
66     
67         ExpressionOpcode opcode;
68         const Type* type;
69         uint32_t firstVN;
70         uint32_t secondVN;
71         uint32_t thirdVN;
72         std::vector<uint32_t> varargs;
73       
74         bool operator< (const Expression& other) const {
75           if (opcode < other.opcode)
76             return true;
77           else if (opcode > other.opcode)
78             return false;
79           else if (type < other.type)
80             return true;
81           else if (type > other.type)
82             return false;
83           else if (firstVN < other.firstVN)
84             return true;
85           else if (firstVN > other.firstVN)
86             return false;
87           else if (secondVN < other.secondVN)
88             return true;
89           else if (secondVN > other.secondVN)
90             return false;
91           else if (thirdVN < other.thirdVN)
92             return true;
93           else if (thirdVN > other.thirdVN)
94             return false;
95           else {
96             if (varargs.size() < other.varargs.size())
97               return true;
98             else if (varargs.size() > other.varargs.size())
99               return false;
100             
101             for (size_t i = 0; i < varargs.size(); ++i)
102               if (varargs[i] < other.varargs[i])
103                 return true;
104               else if (varargs[i] > other.varargs[i])
105                 return false;
106           
107             return false;
108           }
109         }
110       };
111     
112     private:
113       DenseMap<Value*, uint32_t> valueNumbering;
114       std::map<Expression, uint32_t> expressionNumbering;
115   
116       uint32_t nextValueNumber;
117     
118       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
119       Expression::ExpressionOpcode getOpcode(CmpInst* C);
120       Expression::ExpressionOpcode getOpcode(CastInst* C);
121       Expression create_expression(BinaryOperator* BO);
122       Expression create_expression(CmpInst* C);
123       Expression create_expression(ShuffleVectorInst* V);
124       Expression create_expression(ExtractElementInst* C);
125       Expression create_expression(InsertElementInst* V);
126       Expression create_expression(SelectInst* V);
127       Expression create_expression(CastInst* C);
128       Expression create_expression(GetElementPtrInst* G);
129     public:
130       ValueTable() { nextValueNumber = 1; }
131       uint32_t lookup_or_add(Value* V);
132       uint32_t lookup(Value* V) const;
133       void add(Value* V, uint32_t num);
134       void clear();
135       void erase(Value* v);
136       unsigned size();
137   };
138 }
139
140 //===----------------------------------------------------------------------===//
141 //                     ValueTable Internal Functions
142 //===----------------------------------------------------------------------===//
143 ValueTable::Expression::ExpressionOpcode 
144                              ValueTable::getOpcode(BinaryOperator* BO) {
145   switch(BO->getOpcode()) {
146     case Instruction::Add:
147       return Expression::ADD;
148     case Instruction::Sub:
149       return Expression::SUB;
150     case Instruction::Mul:
151       return Expression::MUL;
152     case Instruction::UDiv:
153       return Expression::UDIV;
154     case Instruction::SDiv:
155       return Expression::SDIV;
156     case Instruction::FDiv:
157       return Expression::FDIV;
158     case Instruction::URem:
159       return Expression::UREM;
160     case Instruction::SRem:
161       return Expression::SREM;
162     case Instruction::FRem:
163       return Expression::FREM;
164     case Instruction::Shl:
165       return Expression::SHL;
166     case Instruction::LShr:
167       return Expression::LSHR;
168     case Instruction::AShr:
169       return Expression::ASHR;
170     case Instruction::And:
171       return Expression::AND;
172     case Instruction::Or:
173       return Expression::OR;
174     case Instruction::Xor:
175       return Expression::XOR;
176     
177     // THIS SHOULD NEVER HAPPEN
178     default:
179       assert(0 && "Binary operator with unknown opcode?");
180       return Expression::ADD;
181   }
182 }
183
184 ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
185   if (C->getOpcode() == Instruction::ICmp) {
186     switch (C->getPredicate()) {
187       case ICmpInst::ICMP_EQ:
188         return Expression::ICMPEQ;
189       case ICmpInst::ICMP_NE:
190         return Expression::ICMPNE;
191       case ICmpInst::ICMP_UGT:
192         return Expression::ICMPUGT;
193       case ICmpInst::ICMP_UGE:
194         return Expression::ICMPUGE;
195       case ICmpInst::ICMP_ULT:
196         return Expression::ICMPULT;
197       case ICmpInst::ICMP_ULE:
198         return Expression::ICMPULE;
199       case ICmpInst::ICMP_SGT:
200         return Expression::ICMPSGT;
201       case ICmpInst::ICMP_SGE:
202         return Expression::ICMPSGE;
203       case ICmpInst::ICMP_SLT:
204         return Expression::ICMPSLT;
205       case ICmpInst::ICMP_SLE:
206         return Expression::ICMPSLE;
207       
208       // THIS SHOULD NEVER HAPPEN
209       default:
210         assert(0 && "Comparison with unknown predicate?");
211         return Expression::ICMPEQ;
212     }
213   } else {
214     switch (C->getPredicate()) {
215       case FCmpInst::FCMP_OEQ:
216         return Expression::FCMPOEQ;
217       case FCmpInst::FCMP_OGT:
218         return Expression::FCMPOGT;
219       case FCmpInst::FCMP_OGE:
220         return Expression::FCMPOGE;
221       case FCmpInst::FCMP_OLT:
222         return Expression::FCMPOLT;
223       case FCmpInst::FCMP_OLE:
224         return Expression::FCMPOLE;
225       case FCmpInst::FCMP_ONE:
226         return Expression::FCMPONE;
227       case FCmpInst::FCMP_ORD:
228         return Expression::FCMPORD;
229       case FCmpInst::FCMP_UNO:
230         return Expression::FCMPUNO;
231       case FCmpInst::FCMP_UEQ:
232         return Expression::FCMPUEQ;
233       case FCmpInst::FCMP_UGT:
234         return Expression::FCMPUGT;
235       case FCmpInst::FCMP_UGE:
236         return Expression::FCMPUGE;
237       case FCmpInst::FCMP_ULT:
238         return Expression::FCMPULT;
239       case FCmpInst::FCMP_ULE:
240         return Expression::FCMPULE;
241       case FCmpInst::FCMP_UNE:
242         return Expression::FCMPUNE;
243       
244       // THIS SHOULD NEVER HAPPEN
245       default:
246         assert(0 && "Comparison with unknown predicate?");
247         return Expression::FCMPOEQ;
248     }
249   }
250 }
251
252 ValueTable::Expression::ExpressionOpcode 
253                              ValueTable::getOpcode(CastInst* C) {
254   switch(C->getOpcode()) {
255     case Instruction::Trunc:
256       return Expression::TRUNC;
257     case Instruction::ZExt:
258       return Expression::ZEXT;
259     case Instruction::SExt:
260       return Expression::SEXT;
261     case Instruction::FPToUI:
262       return Expression::FPTOUI;
263     case Instruction::FPToSI:
264       return Expression::FPTOSI;
265     case Instruction::UIToFP:
266       return Expression::UITOFP;
267     case Instruction::SIToFP:
268       return Expression::SITOFP;
269     case Instruction::FPTrunc:
270       return Expression::FPTRUNC;
271     case Instruction::FPExt:
272       return Expression::FPEXT;
273     case Instruction::PtrToInt:
274       return Expression::PTRTOINT;
275     case Instruction::IntToPtr:
276       return Expression::INTTOPTR;
277     case Instruction::BitCast:
278       return Expression::BITCAST;
279     
280     // THIS SHOULD NEVER HAPPEN
281     default:
282       assert(0 && "Cast operator with unknown opcode?");
283       return Expression::BITCAST;
284   }
285 }
286
287 ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
288   Expression e;
289     
290   e.firstVN = lookup_or_add(BO->getOperand(0));
291   e.secondVN = lookup_or_add(BO->getOperand(1));
292   e.thirdVN = 0;
293   e.type = BO->getType();
294   e.opcode = getOpcode(BO);
295   
296   return e;
297 }
298
299 ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
300   Expression e;
301     
302   e.firstVN = lookup_or_add(C->getOperand(0));
303   e.secondVN = lookup_or_add(C->getOperand(1));
304   e.thirdVN = 0;
305   e.type = C->getType();
306   e.opcode = getOpcode(C);
307   
308   return e;
309 }
310
311 ValueTable::Expression ValueTable::create_expression(CastInst* C) {
312   Expression e;
313     
314   e.firstVN = lookup_or_add(C->getOperand(0));
315   e.secondVN = 0;
316   e.thirdVN = 0;
317   e.type = C->getType();
318   e.opcode = getOpcode(C);
319   
320   return e;
321 }
322
323 ValueTable::Expression ValueTable::create_expression(ShuffleVectorInst* S) {
324   Expression e;
325     
326   e.firstVN = lookup_or_add(S->getOperand(0));
327   e.secondVN = lookup_or_add(S->getOperand(1));
328   e.thirdVN = lookup_or_add(S->getOperand(2));
329   e.type = S->getType();
330   e.opcode = Expression::SHUFFLE;
331   
332   return e;
333 }
334
335 ValueTable::Expression ValueTable::create_expression(ExtractElementInst* E) {
336   Expression e;
337     
338   e.firstVN = lookup_or_add(E->getOperand(0));
339   e.secondVN = lookup_or_add(E->getOperand(1));
340   e.thirdVN = 0;
341   e.type = E->getType();
342   e.opcode = Expression::EXTRACT;
343   
344   return e;
345 }
346
347 ValueTable::Expression ValueTable::create_expression(InsertElementInst* I) {
348   Expression e;
349     
350   e.firstVN = lookup_or_add(I->getOperand(0));
351   e.secondVN = lookup_or_add(I->getOperand(1));
352   e.thirdVN = lookup_or_add(I->getOperand(2));
353   e.type = I->getType();
354   e.opcode = Expression::INSERT;
355   
356   return e;
357 }
358
359 ValueTable::Expression ValueTable::create_expression(SelectInst* I) {
360   Expression e;
361     
362   e.firstVN = lookup_or_add(I->getCondition());
363   e.secondVN = lookup_or_add(I->getTrueValue());
364   e.thirdVN = lookup_or_add(I->getFalseValue());
365   e.type = I->getType();
366   e.opcode = Expression::SELECT;
367   
368   return e;
369 }
370
371 ValueTable::Expression ValueTable::create_expression(GetElementPtrInst* G) {
372   Expression e;
373     
374   e.firstVN = lookup_or_add(G->getPointerOperand());
375   e.secondVN = 0;
376   e.thirdVN = 0;
377   e.type = G->getType();
378   e.opcode = Expression::SELECT;
379   
380   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
381        I != E; ++I)
382     e.varargs.push_back(lookup_or_add(*I));
383   
384   return e;
385 }
386
387 //===----------------------------------------------------------------------===//
388 //                     ValueTable External Functions
389 //===----------------------------------------------------------------------===//
390
391 /// lookup_or_add - Returns the value number for the specified value, assigning
392 /// it a new number if it did not have one before.
393 uint32_t ValueTable::lookup_or_add(Value* V) {
394   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
395   if (VI != valueNumbering.end())
396     return VI->second;
397   
398   
399   if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
400     Expression e = create_expression(BO);
401     
402     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
403     if (EI != expressionNumbering.end()) {
404       valueNumbering.insert(std::make_pair(V, EI->second));
405       return EI->second;
406     } else {
407       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
408       valueNumbering.insert(std::make_pair(V, nextValueNumber));
409       
410       return nextValueNumber++;
411     }
412   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
413     Expression e = create_expression(C);
414     
415     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
416     if (EI != expressionNumbering.end()) {
417       valueNumbering.insert(std::make_pair(V, EI->second));
418       return EI->second;
419     } else {
420       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
421       valueNumbering.insert(std::make_pair(V, nextValueNumber));
422       
423       return nextValueNumber++;
424     }
425   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
426     Expression e = create_expression(U);
427     
428     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429     if (EI != expressionNumbering.end()) {
430       valueNumbering.insert(std::make_pair(V, EI->second));
431       return EI->second;
432     } else {
433       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434       valueNumbering.insert(std::make_pair(V, nextValueNumber));
435       
436       return nextValueNumber++;
437     }
438   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
439     Expression e = create_expression(U);
440     
441     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
442     if (EI != expressionNumbering.end()) {
443       valueNumbering.insert(std::make_pair(V, EI->second));
444       return EI->second;
445     } else {
446       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447       valueNumbering.insert(std::make_pair(V, nextValueNumber));
448       
449       return nextValueNumber++;
450     }
451   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
452     Expression e = create_expression(U);
453     
454     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
455     if (EI != expressionNumbering.end()) {
456       valueNumbering.insert(std::make_pair(V, EI->second));
457       return EI->second;
458     } else {
459       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
460       valueNumbering.insert(std::make_pair(V, nextValueNumber));
461       
462       return nextValueNumber++;
463     }
464   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
465     Expression e = create_expression(U);
466     
467     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
468     if (EI != expressionNumbering.end()) {
469       valueNumbering.insert(std::make_pair(V, EI->second));
470       return EI->second;
471     } else {
472       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
473       valueNumbering.insert(std::make_pair(V, nextValueNumber));
474       
475       return nextValueNumber++;
476     }
477   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
478     Expression e = create_expression(U);
479     
480     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
481     if (EI != expressionNumbering.end()) {
482       valueNumbering.insert(std::make_pair(V, EI->second));
483       return EI->second;
484     } else {
485       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
486       valueNumbering.insert(std::make_pair(V, nextValueNumber));
487       
488       return nextValueNumber++;
489     }
490   } else {
491     valueNumbering.insert(std::make_pair(V, nextValueNumber));
492     return nextValueNumber++;
493   }
494 }
495
496 /// lookup - Returns the value number of the specified value. Fails if
497 /// the value has not yet been numbered.
498 uint32_t ValueTable::lookup(Value* V) const {
499   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
500   if (VI != valueNumbering.end())
501     return VI->second;
502   else
503     assert(0 && "Value not numbered?");
504   
505   return 0;
506 }
507
508 /// add - Add the specified value with the given value number, removing
509 /// its old number, if any
510 void ValueTable::add(Value* V, uint32_t num) {
511   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
512   if (VI != valueNumbering.end())
513     valueNumbering.erase(VI);
514   valueNumbering.insert(std::make_pair(V, num));
515 }
516
517 /// clear - Remove all entries from the ValueTable
518 void ValueTable::clear() {
519   valueNumbering.clear();
520   expressionNumbering.clear();
521   nextValueNumber = 1;
522 }
523
524 /// erase - Remove a value from the value numbering
525 void ValueTable::erase(Value* V) {
526   valueNumbering.erase(V);
527 }
528
529 /// size - Return the number of assigned value numbers
530 unsigned ValueTable::size() {
531   // NOTE: zero is never assigned
532   return nextValueNumber;
533 }
534
535 //===----------------------------------------------------------------------===//
536 //                         GVNPRE Pass
537 //===----------------------------------------------------------------------===//
538
539 namespace {
540
541   class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
542     bool runOnFunction(Function &F);
543   public:
544     static char ID; // Pass identification, replacement for typeid
545     GVNPRE() : FunctionPass((intptr_t)&ID) { }
546
547   private:
548     ValueTable VN;
549     std::vector<Instruction*> createdExpressions;
550     
551     std::map<BasicBlock*, SmallPtrSet<Value*, 16> > availableOut;
552     std::map<BasicBlock*, SmallPtrSet<Value*, 16> > anticipatedIn;
553     
554     // This transformation requires dominator postdominator info
555     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
556       AU.setPreservesCFG();
557       AU.addRequired<DominatorTree>();
558     }
559   
560     // Helper fuctions
561     // FIXME: eliminate or document these better
562     void dump(const SmallPtrSet<Value*, 16>& s) const;
563     void clean(SmallPtrSet<Value*, 16>& set, BitVector& presentInSet);
564     Value* find_leader(SmallPtrSet<Value*, 16>& vals,
565                        uint32_t v);
566     Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ);
567     void phi_translate_set(SmallPtrSet<Value*, 16>& anticIn, BasicBlock* pred,
568                            BasicBlock* succ, SmallPtrSet<Value*, 16>& out);
569     
570     void topo_sort(SmallPtrSet<Value*, 16>& set,
571                    std::vector<Value*>& vec);
572     
573     void cleanup();
574     bool elimination();
575     
576     void val_insert(SmallPtrSet<Value*, 16>& s, Value* v);
577     void val_replace(SmallPtrSet<Value*, 16>& s, Value* v);
578     bool dependsOnInvoke(Value* V);
579     void buildsets_availout(BasicBlock::iterator I,
580                             SmallPtrSet<Value*, 16>& currAvail,
581                             SmallPtrSet<PHINode*, 16>& currPhis,
582                             SmallPtrSet<Value*, 16>& currExps,
583                             SmallPtrSet<Value*, 16>& currTemps,
584                             BitVector& availNumbers,
585                             BitVector& expNumbers);
586     bool buildsets_anticout(BasicBlock* BB,
587                             SmallPtrSet<Value*, 16>& anticOut,
588                             std::set<BasicBlock*>& visited);
589     unsigned buildsets_anticin(BasicBlock* BB,
590                            SmallPtrSet<Value*, 16>& anticOut,
591                            SmallPtrSet<Value*, 16>& currExps,
592                            SmallPtrSet<Value*, 16>& currTemps,
593                            std::set<BasicBlock*>& visited);
594     void buildsets(Function& F);
595     
596     void insertion_pre(Value* e, BasicBlock* BB,
597                        std::map<BasicBlock*, Value*>& avail,
598                        SmallPtrSet<Value*, 16>& new_set);
599     unsigned insertion_mergepoint(std::vector<Value*>& workList,
600                                   df_iterator<DomTreeNode*>& D,
601                                   SmallPtrSet<Value*, 16>& new_set);
602     bool insertion(Function& F);
603   
604   };
605   
606   char GVNPRE::ID = 0;
607   
608 }
609
610 // createGVNPREPass - The public interface to this file...
611 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
612
613 RegisterPass<GVNPRE> X("gvnpre",
614                        "Global Value Numbering/Partial Redundancy Elimination");
615
616
617 STATISTIC(NumInsertedVals, "Number of values inserted");
618 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
619 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
620
621 /// find_leader - Given a set and a value number, return the first
622 /// element of the set with that value number, or 0 if no such element
623 /// is present
624 Value* GVNPRE::find_leader(SmallPtrSet<Value*, 16>& vals, uint32_t v) {
625   for (SmallPtrSet<Value*, 16>::iterator I = vals.begin(), E = vals.end();
626        I != E; ++I)
627     if (v == VN.lookup(*I))
628       return *I;
629   
630   return 0;
631 }
632
633 /// val_insert - Insert a value into a set only if there is not a value
634 /// with the same value number already in the set
635 void GVNPRE::val_insert(SmallPtrSet<Value*, 16>& s, Value* v) {
636   uint32_t num = VN.lookup(v);
637   Value* leader = find_leader(s, num);
638   if (leader == 0)
639     s.insert(v);
640 }
641
642 /// val_replace - Insert a value into a set, replacing any values already in
643 /// the set that have the same value number
644 void GVNPRE::val_replace(SmallPtrSet<Value*, 16>& s, Value* v) {
645   uint32_t num = VN.lookup(v);
646   Value* leader = find_leader(s, num);
647   while (leader != 0) {
648     s.erase(leader);
649     leader = find_leader(s, num);
650   }
651   s.insert(v);
652 }
653
654 /// phi_translate - Given a value, its parent block, and a predecessor of its
655 /// parent, translate the value into legal for the predecessor block.  This 
656 /// means translating its operands (and recursively, their operands) through
657 /// any phi nodes in the parent into values available in the predecessor
658 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
659   if (V == 0)
660     return 0;
661   
662   // Unary Operations
663   if (CastInst* U = dyn_cast<CastInst>(V)) {
664     Value* newOp1 = 0;
665     if (isa<Instruction>(U->getOperand(0)))
666       newOp1 = phi_translate(U->getOperand(0), pred, succ);
667     else
668       newOp1 = U->getOperand(0);
669     
670     if (newOp1 == 0)
671       return 0;
672     
673     if (newOp1 != U->getOperand(0)) {
674       Instruction* newVal = 0;
675       if (CastInst* C = dyn_cast<CastInst>(U))
676         newVal = CastInst::create(C->getOpcode(),
677                                   newOp1, C->getType(),
678                                   C->getName()+".expr");
679       
680       uint32_t v = VN.lookup_or_add(newVal);
681       
682       Value* leader = find_leader(availableOut[pred], v);
683       if (leader == 0) {
684         createdExpressions.push_back(newVal);
685         return newVal;
686       } else {
687         VN.erase(newVal);
688         delete newVal;
689         return leader;
690       }
691     }
692   
693   // Binary Operations
694   } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) || 
695       isa<ExtractElementInst>(V)) {
696     User* U = cast<User>(V);
697     
698     Value* newOp1 = 0;
699     if (isa<Instruction>(U->getOperand(0)))
700       newOp1 = phi_translate(U->getOperand(0), pred, succ);
701     else
702       newOp1 = U->getOperand(0);
703     
704     if (newOp1 == 0)
705       return 0;
706     
707     Value* newOp2 = 0;
708     if (isa<Instruction>(U->getOperand(1)))
709       newOp2 = phi_translate(U->getOperand(1), pred, succ);
710     else
711       newOp2 = U->getOperand(1);
712     
713     if (newOp2 == 0)
714       return 0;
715     
716     if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
717       Instruction* newVal = 0;
718       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
719         newVal = BinaryOperator::create(BO->getOpcode(),
720                                         newOp1, newOp2,
721                                         BO->getName()+".expr");
722       else if (CmpInst* C = dyn_cast<CmpInst>(U))
723         newVal = CmpInst::create(C->getOpcode(),
724                                  C->getPredicate(),
725                                  newOp1, newOp2,
726                                  C->getName()+".expr");
727       else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
728         newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
729       
730       uint32_t v = VN.lookup_or_add(newVal);
731       
732       Value* leader = find_leader(availableOut[pred], v);
733       if (leader == 0) {
734         createdExpressions.push_back(newVal);
735         return newVal;
736       } else {
737         VN.erase(newVal);
738         delete newVal;
739         return leader;
740       }
741     }
742   
743   // Ternary Operations
744   } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
745              isa<SelectInst>(V)) {
746     User* U = cast<User>(V);
747     
748     Value* newOp1 = 0;
749     if (isa<Instruction>(U->getOperand(0)))
750       newOp1 = phi_translate(U->getOperand(0), pred, succ);
751     else
752       newOp1 = U->getOperand(0);
753     
754     if (newOp1 == 0)
755       return 0;
756     
757     Value* newOp2 = 0;
758     if (isa<Instruction>(U->getOperand(1)))
759       newOp2 = phi_translate(U->getOperand(1), pred, succ);
760     else
761       newOp2 = U->getOperand(1);
762     
763     if (newOp2 == 0)
764       return 0;
765     
766     Value* newOp3 = 0;
767     if (isa<Instruction>(U->getOperand(2)))
768       newOp3 = phi_translate(U->getOperand(2), pred, succ);
769     else
770       newOp3 = U->getOperand(2);
771     
772     if (newOp3 == 0)
773       return 0;
774     
775     if (newOp1 != U->getOperand(0) ||
776         newOp2 != U->getOperand(1) ||
777         newOp3 != U->getOperand(2)) {
778       Instruction* newVal = 0;
779       if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
780         newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
781                                        S->getName()+".expr");
782       else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
783         newVal = new InsertElementInst(newOp1, newOp2, newOp3,
784                                        I->getName()+".expr");
785       else if (SelectInst* I = dyn_cast<SelectInst>(U))
786         newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
787       
788       uint32_t v = VN.lookup_or_add(newVal);
789       
790       Value* leader = find_leader(availableOut[pred], v);
791       if (leader == 0) {
792         createdExpressions.push_back(newVal);
793         return newVal;
794       } else {
795         VN.erase(newVal);
796         delete newVal;
797         return leader;
798       }
799     }
800   
801   // PHI Nodes
802   } else if (PHINode* P = dyn_cast<PHINode>(V)) {
803     if (P->getParent() == succ)
804       return P->getIncomingValueForBlock(pred);
805   }
806   
807   return V;
808 }
809
810 /// phi_translate_set - Perform phi translation on every element of a set
811 void GVNPRE::phi_translate_set(SmallPtrSet<Value*, 16>& anticIn,
812                               BasicBlock* pred, BasicBlock* succ,
813                               SmallPtrSet<Value*, 16>& out) {
814   for (SmallPtrSet<Value*, 16>::iterator I = anticIn.begin(),
815        E = anticIn.end(); I != E; ++I) {
816     Value* V = phi_translate(*I, pred, succ);
817     if (V != 0)
818       out.insert(V);
819   }
820 }
821
822 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of 
823 /// whose inputs is an invoke instruction.  If this is true, we cannot safely
824 /// PRE the instruction or anything that depends on it.
825 bool GVNPRE::dependsOnInvoke(Value* V) {
826   if (PHINode* p = dyn_cast<PHINode>(V)) {
827     for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
828       if (isa<InvokeInst>(*I))
829         return true;
830     return false;
831   } else {
832     return false;
833   }
834 }
835
836 /// clean - Remove all non-opaque values from the set whose operands are not
837 /// themselves in the set, as well as all values that depend on invokes (see 
838 /// above)
839 void GVNPRE::clean(SmallPtrSet<Value*, 16>& set, BitVector& presentInSet) {
840   std::vector<Value*> worklist;
841   worklist.reserve(set.size());
842   topo_sort(set, worklist);
843   
844   for (unsigned i = 0; i < worklist.size(); ++i) {
845     Value* v = worklist[i];
846     
847     // Handle unary ops
848     if (CastInst* U = dyn_cast<CastInst>(v)) {
849       bool lhsValid = !isa<Instruction>(U->getOperand(0));
850       lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
851       if (lhsValid)
852         lhsValid = !dependsOnInvoke(U->getOperand(0));
853       
854       if (!lhsValid) {
855         set.erase(U);
856         presentInSet.flip(VN.lookup(U));
857       }
858     
859     // Handle binary ops
860     } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
861         isa<ExtractElementInst>(v)) {
862       User* U = cast<User>(v);
863       
864       bool lhsValid = !isa<Instruction>(U->getOperand(0));
865       lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
866       if (lhsValid)
867         lhsValid = !dependsOnInvoke(U->getOperand(0));
868     
869       bool rhsValid = !isa<Instruction>(U->getOperand(1));
870       rhsValid |= presentInSet.test(VN.lookup(U->getOperand(1)));
871       if (rhsValid)
872         rhsValid = !dependsOnInvoke(U->getOperand(1));
873       
874       if (!lhsValid || !rhsValid) {
875         set.erase(U);
876         presentInSet.flip(VN.lookup(U));
877       }
878     
879     // Handle ternary ops
880     } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
881                isa<SelectInst>(v)) {
882       User* U = cast<User>(v);
883     
884       bool lhsValid = !isa<Instruction>(U->getOperand(0));
885       lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
886       if (lhsValid)
887         lhsValid = !dependsOnInvoke(U->getOperand(0));
888       
889       bool rhsValid = !isa<Instruction>(U->getOperand(1));
890       rhsValid |= presentInSet.test(VN.lookup(U->getOperand(1)));
891       if (rhsValid)
892         rhsValid = !dependsOnInvoke(U->getOperand(1));
893       
894       bool thirdValid = !isa<Instruction>(U->getOperand(2));
895       thirdValid |= presentInSet.test(VN.lookup(U->getOperand(2)));
896       if (thirdValid)
897         thirdValid = !dependsOnInvoke(U->getOperand(2));
898     
899       if (!lhsValid || !rhsValid || !thirdValid) {
900         set.erase(U);
901         presentInSet.flip(VN.lookup(U));
902       }
903     }
904   }
905 }
906
907 /// topo_sort - Given a set of values, sort them by topological
908 /// order into the provided vector.
909 void GVNPRE::topo_sort(SmallPtrSet<Value*, 16>& set, std::vector<Value*>& vec) {
910   SmallPtrSet<Value*, 16> visited;
911   std::vector<Value*> stack;
912   for (SmallPtrSet<Value*, 16>::iterator I = set.begin(), E = set.end();
913        I != E; ++I) {
914     if (visited.count(*I) == 0)
915       stack.push_back(*I);
916     
917     while (!stack.empty()) {
918       Value* e = stack.back();
919       
920       // Handle unary ops
921       if (CastInst* U = dyn_cast<CastInst>(e)) {
922         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
923     
924         if (l != 0 && isa<Instruction>(l) &&
925             visited.count(l) == 0)
926           stack.push_back(l);
927         else {
928           vec.push_back(e);
929           visited.insert(e);
930           stack.pop_back();
931         }
932       
933       // Handle binary ops
934       } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
935           isa<ExtractElementInst>(e)) {
936         User* U = cast<User>(e);
937         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
938         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
939     
940         if (l != 0 && isa<Instruction>(l) &&
941             visited.count(l) == 0)
942           stack.push_back(l);
943         else if (r != 0 && isa<Instruction>(r) &&
944                  visited.count(r) == 0)
945           stack.push_back(r);
946         else {
947           vec.push_back(e);
948           visited.insert(e);
949           stack.pop_back();
950         }
951       
952       // Handle ternary ops
953       } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
954                  isa<SelectInst>(e)) {
955         User* U = cast<User>(e);
956         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
957         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
958         Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
959       
960         if (l != 0 && isa<Instruction>(l) &&
961             visited.count(l) == 0)
962           stack.push_back(l);
963         else if (r != 0 && isa<Instruction>(r) &&
964                  visited.count(r) == 0)
965           stack.push_back(r);
966         else if (m != 0 && isa<Instruction>(m) &&
967                  visited.count(m) == 0)
968           stack.push_back(r);
969         else {
970           vec.push_back(e);
971           visited.insert(e);
972           stack.pop_back();
973         }
974       
975       // Handle opaque ops
976       } else {
977         visited.insert(e);
978         vec.push_back(e);
979         stack.pop_back();
980       }
981     }
982     
983     stack.clear();
984   }
985 }
986
987 /// dump - Dump a set of values to standard error
988 void GVNPRE::dump(const SmallPtrSet<Value*, 16>& s) const {
989   DOUT << "{ ";
990   for (SmallPtrSet<Value*, 16>::iterator I = s.begin(), E = s.end();
991        I != E; ++I) {
992     DOUT << "" << VN.lookup(*I) << ": ";
993     DEBUG((*I)->dump());
994   }
995   DOUT << "}\n\n";
996 }
997
998 /// elimination - Phase 3 of the main algorithm.  Perform full redundancy 
999 /// elimination by walking the dominator tree and removing any instruction that 
1000 /// is dominated by another instruction with the same value number.
1001 bool GVNPRE::elimination() {
1002   DOUT << "\n\nPhase 3: Elimination\n\n";
1003   
1004   bool changed_function = false;
1005   
1006   std::vector<std::pair<Instruction*, Value*> > replace;
1007   std::vector<Instruction*> erase;
1008   
1009   DominatorTree& DT = getAnalysis<DominatorTree>();
1010   
1011   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1012          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1013     BasicBlock* BB = DI->getBlock();
1014     
1015     //DOUT << "Block: " << BB->getName() << "\n";
1016     //dump(availableOut[BB]);
1017     //DOUT << "\n\n";
1018     
1019     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1020          BI != BE; ++BI) {
1021
1022       if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1023           isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1024           isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1025           isa<CastInst>(BI)) {
1026          Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1027   
1028         if (leader != 0)
1029           if (Instruction* Instr = dyn_cast<Instruction>(leader))
1030             if (Instr->getParent() != 0 && Instr != BI) {
1031               replace.push_back(std::make_pair(BI, leader));
1032               erase.push_back(BI);
1033               ++NumEliminated;
1034             }
1035       }
1036     }
1037   }
1038   
1039   while (!replace.empty()) {
1040     std::pair<Instruction*, Value*> rep = replace.back();
1041     replace.pop_back();
1042     rep.first->replaceAllUsesWith(rep.second);
1043     changed_function = true;
1044   }
1045     
1046   for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
1047        I != E; ++I)
1048      (*I)->eraseFromParent();
1049   
1050   return changed_function;
1051 }
1052
1053 /// cleanup - Delete any extraneous values that were created to represent
1054 /// expressions without leaders.
1055 void GVNPRE::cleanup() {
1056   while (!createdExpressions.empty()) {
1057     Instruction* I = createdExpressions.back();
1058     createdExpressions.pop_back();
1059     
1060     delete I;
1061   }
1062 }
1063
1064 /// buildsets_availout - When calculating availability, handle an instruction
1065 /// by inserting it into the appropriate sets
1066 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1067                                 SmallPtrSet<Value*, 16>& currAvail,
1068                                 SmallPtrSet<PHINode*, 16>& currPhis,
1069                                 SmallPtrSet<Value*, 16>& currExps,
1070                                 SmallPtrSet<Value*, 16>& currTemps,
1071                                 BitVector& availNumbers,
1072                                 BitVector& expNumbers) {
1073   // Handle PHI nodes
1074   if (PHINode* p = dyn_cast<PHINode>(I)) {
1075     VN.lookup_or_add(p);
1076     expNumbers.resize(VN.size());
1077     availNumbers.resize(VN.size());
1078     
1079     currPhis.insert(p);
1080   
1081   // Handle unary ops
1082   } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1083     Value* leftValue = U->getOperand(0);
1084     
1085     unsigned num = VN.lookup_or_add(U);
1086     expNumbers.resize(VN.size());
1087     availNumbers.resize(VN.size());
1088       
1089     if (isa<Instruction>(leftValue))
1090       if (!expNumbers.test(VN.lookup(leftValue))) {
1091         currExps.insert(leftValue);
1092         expNumbers.set(VN.lookup(leftValue));
1093       }
1094     
1095     if (!expNumbers.test(VN.lookup(U))) {
1096       currExps.insert(U);
1097       expNumbers.set(num);
1098     }
1099   
1100   // Handle binary ops
1101   } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1102              isa<ExtractElementInst>(I)) {
1103     User* U = cast<User>(I);
1104     Value* leftValue = U->getOperand(0);
1105     Value* rightValue = U->getOperand(1);
1106     
1107     unsigned num = VN.lookup_or_add(U);
1108     expNumbers.resize(VN.size());
1109     availNumbers.resize(VN.size());
1110       
1111     if (isa<Instruction>(leftValue))
1112       if (!expNumbers.test(VN.lookup(leftValue))) {
1113         currExps.insert(leftValue);
1114         expNumbers.set(VN.lookup(leftValue));
1115       }
1116     
1117     if (isa<Instruction>(rightValue))
1118       if (!expNumbers.test(VN.lookup(rightValue))) {
1119         currExps.insert(rightValue);
1120         expNumbers.set(VN.lookup(rightValue));
1121       }
1122     
1123     if (!expNumbers.test(VN.lookup(U))) {
1124       currExps.insert(U);
1125       expNumbers.set(num);
1126     }
1127     
1128   // Handle ternary ops
1129   } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1130              isa<SelectInst>(I)) {
1131     User* U = cast<User>(I);
1132     Value* leftValue = U->getOperand(0);
1133     Value* rightValue = U->getOperand(1);
1134     Value* thirdValue = U->getOperand(2);
1135       
1136     VN.lookup_or_add(U);
1137     
1138     unsigned num = VN.lookup_or_add(U);
1139     expNumbers.resize(VN.size());
1140     availNumbers.resize(VN.size());
1141     
1142     if (isa<Instruction>(leftValue))
1143       if (!expNumbers.test(VN.lookup(leftValue))) {
1144         currExps.insert(leftValue);
1145         expNumbers.set(VN.lookup(leftValue));
1146       }
1147     if (isa<Instruction>(rightValue))
1148       if (!expNumbers.test(VN.lookup(rightValue))) {
1149         currExps.insert(rightValue);
1150         expNumbers.set(VN.lookup(rightValue));
1151       }
1152     if (isa<Instruction>(thirdValue))
1153       if (!expNumbers.test(VN.lookup(thirdValue))) {
1154         currExps.insert(thirdValue);
1155         expNumbers.set(VN.lookup(thirdValue));
1156       }
1157     
1158     if (!expNumbers.test(VN.lookup(U))) {
1159       currExps.insert(U);
1160       expNumbers.set(num);
1161     }
1162     
1163   // Handle opaque ops
1164   } else if (!I->isTerminator()){
1165     VN.lookup_or_add(I);
1166     expNumbers.resize(VN.size());
1167     availNumbers.resize(VN.size());
1168     
1169     currTemps.insert(I);
1170   }
1171     
1172   if (!I->isTerminator())
1173     if (!availNumbers.test(VN.lookup(I))) {
1174       currAvail.insert(I);
1175       availNumbers.set(VN.lookup(I));
1176     }
1177 }
1178
1179 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1180 /// set as a function of the ANTIC_IN set of the block's predecessors
1181 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1182                                 SmallPtrSet<Value*, 16>& anticOut,
1183                                 std::set<BasicBlock*>& visited) {
1184   if (BB->getTerminator()->getNumSuccessors() == 1) {
1185     if (BB->getTerminator()->getSuccessor(0) != BB &&
1186         visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1187           DOUT << "DEFER: " << BB->getName() << "\n";
1188       return true;
1189     }
1190     else {
1191       phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1192                         BB,  BB->getTerminator()->getSuccessor(0), anticOut);
1193     }
1194   } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1195     BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1196     anticOut.insert(anticipatedIn[first].begin(), anticipatedIn[first].end());
1197     
1198     for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1199       BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1200       SmallPtrSet<Value*, 16>& succAnticIn = anticipatedIn[currSucc];
1201       
1202       std::vector<Value*> temp;
1203       
1204       for (SmallPtrSet<Value*, 16>::iterator I = anticOut.begin(),
1205            E = anticOut.end(); I != E; ++I)
1206         if (succAnticIn.count(*I) == 0)
1207           temp.push_back(*I);
1208
1209       for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
1210            I != E; ++I)
1211         anticOut.erase(*I);
1212     }
1213   }
1214   
1215   return false;
1216 }
1217
1218 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1219 /// each block.  ANTIC_IN is then a function of ANTIC_OUT and the GEN
1220 /// sets populated in buildsets_availout
1221 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1222                                SmallPtrSet<Value*, 16>& anticOut,
1223                                SmallPtrSet<Value*, 16>& currExps,
1224                                SmallPtrSet<Value*, 16>& currTemps,
1225                                std::set<BasicBlock*>& visited) {
1226   SmallPtrSet<Value*, 16>& anticIn = anticipatedIn[BB];
1227   unsigned old = anticIn.size();
1228       
1229   bool defer = buildsets_anticout(BB, anticOut, visited);
1230   if (defer)
1231     return 0;
1232   
1233   anticIn.clear();
1234   
1235   BitVector numbers(VN.size());
1236   for (SmallPtrSet<Value*, 16>::iterator I = anticOut.begin(),
1237        E = anticOut.end(); I != E; ++I) {
1238     unsigned num = VN.lookup_or_add(*I);
1239     numbers.resize(VN.size());
1240     
1241     if (isa<Instruction>(*I)) {
1242       anticIn.insert(*I);
1243       numbers.set(num);
1244     }
1245   }
1246   for (SmallPtrSet<Value*, 16>::iterator I = currExps.begin(),
1247        E = currExps.end(); I != E; ++I) {
1248     if (!numbers.test(VN.lookup_or_add(*I))) {
1249       anticIn.insert(*I);
1250       numbers.set(VN.lookup(*I));
1251     }
1252   } 
1253   
1254   for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1255        E = currTemps.end(); I != E; ++I) {
1256     anticIn.erase(*I);
1257     numbers.flip(VN.lookup(*I));
1258   }
1259   
1260   clean(anticIn, numbers);
1261   anticOut.clear();
1262   
1263   if (old != anticIn.size())
1264     return 2;
1265   else
1266     return 1;
1267 }
1268
1269 /// buildsets - Phase 1 of the main algorithm.  Construct the AVAIL_OUT
1270 /// and the ANTIC_IN sets.
1271 void GVNPRE::buildsets(Function& F) {
1272   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedExpressions;
1273   std::map<BasicBlock*, SmallPtrSet<PHINode*, 16> > generatedPhis;
1274   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1275
1276   DominatorTree &DT = getAnalysis<DominatorTree>();   
1277   
1278   // Phase 1, Part 1: calculate AVAIL_OUT
1279   
1280   // Top-down walk of the dominator tree
1281   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1282          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1283     
1284     // Get the sets to update for this block
1285     SmallPtrSet<Value*, 16>& currExps = generatedExpressions[DI->getBlock()];
1286     SmallPtrSet<PHINode*, 16>& currPhis = generatedPhis[DI->getBlock()];
1287     SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1288     SmallPtrSet<Value*, 16>& currAvail = availableOut[DI->getBlock()];     
1289     
1290     BasicBlock* BB = DI->getBlock();
1291   
1292     // A block inherits AVAIL_OUT from its dominator
1293     if (DI->getIDom() != 0)
1294     currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
1295                      availableOut[DI->getIDom()->getBlock()].end());
1296     
1297     BitVector availNumbers(VN.size());
1298     for (SmallPtrSet<Value*, 16>::iterator I = currAvail.begin(),
1299         E = currAvail.end(); I != E; ++I)
1300       availNumbers.set(VN.lookup(*I));
1301     
1302     BitVector expNumbers(VN.size());
1303     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1304          BI != BE; ++BI)
1305       buildsets_availout(BI, currAvail, currPhis, currExps,
1306                          currTemps, availNumbers, expNumbers);
1307       
1308   }
1309
1310   // Phase 1, Part 2: calculate ANTIC_IN
1311   
1312   std::set<BasicBlock*> visited;
1313   SmallPtrSet<BasicBlock*, 4> block_changed;
1314   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1315     block_changed.insert(FI);
1316   
1317   bool changed = true;
1318   unsigned iterations = 0;
1319   
1320   while (changed) {
1321     changed = false;
1322     SmallPtrSet<Value*, 16> anticOut;
1323     
1324     // Postorder walk of the CFG
1325     for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1326          BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1327       BasicBlock* BB = *BBI;
1328       
1329       if (block_changed.count(BB) != 0) {
1330         unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1331                                          generatedTemporaries[BB], visited);
1332       
1333         if (ret == 0) {
1334           changed = true;
1335           continue;
1336         } else {
1337           visited.insert(BB);
1338         
1339           if (ret == 2)
1340            for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1341                  PI != PE; ++PI) {
1342               block_changed.insert(*PI);
1343            }
1344           else
1345             block_changed.erase(BB);
1346         
1347           changed |= (ret == 2);
1348         }
1349       }
1350     }
1351     
1352     iterations++;
1353   }
1354   
1355   DOUT << "ITERATIONS: " << iterations << "\n";
1356 }
1357
1358 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1359 /// by inserting appropriate values into the predecessors and a phi node in
1360 /// the main block
1361 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1362                            std::map<BasicBlock*, Value*>& avail,
1363                            SmallPtrSet<Value*, 16>& new_set) {
1364   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1365     Value* e2 = avail[*PI];
1366     if (!find_leader(availableOut[*PI], VN.lookup(e2))) {
1367       User* U = cast<User>(e2);
1368       
1369       Value* s1 = 0;
1370       if (isa<BinaryOperator>(U->getOperand(0)) || 
1371           isa<CmpInst>(U->getOperand(0)) ||
1372           isa<ShuffleVectorInst>(U->getOperand(0)) ||
1373           isa<ExtractElementInst>(U->getOperand(0)) ||
1374           isa<InsertElementInst>(U->getOperand(0)) ||
1375           isa<SelectInst>(U->getOperand(0)) ||
1376           isa<CastInst>(U->getOperand(0)))
1377         s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1378       else
1379         s1 = U->getOperand(0);
1380       
1381       Value* s2 = 0;
1382       
1383       if (isa<BinaryOperator>(U) || 
1384           isa<CmpInst>(U) ||
1385           isa<ShuffleVectorInst>(U) ||
1386           isa<ExtractElementInst>(U) ||
1387           isa<InsertElementInst>(U) ||
1388           isa<SelectInst>(U))
1389         if (isa<BinaryOperator>(U->getOperand(1)) || 
1390             isa<CmpInst>(U->getOperand(1)) ||
1391             isa<ShuffleVectorInst>(U->getOperand(1)) ||
1392             isa<ExtractElementInst>(U->getOperand(1)) ||
1393             isa<InsertElementInst>(U->getOperand(1)) ||
1394             isa<SelectInst>(U->getOperand(1)) ||
1395             isa<CastInst>(U->getOperand(1))) {
1396           s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1397         } else {
1398           s2 = U->getOperand(1);
1399         }
1400       
1401       // Ternary Operators
1402       Value* s3 = 0;
1403       if (isa<ShuffleVectorInst>(U) ||
1404           isa<InsertElementInst>(U) ||
1405           isa<SelectInst>(U))
1406         if (isa<BinaryOperator>(U->getOperand(2)) || 
1407             isa<CmpInst>(U->getOperand(2)) ||
1408             isa<ShuffleVectorInst>(U->getOperand(2)) ||
1409             isa<ExtractElementInst>(U->getOperand(2)) ||
1410             isa<InsertElementInst>(U->getOperand(2)) ||
1411             isa<SelectInst>(U->getOperand(2)) ||
1412             isa<CastInst>(U->getOperand(2))) {
1413           s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1414         } else {
1415           s3 = U->getOperand(2);
1416         }
1417       
1418       Value* newVal = 0;
1419       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1420         newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1421                                         BO->getName()+".gvnpre",
1422                                         (*PI)->getTerminator());
1423       else if (CmpInst* C = dyn_cast<CmpInst>(U))
1424         newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1425                                  C->getName()+".gvnpre", 
1426                                  (*PI)->getTerminator());
1427       else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1428         newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1429                                        (*PI)->getTerminator());
1430       else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1431         newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
1432                                        (*PI)->getTerminator());
1433       else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1434         newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1435                                         (*PI)->getTerminator());
1436       else if (SelectInst* S = dyn_cast<SelectInst>(U))
1437         newVal = new SelectInst(S->getCondition(), S->getTrueValue(),
1438                                 S->getFalseValue(), S->getName()+".gvnpre",
1439                                 (*PI)->getTerminator());
1440       else if (CastInst* C = dyn_cast<CastInst>(U))
1441         newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1442                                   C->getName()+".gvnpre", 
1443                                   (*PI)->getTerminator());
1444                                 
1445                   
1446       VN.add(newVal, VN.lookup(U));
1447                   
1448       SmallPtrSet<Value*, 16>& predAvail = availableOut[*PI];
1449       val_replace(predAvail, newVal);
1450             
1451       std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1452       if (av != avail.end())
1453         avail.erase(av);
1454       avail.insert(std::make_pair(*PI, newVal));
1455                   
1456       ++NumInsertedVals;
1457     }
1458   }
1459               
1460   PHINode* p = 0;
1461               
1462   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1463     if (p == 0)
1464       p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1465                 
1466     p->addIncoming(avail[*PI], *PI);
1467   }
1468
1469   VN.add(p, VN.lookup(e));
1470   val_replace(availableOut[BB], p);
1471   new_set.insert(p);
1472               
1473   ++NumInsertedPhis;
1474 }
1475
1476 /// insertion_mergepoint - When walking the dom tree, check at each merge
1477 /// block for the possibility of a partial redundancy.  If present, eliminate it
1478 unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
1479                                       df_iterator<DomTreeNode*>& D,
1480                                       SmallPtrSet<Value*, 16>& new_set) {
1481   bool changed_function = false;
1482   bool new_stuff = false;
1483   
1484   BasicBlock* BB = D->getBlock();
1485   for (unsigned i = 0; i < workList.size(); ++i) {
1486     Value* e = workList[i];
1487           
1488     if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1489         isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1490         isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e)) {
1491       if (find_leader(availableOut[D->getIDom()->getBlock()],
1492                       VN.lookup(e)) != 0)
1493         continue;
1494             
1495       std::map<BasicBlock*, Value*> avail;
1496       bool by_some = false;
1497       int num_avail = 0;
1498             
1499       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1500            ++PI) {
1501         Value *e2 = phi_translate(e, *PI, BB);
1502         Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1503               
1504         if (e3 == 0) {
1505           std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1506           if (av != avail.end())
1507             avail.erase(av);
1508           avail.insert(std::make_pair(*PI, e2));
1509         } else {
1510           std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1511           if (av != avail.end())
1512             avail.erase(av);
1513           avail.insert(std::make_pair(*PI, e3));
1514                 
1515           by_some = true;
1516           num_avail++;
1517         }
1518       }
1519             
1520       if (by_some && num_avail < std::distance(pred_begin(BB), pred_end(BB))) {
1521         insertion_pre(e, BB, avail, new_set);
1522               
1523         changed_function = true;
1524         new_stuff = true;
1525       }
1526     }
1527   }
1528   
1529   unsigned retval = 0;
1530   if (changed_function)
1531     retval += 1;
1532   if (new_stuff)
1533     retval += 2;
1534   
1535   return retval;
1536 }
1537
1538 /// insert - Phase 2 of the main algorithm.  Walk the dominator tree looking for
1539 /// merge points.  When one is found, check for a partial redundancy.  If one is
1540 /// present, eliminate it.  Repeat this walk until no changes are made.
1541 bool GVNPRE::insertion(Function& F) {
1542   bool changed_function = false;
1543
1544   DominatorTree &DT = getAnalysis<DominatorTree>();  
1545   
1546   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > new_sets;
1547   bool new_stuff = true;
1548   while (new_stuff) {
1549     new_stuff = false;
1550     for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1551          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1552       BasicBlock* BB = DI->getBlock();
1553       
1554       if (BB == 0)
1555         continue;
1556       
1557       SmallPtrSet<Value*, 16>& new_set = new_sets[BB];
1558       SmallPtrSet<Value*, 16>& availOut = availableOut[BB];
1559       SmallPtrSet<Value*, 16>& anticIn = anticipatedIn[BB];
1560       
1561       new_set.clear();
1562       
1563       // Replace leaders with leaders inherited from dominator
1564       if (DI->getIDom() != 0) {
1565         SmallPtrSet<Value*, 16>& dom_set = new_sets[DI->getIDom()->getBlock()];
1566         for (SmallPtrSet<Value*, 16>::iterator I = dom_set.begin(),
1567              E = dom_set.end(); I != E; ++I) {
1568           new_set.insert(*I);
1569           val_replace(availOut, *I);
1570         }
1571       }
1572       
1573       // If there is more than one predecessor...
1574       if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1575         std::vector<Value*> workList;
1576         workList.reserve(anticIn.size());
1577         topo_sort(anticIn, workList);
1578         
1579         unsigned result = insertion_mergepoint(workList, DI, new_set);
1580         if (result & 1)
1581           changed_function = true;
1582         if (result & 2)
1583           new_stuff = true;
1584       }
1585     }
1586   }
1587   
1588   return changed_function;
1589 }
1590
1591 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1592 // function.
1593 //
1594 bool GVNPRE::runOnFunction(Function &F) {
1595   // Clean out global sets from any previous functions
1596   VN.clear();
1597   createdExpressions.clear();
1598   availableOut.clear();
1599   anticipatedIn.clear();
1600   
1601   bool changed_function = false;
1602   
1603   // Phase 1: BuildSets
1604   // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1605   buildsets(F);
1606   
1607   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1608     DOUT << "AVAIL_OUT: " << FI->getName() << "\n";
1609     dump(availableOut[FI]);
1610     DOUT << "\n";
1611     DOUT << "ANTIC_IN: " << FI->getName() << "\n";
1612     dump(anticipatedIn[FI]);
1613     DOUT << "\n\n";
1614   }
1615   
1616   // Phase 2: Insert
1617   // This phase inserts values to make partially redundant values
1618   // fully redundant
1619   changed_function |= insertion(F);
1620   
1621   // Phase 3: Eliminate
1622   // This phase performs trivial full redundancy elimination
1623   changed_function |= elimination();
1624   
1625   // Phase 4: Cleanup
1626   // This phase cleans up values that were created solely
1627   // as leaders for expressions
1628   cleanup();
1629   
1630   return changed_function;
1631 }