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