move some functions, add a comment.
[oota-llvm.git] / lib / Transforms / Scalar / PredicateSimplifier.cpp
index 6b5af293dc040b06df07972f1340d05467e44a34..b8ac1828db8c5ebc2a6bf72387195b50b51eca65 100644 (file)
@@ -2,8 +2,8 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Nick Lewycky 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.
 //
 //===----------------------------------------------------------------------===//
 //
@@ -70,8 +70,7 @@
 //
 // The ValueRanges class stores the known integer bounds of a Value. When we
 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
-// %b = [0, 254]. Because we store these by Value*, you should always
-// canonicalize through the InequalityGraph first.
+// %b = [0, 254].
 //
 // It never stores an empty range, because that means that the code is
 // unreachable. It never stores a single-element range since that's an equality
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Analysis/Dominators.h"
+#include "llvm/Assembly/Writer.h"
 #include "llvm/Support/CFG.h"
-#include "llvm/Support/Compiler.h"
 #include "llvm/Support/ConstantRange.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/InstVisitor.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include <algorithm>
 #include <deque>
-#include <sstream>
 #include <stack>
 using namespace llvm;
 
@@ -111,6 +110,8 @@ STATISTIC(NumSimple      , "Number of simple replacements");
 STATISTIC(NumBlocks      , "Number of blocks marked unreachable");
 STATISTIC(NumSnuggle     , "Number of comparisons snuggled");
 
+static const ConstantRange empty(1, false);
+
 namespace {
   class DomTreeDFS {
   public:
@@ -211,13 +212,19 @@ namespace {
       }
     }
 
+    /// getRootNode - This returns the entry node for the CFG of the function.
     Node *getRootNode() const { return Entry; }
 
+    /// getNodeForBlock - return the node for the specified basic block.
     Node *getNodeForBlock(BasicBlock *BB) const {
       if (!NodeMap.count(BB)) return 0;
       return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
     }
 
+    /// dominates - returns true if the basic block for I1 dominates that of
+    /// the basic block for I2. If the instructions belong to the same basic
+    /// block, the instruction first instruction sequentially in the block is
+    /// considered dominating.
     bool dominates(Instruction *I1, Instruction *I2) {
       BasicBlock *BB1 = I1->getParent(),
                  *BB2 = I2->getParent();
@@ -238,8 +245,12 @@ namespace {
              *Node2 = getNodeForBlock(BB2);
         return Node1 && Node2 && Node1->dominates(Node2);
       }
+      return false; // Not reached
     }
+
   private:
+    /// renumber - calculates the depth first search numberings and applies
+    /// them onto the nodes.
     void renumber() {
       std::stack<std::pair<Node *, Node::iterator> > S;
       unsigned n = 0;
@@ -265,21 +276,21 @@ namespace {
 
 #ifndef NDEBUG
     virtual void dump() const {
-      dump(*cerr.stream());
+      dump(errs());
     }
 
-    void dump(std::ostream &os) const {
+    void dump(raw_ostream &os) const {
       os << "Predicate simplifier DomTreeDFS: \n";
       dump(Entry, 0, os);
       os << "\n\n";
     }
 
-    void dump(Node *N, int depth, std::ostream &os) const {
+    void dump(Node *N, int depth, raw_ostream &os) const {
       ++depth;
       for (int i = 0; i < depth; ++i) { os << " "; }
       os << "[" << depth << "] ";
 
-      os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
+      os << N->getBlock()->getNameStr() << " (" << N->getDFSNumIn()
          << ", " << N->getDFSNumOut() << ")\n";
 
       for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
@@ -332,6 +343,9 @@ namespace {
     UGE = UGT | EQ_BIT
   };
 
+#ifndef NDEBUG
+  /// validPredicate - determines whether a given value is actually a lattice
+  /// value. Only used in assertions or debugging.
   static bool validPredicate(LatticeVal LV) {
     switch (LV) {
       case GT: case GE: case LT: case LE: case NE:
@@ -344,6 +358,7 @@ namespace {
         return false;
     }
   }
+#endif
 
   /// reversePredicate - reverse the direction of the inequality
   static LatticeVal reversePredicate(LatticeVal LV) {
@@ -361,8 +376,12 @@ namespace {
   }
 
   /// ValueNumbering stores the scope-specific value numbers for a given Value.
-  class VISIBILITY_HIDDEN ValueNumbering {
-    class VISIBILITY_HIDDEN VNPair {
+  class ValueNumbering {
+
+    /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
+    /// includes the comparison operators necessary to allow you to store it
+    /// in a sorted vector.
+    class VNPair {
     public:
       Value *V;
       unsigned index;
@@ -383,16 +402,47 @@ namespace {
       bool operator<(Value *RHS) const {
         return V < RHS;
       }
+
+      bool operator>(Value *RHS) const {
+        return V > RHS;
+      }
+
+      friend bool operator<(Value *RHS, const VNPair &pair) {
+        return pair.operator>(RHS);
+      }
     };
 
     typedef std::vector<VNPair> VNMapType;
     VNMapType VNMap;
 
+    /// The canonical choice for value number at index.
     std::vector<Value *> Values;
 
     DomTreeDFS *DTDFS;
 
   public:
+#ifndef NDEBUG
+    virtual ~ValueNumbering() {}
+    virtual void dump() {
+      print(errs());
+    }
+
+    void print(raw_ostream &os) {
+      for (unsigned i = 1; i <= Values.size(); ++i) {
+        os << i << " = ";
+        WriteAsOperand(os, Values[i-1]);
+        os << " {";
+        for (unsigned j = 0; j < VNMap.size(); ++j) {
+          if (VNMap[j].index == i) {
+            WriteAsOperand(os, VNMap[j].V);
+            os << " (" << VNMap[j].Subtree->getDFSNumIn() << ")  ";
+          }
+        }
+        os << "}\n";
+      }
+    }
+#endif
+
     /// compare - returns true if V1 is a better canonical value than V2.
     bool compare(Value *V1, Value *V2) const {
       if (isa<Constant>(V1))
@@ -418,6 +468,9 @@ namespace {
     /// valueNumber - finds the value number for V under the Subtree. If
     /// there is no value number, returns zero.
     unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
+      if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) || 
+          V->getType() == Type::getVoidTy(V->getContext())) return 0;
+
       VNMapType::iterator E = VNMap.end();
       VNPair pair(V, 0, Subtree);
       VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
@@ -429,15 +482,29 @@ namespace {
       return 0;
     }
 
+    /// getOrInsertVN - always returns a value number, creating it if necessary.
+    unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
+      if (unsigned n = valueNumber(V, Subtree))
+        return n;
+      else
+        return newVN(V);
+    }
+
     /// newVN - creates a new value number. Value V must not already have a
     /// value number assigned.
     unsigned newVN(Value *V) {
+      assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
+             "Bad Value for value numbering.");
+      assert(V->getType() != Type::getVoidTy(V->getContext()) &&
+             "Won't value number a void value");
+
       Values.push_back(V);
 
       VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
-      assert(!std::binary_search(VNMap.begin(), VNMap.end(), pair) &&
+      VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
+      assert((I == VNMap.end() || value(I->index) != V) &&
              "Attempt to create a duplicate value number.");
-      VNMap.insert(std::lower_bound(VNMap.begin(), VNMap.end(), pair), pair);
+      VNMap.insert(I, pair);
 
       return Values.size();
     }
@@ -489,7 +556,7 @@ namespace {
         VNMapType::iterator I = std::lower_bound(B, E, pair);
         if (I != E && I->V == V && I->Subtree == Subtree)
           I->index = n; // Update best choice
-       else
+        else
           VNMap.insert(I, pair); // New Value
 
         // XXX: we currently don't have to worry about updating values with
@@ -506,12 +573,12 @@ namespace {
 
     /// remove - removes all references to value V.
     void remove(Value *V) {
-      VNMapType::iterator B = VNMap.begin();
+      VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
       VNPair pair(V, 0, DTDFS->getRootNode());
-      VNMapType::iterator J = std::upper_bound(B, VNMap.end(), pair);
+      VNMapType::iterator J = std::upper_bound(B, E, pair);
       VNMapType::iterator I = J;
 
-      while (I != B && I->V == V) --I;
+      while (I != B && (I == E || I->V == V)) --I;
 
       VNMap.erase(I, J);
     }
@@ -524,7 +591,7 @@ namespace {
   ///
   /// The InequalityGraph class may invalidate Node*s after any mutator call.
   /// @brief The InequalityGraph stores the relationships between values.
-  class VISIBILITY_HIDDEN InequalityGraph {
+  class InequalityGraph {
     ValueNumbering &VN;
     DomTreeDFS::Node *TreeRoot;
 
@@ -540,7 +607,7 @@ namespace {
     /// and contains a pointer to the other end. The edge contains a lattice
     /// value specifying the relationship and an DomTreeDFS::Node specifying
     /// the root in the dominator tree to which this edge applies.
-    class VISIBILITY_HIDDEN Edge {
+    class Edge {
     public:
       Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
         : To(T), LV(V), Subtree(ST) {}
@@ -571,7 +638,7 @@ namespace {
     /// for the node, as well as the relationships with the neighbours.
     ///
     /// @brief A single node in the InequalityGraph.
-    class VISIBILITY_HIDDEN Node {
+    class Node {
       friend class InequalityGraph;
 
       typedef SmallVector<Edge, 4> RelationsType;
@@ -588,10 +655,10 @@ namespace {
 #ifndef NDEBUG
       virtual ~Node() {}
       virtual void dump() const {
-        dump(*cerr.stream());
+        dump(errs());
       }
     private:
-      void dump(std::ostream &os) const {
+      void dump(raw_ostream &os) const {
         static const std::string names[32] =
           { "000000", "000001", "000002", "000003", "000004", "000005",
             "000006", "000007", "000008", "000009", "     >", "    >=",
@@ -601,8 +668,7 @@ namespace {
             "    !=", "000031" };
         for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
           os << names[NI->LV] << " " << NI->To
-             << " (" << NI->Subtree->getDFSNumIn() << ")";
-          if (NI != NE) os << ", ";
+             << " (" << NI->Subtree->getDFSNumIn() << "), ";
         }
       }
     public:
@@ -633,41 +699,46 @@ namespace {
         return E;
       }
 
-      /// Updates the lattice value for a given node. Create a new entry if
-      /// one doesn't exist, otherwise it merges the values. The new lattice
-      /// value must not be inconsistent with any previously existing value.
+      /// update - updates the lattice value for a given node, creating a new
+      /// entry if one doesn't exist. The new lattice value must not be
+      /// inconsistent with any previously existing value.
       void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
         assert(validPredicate(R) && "Invalid predicate.");
-        iterator I = find(n, Subtree);
-        if (I == end()) {
-          Edge edge(n, R, Subtree);
-          iterator Insert = std::lower_bound(begin(), end(), edge);
-          Relations.insert(Insert, edge);
-        } else {
-          LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
-          assert(validPredicate(LV) && "Invalid union of lattice values.");
-          if (LV != I->LV) {
-            if (Subtree != I->Subtree) {
-              assert(Subtree->DominatedBy(I->Subtree) &&
-                     "Find returned subtree that doesn't apply.");
-
-              Edge edge(n, R, Subtree);
-              iterator Insert = std::lower_bound(begin(), end(), edge);
-              Relations.insert(Insert, edge); // invalidates I
-              I = find(n, Subtree);
-            }
 
-            // Also, we have to tighten any edge that Subtree dominates.
-            for (iterator B = begin(); I->To == n; --I) {
-              if (I->Subtree->DominatedBy(Subtree)) {
-                LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
-                assert(validPredicate(LV) && "Invalid union of lattice values");
-                I->LV = LV;
-              }
-              if (I == B) break;
+        Edge edge(n, R, Subtree);
+        iterator B = begin(), E = end();
+        iterator I = std::lower_bound(B, E, edge);
+
+        iterator J = I;
+        while (J != E && J->To == n) {
+          if (Subtree->DominatedBy(J->Subtree))
+            break;
+          ++J;
+        }
+
+        if (J != E && J->To == n) {
+          edge.LV = static_cast<LatticeVal>(J->LV & R);
+          assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
+
+          if (edge.LV == J->LV)
+            return; // This update adds nothing new.
+        }
+
+        if (I != B) {
+          // We also have to tighten any edge beneath our update.
+          for (iterator K = I - 1; K->To == n; --K) {
+            if (K->Subtree->DominatedBy(Subtree)) {
+              LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
+              assert(validPredicate(LV) && "Invalid union of lattice values");
+              K->LV = LV;
             }
+            if (K == B) break;
           }
         }
+
+        // Insert new edge at Subtree if it isn't already there.
+        if (I == E || I->To != n || Subtree != I->Subtree)
+          Relations.insert(I, edge);
       }
     };
 
@@ -676,26 +747,14 @@ namespace {
     std::vector<Node> Nodes;
 
   public:
-    /// node - returns the node object at a given index retrieved from getNode.
-    /// Index zero is reserved and may not be passed in here. The pointer
-    /// returned is valid until the next call to newNode or getOrInsertNode.
+    /// node - returns the node object at a given value number. The pointer
+    /// returned may be invalidated on the next call to node().
     Node *node(unsigned index) {
-      assert(index != 0 && "Zero index is reserved for not found.");
-      assert(index <= Nodes.size() && "Index out of range.");
+      assert(VN.value(index)); // This triggers the necessary checks.
+      if (Nodes.size() < index) Nodes.resize(index);
       return &Nodes[index-1];
     }
 
-    /// newNode - creates a new node for a given Value and returns the index.
-    unsigned newNode(Value *V) {
-      assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
-             "Bad Value for node.");
-      assert(V->getType() != Type::VoidTy && "Void node?");
-
-      unsigned n = VN.newVN(V);
-      if (Nodes.size() < n) Nodes.resize(n);
-      return n;
-    }
-
     /// isRelatedBy - true iff n1 op n2
     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
                      LatticeVal LV) {
@@ -721,9 +780,6 @@ namespace {
         assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
                "Contradictory inequality.");
 
-      Node *N1 = node(n1);
-      Node *N2 = node(n2);
-
       // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
       // add %a < %n2 too. This keeps the graph fully connected.
       if (LV1 != NE) {
@@ -735,7 +791,7 @@ namespace {
         unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
         unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
 
-        for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
+        for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
           if (I->LV != NE && I->To != n2) {
 
             DomTreeDFS::Node *Local_Subtree = NULL;
@@ -766,13 +822,13 @@ namespace {
                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
 
                 node(I->To)->update(n2, NewLV, Local_Subtree);
-                N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
+                node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
               }
             }
           }
         }
 
-        for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
+        for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
           if (I->LV != NE && I->To != n1) {
             DomTreeDFS::Node *Local_Subtree = NULL;
             if (Subtree->DominatedBy(I->Subtree))
@@ -801,7 +857,7 @@ namespace {
 
                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
 
-                N1->update(I->To, NewLV, Local_Subtree);
+                node(n1)->update(I->To, NewLV, Local_Subtree);
                 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
               }
             }
@@ -809,8 +865,8 @@ namespace {
         }
       }
 
-      N1->update(n2, LV1, Subtree);
-      N2->update(n1, reversePredicate(LV1), Subtree);
+      node(n1)->update(n2, LV1, Subtree);
+      node(n2)->update(n1, reversePredicate(LV1), Subtree);
     }
 
     /// remove - removes a node from the graph by removing all references to
@@ -830,10 +886,10 @@ namespace {
 #ifndef NDEBUG
     virtual ~InequalityGraph() {}
     virtual void dump() {
-      dump(*cerr.stream());
+      dump(errs());
     }
 
-    void dump(std::ostream &os) {
+    void dump(raw_ostream &os) {
       for (unsigned i = 1; i <= Nodes.size(); ++i) {
         os << i << " = {";
         node(i)->dump(os);
@@ -847,142 +903,87 @@ namespace {
 
   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
   /// in the InequalityGraph.
-  class VISIBILITY_HIDDEN ValueRanges {
-
-    /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
-    /// the scope of a rooted subtree in the dominator tree.
-    class VISIBILITY_HIDDEN ScopedRange {
-    public:
-      ScopedRange(Value *V, ConstantRange CR, DomTreeDFS::Node *ST)
-        : V(V), CR(CR), Subtree(ST) {}
+  class ValueRanges {
+    ValueNumbering &VN;
+    TargetData *TD;
+    LLVMContext *Context;
 
-      Value *V;
-      ConstantRange CR;
-      DomTreeDFS::Node *Subtree;
+    class ScopedRange {
+      typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
+              RangeListType;
+      RangeListType RangeList;
 
-      bool operator<(const ScopedRange &range) const {
-        if (V != range.V) return V < range.V;
-        return *Subtree < *range.Subtree;
+      static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
+                      const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
+        return *LHS.first < *RHS.first;
       }
 
-      bool operator<(const Value *value) const {
-        return V < value;
+    public:
+#ifndef NDEBUG
+      virtual ~ScopedRange() {}
+      virtual void dump() const {
+        dump(errs());
       }
 
-      bool operator>(const Value *value) const {
-          return V > value;
+      void dump(raw_ostream &os) const {
+        os << "{";
+        for (const_iterator I = begin(), E = end(); I != E; ++I) {
+          os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
+        }
+        os << "}";
       }
+#endif
 
-      friend bool operator<(const Value *value, const ScopedRange &range) {
-          return range.operator>(value);
-      }
-    };
+      typedef RangeListType::iterator       iterator;
+      typedef RangeListType::const_iterator const_iterator;
 
-    TargetData *TD;
+      iterator begin() { return RangeList.begin(); }
+      iterator end()   { return RangeList.end(); }
+      const_iterator begin() const { return RangeList.begin(); }
+      const_iterator end()   const { return RangeList.end(); }
 
-    std::vector<ScopedRange> Ranges;
-    typedef std::vector<ScopedRange>::iterator iterator;
+      iterator find(DomTreeDFS::Node *Subtree) {
+        iterator E = end();
+        iterator I = std::lower_bound(begin(), E,
+                                      std::make_pair(Subtree, empty), swo);
 
-    // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
-    // intrusive domtree-scoped container is in order?
+        while (I != E && !I->first->dominates(Subtree)) ++I;
+        return I;
+      }
 
-    iterator begin() { return Ranges.begin(); }
-    iterator end()   { return Ranges.end();   }
+      const_iterator find(DomTreeDFS::Node *Subtree) const {
+        const_iterator E = end();
+        const_iterator I = std::lower_bound(begin(), E,
+                                            std::make_pair(Subtree, empty), swo);
 
-    iterator find(Value *V, DomTreeDFS::Node *Subtree) {
-      iterator E = end();
-      for (iterator I = std::lower_bound(begin(), E, V);
-           I != E && I->V == V; ++I) {
-        if (Subtree->DominatedBy(I->Subtree))
-          return I;
+        while (I != E && !I->first->dominates(Subtree)) ++I;
+        return I;
       }
-      return E;
-    }
 
-    void update(Value *V, ConstantRange CR, DomTreeDFS::Node *Subtree) {
-      assert(!CR.isEmptySet() && "Empty ConstantRange!");
-      if (CR.isFullSet()) return;
+      void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
+        assert(!CR.isEmptySet() && "Empty ConstantRange.");
+        assert(!CR.isSingleElement() && "Refusing to store single element.");
 
-      iterator I = find(V, Subtree);
-      if (I == end()) {
-        ScopedRange range(V, CR, Subtree);
-        iterator Insert = std::lower_bound(begin(), end(), range);
-        Ranges.insert(Insert, range);
-      } else {
-        CR = CR.intersectWith(I->CR);
-        assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
-
-        if (CR != I->CR) {
-          if (Subtree != I->Subtree) {
-            assert(Subtree->DominatedBy(I->Subtree) &&
-                   "Find returned subtree that doesn't apply.");
-
-            ScopedRange range(V, CR, Subtree);
-            iterator Insert = std::lower_bound(begin(), end(), range);
-            Ranges.insert(Insert, range); // invalidates I
-            I = find(V, Subtree);
-          }
+        iterator E = end();
+        iterator I =
+            std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
 
-          // Also, we have to tighten any edge that Subtree dominates.
-          for (iterator B = begin(); I->V == V; --I) {
-            if (I->Subtree->DominatedBy(Subtree)) {
-              I->CR = CR.intersectWith(I->CR);
-              assert(!I->CR.isEmptySet() &&
-                     "Empty intersection of ConstantRanges!");
-            }
-            if (I == B) break;
-          }
-        }
+        if (I != end() && I->first == Subtree) {
+          ConstantRange CR2 = I->second.intersectWith(CR);
+          assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
+                 "Invalid union of ranges.");
+          I->second = CR2;
+        } else
+          RangeList.insert(I, std::make_pair(Subtree, CR));
       }
-    }
+    };
 
-    /// range - Creates a ConstantRange representing the set of all values
-    /// that match the ICmpInst::Predicate with any of the values in CR.
-    ConstantRange range(ICmpInst::Predicate ICmpOpcode,
-                        const ConstantRange &CR) {
-      uint32_t W = CR.getBitWidth();
-      switch (ICmpOpcode) {
-        default: assert(!"Invalid ICmp opcode to range()");
-        case ICmpInst::ICMP_EQ:
-          return ConstantRange(CR.getLower(), CR.getUpper());
-        case ICmpInst::ICMP_NE:
-          if (CR.isSingleElement())
-            return ConstantRange(CR.getUpper(), CR.getLower());
-          return ConstantRange(W);
-        case ICmpInst::ICMP_ULT:
-          return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
-        case ICmpInst::ICMP_SLT:
-          return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
-        case ICmpInst::ICMP_ULE: {
-          APInt UMax(CR.getUnsignedMax());
-          if (UMax.isMaxValue())
-            return ConstantRange(W);
-          return ConstantRange(APInt::getMinValue(W), UMax + 1);
-        }
-        case ICmpInst::ICMP_SLE: {
-          APInt SMax(CR.getSignedMax());
-          if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
-            return ConstantRange(W);
-          return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
-        }
-        case ICmpInst::ICMP_UGT:
-          return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
-        case ICmpInst::ICMP_SGT:
-          return ConstantRange(CR.getSignedMin() + 1,
-                               APInt::getSignedMinValue(W));
-        case ICmpInst::ICMP_UGE: {
-          APInt UMin(CR.getUnsignedMin());
-          if (UMin.isMinValue())
-            return ConstantRange(W);
-          return ConstantRange(UMin, APInt::getNullValue(W));
-        }
-        case ICmpInst::ICMP_SGE: {
-          APInt SMin(CR.getSignedMin());
-          if (SMin.isMinSignedValue())
-            return ConstantRange(W);
-          return ConstantRange(SMin, APInt::getSignedMinValue(W));
-        }
-      }
+    std::vector<ScopedRange> Ranges;
+
+    void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
+      if (CR.isFullSet()) return;
+      if (Ranges.size() < n) Ranges.resize(n);
+      Ranges[n-1].update(CR, Subtree);
     }
 
     /// create - Creates a ConstantRange that matches the given LatticeVal
@@ -991,7 +992,7 @@ namespace {
       assert(!CR.isEmptySet() && "Can't deal with empty set.");
 
       if (LV == NE)
-        return range(ICmpInst::ICMP_NE, CR);
+        return ConstantRange::makeICmpRegion(ICmpInst::ICMP_NE, CR);
 
       unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
       unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
@@ -1000,18 +1001,18 @@ namespace {
       ConstantRange Range(CR.getBitWidth());
 
       if (LV_s == SGT_BIT) {
-        Range = Range.intersectWith(range(
+        Range = Range.intersectWith(ConstantRange::makeICmpRegion(
                     hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
       } else if (LV_s == SLT_BIT) {
-        Range = Range.intersectWith(range(
+        Range = Range.intersectWith(ConstantRange::makeICmpRegion(
                     hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
       }
 
       if (LV_u == UGT_BIT) {
-        Range = Range.intersectWith(range(
+        Range = Range.intersectWith(ConstantRange::makeICmpRegion(
                     hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
       } else if (LV_u == ULT_BIT) {
-        Range = Range.intersectWith(range(
+        Range = Range.intersectWith(ConstantRange::makeICmpRegion(
                     hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
       }
 
@@ -1019,29 +1020,54 @@ namespace {
     }
 
 #ifndef NDEBUG
-    bool isCanonical(Value *V, DomTreeDFS::Node *Subtree, VRPSolver *VRP);
+    bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
+      return V == VN.canonicalize(V, Subtree);
+    }
 #endif
 
   public:
 
-    explicit ValueRanges(TargetData *TD) : TD(TD) {}
+    ValueRanges(ValueNumbering &VN, TargetData *TD, LLVMContext *C) :
+      VN(VN), TD(TD), Context(C) {}
 
-    // rangeFromValue - converts a Value into a range. If the value is a
-    // constant it constructs the single element range, otherwise it performs
-    // a lookup. The width W must be retrieved from typeToWidth and may not
-    // be zero.
-    ConstantRange rangeFromValue(Value *V, DomTreeDFS::Node *Subtree,
-                                 uint32_t W) {
-      if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
-        return ConstantRange(C->getValue());
-      } else if (isa<ConstantPointerNull>(V)) {
-        return ConstantRange(APInt::getNullValue(W));
-      } else {
-        iterator I = find(V, Subtree);
-        if (I != end())
-          return I->CR;
+#ifndef NDEBUG
+    virtual ~ValueRanges() {}
+
+    virtual void dump() const {
+      dump(errs());
+    }
+
+    void dump(raw_ostream &os) const {
+      for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
+        os << (i+1) << " = ";
+        Ranges[i].dump(os);
+        os << "\n";
       }
-      return ConstantRange(W);
+    }
+#endif
+
+    /// range - looks up the ConstantRange associated with a value number.
+    ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
+      assert(VN.value(n)); // performs range checks
+
+      if (n <= Ranges.size()) {
+        ScopedRange::iterator I = Ranges[n-1].find(Subtree);
+        if (I != Ranges[n-1].end()) return I->second;
+      }
+
+      Value *V = VN.value(n);
+      ConstantRange CR = range(V);
+      return CR;
+    }
+
+    /// range - determine a range from a Value without performing any lookups.
+    ConstantRange range(Value *V) const {
+      if (ConstantInt *C = dyn_cast<ConstantInt>(V))
+        return ConstantRange(C->getValue());
+      else if (isa<ConstantPointerNull>(V))
+        return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
+      else
+        return ConstantRange(typeToWidth(V->getType()));
     }
 
     // typeToWidth - returns the number of bits necessary to store a value of
@@ -1049,22 +1075,12 @@ namespace {
     uint32_t typeToWidth(const Type *Ty) const {
       if (TD)
         return TD->getTypeSizeInBits(Ty);
-
-      if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
-        return ITy->getBitWidth();
-
-      return 0;
+      else
+        return Ty->getPrimitiveSizeInBits();
     }
 
-    bool isRelatedBy(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
-                     LatticeVal LV) {
-      uint32_t W = typeToWidth(V1->getType());
-      if (!W) return false;
-
-      ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
-      ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
-
-      // True iff all values in CR1 are LV to all values in CR2.
+    static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
+                            LatticeVal LV) {
       switch (LV) {
       default: assert(!"Impossible lattice value!");
       case NE:
@@ -1112,22 +1128,27 @@ namespace {
       }
     }
 
+    bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
+                     LatticeVal LV) {
+      ConstantRange CR1 = range(n1, Subtree);
+      ConstantRange CR2 = range(n2, Subtree);
+
+      // True iff all values in CR1 are LV to all values in CR2.
+      return isRelatedBy(CR1, CR2, LV);
+    }
+
     void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
                        VRPSolver *VRP);
     void markBlock(VRPSolver *VRP);
 
-    void mergeInto(Value **I, unsigned n, Value *New,
+    void mergeInto(Value **I, unsigned n, unsigned New,
                    DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
-      assert(isCanonical(New, Subtree, VRP) && "Best choice not canonical?");
-
-      uint32_t W = typeToWidth(New->getType());
-      if (!W) return;
-
-      ConstantRange CR_New = rangeFromValue(New, Subtree, W);
+      ConstantRange CR_New = range(New, Subtree);
       ConstantRange Merged = CR_New;
 
       for (; n != 0; ++I, --n) {
-        ConstantRange CR_Kill = rangeFromValue(*I, Subtree, W);
+        unsigned i = VN.valueNumber(*I, Subtree);
+        ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
         if (CR_Kill.isFullSet()) continue;
         Merged = Merged.intersectWith(CR_Kill);
       }
@@ -1137,45 +1158,43 @@ namespace {
       applyRange(New, Merged, Subtree, VRP);
     }
 
-    void applyRange(Value *V, const ConstantRange &CR,
+    void applyRange(unsigned n, const ConstantRange &CR,
                     DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
-      assert(isCanonical(V, Subtree, VRP) && "Value not canonical.");
+      ConstantRange Merged = CR.intersectWith(range(n, Subtree));
+      if (Merged.isEmptySet()) {
+        markBlock(VRP);
+        return;
+      }
 
-      if (const APInt *I = CR.getSingleElement()) {
+      if (const APInt *I = Merged.getSingleElement()) {
+        Value *V = VN.value(n); // XXX: redesign worklist.
         const Type *Ty = V->getType();
         if (Ty->isInteger()) {
-          addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
+          addToWorklist(V, ConstantInt::get(*Context, *I),
+                        ICmpInst::ICMP_EQ, VRP);
           return;
         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
           assert(*I == 0 && "Pointer is null but not zero?");
           addToWorklist(V, ConstantPointerNull::get(PTy),
-                      ICmpInst::ICMP_EQ, VRP);
+                        ICmpInst::ICMP_EQ, VRP);
           return;
         }
       }
 
-      ConstantRange Merged = CR.intersectWith(
-                                rangeFromValue(V, Subtree, CR.getBitWidth()));
-      if (Merged.isEmptySet()) {
-        markBlock(VRP);
-        return;
-      }
-
-      update(V, Merged, Subtree);
+      update(n, Merged, Subtree);
     }
 
-    void addNotEquals(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
+    void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
                       VRPSolver *VRP) {
-      uint32_t W = typeToWidth(V1->getType());
-      if (!W) return;
+      ConstantRange CR1 = range(n1, Subtree);
+      ConstantRange CR2 = range(n2, Subtree);
 
-      ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
-      ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
+      uint32_t W = CR1.getBitWidth();
 
       if (const APInt *I = CR1.getSingleElement()) {
         if (CR2.isFullSet()) {
           ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
         } else if (*I == CR2.getLower()) {
           APInt NewLower(CR2.getLower() + 1),
                 NewUpper(CR2.getUpper());
@@ -1183,7 +1202,7 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR2(NewLower, NewUpper);
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
         } else if (*I == CR2.getUpper() - 1) {
           APInt NewLower(CR2.getLower()),
                 NewUpper(CR2.getUpper() - 1);
@@ -1191,14 +1210,14 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR2(NewLower, NewUpper);
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
         }
       }
 
       if (const APInt *I = CR2.getSingleElement()) {
         if (CR1.isFullSet()) {
           ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
         } else if (*I == CR1.getLower()) {
           APInt NewLower(CR1.getLower() + 1),
                 NewUpper(CR1.getUpper());
@@ -1206,7 +1225,7 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR1(NewLower, NewUpper);
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
         } else if (*I == CR1.getUpper() - 1) {
           APInt NewLower(CR1.getLower()),
                 NewUpper(CR1.getUpper() - 1);
@@ -1214,40 +1233,34 @@ namespace {
             NewLower = NewUpper = APInt::getMinValue(W);
 
           ConstantRange NewCR1(NewLower, NewUpper);
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
         }
       }
     }
 
-    void addInequality(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
+    void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
                        LatticeVal LV, VRPSolver *VRP) {
-      assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
-
-      assert(isCanonical(V1, Subtree, VRP) && "Value not canonical.");
-      assert(isCanonical(V2, Subtree, VRP) && "Value not canonical.");
+      assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
 
       if (LV == NE) {
-        addNotEquals(V1, V2, Subtree, VRP);
+        addNotEquals(n1, n2, Subtree, VRP);
         return;
       }
 
-      uint32_t W = typeToWidth(V1->getType());
-      if (!W) return;
-
-      ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
-      ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
+      ConstantRange CR1 = range(n1, Subtree);
+      ConstantRange CR2 = range(n2, Subtree);
 
       if (!CR1.isSingleElement()) {
         ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
         if (NewCR1 != CR1)
-          applyRange(V1, NewCR1, Subtree, VRP);
+          applyRange(n1, NewCR1, Subtree, VRP);
       }
 
       if (!CR2.isSingleElement()) {
-        ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
-                                                        CR1));
+        ConstantRange NewCR2 = CR2.intersectWith(
+                                       create(reversePredicate(LV), CR1));
         if (NewCR2 != CR2)
-          applyRange(V2, NewCR2, Subtree, VRP);
+          applyRange(n2, NewCR2, Subtree, VRP);
       }
     }
   };
@@ -1256,7 +1269,7 @@ namespace {
   /// another discovered to be unreachable. This is used to cull the graph when
   /// analyzing instructions, and to mark blocks with the "unreachable"
   /// terminator instruction after the function has executed.
-  class VISIBILITY_HIDDEN UnreachableBlocks {
+  class UnreachableBlocks {
   private:
     std::vector<BasicBlock *> DeadBlocks;
 
@@ -1286,7 +1299,7 @@ namespace {
            E = DeadBlocks.end(); I != E; ++I) {
         BasicBlock *BB = *I;
 
-        DOUT << "unreachable block: " << BB->getName() << "\n";
+        DEBUG(errs() << "unreachable block: " << BB->getName() << "\n");
 
         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
              SI != SE; ++SI) {
@@ -1297,7 +1310,7 @@ namespace {
         TerminatorInst *TI = BB->getTerminator();
         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
         TI->eraseFromParent();
-        new UnreachableInst(BB);
+        new UnreachableInst(BB->getContext(), BB);
         ++NumBlocks;
         modified = true;
       }
@@ -1310,7 +1323,7 @@ namespace {
   /// variables, and forwards changes along to the InequalityGraph. It
   /// also maintains the correct choice for "canonical" in the IG.
   /// @brief VRPSolver calculates inferences from a new relationship.
-  class VISIBILITY_HIDDEN VRPSolver {
+  class VRPSolver {
   private:
     friend class ValueRanges;
 
@@ -1332,6 +1345,7 @@ namespace {
     BasicBlock *TopBB;
     Instruction *TopInst;
     bool &modified;
+    LLVMContext *Context;
 
     typedef InequalityGraph::Node Node;
 
@@ -1356,6 +1370,7 @@ namespace {
         if (!Node) return false;
         return Top->dominates(Node);
       }
+      return false; // Not reached
     }
 
     // aboveOrBelow - true if the Instruction either dominates or is dominated
@@ -1369,11 +1384,13 @@ namespace {
     }
 
     bool makeEqual(Value *V1, Value *V2) {
-      DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
-      DOUT << "context is ";
-      if (TopInst) DOUT << "I: " << *TopInst << "\n";
-      else DOUT << "BB: " << TopBB->getName()
-                << "(" << Top->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "makeEqual(" << *V1 << ", " << *V2 << ")\n");
+      DEBUG(errs() << "context is ");
+      DEBUG(if (TopInst) 
+              errs() << "I: " << *TopInst << "\n";
+            else 
+              errs() << "BB: " << TopBB->getName()
+                     << "(" << Top->getDFSNumIn() << ")\n");
 
       assert(V1->getType() == V2->getType() &&
              "Can't make two values with different types equal.");
@@ -1406,19 +1423,18 @@ namespace {
         // be EQ and that's invalid. What we're doing is looking for any nodes
         // %z such that %x <= %z and %y >= %z, and vice versa.
 
-        Node *N1 = IG.node(n1);
-        Node *N2 = IG.node(n2);
-        Node::iterator end = N2->end();
+        Node::iterator end = IG.node(n2)->end();
 
         // Find the intersection between N1 and N2 which is dominated by
         // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
         // Remove.
-        for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
+        for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
+             I != E; ++I) {
           if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
 
           unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
           unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
-          Node::iterator NI = N2->find(I->To, Top);
+          Node::iterator NI = IG.node(n2)->find(I->To, Top);
           if (NI != end) {
             LatticeVal NILV = reversePredicate(NI->LV);
             unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
@@ -1452,7 +1468,7 @@ namespace {
       }
 
       // We'd like to allow makeEqual on two values to perform a simple
-      // substitution without every creating nodes in the IG whenever possible.
+      // substitution without creating nodes in the IG whenever possible.
       //
       // The first iteration through this loop operates on V2 before going
       // through the Remove list and operating on those too. If all of the
@@ -1466,16 +1482,16 @@ namespace {
         Instruction *I2 = dyn_cast<Instruction>(R);
         if (I2 && below(I2)) {
           std::vector<Instruction *> ToNotify;
-          for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
+          for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
                UI != UE;) {
             Use &TheUse = UI.getUse();
             ++UI;
-            if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
-              ToNotify.push_back(I);
+            Instruction *I = cast<Instruction>(TheUse.getUser());
+            ToNotify.push_back(I);
           }
 
-          DOUT << "Simply removing " << *I2
-               << ", replacing with " << *V1 << "\n";
+          DEBUG(errs() << "Simply removing " << *I2
+                       << ", replacing with " << *V1 << "\n");
           I2->replaceAllUsesWith(V1);
           // leave it dead; it'll get erased later.
           ++NumInstruction;
@@ -1506,8 +1522,8 @@ namespace {
 
         // If that killed the instruction, stop here.
         if (I2 && isInstructionTriviallyDead(I2)) {
-          DOUT << "Killed all uses of " << *I2
-               << ", replacing with " << *V1 << "\n";
+          DEBUG(errs() << "Killed all uses of " << *I2
+                       << ", replacing with " << *V1 << "\n");
           continue;
         }
 
@@ -1518,7 +1534,7 @@ namespace {
 
       if (!isa<Constant>(V1)) {
         if (Remove.empty()) {
-          VR.mergeInto(&V2, 1, V1, Top, this);
+          VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
         } else {
           std::vector<Value*> RemoveVals;
           RemoveVals.reserve(Remove.size());
@@ -1529,21 +1545,22 @@ namespace {
             if (!V->use_empty())
               RemoveVals.push_back(V);
           }
-          VR.mergeInto(&RemoveVals[0], RemoveVals.size(), V1, Top, this);
+          VR.mergeInto(&RemoveVals[0], RemoveVals.size(), 
+                       VN.getOrInsertVN(V1, Top), Top, this);
         }
       }
 
       if (mergeIGNode) {
         // Create N1.
-        if (!n1) n1 = IG.newNode(V1);
+        if (!n1) n1 = VN.getOrInsertVN(V1, Top);
+        IG.node(n1); // Ensure that IG.Nodes won't get resized
 
         // Migrate relationships from removed nodes to N1.
-        Node *N1 = IG.node(n1);
         for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
              I != E; ++I) {
           unsigned n = *I;
-          Node *N = IG.node(n);
-          for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
+          for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
+               NI != NE; ++NI) {
             if (NI->Subtree->DominatedBy(Top)) {
               if (NI->To == n1) {
                 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
@@ -1553,7 +1570,7 @@ namespace {
                 continue;
 
               IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
-              N1->update(NI->To, NI->LV, Top);
+              IG.node(n1)->update(NI->To, NI->LV, Top);
             }
           }
         }
@@ -1598,10 +1615,9 @@ namespace {
           ++UI;
           Value *V = TheUse.getUser();
           if (!V->use_empty()) {
-            if (Instruction *Inst = dyn_cast<Instruction>(V)) {
-              if (aboveOrBelow(Inst))
-                opsToDef(Inst);
-            }
+            Instruction *Inst = cast<Instruction>(V);
+            if (aboveOrBelow(Inst))
+              opsToDef(Inst);
           }
         }
       }
@@ -1651,7 +1667,8 @@ namespace {
         Top(DTDFS->getNodeForBlock(TopBB)),
         TopBB(TopBB),
         TopInst(NULL),
-        modified(modified)
+        modified(modified),
+        Context(&TopBB->getContext())
     {
       assert(Top && "VRPSolver created for unreachable basic block.");
     }
@@ -1667,7 +1684,8 @@ namespace {
         Top(DTDFS->getNodeForBlock(TopInst->getParent())),
         TopBB(TopInst->getParent()),
         TopInst(TopInst),
-        modified(modified)
+        modified(modified),
+        Context(&TopInst->getContext())
     {
       assert(Top && "VRPSolver created for unreachable basic block.");
       assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
@@ -1677,30 +1695,46 @@ namespace {
       if (Constant *C1 = dyn_cast<Constant>(V1))
         if (Constant *C2 = dyn_cast<Constant>(V2))
           return ConstantExpr::getCompare(Pred, C1, C2) ==
-                 ConstantInt::getTrue();
-
-      if (unsigned n1 = VN.valueNumber(V1, Top))
-        if (unsigned n2 = VN.valueNumber(V2, Top)) {
-          if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
-                               Pred == ICmpInst::ICMP_ULE ||
-                               Pred == ICmpInst::ICMP_UGE ||
-                               Pred == ICmpInst::ICMP_SLE ||
-                               Pred == ICmpInst::ICMP_SGE;
-          if (Pred == ICmpInst::ICMP_EQ) return false;
-          if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
-        }
+                 ConstantInt::getTrue(*Context);
+
+      unsigned n1 = VN.valueNumber(V1, Top);
+      unsigned n2 = VN.valueNumber(V2, Top);
 
+      if (n1 && n2) {
+        if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
+                             Pred == ICmpInst::ICMP_ULE ||
+                             Pred == ICmpInst::ICMP_UGE ||
+                             Pred == ICmpInst::ICMP_SLE ||
+                             Pred == ICmpInst::ICMP_SGE;
+        if (Pred == ICmpInst::ICMP_EQ) return false;
+        if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
+        if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
+      }
+
+      if ((n1 && !n2 && isa<Constant>(V2)) ||
+          (n2 && !n1 && isa<Constant>(V1))) {
+        ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
+        ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
+
+        if (Pred == ICmpInst::ICMP_EQ)
+          return CR1.isSingleElement() &&
+                 CR1.getSingleElement() == CR2.getSingleElement();
+
+        return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
+      }
       if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
-      return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
+      return false;
     }
 
     /// add - adds a new property to the work queue
     void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
              Instruction *I = NULL) {
-      DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
-      if (I) DOUT << " context: " << *I;
-      else DOUT << " default context (" << Top->getDFSNumIn() << ")";
-      DOUT << "\n";
+      DEBUG(errs() << "adding " << *V1 << " " << Pred << " " << *V2);
+      if (I)
+        DEBUG(errs() << " context: " << *I);
+      else 
+        DEBUG(errs() << " default context (" << Top->getDFSNumIn() << ")");
+      DEBUG(errs() << "\n");
 
       assert(V1->getType() == V2->getType() &&
              "Can't relate two values with different types.");
@@ -1729,7 +1763,7 @@ namespace {
         switch (BO->getOpcode()) {
           case Instruction::And: {
             // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
-            ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
+            ConstantInt *CI = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
             if (Canonical == CI) {
               add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
               add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
@@ -1754,7 +1788,8 @@ namespace {
 
             if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
               if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
-                add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
+                add(RHS,
+                  ConstantInt::get(*Context, CI->getValue() ^ Arg->getValue()),
                     ICmpInst::ICMP_EQ, NewContext);
               }
             }
@@ -1774,10 +1809,10 @@ namespace {
         // "icmp ult i32 %a, %y" EQ true then %a u< y
         // etc.
 
-        if (Canonical == ConstantInt::getTrue()) {
+        if (Canonical == ConstantInt::getTrue(*Context)) {
           add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
               NewContext);
-        } else if (Canonical == ConstantInt::getFalse()) {
+        } else if (Canonical == ConstantInt::getFalse(*Context)) {
           add(IC->getOperand(0), IC->getOperand(1),
               ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
         }
@@ -1793,11 +1828,11 @@ namespace {
         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
           if (Canonical == VN.canonicalize(True, Top) ||
               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
-            add(SI->getCondition(), ConstantInt::getTrue(),
+            add(SI->getCondition(), ConstantInt::getTrue(*Context),
                 ICmpInst::ICMP_EQ, NewContext);
           else if (Canonical == VN.canonicalize(False, Top) ||
                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
-            add(SI->getCondition(), ConstantInt::getFalse(),
+            add(SI->getCondition(), ConstantInt::getFalse(*Context),
                 ICmpInst::ICMP_EQ, NewContext);
         }
       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
@@ -1817,10 +1852,10 @@ namespace {
       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
         const Type *SrcTy = CI->getSrcTy();
 
-        Value *TheCI = VN.canonicalize(CI, Top);
+        unsigned ci = VN.getOrInsertVN(CI, Top);
         uint32_t W = VR.typeToWidth(SrcTy);
         if (!W) return;
-        ConstantRange CR = VR.rangeFromValue(TheCI, Top, W);
+        ConstantRange CR = VR.range(ci, Top);
 
         if (CR.isFullSet()) return;
 
@@ -1828,11 +1863,11 @@ namespace {
           default: break;
           case Instruction::ZExt:
           case Instruction::SExt:
-            VR.applyRange(VN.canonicalize(CI->getOperand(0), Top),
+            VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
                           CR.truncate(W), Top, this);
             break;
           case Instruction::BitCast:
-            VR.applyRange(VN.canonicalize(CI->getOperand(0), Top),
+            VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
                           CR, Top, this);
             break;
         }
@@ -1866,26 +1901,81 @@ namespace {
         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
 
         Constant *Zero = Constant::getNullValue(Ty);
-        ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
+        Constant *One = ConstantInt::get(Ty, 1);
+        ConstantInt *AllOnes = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
 
         switch (Opcode) {
           default: break;
           case Instruction::LShr:
           case Instruction::AShr:
           case Instruction::Shl:
+            if (Op1 == Zero) {
+              add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
+              return;
+            }
+            break;
           case Instruction::Sub:
             if (Op1 == Zero) {
               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
               return;
             }
+            if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
+              unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
+              ConstantRange CR = VR.range(n_ci0, Top);
+              if (!CR.isFullSet()) {
+                CR.subtract(CI0->getValue());
+                unsigned n_bo = VN.getOrInsertVN(BO, Top);
+                VR.applyRange(n_bo, CR, Top, this);
+                return;
+              }
+            }
+            if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
+              unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
+              ConstantRange CR = VR.range(n_ci1, Top);
+              if (!CR.isFullSet()) {
+                CR.subtract(CI1->getValue());
+                unsigned n_bo = VN.getOrInsertVN(BO, Top);
+                VR.applyRange(n_bo, CR, Top, this);
+                return;
+              }
+            }
             break;
           case Instruction::Or:
             if (Op0 == AllOnes || Op1 == AllOnes) {
               add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
               return;
-            } // fall-through
-          case Instruction::Xor:
+            }
+            if (Op0 == Zero) {
+              add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
+              return;
+            } else if (Op1 == Zero) {
+              add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
+              return;
+            }
+            break;
           case Instruction::Add:
+            if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
+              unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
+              ConstantRange CR = VR.range(n_ci0, Top);
+              if (!CR.isFullSet()) {
+                CR.subtract(-CI0->getValue());
+                unsigned n_bo = VN.getOrInsertVN(BO, Top);
+                VR.applyRange(n_bo, CR, Top, this);
+                return;
+              }
+            }
+            if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
+              unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
+              ConstantRange CR = VR.range(n_ci1, Top);
+              if (!CR.isFullSet()) {
+                CR.subtract(-CI1->getValue());
+                unsigned n_bo = VN.getOrInsertVN(BO, Top);
+                VR.applyRange(n_bo, CR, Top, this);
+                return;
+              }
+            }
+            // fall-through
+          case Instruction::Xor:
             if (Op0 == Zero) {
               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
               return;
@@ -1902,19 +1992,30 @@ namespace {
               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
               return;
             }
-            // fall-through
+            if (Op0 == Zero || Op1 == Zero) {
+              add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
+              return;
+            }
+            break;
           case Instruction::Mul:
             if (Op0 == Zero || Op1 == Zero) {
               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
               return;
             }
+            if (Op0 == One) {
+              add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
+              return;
+            } else if (Op1 == One) {
+              add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
+              return;
+            }
             break;
         }
 
         // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
         // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
         // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
-        // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
+        // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
 
         Value *Known = Op0, *Unknown = Op1,
               *TheBO = VN.canonicalize(BO, Top);
@@ -1928,7 +2029,7 @@ namespace {
               if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
               // otherwise, fall-through.
             case Instruction::Sub:
-              if (Unknown == Op1) break;
+              if (Unknown == Op0) break;
               // otherwise, fall-through.
             case Instruction::Xor:
             case Instruction::Add:
@@ -1937,10 +2038,8 @@ namespace {
             case Instruction::UDiv:
             case Instruction::SDiv:
               if (Unknown == Op1) break;
-              if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
-                Constant *One = ConstantInt::get(Ty, 1);
+              if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
                 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
-              }
               break;
           }
         }
@@ -1956,11 +2055,11 @@ namespace {
         Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
 
         ICmpInst::Predicate Pred = IC->getPredicate();
-        if (isRelatedBy(Op0, Op1, Pred)) {
-          add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
-        } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
-          add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
-        }
+        if (isRelatedBy(Op0, Op1, Pred))
+          add(IC, ConstantInt::getTrue(*Context), ICmpInst::ICMP_EQ, NewContext);
+        else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
+          add(IC, ConstantInt::getFalse(*Context),
+              ICmpInst::ICMP_EQ, NewContext);
 
       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
         if (I->getType()->isFPOrFPVector()) return;
@@ -1971,9 +2070,9 @@ namespace {
         // %b EQ %c then %a EQ %b
 
         Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
-        if (Canonical == ConstantInt::getTrue()) {
+        if (Canonical == ConstantInt::getTrue(*Context)) {
           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
-        } else if (Canonical == ConstantInt::getFalse()) {
+        } else if (Canonical == ConstantInt::getFalse(*Context)) {
           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
         } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
                    VN.canonicalize(SI->getFalseValue(), Top)) {
@@ -1992,25 +2091,25 @@ namespace {
         }
 
         uint32_t W = VR.typeToWidth(DestTy);
-        Value *TheCI = VN.canonicalize(CI, Top);
-        ConstantRange CR = VR.rangeFromValue(Op, Top, W);
+        unsigned ci = VN.getOrInsertVN(CI, Top);
+        ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
 
         if (!CR.isFullSet()) {
           switch (Opcode) {
             default: break;
             case Instruction::ZExt:
-              VR.applyRange(TheCI, CR.zeroExtend(W), Top, this);
+              VR.applyRange(ci, CR.zeroExtend(W), Top, this);
               break;
             case Instruction::SExt:
-              VR.applyRange(TheCI, CR.signExtend(W), Top, this);
+              VR.applyRange(ci, CR.signExtend(W), Top, this);
               break;
             case Instruction::Trunc: {
               ConstantRange Result = CR.truncate(W);
               if (!Result.isFullSet())
-                VR.applyRange(TheCI, Result, Top, this);
+                VR.applyRange(ci, Result, Top, this);
             } break;
             case Instruction::BitCast:
-              VR.applyRange(TheCI, CR, Top, this);
+              VR.applyRange(ci, CR, Top, this);
               break;
             // TODO: other casts?
           }
@@ -2034,9 +2133,9 @@ namespace {
 
     /// solve - process the work queue
     void solve() {
-      //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
+      //DEBUG(errs() << "WorkList entry, size: " << WorkList.size() << "\n");
       while (!WorkList.empty()) {
-        //DOUT << "WorkList size: " << WorkList.size() << "\n";
+        //DEBUG(errs() << "WorkList size: " << WorkList.size() << "\n");
 
         Operation &O = WorkList.front();
         TopInst = O.ContextInst;
@@ -2049,19 +2148,23 @@ namespace {
         assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
         assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
 
-        DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
-        if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
-        else DOUT << " context block: " << O.ContextBB->getName();
-        DOUT << "\n";
+        DEBUG(errs() << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
+              if (O.ContextInst) 
+                errs() << " context inst: " << *O.ContextInst;
+              else
+                errs() << " context block: " << O.ContextBB->getName();
+              errs() << "\n";
 
-        DEBUG(IG.dump());
+              VN.dump();
+              IG.dump();
+              VR.dump(););
 
         // If they're both Constant, skip it. Check for contradiction and mark
         // the BB as unreachable if so.
         if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
           if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
             if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
-                ConstantInt::getFalse())
+                ConstantInt::getFalse(*Context))
               UB.mark(TopBB);
 
             WorkList.pop_front();
@@ -2091,10 +2194,10 @@ namespace {
               continue;
             }
 
-            unsigned n1 = VN.valueNumber(O.LHS, Top);
-            unsigned n2 = VN.valueNumber(O.RHS, Top);
+            unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
+            unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
 
-            if (n1 && n1 == n2) {
+            if (n1 == n2) {
               if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
                   O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
                 UB.mark(TopBB);
@@ -2103,19 +2206,16 @@ namespace {
               continue;
             }
 
-            if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
-                (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
+            if (VR.isRelatedBy(n1, n2, Top, LV) ||
+                IG.isRelatedBy(n1, n2, Top, LV)) {
               WorkList.pop_front();
               continue;
             }
 
-            VR.addInequality(O.LHS, O.RHS, Top, LV, this);
+            VR.addInequality(n1, n2, Top, LV, this);
             if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
-                LV == NE) {
-              if (!n1) n1 = IG.newNode(O.LHS);
-              if (!n2) n2 = IG.newNode(O.RHS);
+                LV == NE)
               IG.addInequality(n1, n2, Top, LV);
-            }
 
             if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
               if (aboveOrBelow(I1))
@@ -2126,10 +2226,9 @@ namespace {
                    UE = O.LHS->use_end(); UI != UE;) {
                 Use &TheUse = UI.getUse();
                 ++UI;
-                if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
-                  if (aboveOrBelow(I))
-                    opsToDef(I);
-                }
+                Instruction *I = cast<Instruction>(TheUse.getUser());
+                if (aboveOrBelow(I))
+                  opsToDef(I);
               }
             }
             if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
@@ -2141,10 +2240,9 @@ namespace {
                    UE = O.RHS->use_end(); UI != UE;) {
                 Use &TheUse = UI.getUse();
                 ++UI;
-                if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
-                  if (aboveOrBelow(I))
-                    opsToDef(I);
-                }
+                Instruction *I = cast<Instruction>(TheUse.getUser());
+                if (aboveOrBelow(I))
+                  opsToDef(I);
               }
             }
           }
@@ -2163,18 +2261,11 @@ namespace {
     VRP->UB.mark(VRP->TopBB);
   }
 
-#ifndef NDEBUG
-  bool ValueRanges::isCanonical(Value *V, DomTreeDFS::Node *Subtree,
-                                VRPSolver *VRP) {
-    return V == VRP->VN.canonicalize(V, Subtree);
-  }
-#endif
-
   /// PredicateSimplifier - This class is a simplifier that replaces
   /// one equivalent variable with another. It also tracks what
   /// can't be equal and will solve setcc instructions when possible.
   /// @brief Root of the predicate simplifier optimization.
-  class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
+  class PredicateSimplifier : public FunctionPass {
     DomTreeDFS *DTDFS;
     bool modified;
     ValueNumbering *VN;
@@ -2184,27 +2275,26 @@ namespace {
 
     std::vector<DomTreeDFS::Node *> WorkList;
 
+    LLVMContext *Context;
   public:
     static char ID; // Pass identification, replacement for typeid
-    PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
+    PredicateSimplifier() : FunctionPass(&ID) {}
 
     bool runOnFunction(Function &F);
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequiredID(BreakCriticalEdgesID);
       AU.addRequired<DominatorTree>();
-      AU.addRequired<TargetData>();
-      AU.addPreserved<TargetData>();
     }
 
   private:
-    /// Forwards - Adds new properties into PropertySet and uses them to
+    /// Forwards - Adds new properties to VRPSolver and uses them to
     /// simplify instructions. Because new properties sometimes apply to
     /// a transition from one BasicBlock to another, this will use the
     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
-    /// basic block with the new PropertySet.
+    /// basic block.
     /// @brief Performs abstract execution of the program.
-    class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
+    class Forwards : public InstVisitor<Forwards> {
       friend class InstVisitor<Forwards>;
       PredicateSimplifier *PS;
       DomTreeDFS::Node *DTNode;
@@ -2251,18 +2341,19 @@ namespace {
     // Visits each instruction in the basic block.
     void visitBasicBlock(DomTreeDFS::Node *Node) {
       BasicBlock *BB = Node->getBlock();
-      DOUT << "Entering Basic Block: " << BB->getName()
-           << " (" << Node->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "Entering Basic Block: " << BB->getName()
+            << " (" << Node->getDFSNumIn() << ")\n");
       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
         visitInstruction(I++, Node);
       }
     }
 
-    // Tries to simplify each Instruction and add new properties to
-    // the PropertySet.
+    // Tries to simplify each Instruction and add new properties.
     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
-      DOUT << "Considering instruction " << *I << "\n";
+      DEBUG(errs() << "Considering instruction " << *I << "\n");
+      DEBUG(VN->dump());
       DEBUG(IG->dump());
+      DEBUG(VR->dump());
 
       // Sometimes instructions are killed in earlier analysis.
       if (isInstructionTriviallyDead(I)) {
@@ -2282,7 +2373,7 @@ namespace {
       if (V != I) {
         modified = true;
         ++NumInstruction;
-        DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
+        DEBUG(errs() << "Removing " << *I << ", replacing with " << *V << "\n");
         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
           if (VN->value(n) == I) IG->remove(n);
         VN->remove(I);
@@ -2299,33 +2390,40 @@ namespace {
         if (V != Oper) {
           modified = true;
           ++NumVarsReplaced;
-          DOUT << "Resolving " << *I;
+          DEBUG(errs() << "Resolving " << *I);
           I->setOperand(i, V);
-          DOUT << " into " << *I;
+          DEBUG(errs() << " into " << *I);
         }
       }
 #endif
 
       std::string name = I->getParent()->getName();
-      DOUT << "push (%" << name << ")\n";
+      DEBUG(errs() << "push (%" << name << ")\n");
       Forwards visit(this, DT);
       visit.visit(*I);
-      DOUT << "pop (%" << name << ")\n";
+      DEBUG(errs() << "pop (%" << name << ")\n");
     }
   };
 
   bool PredicateSimplifier::runOnFunction(Function &F) {
     DominatorTree *DT = &getAnalysis<DominatorTree>();
     DTDFS = new DomTreeDFS(DT);
-    TargetData *TD = &getAnalysis<TargetData>();
+    TargetData *TD = getAnalysisIfAvailable<TargetData>();
+
+    // FIXME: PredicateSimplifier should still be able to do basic
+    // optimizations without TargetData. But for now, just exit if
+    // it's not available.
+    if (!TD) return false;
+
+    Context = &F.getContext();
 
-    DOUT << "Entering Function: " << F.getName() << "\n";
+    DEBUG(errs() << "Entering Function: " << F.getName() << "\n");
 
     modified = false;
     DomTreeDFS::Node *Root = DTDFS->getRootNode();
     VN = new ValueNumbering(DTDFS);
     IG = new InequalityGraph(*VN, Root);
-    VR = new ValueRanges(TD);
+    VR = new ValueRanges(*VN, TD, Context);
     WorkList.push_back(Root);
 
     do {
@@ -2337,6 +2435,7 @@ namespace {
     delete DTDFS;
     delete VR;
     delete IG;
+    delete VN;
 
     modified |= UB.kill();
 
@@ -2362,24 +2461,32 @@ namespace {
       return;
     }
 
+    LLVMContext *Context = &BI.getContext();
+
     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
          I != E; ++I) {
       BasicBlock *Dest = (*I)->getBlock();
-      DOUT << "Branch thinking about %" << Dest->getName()
-           << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "Branch thinking about %" << Dest->getName()
+            << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n");
 
       if (Dest == TrueDest) {
-        DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
+        DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
+              << ") true set:\n");
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
-        VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
+        VRP.add(ConstantInt::getTrue(*Context), Condition, ICmpInst::ICMP_EQ);
         VRP.solve();
+        DEBUG(VN.dump());
         DEBUG(IG.dump());
+        DEBUG(VR.dump());
       } else if (Dest == FalseDest) {
-        DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
+        DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
+              << ") false set:\n");
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
-        VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
+        VRP.add(ConstantInt::getFalse(*Context), Condition, ICmpInst::ICMP_EQ);
         VRP.solve();
+        DEBUG(VN.dump());
         DEBUG(IG.dump());
+        DEBUG(VR.dump());
       }
 
       PS->proceedToSuccessor(*I);
@@ -2395,8 +2502,8 @@ namespace {
     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
          I != E; ++I) {
       BasicBlock *BB = (*I)->getBlock();
-      DOUT << "Switch thinking about BB %" << BB->getName()
-           << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "Switch thinking about BB %" << BB->getName()
+            << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n");
 
       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
       if (BB == SI.getDefaultDest()) {
@@ -2414,17 +2521,19 @@ namespace {
 
   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
-    VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
+    VRP.add(Constant::getNullValue(AI.getType()),
+            &AI, ICmpInst::ICMP_NE);
     VRP.solve();
   }
 
   void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
     Value *Ptr = LI.getPointerOperand();
-    // avoid "load uint* null" -> null NE null.
+    // avoid "load i8* null" -> null NE null.
     if (isa<Constant>(Ptr)) return;
 
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
-    VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
+    VRP.add(Constant::getNullValue(Ptr->getType()),
+            Ptr, ICmpInst::ICMP_NE);
     VRP.solve();
   }
 
@@ -2433,27 +2542,30 @@ namespace {
     if (isa<Constant>(Ptr)) return;
 
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
-    VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
+    VRP.add(Constant::getNullValue(Ptr->getType()),
+            Ptr, ICmpInst::ICMP_NE);
     VRP.solve();
   }
 
   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
+    LLVMContext &Context = SI.getContext();
     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
-    VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
-    VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
+    VRP.add(ConstantInt::get(Context, Min), &SI, ICmpInst::ICMP_SLE);
+    VRP.add(ConstantInt::get(Context, Max), &SI, ICmpInst::ICMP_SGE);
     VRP.solve();
   }
 
   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
+    LLVMContext &Context = ZI.getContext();
     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
-    VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
+    VRP.add(ConstantInt::get(Context, Max), &ZI, ICmpInst::ICMP_UGE);
     VRP.solve();
   }
 
@@ -2468,8 +2580,8 @@ namespace {
       case Instruction::SDiv: {
         Value *Divisor = BO.getOperand(1);
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
-        VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
-                ICmpInst::ICMP_NE);
+        VRP.add(Constant::getNullValue(Divisor->getType()), 
+                Divisor, ICmpInst::ICMP_NE);
         VRP.solve();
         break;
       }
@@ -2542,6 +2654,8 @@ namespace {
 
     Pred = IC.getPredicate();
 
+    LLVMContext &Context = IC.getContext();
+
     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
       ConstantInt *NextVal = 0;
       switch (Pred) {
@@ -2549,21 +2663,21 @@ namespace {
         case ICmpInst::ICMP_SLT:
         case ICmpInst::ICMP_ULT:
           if (Op1->getValue() != 0)
-            NextVal = ConstantInt::get(Op1->getValue()-1);
+            NextVal = ConstantInt::get(Context, Op1->getValue()-1);
          break;
         case ICmpInst::ICMP_SGT:
         case ICmpInst::ICMP_UGT:
           if (!Op1->getValue().isAllOnesValue())
-            NextVal = ConstantInt::get(Op1->getValue()+1);
+            NextVal = ConstantInt::get(Context, Op1->getValue()+1);
          break;
-
       }
+
       if (NextVal) {
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
         if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
                             ICmpInst::getInversePredicate(Pred))) {
-          ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
-                                         NextVal, "", &IC);
+          ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ, 
+                                         IC.getOperand(0), NextVal, "");
           NewIC->takeName(&IC);
           IC.replaceAllUsesWith(NewIC);
 
@@ -2579,12 +2693,12 @@ namespace {
       }
     }
   }
-
-  char PredicateSimplifier::ID = 0;
-  RegisterPass<PredicateSimplifier> X("predsimplify",
-                                      "Predicate Simplifier");
 }
 
+char PredicateSimplifier::ID = 0;
+static RegisterPass<PredicateSimplifier>
+X("predsimplify", "Predicate Simplifier");
+
 FunctionPass *llvm::createPredicateSimplifierPass() {
   return new PredicateSimplifier();
 }