Reapplied r81355 with the problems fixed.
[oota-llvm.git] / lib / Transforms / Scalar / GVNPRE.cpp
index 0a985bc75cf35908e3af86b2cd8535b45c23f4dc..b7462f2ac214fbbe38d5898c53f75d5bd0741d8c 100644 (file)
@@ -2,8 +2,8 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by the Owen Anderson and is distributed under
-// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
@@ -16,6 +16,9 @@
 // live ranges, and should be used with caution on platforms that are very 
 // sensitive to register pressure.
 //
+// Note that this pass does the value numbering itself, it does not use the
+// ValueNumbering analysis passes.
+//
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "gvnpre"
 #include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
 #include "llvm/Support/CFG.h"
-#include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <algorithm>
 #include <deque>
 #include <map>
-#include <vector>
-#include <set>
 using namespace llvm;
 
 //===----------------------------------------------------------------------===//
 //                         ValueTable Class
 //===----------------------------------------------------------------------===//
 
+namespace {
+
 /// This class holds the mapping between values and value numbers.  It is used
 /// as an efficient mechanism to determine the expression-wise equivalence of
 /// two values.
 
-namespace {
-  class VISIBILITY_HIDDEN ValueTable {
-    public:
-      struct Expression {
-        enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
-                              FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
-                              ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
-                              ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
-                              FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
-                              FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
-                              FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
-                              SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
-                              FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
-                              PTRTOINT, INTTOPTR, BITCAST, GEP};
-    
-        ExpressionOpcode opcode;
-        const Type* type;
-        uint32_t firstVN;
-        uint32_t secondVN;
-        uint32_t thirdVN;
-        std::vector<uint32_t> varargs;
+struct Expression {
+  enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
+                          UDIV, SDIV, FDIV, UREM, SREM,
+                          FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
+                          ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
+                          ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
+                          FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
+                          FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
+                          FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
+                          SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
+                          FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
+                          PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
+                          TOMBSTONE };
+
+  ExpressionOpcode opcode;
+  const Type* type;
+  uint32_t firstVN;
+  uint32_t secondVN;
+  uint32_t thirdVN;
+  SmallVector<uint32_t, 4> varargs;
+  
+  Expression() { }
+  explicit Expression(ExpressionOpcode o) : opcode(o) { }
+  
+  bool operator==(const Expression &other) const {
+    if (opcode != other.opcode)
+      return false;
+    else if (opcode == EMPTY || opcode == TOMBSTONE)
+      return true;
+    else if (type != other.type)
+      return false;
+    else if (firstVN != other.firstVN)
+      return false;
+    else if (secondVN != other.secondVN)
+      return false;
+    else if (thirdVN != other.thirdVN)
+      return false;
+    else {
+      if (varargs.size() != other.varargs.size())
+        return false;
       
-        bool operator< (const Expression& other) const {
-          if (opcode < other.opcode)
-            return true;
-          else if (opcode > other.opcode)
-            return false;
-          else if (type < other.type)
-            return true;
-          else if (type > other.type)
-            return false;
-          else if (firstVN < other.firstVN)
-            return true;
-          else if (firstVN > other.firstVN)
-            return false;
-          else if (secondVN < other.secondVN)
-            return true;
-          else if (secondVN > other.secondVN)
-            return false;
-          else if (thirdVN < other.thirdVN)
-            return true;
-          else if (thirdVN > other.thirdVN)
-            return false;
-          else {
-            if (varargs.size() < other.varargs.size())
-              return true;
-            else if (varargs.size() > other.varargs.size())
-              return false;
-            
-            for (size_t i = 0; i < varargs.size(); ++i)
-              if (varargs[i] < other.varargs[i])
-                return true;
-              else if (varargs[i] > other.varargs[i])
-                return false;
-          
-            return false;
-          }
-        }
-      };
+      for (size_t i = 0; i < varargs.size(); ++i)
+        if (varargs[i] != other.varargs[i])
+          return false;
     
+      return true;
+    }
+  }
+  
+  bool operator!=(const Expression &other) const {
+    if (opcode != other.opcode)
+      return true;
+    else if (opcode == EMPTY || opcode == TOMBSTONE)
+      return false;
+    else if (type != other.type)
+      return true;
+    else if (firstVN != other.firstVN)
+      return true;
+    else if (secondVN != other.secondVN)
+      return true;
+    else if (thirdVN != other.thirdVN)
+      return true;
+    else {
+      if (varargs.size() != other.varargs.size())
+        return true;
+      
+      for (size_t i = 0; i < varargs.size(); ++i)
+        if (varargs[i] != other.varargs[i])
+          return true;
+    
+      return false;
+    }
+  }
+};
+
+}
+
+namespace {
+  class ValueTable {
     private:
       DenseMap<Value*, uint32_t> valueNumbering;
-      std::map<Expression, uint32_t> expressionNumbering;
+      DenseMap<Expression, uint32_t> expressionNumbering;
   
       uint32_t nextValueNumber;
     
@@ -138,18 +161,58 @@ namespace {
   };
 }
 
+namespace llvm {
+template <> struct DenseMapInfo<Expression> {
+  static inline Expression getEmptyKey() {
+    return Expression(Expression::EMPTY);
+  }
+  
+  static inline Expression getTombstoneKey() {
+    return Expression(Expression::TOMBSTONE);
+  }
+  
+  static unsigned getHashValue(const Expression e) {
+    unsigned hash = e.opcode;
+    
+    hash = e.firstVN + hash * 37;
+    hash = e.secondVN + hash * 37;
+    hash = e.thirdVN + hash * 37;
+    
+    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
+            (unsigned)((uintptr_t)e.type >> 9)) +
+           hash * 37;
+    
+    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
+         E = e.varargs.end(); I != E; ++I)
+      hash = *I + hash * 37;
+    
+    return hash;
+  }
+  static bool isEqual(const Expression &LHS, const Expression &RHS) {
+    return LHS == RHS;
+  }
+  static bool isPod() { return true; }
+};
+}
+
 //===----------------------------------------------------------------------===//
 //                     ValueTable Internal Functions
 //===----------------------------------------------------------------------===//
-ValueTable::Expression::ExpressionOpcode 
+Expression::ExpressionOpcode 
                              ValueTable::getOpcode(BinaryOperator* BO) {
   switch(BO->getOpcode()) {
     case Instruction::Add:
       return Expression::ADD;
+    case Instruction::FAdd:
+      return Expression::FADD;
     case Instruction::Sub:
       return Expression::SUB;
+    case Instruction::FSub:
+      return Expression::FSUB;
     case Instruction::Mul:
       return Expression::MUL;
+    case Instruction::FMul:
+      return Expression::FMUL;
     case Instruction::UDiv:
       return Expression::UDIV;
     case Instruction::SDiv:
@@ -177,12 +240,12 @@ ValueTable::Expression::ExpressionOpcode
     
     // THIS SHOULD NEVER HAPPEN
     default:
-      assert(0 && "Binary operator with unknown opcode?");
+      llvm_unreachable("Binary operator with unknown opcode?");
       return Expression::ADD;
   }
 }
 
-ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
+Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
   if (C->getOpcode() == Instruction::ICmp) {
     switch (C->getPredicate()) {
       case ICmpInst::ICMP_EQ:
@@ -208,7 +271,7 @@ ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
       
       // THIS SHOULD NEVER HAPPEN
       default:
-        assert(0 && "Comparison with unknown predicate?");
+        llvm_unreachable("Comparison with unknown predicate?");
         return Expression::ICMPEQ;
     }
   } else {
@@ -244,13 +307,13 @@ ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
       
       // THIS SHOULD NEVER HAPPEN
       default:
-        assert(0 && "Comparison with unknown predicate?");
+        llvm_unreachable("Comparison with unknown predicate?");
         return Expression::FCMPOEQ;
     }
   }
 }
 
-ValueTable::Expression::ExpressionOpcode 
+Expression::ExpressionOpcode 
                              ValueTable::getOpcode(CastInst* C) {
   switch(C->getOpcode()) {
     case Instruction::Trunc:
@@ -280,12 +343,12 @@ ValueTable::Expression::ExpressionOpcode
     
     // THIS SHOULD NEVER HAPPEN
     default:
-      assert(0 && "Cast operator with unknown opcode?");
+      llvm_unreachable("Cast operator with unknown opcode?");
       return Expression::BITCAST;
   }
 }
 
-ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
+Expression ValueTable::create_expression(BinaryOperator* BO) {
   Expression e;
     
   e.firstVN = lookup_or_add(BO->getOperand(0));
@@ -297,7 +360,7 @@ ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
+Expression ValueTable::create_expression(CmpInst* C) {
   Expression e;
     
   e.firstVN = lookup_or_add(C->getOperand(0));
@@ -309,7 +372,7 @@ ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(CastInst* C) {
+Expression ValueTable::create_expression(CastInst* C) {
   Expression e;
     
   e.firstVN = lookup_or_add(C->getOperand(0));
@@ -321,7 +384,7 @@ ValueTable::Expression ValueTable::create_expression(CastInst* C) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(ShuffleVectorInst* S) {
+Expression ValueTable::create_expression(ShuffleVectorInst* S) {
   Expression e;
     
   e.firstVN = lookup_or_add(S->getOperand(0));
@@ -333,7 +396,7 @@ ValueTable::Expression ValueTable::create_expression(ShuffleVectorInst* S) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(ExtractElementInst* E) {
+Expression ValueTable::create_expression(ExtractElementInst* E) {
   Expression e;
     
   e.firstVN = lookup_or_add(E->getOperand(0));
@@ -345,7 +408,7 @@ ValueTable::Expression ValueTable::create_expression(ExtractElementInst* E) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(InsertElementInst* I) {
+Expression ValueTable::create_expression(InsertElementInst* I) {
   Expression e;
     
   e.firstVN = lookup_or_add(I->getOperand(0));
@@ -357,7 +420,7 @@ ValueTable::Expression ValueTable::create_expression(InsertElementInst* I) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(SelectInst* I) {
+Expression ValueTable::create_expression(SelectInst* I) {
   Expression e;
     
   e.firstVN = lookup_or_add(I->getCondition());
@@ -369,14 +432,14 @@ ValueTable::Expression ValueTable::create_expression(SelectInst* I) {
   return e;
 }
 
-ValueTable::Expression ValueTable::create_expression(GetElementPtrInst* G) {
+Expression ValueTable::create_expression(GetElementPtrInst* G) {
   Expression e;
     
   e.firstVN = lookup_or_add(G->getPointerOperand());
   e.secondVN = 0;
   e.thirdVN = 0;
   e.type = G->getType();
-  e.opcode = Expression::SELECT;
+  e.opcode = Expression::GEP;
   
   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
        I != E; ++I)
@@ -400,7 +463,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
     Expression e = create_expression(BO);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -413,7 +476,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
     Expression e = create_expression(C);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -426,7 +489,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
     Expression e = create_expression(U);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -439,7 +502,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
     Expression e = create_expression(U);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -452,7 +515,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
     Expression e = create_expression(U);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -465,7 +528,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
     Expression e = create_expression(U);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -478,7 +541,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
     Expression e = create_expression(U);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -491,7 +554,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) {
   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
     Expression e = create_expression(U);
     
-    std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
+    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
     if (EI != expressionNumbering.end()) {
       valueNumbering.insert(std::make_pair(V, EI->second));
       return EI->second;
@@ -514,7 +577,7 @@ uint32_t ValueTable::lookup(Value* V) const {
   if (VI != valueNumbering.end())
     return VI->second;
   else
-    assert(0 && "Value not numbered?");
+    llvm_unreachable("Value not numbered?");
   
   return 0;
 }
@@ -546,8 +609,10 @@ unsigned ValueTable::size() {
   return nextValueNumber;
 }
 
+namespace {
+
 //===----------------------------------------------------------------------===//
-//                         ValueTable Class
+//                       ValueNumberedSet Class
 //===----------------------------------------------------------------------===//
 
 class ValueNumberedSet {
@@ -556,6 +621,10 @@ class ValueNumberedSet {
     BitVector numbers;
   public:
     ValueNumberedSet() { numbers.resize(1); }
+    ValueNumberedSet(const ValueNumberedSet& other) {
+      numbers = other.numbers;
+      contents = other.contents;
+    }
     
     typedef SmallPtrSet<Value*, 8>::iterator iterator;
     
@@ -565,21 +634,27 @@ class ValueNumberedSet {
     bool insert(Value* v) { return contents.insert(v); }
     void insert(iterator I, iterator E) { contents.insert(I, E); }
     void erase(Value* v) { contents.erase(v); }
+    unsigned count(Value* v) { return contents.count(v); }
     size_t size() { return contents.size(); }
     
-    void set(unsigned i) {
+    void set(unsigned i)  {
       if (i >= numbers.size())
         numbers.resize(i+1);
       
       numbers.set(i);
     }
     
-    void reset(unsigned i) {
+    void operator=(const ValueNumberedSet& other) {
+      contents = other.contents;
+      numbers = other.numbers;
+    }
+    
+    void reset(unsigned i)  {
       if (i < numbers.size())
         numbers.reset(i);
     }
     
-    bool test(unsigned i) {
+    bool test(unsigned i)  {
       if (i >= numbers.size())
         return false;
       
@@ -592,25 +667,26 @@ class ValueNumberedSet {
     }
 };
 
+}
+
 //===----------------------------------------------------------------------===//
 //                         GVNPRE Pass
 //===----------------------------------------------------------------------===//
 
 namespace {
-
-  class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
+  class GVNPRE : public FunctionPass {
     bool runOnFunction(Function &F);
   public:
     static char ID; // Pass identification, replacement for typeid
-    GVNPRE() : FunctionPass((intptr_t)&ID) { }
+    GVNPRE() : FunctionPass(&ID) {}
 
   private:
     ValueTable VN;
-    std::vector<Instruction*> createdExpressions;
+    SmallVector<Instruction*, 8> createdExpressions;
     
-    std::map<BasicBlock*, ValueNumberedSet> availableOut;
-    std::map<BasicBlock*, ValueNumberedSet> anticipatedIn;
-    std::map<BasicBlock*, ValueNumberedSet> generatedPhis;
+    DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
+    DenseMap<BasicBlock*, ValueNumberedSet> anticipatedIn;
+    DenseMap<BasicBlock*, ValueNumberedSet> generatedPhis;
     
     // This transformation requires dominator postdominator info
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
@@ -622,22 +698,22 @@ namespace {
   
     // Helper fuctions
     // FIXME: eliminate or document these better
-    void dump(ValueNumberedSet& s) const;
-    void clean(ValueNumberedSet& set);
-    Value* find_leader(ValueNumberedSet& vals, uint32_t v);
-    Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ);
+    void dump(ValueNumberedSet& s) const ;
+    void clean(ValueNumberedSet& set) ;
+    Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
+    Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) ;
     void phi_translate_set(ValueNumberedSet& anticIn, BasicBlock* pred,
-                           BasicBlock* succ, ValueNumberedSet& out);
+                           BasicBlock* succ, ValueNumberedSet& out) ;
     
     void topo_sort(ValueNumberedSet& set,
-                   std::vector<Value*>& vec);
+                   SmallVector<Value*, 8>& vec) ;
     
-    void cleanup();
-    bool elimination();
+    void cleanup() ;
+    bool elimination() ;
     
-    void val_insert(ValueNumberedSet& s, Value* v);
-    void val_replace(ValueNumberedSet& s, Value* v);
-    bool dependsOnInvoke(Value* V);
+    void val_insert(ValueNumberedSet& s, Value* v) ;
+    void val_replace(ValueNumberedSet& s, Value* v) ;
+    bool dependsOnInvoke(Value* V) ;
     void buildsets_availout(BasicBlock::iterator I,
                             ValueNumberedSet& currAvail,
                             ValueNumberedSet& currPhis,
@@ -645,21 +721,21 @@ namespace {
                             SmallPtrSet<Value*, 16>& currTemps);
     bool buildsets_anticout(BasicBlock* BB,
                             ValueNumberedSet& anticOut,
-                            std::set<BasicBlock*>& visited);
+                            SmallPtrSet<BasicBlock*, 8>& visited);
     unsigned buildsets_anticin(BasicBlock* BB,
                            ValueNumberedSet& anticOut,
                            ValueNumberedSet& currExps,
                            SmallPtrSet<Value*, 16>& currTemps,
-                           std::set<BasicBlock*>& visited);
-    void buildsets(Function& F);
+                           SmallPtrSet<BasicBlock*, 8>& visited);
+    void buildsets(Function& F) ;
     
     void insertion_pre(Value* e, BasicBlock* BB,
-                       std::map<BasicBlock*, Value*>& avail,
-                      std::map<BasicBlock*,ValueNumberedSet>& new_set);
-    unsigned insertion_mergepoint(std::vector<Value*>& workList,
+                       DenseMap<BasicBlock*, Value*>& avail,
+                       std::map<BasicBlock*,ValueNumberedSet>& new_set);
+    unsigned insertion_mergepoint(SmallVector<Value*, 8>& workList,
                                   df_iterator<DomTreeNode*>& D,
                       std::map<BasicBlock*, ValueNumberedSet>& new_set);
-    bool insertion(Function& F);
+    bool insertion(Function& F) ;
   
   };
   
@@ -670,8 +746,8 @@ namespace {
 // createGVNPREPass - The public interface to this file...
 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
 
-RegisterPass<GVNPRE> X("gvnpre",
-                       "Global Value Numbering/Partial Redundancy Elimination");
+static RegisterPass<GVNPRE> X("gvnpre",
+                      "Global Value Numbering/Partial Redundancy Elimination");
 
 
 STATISTIC(NumInsertedVals, "Number of values inserted");
@@ -690,6 +766,7 @@ Value* GVNPRE::find_leader(ValueNumberedSet& vals, uint32_t v) {
     if (v == VN.lookup(*I))
       return *I;
   
+  llvm_unreachable("No leader found, but present bit is set?");
   return 0;
 }
 
@@ -704,13 +781,14 @@ void GVNPRE::val_insert(ValueNumberedSet& s, Value* v) {
 /// val_replace - Insert a value into a set, replacing any values already in
 /// the set that have the same value number
 void GVNPRE::val_replace(ValueNumberedSet& s, Value* v) {
+  if (s.count(v)) return;
+  
   uint32_t num = VN.lookup(v);
   Value* leader = find_leader(s, num);
-  while (leader != 0) {
+  if (leader != 0)
     s.erase(leader);
-    leader = find_leader(s, num);
-  }
   s.insert(v);
+  s.set(num);
 }
 
 /// phi_translate - Given a value, its parent block, and a predecessor of its
@@ -735,7 +813,7 @@ Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
     if (newOp1 != U->getOperand(0)) {
       Instruction* newVal = 0;
       if (CastInst* C = dyn_cast<CastInst>(U))
-        newVal = CastInst::create(C->getOpcode(),
+        newVal = CastInst::Create(C->getOpcode(),
                                   newOp1, C->getType(),
                                   C->getName()+".expr");
       
@@ -778,16 +856,17 @@ Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
     if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
       Instruction* newVal = 0;
       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
-        newVal = BinaryOperator::create(BO->getOpcode(),
+        newVal = BinaryOperator::Create(BO->getOpcode(),
                                         newOp1, newOp2,
                                         BO->getName()+".expr");
       else if (CmpInst* C = dyn_cast<CmpInst>(U))
-        newVal = CmpInst::create(C->getOpcode(),
+        newVal = CmpInst::Create(C->getOpcode(),
                                  C->getPredicate(),
                                  newOp1, newOp2,
                                  C->getName()+".expr");
       else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
-        newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
+        newVal = ExtractElementInst::Create(newOp1, newOp2, 
+                                            E->getName()+".expr");
       
       uint32_t v = VN.lookup_or_add(newVal);
       
@@ -840,12 +919,13 @@ Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
       Instruction* newVal = 0;
       if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
         newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
-                                       S->getName()+".expr");
+                                       S->getName() + ".expr");
       else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
-        newVal = new InsertElementInst(newOp1, newOp2, newOp3,
-                                       I->getName()+".expr");
+        newVal = InsertElementInst::Create(newOp1, newOp2, newOp3,
+                                           I->getName() + ".expr");
       else if (SelectInst* I = dyn_cast<SelectInst>(U))
-        newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
+        newVal = SelectInst::Create(newOp1, newOp2, newOp3,
+                                    I->getName() + ".expr");
       
       uint32_t v = VN.lookup_or_add(newVal);
       
@@ -872,7 +952,7 @@ Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
       return 0;
     
     bool changed_idx = false;
-    std::vector<Value*> newIdx;
+    SmallVector<Value*, 4> newIdx;
     for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
          I != E; ++I)
       if (isa<Instruction>(*I)) {
@@ -885,9 +965,10 @@ Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
       }
     
     if (newOp1 != U->getPointerOperand() || changed_idx) {
-      Instruction* newVal = new GetElementPtrInst(newOp1,
-                                       &newIdx[0], newIdx.size(),
-                                       U->getName()+".expr");
+      Instruction* newVal =
+          GetElementPtrInst::Create(newOp1,
+                                    newIdx.begin(), newIdx.end(),
+                                    U->getName()+".expr");
       
       uint32_t v = VN.lookup_or_add(newVal);
       
@@ -943,7 +1024,7 @@ bool GVNPRE::dependsOnInvoke(Value* V) {
 /// themselves in the set, as well as all values that depend on invokes (see 
 /// above)
 void GVNPRE::clean(ValueNumberedSet& set) {
-  std::vector<Value*> worklist;
+  SmallVector<Value*, 8> worklist;
   worklist.reserve(set.size());
   topo_sort(set, worklist);
   
@@ -1032,9 +1113,9 @@ void GVNPRE::clean(ValueNumberedSet& set) {
 
 /// topo_sort - Given a set of values, sort them by topological
 /// order into the provided vector.
-void GVNPRE::topo_sort(ValueNumberedSet& set, std::vector<Value*>& vec) {
+void GVNPRE::topo_sort(ValueNumberedSet& set, SmallVector<Value*, 8>& vec) {
   SmallPtrSet<Value*, 16> visited;
-  std::vector<Value*> stack;
+  SmallVector<Value*, 8> stack;
   for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
        I != E; ++I) {
     if (visited.count(*I) == 0)
@@ -1137,25 +1218,23 @@ void GVNPRE::topo_sort(ValueNumberedSet& set, std::vector<Value*>& vec) {
 
 /// dump - Dump a set of values to standard error
 void GVNPRE::dump(ValueNumberedSet& s) const {
-  DOUT << "{ ";
+  DEBUG(errs() << "{ ");
   for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
        I != E; ++I) {
-    DOUT << "" << VN.lookup(*I) << ": ";
+    DEBUG(errs() << "" << VN.lookup(*I) << ": ");
     DEBUG((*I)->dump());
   }
-  DOUT << "}\n\n";
+  DEBUG(errs() << "}\n\n");
 }
 
 /// elimination - Phase 3 of the main algorithm.  Perform full redundancy 
 /// elimination by walking the dominator tree and removing any instruction that 
 /// is dominated by another instruction with the same value number.
 bool GVNPRE::elimination() {
-  DOUT << "\n\nPhase 3: Elimination\n\n";
-  
   bool changed_function = false;
   
-  std::vector<std::pair<Instruction*, Value*> > replace;
-  std::vector<Instruction*> erase;
+  SmallVector<std::pair<Instruction*, Value*>, 8> replace;
+  SmallVector<Instruction*, 8> erase;
   
   DominatorTree& DT = getAnalysis<DominatorTree>();
   
@@ -1163,10 +1242,6 @@ bool GVNPRE::elimination() {
          E = df_end(DT.getRootNode()); DI != E; ++DI) {
     BasicBlock* BB = DI->getBlock();
     
-    //DOUT << "Block: " << BB->getName() << "\n";
-    //dump(availableOut[BB]);
-    //DOUT << "\n\n";
-    
     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
          BI != BE; ++BI) {
 
@@ -1174,15 +1249,17 @@ bool GVNPRE::elimination() {
           isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
           isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
           isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
-         Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
-  
-        if (leader != 0)
+        
+        if (availableOut[BB].test(VN.lookup(BI)) &&
+            !availableOut[BB].count(BI)) {
+          Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
           if (Instruction* Instr = dyn_cast<Instruction>(leader))
             if (Instr->getParent() != 0 && Instr != BI) {
               replace.push_back(std::make_pair(BI, leader));
               erase.push_back(BI);
               ++NumEliminated;
             }
+        }
       }
     }
   }
@@ -1194,8 +1271,8 @@ bool GVNPRE::elimination() {
     changed_function = true;
   }
     
-  for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
-       I != E; ++I)
+  for (SmallVector<Instruction*, 8>::iterator I = erase.begin(),
+       E = erase.end(); I != E; ++I)
      (*I)->eraseFromParent();
   
   return changed_function;
@@ -1346,11 +1423,10 @@ void GVNPRE::buildsets_availout(BasicBlock::iterator I,
 /// set as a function of the ANTIC_IN set of the block's predecessors
 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
                                 ValueNumberedSet& anticOut,
-                                std::set<BasicBlock*>& visited) {
+                                SmallPtrSet<BasicBlock*, 8>& visited) {
   if (BB->getTerminator()->getNumSuccessors() == 1) {
     if (BB->getTerminator()->getSuccessor(0) != BB &&
         visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
-          DOUT << "DEFER: " << BB->getName() << "\n";
       return true;
     }
     else {
@@ -1369,14 +1445,14 @@ bool GVNPRE::buildsets_anticout(BasicBlock* BB,
       BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
       ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
       
-      std::vector<Value*> temp;
+      SmallVector<Value*, 16> temp;
       
       for (ValueNumberedSet::iterator I = anticOut.begin(),
            E = anticOut.end(); I != E; ++I)
         if (!succAnticIn.test(VN.lookup(*I)))
           temp.push_back(*I);
 
-      for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
+      for (SmallVector<Value*, 16>::iterator I = temp.begin(), E = temp.end();
            I != E; ++I) {
         anticOut.erase(*I);
         anticOut.reset(VN.lookup(*I));
@@ -1394,7 +1470,7 @@ unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
                                ValueNumberedSet& anticOut,
                                ValueNumberedSet& currExps,
                                SmallPtrSet<Value*, 16>& currTemps,
-                               std::set<BasicBlock*>& visited) {
+                               SmallPtrSet<BasicBlock*, 8>& visited) {
   ValueNumberedSet& anticIn = anticipatedIn[BB];
   unsigned old = anticIn.size();
       
@@ -1435,8 +1511,8 @@ unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
 /// buildsets - Phase 1 of the main algorithm.  Construct the AVAIL_OUT
 /// and the ANTIC_IN sets.
 void GVNPRE::buildsets(Function& F) {
-  std::map<BasicBlock*, ValueNumberedSet> generatedExpressions;
-  std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
+  DenseMap<BasicBlock*, ValueNumberedSet> generatedExpressions;
+  DenseMap<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
 
   DominatorTree &DT = getAnalysis<DominatorTree>();   
   
@@ -1456,12 +1532,7 @@ void GVNPRE::buildsets(Function& F) {
   
     // A block inherits AVAIL_OUT from its dominator
     if (DI->getIDom() != 0)
-    currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
-                     availableOut[DI->getIDom()->getBlock()].end());
-    
-    for (ValueNumberedSet::iterator I = currAvail.begin(),
-        E = currAvail.end(); I != E; ++I)
-      currAvail.set(VN.lookup(*I));
+      currAvail = availableOut[DI->getIDom()->getBlock()];
 
     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
          BI != BE; ++BI)
@@ -1472,7 +1543,7 @@ void GVNPRE::buildsets(Function& F) {
 
   // Phase 1, Part 2: calculate ANTIC_IN
   
-  std::set<BasicBlock*> visited;
+  SmallPtrSet<BasicBlock*, 8> visited;
   SmallPtrSet<BasicBlock*, 4> block_changed;
   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
     block_changed.insert(FI);
@@ -1514,18 +1585,15 @@ void GVNPRE::buildsets(Function& F) {
     
     iterations++;
   }
-  
-  DOUT << "ITERATIONS: " << iterations << "\n";
 }
 
 /// insertion_pre - When a partial redundancy has been identified, eliminate it
 /// by inserting appropriate values into the predecessors and a phi node in
 /// the main block
 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
-                           std::map<BasicBlock*, Value*>& avail,
+                           DenseMap<BasicBlock*, Value*>& avail,
                     std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
-    DOUT << "PRED: " << (*PI)->getName() << "\n";
     Value* e2 = avail[*PI];
     if (!availableOut[*PI].test(VN.lookup(e2))) {
       User* U = cast<User>(e2);
@@ -1550,7 +1618,7 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
           isa<ShuffleVectorInst>(U) ||
           isa<ExtractElementInst>(U) ||
           isa<InsertElementInst>(U) ||
-          isa<SelectInst>(U))
+          isa<SelectInst>(U)) {
         if (isa<BinaryOperator>(U->getOperand(1)) || 
             isa<CmpInst>(U->getOperand(1)) ||
             isa<ShuffleVectorInst>(U->getOperand(1)) ||
@@ -1563,12 +1631,13 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
         } else {
           s2 = U->getOperand(1);
         }
+      }
       
       // Ternary Operators
       Value* s3 = 0;
       if (isa<ShuffleVectorInst>(U) ||
           isa<InsertElementInst>(U) ||
-          isa<SelectInst>(U))
+          isa<SelectInst>(U)) {
         if (isa<BinaryOperator>(U->getOperand(2)) || 
             isa<CmpInst>(U->getOperand(2)) ||
             isa<ShuffleVectorInst>(U->getOperand(2)) ||
@@ -1581,9 +1650,10 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
         } else {
           s3 = U->getOperand(2);
         }
+      }
       
       // Vararg operators
-      std::vector<Value*> sVarargs;
+      SmallVector<Value*, 4> sVarargs;
       if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
         for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
              OE = G->idx_end(); OI != OE; ++OI) {
@@ -1605,35 +1675,35 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
       
       Value* newVal = 0;
       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
-        newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
+        newVal = BinaryOperator::Create(BO->getOpcode(), s1, s2,
                                         BO->getName()+".gvnpre",
                                         (*PI)->getTerminator());
       else if (CmpInst* C = dyn_cast<CmpInst>(U))
-        newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
+        newVal = CmpInst::Create(C->getOpcode(),
+                                 C->getPredicate(), s1, s2,
                                  C->getName()+".gvnpre", 
                                  (*PI)->getTerminator());
       else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
         newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
                                        (*PI)->getTerminator());
       else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
-        newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
-                                       (*PI)->getTerminator());
+        newVal = InsertElementInst::Create(s1, s2, s3, S->getName()+".gvnpre",
+                                           (*PI)->getTerminator());
       else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
-        newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
+        newVal = ExtractElementInst::Create(s1, s2, S->getName()+".gvnpre",
                                         (*PI)->getTerminator());
       else if (SelectInst* S = dyn_cast<SelectInst>(U))
-        newVal = new SelectInst(s1, s2, s3, S->getName()+".gvnpre",
-                                (*PI)->getTerminator());
+        newVal = SelectInst::Create(s1, s2, s3, S->getName()+".gvnpre",
+                                    (*PI)->getTerminator());
       else if (CastInst* C = dyn_cast<CastInst>(U))
-        newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
+        newVal = CastInst::Create(C->getOpcode(), s1, C->getType(),
                                   C->getName()+".gvnpre", 
                                   (*PI)->getTerminator());
       else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
-        newVal = new GetElementPtrInst(s1, &sVarargs[0], sVarargs.size(), 
-                                       G->getName()+".gvnpre", 
-                                       (*PI)->getTerminator());
-                                
-                  
+        newVal = GetElementPtrInst::Create(s1, sVarargs.begin(), sVarargs.end(),
+                                           G->getName()+".gvnpre", 
+                                           (*PI)->getTerminator());
+
       VN.add(newVal, VN.lookup(U));
                   
       ValueNumberedSet& predAvail = availableOut[*PI];
@@ -1641,7 +1711,7 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
       val_replace(new_sets[*PI], newVal);
       predAvail.set(VN.lookup(newVal));
             
-      std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
+      DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
       if (av != avail.end())
         avail.erase(av);
       avail.insert(std::make_pair(*PI, newVal));
@@ -1654,7 +1724,7 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
               
   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
     if (p == 0)
-      p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
+      p = PHINode::Create(avail[*PI]->getType(), "gvnpre-join", BB->begin());
     
     p->addIncoming(avail[*PI], *PI);
   }
@@ -1672,7 +1742,7 @@ void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
 
 /// insertion_mergepoint - When walking the dom tree, check at each merge
 /// block for the possibility of a partial redundancy.  If present, eliminate it
-unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
+unsigned GVNPRE::insertion_mergepoint(SmallVector<Value*, 8>& workList,
                                       df_iterator<DomTreeNode*>& D,
                     std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
   bool changed_function = false;
@@ -1689,7 +1759,7 @@ unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
       if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
         continue;
             
-      std::map<BasicBlock*, Value*> avail;
+      DenseMap<BasicBlock*, Value*> avail;
       bool by_some = false;
       bool all_same = true;
       Value * first_s = 0;
@@ -1700,13 +1770,13 @@ unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
         Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
               
         if (e3 == 0) {
-          std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
+          DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
           if (av != avail.end())
             avail.erase(av);
           avail.insert(std::make_pair(*PI, e2));
           all_same = false;
         } else {
-          std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
+          DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
           if (av != avail.end())
             avail.erase(av);
           avail.insert(std::make_pair(*PI, e3));
@@ -1772,7 +1842,7 @@ bool GVNPRE::insertion(Function& F) {
       
       // If there is more than one predecessor...
       if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
-        std::vector<Value*> workList;
+        SmallVector<Value*, 8> workList;
         workList.reserve(anticIn.size());
         topo_sort(anticIn, workList);