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