Begin the painful process of tearing apart the rat'ss nest that is Constants.cpp...
[oota-llvm.git] / lib / Transforms / Scalar / PredicateSimplifier.cpp
1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Path-sensitive optimizer. In a branch where x == y, replace uses of
11 // x with y. Permits further optimization, such as the elimination of
12 // the unreachable call:
13 //
14 // void test(int *p, int *q)
15 // {
16 //   if (p != q)
17 //     return;
18 // 
19 //   if (*p != *q)
20 //     foo(); // unreachable
21 // }
22 //
23 //===----------------------------------------------------------------------===//
24 //
25 // The InequalityGraph focusses on four properties; equals, not equals,
26 // less-than and less-than-or-equals-to. The greater-than forms are also held
27 // just to allow walking from a lesser node to a greater one. These properties
28 // are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
29 //
30 // These relationships define a graph between values of the same type. Each
31 // Value is stored in a map table that retrieves the associated Node. This
32 // is how EQ relationships are stored; the map contains pointers from equal
33 // Value to the same node. The node contains a most canonical Value* form
34 // and the list of known relationships with other nodes.
35 //
36 // If two nodes are known to be inequal, then they will contain pointers to
37 // each other with an "NE" relationship. If node getNode(%x) is less than
38 // getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39 // <%x, LT>. This allows us to tie nodes together into a graph like this:
40 //
41 //   %a < %b < %c < %d
42 //
43 // with four nodes representing the properties. The InequalityGraph provides
44 // querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
45 // To find a relationship, we start with one of the nodes any binary search
46 // through its list to find where the relationships with the second node start.
47 // Then we iterate through those to find the first relationship that dominates
48 // our context node.
49 //
50 // To create these properties, we wait until a branch or switch instruction
51 // implies that a particular value is true (or false). The VRPSolver is
52 // responsible for analyzing the variable and seeing what new inferences
53 // can be made from each property. For example:
54 //
55 //   %P = icmp ne i32* %ptr, null
56 //   %a = and i1 %P, %Q
57 //   br i1 %a label %cond_true, label %cond_false
58 //
59 // For the true branch, the VRPSolver will start with %a EQ true and look at
60 // the definition of %a and find that it can infer that %P and %Q are both
61 // true. From %P being true, it can infer that %ptr NE null. For the false
62 // branch it can't infer anything from the "and" instruction.
63 //
64 // Besides branches, we can also infer properties from instruction that may
65 // have undefined behaviour in certain cases. For example, the dividend of
66 // a division may never be zero. After the division instruction, we may assume
67 // that the dividend is not equal to zero.
68 //
69 //===----------------------------------------------------------------------===//
70 //
71 // The ValueRanges class stores the known integer bounds of a Value. When we
72 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
73 // %b = [0, 254].
74 //
75 // It never stores an empty range, because that means that the code is
76 // unreachable. It never stores a single-element range since that's an equality
77 // relationship and better stored in the InequalityGraph, nor an empty range
78 // since that is better stored in UnreachableBlocks.
79 //
80 //===----------------------------------------------------------------------===//
81
82 #define DEBUG_TYPE "predsimplify"
83 #include "llvm/Transforms/Scalar.h"
84 #include "llvm/Constants.h"
85 #include "llvm/DerivedTypes.h"
86 #include "llvm/Instructions.h"
87 #include "llvm/Pass.h"
88 #include "llvm/ADT/DepthFirstIterator.h"
89 #include "llvm/ADT/SetOperations.h"
90 #include "llvm/ADT/SetVector.h"
91 #include "llvm/ADT/Statistic.h"
92 #include "llvm/ADT/STLExtras.h"
93 #include "llvm/Analysis/Dominators.h"
94 #include "llvm/Assembly/Writer.h"
95 #include "llvm/Support/CFG.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/ConstantRange.h"
98 #include "llvm/Support/Debug.h"
99 #include "llvm/Support/InstVisitor.h"
100 #include "llvm/Target/TargetData.h"
101 #include "llvm/Transforms/Utils/Local.h"
102 #include <algorithm>
103 #include <deque>
104 #include <stack>
105 using namespace llvm;
106
107 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
108 STATISTIC(NumInstruction , "Number of instructions removed");
109 STATISTIC(NumSimple      , "Number of simple replacements");
110 STATISTIC(NumBlocks      , "Number of blocks marked unreachable");
111 STATISTIC(NumSnuggle     , "Number of comparisons snuggled");
112
113 static const ConstantRange empty(1, false);
114
115 namespace {
116   class DomTreeDFS {
117   public:
118     class Node {
119       friend class DomTreeDFS;
120     public:
121       typedef std::vector<Node *>::iterator       iterator;
122       typedef std::vector<Node *>::const_iterator const_iterator;
123
124       unsigned getDFSNumIn()  const { return DFSin;  }
125       unsigned getDFSNumOut() const { return DFSout; }
126
127       BasicBlock *getBlock() const { return BB; }
128
129       iterator begin() { return Children.begin(); }
130       iterator end()   { return Children.end();   }
131
132       const_iterator begin() const { return Children.begin(); }
133       const_iterator end()   const { return Children.end();   }
134
135       bool dominates(const Node *N) const {
136         return DFSin <= N->DFSin && DFSout >= N->DFSout;
137       }
138
139       bool DominatedBy(const Node *N) const {
140         return N->dominates(this);
141       }
142
143       /// Sorts by the number of descendants. With this, you can iterate
144       /// through a sorted list and the first matching entry is the most
145       /// specific match for your basic block. The order provided is stable;
146       /// DomTreeDFS::Nodes with the same number of descendants are sorted by
147       /// DFS in number.
148       bool operator<(const Node &N) const {
149         unsigned   spread =   DFSout -   DFSin;
150         unsigned N_spread = N.DFSout - N.DFSin;
151         if (spread == N_spread) return DFSin < N.DFSin;
152         return spread < N_spread;
153       }
154       bool operator>(const Node &N) const { return N < *this; }
155
156     private:
157       unsigned DFSin, DFSout;
158       BasicBlock *BB;
159
160       std::vector<Node *> Children;
161     };
162
163     // XXX: this may be slow. Instead of using "new" for each node, consider
164     // putting them in a vector to keep them contiguous.
165     explicit DomTreeDFS(DominatorTree *DT) {
166       std::stack<std::pair<Node *, DomTreeNode *> > S;
167
168       Entry = new Node;
169       Entry->BB = DT->getRootNode()->getBlock();
170       S.push(std::make_pair(Entry, DT->getRootNode()));
171
172       NodeMap[Entry->BB] = Entry;
173
174       while (!S.empty()) {
175         std::pair<Node *, DomTreeNode *> &Pair = S.top();
176         Node *N = Pair.first;
177         DomTreeNode *DTNode = Pair.second;
178         S.pop();
179
180         for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
181              I != E; ++I) {
182           Node *NewNode = new Node;
183           NewNode->BB = (*I)->getBlock();
184           N->Children.push_back(NewNode);
185           S.push(std::make_pair(NewNode, *I));
186
187           NodeMap[NewNode->BB] = NewNode;
188         }
189       }
190
191       renumber();
192
193 #ifndef NDEBUG
194       DEBUG(dump());
195 #endif
196     }
197
198 #ifndef NDEBUG
199     virtual
200 #endif
201     ~DomTreeDFS() {
202       std::stack<Node *> S;
203
204       S.push(Entry);
205       while (!S.empty()) {
206         Node *N = S.top(); S.pop();
207
208         for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
209           S.push(*I);
210
211         delete N;
212       }
213     }
214
215     /// getRootNode - This returns the entry node for the CFG of the function.
216     Node *getRootNode() const { return Entry; }
217
218     /// getNodeForBlock - return the node for the specified basic block.
219     Node *getNodeForBlock(BasicBlock *BB) const {
220       if (!NodeMap.count(BB)) return 0;
221       return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
222     }
223
224     /// dominates - returns true if the basic block for I1 dominates that of
225     /// the basic block for I2. If the instructions belong to the same basic
226     /// block, the instruction first instruction sequentially in the block is
227     /// considered dominating.
228     bool dominates(Instruction *I1, Instruction *I2) {
229       BasicBlock *BB1 = I1->getParent(),
230                  *BB2 = I2->getParent();
231       if (BB1 == BB2) {
232         if (isa<TerminatorInst>(I1)) return false;
233         if (isa<TerminatorInst>(I2)) return true;
234         if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
235         if (!isa<PHINode>(I1) &&  isa<PHINode>(I2)) return false;
236
237         for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
238              I != E; ++I) {
239           if (&*I == I1) return true;
240           else if (&*I == I2) return false;
241         }
242         assert(!"Instructions not found in parent BasicBlock?");
243       } else {
244         Node *Node1 = getNodeForBlock(BB1),
245              *Node2 = getNodeForBlock(BB2);
246         return Node1 && Node2 && Node1->dominates(Node2);
247       }
248       return false; // Not reached
249     }
250
251   private:
252     /// renumber - calculates the depth first search numberings and applies
253     /// them onto the nodes.
254     void renumber() {
255       std::stack<std::pair<Node *, Node::iterator> > S;
256       unsigned n = 0;
257
258       Entry->DFSin = ++n;
259       S.push(std::make_pair(Entry, Entry->begin()));
260
261       while (!S.empty()) {
262         std::pair<Node *, Node::iterator> &Pair = S.top();
263         Node *N = Pair.first;
264         Node::iterator &I = Pair.second;
265
266         if (I == N->end()) {
267           N->DFSout = ++n;
268           S.pop();
269         } else {
270           Node *Next = *I++;
271           Next->DFSin = ++n;
272           S.push(std::make_pair(Next, Next->begin()));
273         }
274       }
275     }
276
277 #ifndef NDEBUG
278     virtual void dump() const {
279       dump(*cerr.stream());
280     }
281
282     void dump(std::ostream &os) const {
283       os << "Predicate simplifier DomTreeDFS: \n";
284       dump(Entry, 0, os);
285       os << "\n\n";
286     }
287
288     void dump(Node *N, int depth, std::ostream &os) const {
289       ++depth;
290       for (int i = 0; i < depth; ++i) { os << " "; }
291       os << "[" << depth << "] ";
292
293       os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
294          << ", " << N->getDFSNumOut() << ")\n";
295
296       for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
297         dump(*I, depth, os);
298     }
299 #endif
300
301     Node *Entry;
302     std::map<BasicBlock *, Node *> NodeMap;
303   };
304
305   // SLT SGT ULT UGT EQ
306   //   0   1   0   1  0 -- GT                  10
307   //   0   1   0   1  1 -- GE                  11
308   //   0   1   1   0  0 -- SGTULT              12
309   //   0   1   1   0  1 -- SGEULE              13
310   //   0   1   1   1  0 -- SGT                 14
311   //   0   1   1   1  1 -- SGE                 15
312   //   1   0   0   1  0 -- SLTUGT              18
313   //   1   0   0   1  1 -- SLEUGE              19
314   //   1   0   1   0  0 -- LT                  20
315   //   1   0   1   0  1 -- LE                  21
316   //   1   0   1   1  0 -- SLT                 22
317   //   1   0   1   1  1 -- SLE                 23
318   //   1   1   0   1  0 -- UGT                 26
319   //   1   1   0   1  1 -- UGE                 27
320   //   1   1   1   0  0 -- ULT                 28
321   //   1   1   1   0  1 -- ULE                 29
322   //   1   1   1   1  0 -- NE                  30
323   enum LatticeBits {
324     EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
325   };
326   enum LatticeVal {
327     GT = SGT_BIT | UGT_BIT,
328     GE = GT | EQ_BIT,
329     LT = SLT_BIT | ULT_BIT,
330     LE = LT | EQ_BIT,
331     NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
332     SGTULT = SGT_BIT | ULT_BIT,
333     SGEULE = SGTULT | EQ_BIT,
334     SLTUGT = SLT_BIT | UGT_BIT,
335     SLEUGE = SLTUGT | EQ_BIT,
336     ULT = SLT_BIT | SGT_BIT | ULT_BIT,
337     UGT = SLT_BIT | SGT_BIT | UGT_BIT,
338     SLT = SLT_BIT | ULT_BIT | UGT_BIT,
339     SGT = SGT_BIT | ULT_BIT | UGT_BIT,
340     SLE = SLT | EQ_BIT,
341     SGE = SGT | EQ_BIT,
342     ULE = ULT | EQ_BIT,
343     UGE = UGT | EQ_BIT
344   };
345
346 #ifndef NDEBUG
347   /// validPredicate - determines whether a given value is actually a lattice
348   /// value. Only used in assertions or debugging.
349   static bool validPredicate(LatticeVal LV) {
350     switch (LV) {
351       case GT: case GE: case LT: case LE: case NE:
352       case SGTULT: case SGT: case SGEULE:
353       case SLTUGT: case SLT: case SLEUGE:
354       case ULT: case UGT:
355       case SLE: case SGE: case ULE: case UGE:
356         return true;
357       default:
358         return false;
359     }
360   }
361 #endif
362
363   /// reversePredicate - reverse the direction of the inequality
364   static LatticeVal reversePredicate(LatticeVal LV) {
365     unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
366
367     if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
368       reverse |= (SLT_BIT|SGT_BIT);
369
370     if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
371       reverse |= (ULT_BIT|UGT_BIT);
372
373     LatticeVal Rev = static_cast<LatticeVal>(reverse);
374     assert(validPredicate(Rev) && "Failed reversing predicate.");
375     return Rev;
376   }
377
378   /// ValueNumbering stores the scope-specific value numbers for a given Value.
379   class VISIBILITY_HIDDEN ValueNumbering {
380
381     /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
382     /// includes the comparison operators necessary to allow you to store it
383     /// in a sorted vector.
384     class VISIBILITY_HIDDEN VNPair {
385     public:
386       Value *V;
387       unsigned index;
388       DomTreeDFS::Node *Subtree;
389
390       VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
391         : V(V), index(index), Subtree(Subtree) {}
392
393       bool operator==(const VNPair &RHS) const {
394         return V == RHS.V && Subtree == RHS.Subtree;
395       }
396
397       bool operator<(const VNPair &RHS) const {
398         if (V != RHS.V) return V < RHS.V;
399         return *Subtree < *RHS.Subtree;
400       }
401
402       bool operator<(Value *RHS) const {
403         return V < RHS;
404       }
405
406       bool operator>(Value *RHS) const {
407         return V > RHS;
408       }
409
410       friend bool operator<(Value *RHS, const VNPair &pair) {
411         return pair.operator>(RHS);
412       }
413     };
414
415     typedef std::vector<VNPair> VNMapType;
416     VNMapType VNMap;
417
418     /// The canonical choice for value number at index.
419     std::vector<Value *> Values;
420
421     DomTreeDFS *DTDFS;
422
423   public:
424 #ifndef NDEBUG
425     virtual ~ValueNumbering() {}
426     virtual void dump() {
427       dump(*cerr.stream());
428     }
429
430     void dump(std::ostream &os) {
431       for (unsigned i = 1; i <= Values.size(); ++i) {
432         os << i << " = ";
433         WriteAsOperand(os, Values[i-1]);
434         os << " {";
435         for (unsigned j = 0; j < VNMap.size(); ++j) {
436           if (VNMap[j].index == i) {
437             WriteAsOperand(os, VNMap[j].V);
438             os << " (" << VNMap[j].Subtree->getDFSNumIn() << ")  ";
439           }
440         }
441         os << "}\n";
442       }
443     }
444 #endif
445
446     /// compare - returns true if V1 is a better canonical value than V2.
447     bool compare(Value *V1, Value *V2) const {
448       if (isa<Constant>(V1))
449         return !isa<Constant>(V2);
450       else if (isa<Constant>(V2))
451         return false;
452       else if (isa<Argument>(V1))
453         return !isa<Argument>(V2);
454       else if (isa<Argument>(V2))
455         return false;
456
457       Instruction *I1 = dyn_cast<Instruction>(V1);
458       Instruction *I2 = dyn_cast<Instruction>(V2);
459
460       if (!I1 || !I2)
461         return V1->getNumUses() < V2->getNumUses();
462
463       return DTDFS->dominates(I1, I2);
464     }
465
466     ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
467
468     /// valueNumber - finds the value number for V under the Subtree. If
469     /// there is no value number, returns zero.
470     unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
471       if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
472           || V->getType() == Type::VoidTy) return 0;
473
474       VNMapType::iterator E = VNMap.end();
475       VNPair pair(V, 0, Subtree);
476       VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
477       while (I != E && I->V == V) {
478         if (I->Subtree->dominates(Subtree))
479           return I->index;
480         ++I;
481       }
482       return 0;
483     }
484
485     /// getOrInsertVN - always returns a value number, creating it if necessary.
486     unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
487       if (unsigned n = valueNumber(V, Subtree))
488         return n;
489       else
490         return newVN(V);
491     }
492
493     /// newVN - creates a new value number. Value V must not already have a
494     /// value number assigned.
495     unsigned newVN(Value *V) {
496       assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
497              "Bad Value for value numbering.");
498       assert(V->getType() != Type::VoidTy && "Won't value number a void value");
499
500       Values.push_back(V);
501
502       VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
503       VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
504       assert((I == VNMap.end() || value(I->index) != V) &&
505              "Attempt to create a duplicate value number.");
506       VNMap.insert(I, pair);
507
508       return Values.size();
509     }
510
511     /// value - returns the Value associated with a value number.
512     Value *value(unsigned index) const {
513       assert(index != 0 && "Zero index is reserved for not found.");
514       assert(index <= Values.size() && "Index out of range.");
515       return Values[index-1];
516     }
517
518     /// canonicalize - return a Value that is equal to V under Subtree.
519     Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
520       if (isa<Constant>(V)) return V;
521
522       if (unsigned n = valueNumber(V, Subtree))
523         return value(n);
524       else
525         return V;
526     }
527
528     /// addEquality - adds that value V belongs to the set of equivalent
529     /// values defined by value number n under Subtree.
530     void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
531       assert(canonicalize(value(n), Subtree) == value(n) &&
532              "Node's 'canonical' choice isn't best within this subtree.");
533
534       // Suppose that we are given "%x -> node #1 (%y)". The problem is that
535       // we may already have "%z -> node #2 (%x)" somewhere above us in the
536       // graph. We need to find those edges and add "%z -> node #1 (%y)"
537       // to keep the lookups canonical.
538
539       std::vector<Value *> ToRepoint(1, V);
540
541       if (unsigned Conflict = valueNumber(V, Subtree)) {
542         for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
543              I != E; ++I) {
544           if (I->index == Conflict && I->Subtree->dominates(Subtree))
545             ToRepoint.push_back(I->V);
546         }
547       }
548
549       for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
550            VE = ToRepoint.end(); VI != VE; ++VI) {
551         Value *V = *VI;
552
553         VNPair pair(V, n, Subtree);
554         VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
555         VNMapType::iterator I = std::lower_bound(B, E, pair);
556         if (I != E && I->V == V && I->Subtree == Subtree)
557           I->index = n; // Update best choice
558         else
559           VNMap.insert(I, pair); // New Value
560
561         // XXX: we currently don't have to worry about updating values with
562         // more specific Subtrees, but we will need to for PHI node support.
563
564 #ifndef NDEBUG
565         Value *V_n = value(n);
566         if (isa<Constant>(V) && isa<Constant>(V_n)) {
567           assert(V == V_n && "Constant equals different constant?");
568         }
569 #endif
570       }
571     }
572
573     /// remove - removes all references to value V.
574     void remove(Value *V) {
575       VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
576       VNPair pair(V, 0, DTDFS->getRootNode());
577       VNMapType::iterator J = std::upper_bound(B, E, pair);
578       VNMapType::iterator I = J;
579
580       while (I != B && (I == E || I->V == V)) --I;
581
582       VNMap.erase(I, J);
583     }
584   };
585
586   /// The InequalityGraph stores the relationships between values.
587   /// Each Value in the graph is assigned to a Node. Nodes are pointer
588   /// comparable for equality. The caller is expected to maintain the logical
589   /// consistency of the system.
590   ///
591   /// The InequalityGraph class may invalidate Node*s after any mutator call.
592   /// @brief The InequalityGraph stores the relationships between values.
593   class VISIBILITY_HIDDEN InequalityGraph {
594     ValueNumbering &VN;
595     DomTreeDFS::Node *TreeRoot;
596
597     InequalityGraph();                  // DO NOT IMPLEMENT
598     InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
599   public:
600     InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
601       : VN(VN), TreeRoot(TreeRoot) {}
602
603     class Node;
604
605     /// An Edge is contained inside a Node making one end of the edge implicit
606     /// and contains a pointer to the other end. The edge contains a lattice
607     /// value specifying the relationship and an DomTreeDFS::Node specifying
608     /// the root in the dominator tree to which this edge applies.
609     class VISIBILITY_HIDDEN Edge {
610     public:
611       Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
612         : To(T), LV(V), Subtree(ST) {}
613
614       unsigned To;
615       LatticeVal LV;
616       DomTreeDFS::Node *Subtree;
617
618       bool operator<(const Edge &edge) const {
619         if (To != edge.To) return To < edge.To;
620         return *Subtree < *edge.Subtree;
621       }
622
623       bool operator<(unsigned to) const {
624         return To < to;
625       }
626
627       bool operator>(unsigned to) const {
628         return To > to;
629       }
630
631       friend bool operator<(unsigned to, const Edge &edge) {
632         return edge.operator>(to);
633       }
634     };
635
636     /// A single node in the InequalityGraph. This stores the canonical Value
637     /// for the node, as well as the relationships with the neighbours.
638     ///
639     /// @brief A single node in the InequalityGraph.
640     class VISIBILITY_HIDDEN Node {
641       friend class InequalityGraph;
642
643       typedef SmallVector<Edge, 4> RelationsType;
644       RelationsType Relations;
645
646       // TODO: can this idea improve performance?
647       //friend class std::vector<Node>;
648       //Node(Node &N) { RelationsType.swap(N.RelationsType); }
649
650     public:
651       typedef RelationsType::iterator       iterator;
652       typedef RelationsType::const_iterator const_iterator;
653
654 #ifndef NDEBUG
655       virtual ~Node() {}
656       virtual void dump() const {
657         dump(*cerr.stream());
658       }
659     private:
660       void dump(std::ostream &os) const {
661         static const std::string names[32] =
662           { "000000", "000001", "000002", "000003", "000004", "000005",
663             "000006", "000007", "000008", "000009", "     >", "    >=",
664             "  s>u<", "s>=u<=", "    s>", "   s>=", "000016", "000017",
665             "  s<u>", "s<=u>=", "     <", "    <=", "    s<", "   s<=",
666             "000024", "000025", "    u>", "   u>=", "    u<", "   u<=",
667             "    !=", "000031" };
668         for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
669           os << names[NI->LV] << " " << NI->To
670              << " (" << NI->Subtree->getDFSNumIn() << "), ";
671         }
672       }
673     public:
674 #endif
675
676       iterator begin()             { return Relations.begin(); }
677       iterator end()               { return Relations.end();   }
678       const_iterator begin() const { return Relations.begin(); }
679       const_iterator end()   const { return Relations.end();   }
680
681       iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
682         iterator E = end();
683         for (iterator I = std::lower_bound(begin(), E, n);
684              I != E && I->To == n; ++I) {
685           if (Subtree->DominatedBy(I->Subtree))
686             return I;
687         }
688         return E;
689       }
690
691       const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
692         const_iterator E = end();
693         for (const_iterator I = std::lower_bound(begin(), E, n);
694              I != E && I->To == n; ++I) {
695           if (Subtree->DominatedBy(I->Subtree))
696             return I;
697         }
698         return E;
699       }
700
701       /// update - updates the lattice value for a given node, creating a new
702       /// entry if one doesn't exist. The new lattice value must not be
703       /// inconsistent with any previously existing value.
704       void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
705         assert(validPredicate(R) && "Invalid predicate.");
706
707         Edge edge(n, R, Subtree);
708         iterator B = begin(), E = end();
709         iterator I = std::lower_bound(B, E, edge);
710
711         iterator J = I;
712         while (J != E && J->To == n) {
713           if (Subtree->DominatedBy(J->Subtree))
714             break;
715           ++J;
716         }
717
718         if (J != E && J->To == n) {
719           edge.LV = static_cast<LatticeVal>(J->LV & R);
720           assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
721
722           if (edge.LV == J->LV)
723             return; // This update adds nothing new.
724         }
725
726         if (I != B) {
727           // We also have to tighten any edge beneath our update.
728           for (iterator K = I - 1; K->To == n; --K) {
729             if (K->Subtree->DominatedBy(Subtree)) {
730               LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
731               assert(validPredicate(LV) && "Invalid union of lattice values");
732               K->LV = LV;
733             }
734             if (K == B) break;
735           }
736         }
737
738         // Insert new edge at Subtree if it isn't already there.
739         if (I == E || I->To != n || Subtree != I->Subtree)
740           Relations.insert(I, edge);
741       }
742     };
743
744   private:
745
746     std::vector<Node> Nodes;
747
748   public:
749     /// node - returns the node object at a given value number. The pointer
750     /// returned may be invalidated on the next call to node().
751     Node *node(unsigned index) {
752       assert(VN.value(index)); // This triggers the necessary checks.
753       if (Nodes.size() < index) Nodes.resize(index);
754       return &Nodes[index-1];
755     }
756
757     /// isRelatedBy - true iff n1 op n2
758     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
759                      LatticeVal LV) {
760       if (n1 == n2) return LV & EQ_BIT;
761
762       Node *N1 = node(n1);
763       Node::iterator I = N1->find(n2, Subtree), E = N1->end();
764       if (I != E) return (I->LV & LV) == I->LV;
765
766       return false;
767     }
768
769     // The add* methods assume that your input is logically valid and may 
770     // assertion-fail or infinitely loop if you attempt a contradiction.
771
772     /// addInequality - Sets n1 op n2.
773     /// It is also an error to call this on an inequality that is already true.
774     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
775                        LatticeVal LV1) {
776       assert(n1 != n2 && "A node can't be inequal to itself.");
777
778       if (LV1 != NE)
779         assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
780                "Contradictory inequality.");
781
782       // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
783       // add %a < %n2 too. This keeps the graph fully connected.
784       if (LV1 != NE) {
785         // Break up the relationship into signed and unsigned comparison parts.
786         // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
787         // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
788         // should have the EQ_BIT iff it's set for both op1 and op2.
789
790         unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
791         unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
792
793         for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
794           if (I->LV != NE && I->To != n2) {
795
796             DomTreeDFS::Node *Local_Subtree = NULL;
797             if (Subtree->DominatedBy(I->Subtree))
798               Local_Subtree = Subtree;
799             else if (I->Subtree->DominatedBy(Subtree))
800               Local_Subtree = I->Subtree;
801
802             if (Local_Subtree) {
803               unsigned new_relationship = 0;
804               LatticeVal ILV = reversePredicate(I->LV);
805               unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
806               unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
807
808               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
809                 new_relationship |= ILV_s;
810               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
811                 new_relationship |= ILV_u;
812
813               if (new_relationship) {
814                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
815                   new_relationship |= (SLT_BIT|SGT_BIT);
816                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
817                   new_relationship |= (ULT_BIT|UGT_BIT);
818                 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
819                   new_relationship |= EQ_BIT;
820
821                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
822
823                 node(I->To)->update(n2, NewLV, Local_Subtree);
824                 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
825               }
826             }
827           }
828         }
829
830         for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
831           if (I->LV != NE && I->To != n1) {
832             DomTreeDFS::Node *Local_Subtree = NULL;
833             if (Subtree->DominatedBy(I->Subtree))
834               Local_Subtree = Subtree;
835             else if (I->Subtree->DominatedBy(Subtree))
836               Local_Subtree = I->Subtree;
837
838             if (Local_Subtree) {
839               unsigned new_relationship = 0;
840               unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
841               unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
842
843               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
844                 new_relationship |= ILV_s;
845
846               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
847                 new_relationship |= ILV_u;
848
849               if (new_relationship) {
850                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
851                   new_relationship |= (SLT_BIT|SGT_BIT);
852                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
853                   new_relationship |= (ULT_BIT|UGT_BIT);
854                 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
855                   new_relationship |= EQ_BIT;
856
857                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
858
859                 node(n1)->update(I->To, NewLV, Local_Subtree);
860                 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
861               }
862             }
863           }
864         }
865       }
866
867       node(n1)->update(n2, LV1, Subtree);
868       node(n2)->update(n1, reversePredicate(LV1), Subtree);
869     }
870
871     /// remove - removes a node from the graph by removing all references to
872     /// and from it.
873     void remove(unsigned n) {
874       Node *N = node(n);
875       for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
876         Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
877         do {
878           node(NI->To)->Relations.erase(Iter);
879           Iter = node(NI->To)->find(n, TreeRoot);
880         } while (Iter != node(NI->To)->end());
881       }
882       N->Relations.clear();
883     }
884
885 #ifndef NDEBUG
886     virtual ~InequalityGraph() {}
887     virtual void dump() {
888       dump(*cerr.stream());
889     }
890
891     void dump(std::ostream &os) {
892       for (unsigned i = 1; i <= Nodes.size(); ++i) {
893         os << i << " = {";
894         node(i)->dump(os);
895         os << "}\n";
896       }
897     }
898 #endif
899   };
900
901   class VRPSolver;
902
903   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
904   /// in the InequalityGraph.
905   class VISIBILITY_HIDDEN ValueRanges {
906     ValueNumbering &VN;
907     TargetData *TD;
908
909     class VISIBILITY_HIDDEN ScopedRange {
910       typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
911               RangeListType;
912       RangeListType RangeList;
913
914       static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
915                       const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
916         return *LHS.first < *RHS.first;
917       }
918
919     public:
920 #ifndef NDEBUG
921       virtual ~ScopedRange() {}
922       virtual void dump() const {
923         dump(*cerr.stream());
924       }
925
926       void dump(std::ostream &os) const {
927         os << "{";
928         for (const_iterator I = begin(), E = end(); I != E; ++I) {
929           os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
930         }
931         os << "}";
932       }
933 #endif
934
935       typedef RangeListType::iterator       iterator;
936       typedef RangeListType::const_iterator const_iterator;
937
938       iterator begin() { return RangeList.begin(); }
939       iterator end()   { return RangeList.end(); }
940       const_iterator begin() const { return RangeList.begin(); }
941       const_iterator end()   const { return RangeList.end(); }
942
943       iterator find(DomTreeDFS::Node *Subtree) {
944         iterator E = end();
945         iterator I = std::lower_bound(begin(), E,
946                                       std::make_pair(Subtree, empty), swo);
947
948         while (I != E && !I->first->dominates(Subtree)) ++I;
949         return I;
950       }
951
952       const_iterator find(DomTreeDFS::Node *Subtree) const {
953         const_iterator E = end();
954         const_iterator I = std::lower_bound(begin(), E,
955                                             std::make_pair(Subtree, empty), swo);
956
957         while (I != E && !I->first->dominates(Subtree)) ++I;
958         return I;
959       }
960
961       void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
962         assert(!CR.isEmptySet() && "Empty ConstantRange.");
963         assert(!CR.isSingleElement() && "Refusing to store single element.");
964
965         iterator E = end();
966         iterator I =
967             std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
968
969         if (I != end() && I->first == Subtree) {
970           ConstantRange CR2 = I->second.maximalIntersectWith(CR);
971           assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
972                  "Invalid union of ranges.");
973           I->second = CR2;
974         } else
975           RangeList.insert(I, std::make_pair(Subtree, CR));
976       }
977     };
978
979     std::vector<ScopedRange> Ranges;
980
981     void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
982       if (CR.isFullSet()) return;
983       if (Ranges.size() < n) Ranges.resize(n);
984       Ranges[n-1].update(CR, Subtree);
985     }
986
987     /// create - Creates a ConstantRange that matches the given LatticeVal
988     /// relation with a given integer.
989     ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
990       assert(!CR.isEmptySet() && "Can't deal with empty set.");
991
992       if (LV == NE)
993         return ConstantRange::makeICmpRegion(ICmpInst::ICMP_NE, CR);
994
995       unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
996       unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
997       bool hasEQ = LV & EQ_BIT;
998
999       ConstantRange Range(CR.getBitWidth());
1000
1001       if (LV_s == SGT_BIT) {
1002         Range = Range.maximalIntersectWith(ConstantRange::makeICmpRegion(
1003                     hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1004       } else if (LV_s == SLT_BIT) {
1005         Range = Range.maximalIntersectWith(ConstantRange::makeICmpRegion(
1006                     hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1007       }
1008
1009       if (LV_u == UGT_BIT) {
1010         Range = Range.maximalIntersectWith(ConstantRange::makeICmpRegion(
1011                     hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1012       } else if (LV_u == ULT_BIT) {
1013         Range = Range.maximalIntersectWith(ConstantRange::makeICmpRegion(
1014                     hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1015       }
1016
1017       return Range;
1018     }
1019
1020 #ifndef NDEBUG
1021     bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1022       return V == VN.canonicalize(V, Subtree);
1023     }
1024 #endif
1025
1026   public:
1027
1028     ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
1029
1030 #ifndef NDEBUG
1031     virtual ~ValueRanges() {}
1032
1033     virtual void dump() const {
1034       dump(*cerr.stream());
1035     }
1036
1037     void dump(std::ostream &os) const {
1038       for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1039         os << (i+1) << " = ";
1040         Ranges[i].dump(os);
1041         os << "\n";
1042       }
1043     }
1044 #endif
1045
1046     /// range - looks up the ConstantRange associated with a value number.
1047     ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1048       assert(VN.value(n)); // performs range checks
1049
1050       if (n <= Ranges.size()) {
1051         ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1052         if (I != Ranges[n-1].end()) return I->second;
1053       }
1054
1055       Value *V = VN.value(n);
1056       ConstantRange CR = range(V);
1057       return CR;
1058     }
1059
1060     /// range - determine a range from a Value without performing any lookups.
1061     ConstantRange range(Value *V) const {
1062       if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1063         return ConstantRange(C->getValue());
1064       else if (isa<ConstantPointerNull>(V))
1065         return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1066       else
1067         return ConstantRange(typeToWidth(V->getType()));
1068     }
1069
1070     // typeToWidth - returns the number of bits necessary to store a value of
1071     // this type, or zero if unknown.
1072     uint32_t typeToWidth(const Type *Ty) const {
1073       if (TD)
1074         return TD->getTypeSizeInBits(Ty);
1075       else
1076         return Ty->getPrimitiveSizeInBits();
1077     }
1078
1079     static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1080                             LatticeVal LV) {
1081       switch (LV) {
1082       default: assert(!"Impossible lattice value!");
1083       case NE:
1084         return CR1.maximalIntersectWith(CR2).isEmptySet();
1085       case ULT:
1086         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1087       case ULE:
1088         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1089       case UGT:
1090         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1091       case UGE:
1092         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1093       case SLT:
1094         return CR1.getSignedMax().slt(CR2.getSignedMin());
1095       case SLE:
1096         return CR1.getSignedMax().sle(CR2.getSignedMin());
1097       case SGT:
1098         return CR1.getSignedMin().sgt(CR2.getSignedMax());
1099       case SGE:
1100         return CR1.getSignedMin().sge(CR2.getSignedMax());
1101       case LT:
1102         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1103                CR1.getSignedMax().slt(CR2.getUnsignedMin());
1104       case LE:
1105         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1106                CR1.getSignedMax().sle(CR2.getUnsignedMin());
1107       case GT:
1108         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1109                CR1.getSignedMin().sgt(CR2.getSignedMax());
1110       case GE:
1111         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1112                CR1.getSignedMin().sge(CR2.getSignedMax());
1113       case SLTUGT:
1114         return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1115                CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1116       case SLEUGE:
1117         return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1118                CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1119       case SGTULT:
1120         return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1121                CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1122       case SGEULE:
1123         return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1124                CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1125       }
1126     }
1127
1128     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1129                      LatticeVal LV) {
1130       ConstantRange CR1 = range(n1, Subtree);
1131       ConstantRange CR2 = range(n2, Subtree);
1132
1133       // True iff all values in CR1 are LV to all values in CR2.
1134       return isRelatedBy(CR1, CR2, LV);
1135     }
1136
1137     void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1138                        VRPSolver *VRP);
1139     void markBlock(VRPSolver *VRP);
1140
1141     void mergeInto(Value **I, unsigned n, unsigned New,
1142                    DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1143       ConstantRange CR_New = range(New, Subtree);
1144       ConstantRange Merged = CR_New;
1145
1146       for (; n != 0; ++I, --n) {
1147         unsigned i = VN.valueNumber(*I, Subtree);
1148         ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1149         if (CR_Kill.isFullSet()) continue;
1150         Merged = Merged.maximalIntersectWith(CR_Kill);
1151       }
1152
1153       if (Merged.isFullSet() || Merged == CR_New) return;
1154
1155       applyRange(New, Merged, Subtree, VRP);
1156     }
1157
1158     void applyRange(unsigned n, const ConstantRange &CR,
1159                     DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1160       ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
1161       if (Merged.isEmptySet()) {
1162         markBlock(VRP);
1163         return;
1164       }
1165
1166       if (const APInt *I = Merged.getSingleElement()) {
1167         Value *V = VN.value(n); // XXX: redesign worklist.
1168         const Type *Ty = V->getType();
1169         if (Ty->isInteger()) {
1170           addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1171           return;
1172         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1173           assert(*I == 0 && "Pointer is null but not zero?");
1174           addToWorklist(V, ConstantPointerNull::get(PTy),
1175                         ICmpInst::ICMP_EQ, VRP);
1176           return;
1177         }
1178       }
1179
1180       update(n, Merged, Subtree);
1181     }
1182
1183     void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1184                       VRPSolver *VRP) {
1185       ConstantRange CR1 = range(n1, Subtree);
1186       ConstantRange CR2 = range(n2, Subtree);
1187
1188       uint32_t W = CR1.getBitWidth();
1189
1190       if (const APInt *I = CR1.getSingleElement()) {
1191         if (CR2.isFullSet()) {
1192           ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1193           applyRange(n2, NewCR2, Subtree, VRP);
1194         } else if (*I == CR2.getLower()) {
1195           APInt NewLower(CR2.getLower() + 1),
1196                 NewUpper(CR2.getUpper());
1197           if (NewLower == NewUpper)
1198             NewLower = NewUpper = APInt::getMinValue(W);
1199
1200           ConstantRange NewCR2(NewLower, NewUpper);
1201           applyRange(n2, NewCR2, Subtree, VRP);
1202         } else if (*I == CR2.getUpper() - 1) {
1203           APInt NewLower(CR2.getLower()),
1204                 NewUpper(CR2.getUpper() - 1);
1205           if (NewLower == NewUpper)
1206             NewLower = NewUpper = APInt::getMinValue(W);
1207
1208           ConstantRange NewCR2(NewLower, NewUpper);
1209           applyRange(n2, NewCR2, Subtree, VRP);
1210         }
1211       }
1212
1213       if (const APInt *I = CR2.getSingleElement()) {
1214         if (CR1.isFullSet()) {
1215           ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1216           applyRange(n1, NewCR1, Subtree, VRP);
1217         } else if (*I == CR1.getLower()) {
1218           APInt NewLower(CR1.getLower() + 1),
1219                 NewUpper(CR1.getUpper());
1220           if (NewLower == NewUpper)
1221             NewLower = NewUpper = APInt::getMinValue(W);
1222
1223           ConstantRange NewCR1(NewLower, NewUpper);
1224           applyRange(n1, NewCR1, Subtree, VRP);
1225         } else if (*I == CR1.getUpper() - 1) {
1226           APInt NewLower(CR1.getLower()),
1227                 NewUpper(CR1.getUpper() - 1);
1228           if (NewLower == NewUpper)
1229             NewLower = NewUpper = APInt::getMinValue(W);
1230
1231           ConstantRange NewCR1(NewLower, NewUpper);
1232           applyRange(n1, NewCR1, Subtree, VRP);
1233         }
1234       }
1235     }
1236
1237     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1238                        LatticeVal LV, VRPSolver *VRP) {
1239       assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1240
1241       if (LV == NE) {
1242         addNotEquals(n1, n2, Subtree, VRP);
1243         return;
1244       }
1245
1246       ConstantRange CR1 = range(n1, Subtree);
1247       ConstantRange CR2 = range(n2, Subtree);
1248
1249       if (!CR1.isSingleElement()) {
1250         ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
1251         if (NewCR1 != CR1)
1252           applyRange(n1, NewCR1, Subtree, VRP);
1253       }
1254
1255       if (!CR2.isSingleElement()) {
1256         ConstantRange NewCR2 = CR2.maximalIntersectWith(
1257                                        create(reversePredicate(LV), CR1));
1258         if (NewCR2 != CR2)
1259           applyRange(n2, NewCR2, Subtree, VRP);
1260       }
1261     }
1262   };
1263
1264   /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1265   /// another discovered to be unreachable. This is used to cull the graph when
1266   /// analyzing instructions, and to mark blocks with the "unreachable"
1267   /// terminator instruction after the function has executed.
1268   class VISIBILITY_HIDDEN UnreachableBlocks {
1269   private:
1270     std::vector<BasicBlock *> DeadBlocks;
1271
1272   public:
1273     /// mark - mark a block as dead
1274     void mark(BasicBlock *BB) {
1275       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1276       std::vector<BasicBlock *>::iterator I =
1277         std::lower_bound(DeadBlocks.begin(), E, BB);
1278
1279       if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1280     }
1281
1282     /// isDead - returns whether a block is known to be dead already
1283     bool isDead(BasicBlock *BB) {
1284       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1285       std::vector<BasicBlock *>::iterator I =
1286         std::lower_bound(DeadBlocks.begin(), E, BB);
1287
1288       return I != E && *I == BB;
1289     }
1290
1291     /// kill - replace the dead blocks' terminator with an UnreachableInst.
1292     bool kill() {
1293       bool modified = false;
1294       for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1295            E = DeadBlocks.end(); I != E; ++I) {
1296         BasicBlock *BB = *I;
1297
1298         DOUT << "unreachable block: " << BB->getName() << "\n";
1299
1300         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1301              SI != SE; ++SI) {
1302           BasicBlock *Succ = *SI;
1303           Succ->removePredecessor(BB);
1304         }
1305
1306         TerminatorInst *TI = BB->getTerminator();
1307         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1308         TI->eraseFromParent();
1309         new UnreachableInst(BB);
1310         ++NumBlocks;
1311         modified = true;
1312       }
1313       DeadBlocks.clear();
1314       return modified;
1315     }
1316   };
1317
1318   /// VRPSolver keeps track of how changes to one variable affect other
1319   /// variables, and forwards changes along to the InequalityGraph. It
1320   /// also maintains the correct choice for "canonical" in the IG.
1321   /// @brief VRPSolver calculates inferences from a new relationship.
1322   class VISIBILITY_HIDDEN VRPSolver {
1323   private:
1324     friend class ValueRanges;
1325
1326     struct Operation {
1327       Value *LHS, *RHS;
1328       ICmpInst::Predicate Op;
1329
1330       BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1331       Instruction *ContextInst;
1332     };
1333     std::deque<Operation> WorkList;
1334
1335     ValueNumbering &VN;
1336     InequalityGraph &IG;
1337     UnreachableBlocks &UB;
1338     ValueRanges &VR;
1339     DomTreeDFS *DTDFS;
1340     DomTreeDFS::Node *Top;
1341     BasicBlock *TopBB;
1342     Instruction *TopInst;
1343     bool &modified;
1344     LLVMContext *Context;
1345
1346     typedef InequalityGraph::Node Node;
1347
1348     // below - true if the Instruction is dominated by the current context
1349     // block or instruction
1350     bool below(Instruction *I) {
1351       BasicBlock *BB = I->getParent();
1352       if (TopInst && TopInst->getParent() == BB) {
1353         if (isa<TerminatorInst>(TopInst)) return false;
1354         if (isa<TerminatorInst>(I)) return true;
1355         if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1356         if (!isa<PHINode>(TopInst) &&  isa<PHINode>(I)) return false;
1357
1358         for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1359              Iter != E; ++Iter) {
1360           if (&*Iter == TopInst) return true;
1361           else if (&*Iter == I) return false;
1362         }
1363         assert(!"Instructions not found in parent BasicBlock?");
1364       } else {
1365         DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1366         if (!Node) return false;
1367         return Top->dominates(Node);
1368       }
1369       return false; // Not reached
1370     }
1371
1372     // aboveOrBelow - true if the Instruction either dominates or is dominated
1373     // by the current context block or instruction
1374     bool aboveOrBelow(Instruction *I) {
1375       BasicBlock *BB = I->getParent();
1376       DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1377       if (!Node) return false;
1378
1379       return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1380     }
1381
1382     bool makeEqual(Value *V1, Value *V2) {
1383       DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
1384       DOUT << "context is ";
1385       if (TopInst) DOUT << "I: " << *TopInst << "\n";
1386       else DOUT << "BB: " << TopBB->getName()
1387                 << "(" << Top->getDFSNumIn() << ")\n";
1388
1389       assert(V1->getType() == V2->getType() &&
1390              "Can't make two values with different types equal.");
1391
1392       if (V1 == V2) return true;
1393
1394       if (isa<Constant>(V1) && isa<Constant>(V2))
1395         return false;
1396
1397       unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1398
1399       if (n1 && n2) {
1400         if (n1 == n2) return true;
1401         if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1402       }
1403
1404       if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1405       if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1406
1407       assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1408
1409       assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1410
1411       SetVector<unsigned> Remove;
1412       if (n2) Remove.insert(n2);
1413
1414       if (n1 && n2) {
1415         // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1416         // We can't just merge %x and %y because the relationship with %z would
1417         // be EQ and that's invalid. What we're doing is looking for any nodes
1418         // %z such that %x <= %z and %y >= %z, and vice versa.
1419
1420         Node::iterator end = IG.node(n2)->end();
1421
1422         // Find the intersection between N1 and N2 which is dominated by
1423         // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1424         // Remove.
1425         for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1426              I != E; ++I) {
1427           if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1428
1429           unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1430           unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1431           Node::iterator NI = IG.node(n2)->find(I->To, Top);
1432           if (NI != end) {
1433             LatticeVal NILV = reversePredicate(NI->LV);
1434             unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1435             unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1436
1437             if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1438                 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1439               Remove.insert(I->To);
1440           }
1441         }
1442
1443         // See if one of the nodes about to be removed is actually a better
1444         // canonical choice than n1.
1445         unsigned orig_n1 = n1;
1446         SetVector<unsigned>::iterator DontRemove = Remove.end();
1447         for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1448              E = Remove.end(); I != E; ++I) {
1449           unsigned n = *I;
1450           Value *V = VN.value(n);
1451           if (VN.compare(V, V1)) {
1452             V1 = V;
1453             n1 = n;
1454             DontRemove = I;
1455           }
1456         }
1457         if (DontRemove != Remove.end()) {
1458           unsigned n = *DontRemove;
1459           Remove.remove(n);
1460           Remove.insert(orig_n1);
1461         }
1462       }
1463
1464       // We'd like to allow makeEqual on two values to perform a simple
1465       // substitution without creating nodes in the IG whenever possible.
1466       //
1467       // The first iteration through this loop operates on V2 before going
1468       // through the Remove list and operating on those too. If all of the
1469       // iterations performed simple replacements then we exit early.
1470       bool mergeIGNode = false;
1471       unsigned i = 0;
1472       for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1473         if (i) R = VN.value(Remove[i]); // skip n2.
1474
1475         // Try to replace the whole instruction. If we can, we're done.
1476         Instruction *I2 = dyn_cast<Instruction>(R);
1477         if (I2 && below(I2)) {
1478           std::vector<Instruction *> ToNotify;
1479           for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
1480                UI != UE;) {
1481             Use &TheUse = UI.getUse();
1482             ++UI;
1483             Instruction *I = cast<Instruction>(TheUse.getUser());
1484             ToNotify.push_back(I);
1485           }
1486
1487           DOUT << "Simply removing " << *I2
1488                << ", replacing with " << *V1 << "\n";
1489           I2->replaceAllUsesWith(V1);
1490           // leave it dead; it'll get erased later.
1491           ++NumInstruction;
1492           modified = true;
1493
1494           for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1495                IE = ToNotify.end(); II != IE; ++II) {
1496             opsToDef(*II);
1497           }
1498
1499           continue;
1500         }
1501
1502         // Otherwise, replace all dominated uses.
1503         for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1504              UI != UE;) {
1505           Use &TheUse = UI.getUse();
1506           ++UI;
1507           if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1508             if (below(I)) {
1509               TheUse.set(V1);
1510               modified = true;
1511               ++NumVarsReplaced;
1512               opsToDef(I);
1513             }
1514           }
1515         }
1516
1517         // If that killed the instruction, stop here.
1518         if (I2 && isInstructionTriviallyDead(I2)) {
1519           DOUT << "Killed all uses of " << *I2
1520                << ", replacing with " << *V1 << "\n";
1521           continue;
1522         }
1523
1524         // If we make it to here, then we will need to create a node for N1.
1525         // Otherwise, we can skip out early!
1526         mergeIGNode = true;
1527       }
1528
1529       if (!isa<Constant>(V1)) {
1530         if (Remove.empty()) {
1531           VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1532         } else {
1533           std::vector<Value*> RemoveVals;
1534           RemoveVals.reserve(Remove.size());
1535
1536           for (SetVector<unsigned>::iterator I = Remove.begin(),
1537                E = Remove.end(); I != E; ++I) {
1538             Value *V = VN.value(*I);
1539             if (!V->use_empty())
1540               RemoveVals.push_back(V);
1541           }
1542           VR.mergeInto(&RemoveVals[0], RemoveVals.size(), 
1543                        VN.getOrInsertVN(V1, Top), Top, this);
1544         }
1545       }
1546
1547       if (mergeIGNode) {
1548         // Create N1.
1549         if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1550         IG.node(n1); // Ensure that IG.Nodes won't get resized
1551
1552         // Migrate relationships from removed nodes to N1.
1553         for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1554              I != E; ++I) {
1555           unsigned n = *I;
1556           for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1557                NI != NE; ++NI) {
1558             if (NI->Subtree->DominatedBy(Top)) {
1559               if (NI->To == n1) {
1560                 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1561                 continue;
1562               }
1563               if (Remove.count(NI->To))
1564                 continue;
1565
1566               IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1567               IG.node(n1)->update(NI->To, NI->LV, Top);
1568             }
1569           }
1570         }
1571
1572         // Point V2 (and all items in Remove) to N1.
1573         if (!n2)
1574           VN.addEquality(n1, V2, Top);
1575         else {
1576           for (SetVector<unsigned>::iterator I = Remove.begin(),
1577                E = Remove.end(); I != E; ++I) {
1578             VN.addEquality(n1, VN.value(*I), Top);
1579           }
1580         }
1581
1582         // If !Remove.empty() then V2 = Remove[0]->getValue().
1583         // Even when Remove is empty, we still want to process V2.
1584         i = 0;
1585         for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1586           if (i) R = VN.value(Remove[i]); // skip n2.
1587
1588           if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1589             if (aboveOrBelow(I2))
1590             defToOps(I2);
1591           }
1592           for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1593                UI != UE;) {
1594             Use &TheUse = UI.getUse();
1595             ++UI;
1596             if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1597               if (aboveOrBelow(I))
1598                 opsToDef(I);
1599             }
1600           }
1601         }
1602       }
1603
1604       // re-opsToDef all dominated users of V1.
1605       if (Instruction *I = dyn_cast<Instruction>(V1)) {
1606         for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1607              UI != UE;) {
1608           Use &TheUse = UI.getUse();
1609           ++UI;
1610           Value *V = TheUse.getUser();
1611           if (!V->use_empty()) {
1612             Instruction *Inst = cast<Instruction>(V);
1613             if (aboveOrBelow(Inst))
1614               opsToDef(Inst);
1615           }
1616         }
1617       }
1618
1619       return true;
1620     }
1621
1622     /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1623     /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1624     static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1625       switch (Pred) {
1626         case ICmpInst::ICMP_EQ:
1627           assert(!"No matching lattice value.");
1628           return static_cast<LatticeVal>(EQ_BIT);
1629         default:
1630           assert(!"Invalid 'icmp' predicate.");
1631         case ICmpInst::ICMP_NE:
1632           return NE;
1633         case ICmpInst::ICMP_UGT:
1634           return UGT;
1635         case ICmpInst::ICMP_UGE:
1636           return UGE;
1637         case ICmpInst::ICMP_ULT:
1638           return ULT;
1639         case ICmpInst::ICMP_ULE:
1640           return ULE;
1641         case ICmpInst::ICMP_SGT:
1642           return SGT;
1643         case ICmpInst::ICMP_SGE:
1644           return SGE;
1645         case ICmpInst::ICMP_SLT:
1646           return SLT;
1647         case ICmpInst::ICMP_SLE:
1648           return SLE;
1649       }
1650     }
1651
1652   public:
1653     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1654               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1655               BasicBlock *TopBB)
1656       : VN(VN),
1657         IG(IG),
1658         UB(UB),
1659         VR(VR),
1660         DTDFS(DTDFS),
1661         Top(DTDFS->getNodeForBlock(TopBB)),
1662         TopBB(TopBB),
1663         TopInst(NULL),
1664         modified(modified),
1665         Context(TopBB->getContext())
1666     {
1667       assert(Top && "VRPSolver created for unreachable basic block.");
1668     }
1669
1670     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1671               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1672               Instruction *TopInst)
1673       : VN(VN),
1674         IG(IG),
1675         UB(UB),
1676         VR(VR),
1677         DTDFS(DTDFS),
1678         Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1679         TopBB(TopInst->getParent()),
1680         TopInst(TopInst),
1681         modified(modified)
1682     {
1683       assert(Top && "VRPSolver created for unreachable basic block.");
1684       assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1685     }
1686
1687     bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1688       if (Constant *C1 = dyn_cast<Constant>(V1))
1689         if (Constant *C2 = dyn_cast<Constant>(V2))
1690           return ConstantExpr::getCompare(Pred, C1, C2) ==
1691                  ConstantInt::getTrue();
1692
1693       unsigned n1 = VN.valueNumber(V1, Top);
1694       unsigned n2 = VN.valueNumber(V2, Top);
1695
1696       if (n1 && n2) {
1697         if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1698                              Pred == ICmpInst::ICMP_ULE ||
1699                              Pred == ICmpInst::ICMP_UGE ||
1700                              Pred == ICmpInst::ICMP_SLE ||
1701                              Pred == ICmpInst::ICMP_SGE;
1702         if (Pred == ICmpInst::ICMP_EQ) return false;
1703         if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1704         if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1705       }
1706
1707       if ((n1 && !n2 && isa<Constant>(V2)) ||
1708           (n2 && !n1 && isa<Constant>(V1))) {
1709         ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1710         ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1711
1712         if (Pred == ICmpInst::ICMP_EQ)
1713           return CR1.isSingleElement() &&
1714                  CR1.getSingleElement() == CR2.getSingleElement();
1715
1716         return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1717       }
1718       if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1719       return false;
1720     }
1721
1722     /// add - adds a new property to the work queue
1723     void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1724              Instruction *I = NULL) {
1725       DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1726       if (I) DOUT << " context: " << *I;
1727       else DOUT << " default context (" << Top->getDFSNumIn() << ")";
1728       DOUT << "\n";
1729
1730       assert(V1->getType() == V2->getType() &&
1731              "Can't relate two values with different types.");
1732
1733       WorkList.push_back(Operation());
1734       Operation &O = WorkList.back();
1735       O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1736       O.ContextBB = I ? I->getParent() : TopBB;
1737     }
1738
1739     /// defToOps - Given an instruction definition that we've learned something
1740     /// new about, find any new relationships between its operands.
1741     void defToOps(Instruction *I) {
1742       Instruction *NewContext = below(I) ? I : TopInst;
1743       Value *Canonical = VN.canonicalize(I, Top);
1744
1745       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1746         const Type *Ty = BO->getType();
1747         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1748
1749         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1750         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1751
1752         // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1753
1754         switch (BO->getOpcode()) {
1755           case Instruction::And: {
1756             // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1757             ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
1758             if (Canonical == CI) {
1759               add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1760               add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1761             }
1762           } break;
1763           case Instruction::Or: {
1764             // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1765             Constant *Zero = Context->getNullValue(Ty);
1766             if (Canonical == Zero) {
1767               add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1768               add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1769             }
1770           } break;
1771           case Instruction::Xor: {
1772             // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1773             // "xor i32 %c, %a" EQ %c then %a EQ 0
1774             // "xor i32 %c, %a" NE %c then %a NE 0
1775             // Repeat the above, with order of operands reversed.
1776             Value *LHS = Op0;
1777             Value *RHS = Op1;
1778             if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1779
1780             if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1781               if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1782                 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
1783                     ICmpInst::ICMP_EQ, NewContext);
1784               }
1785             }
1786             if (Canonical == LHS) {
1787               if (isa<ConstantInt>(Canonical))
1788                 add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_EQ,
1789                     NewContext);
1790             } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1791               add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_NE,
1792                   NewContext);
1793             }
1794           } break;
1795           default:
1796             break;
1797         }
1798       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1799         // "icmp ult i32 %a, %y" EQ true then %a u< y
1800         // etc.
1801
1802         if (Canonical == ConstantInt::getTrue()) {
1803           add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1804               NewContext);
1805         } else if (Canonical == ConstantInt::getFalse()) {
1806           add(IC->getOperand(0), IC->getOperand(1),
1807               ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1808         }
1809       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1810         if (I->getType()->isFPOrFPVector()) return;
1811
1812         // Given: "%a = select i1 %x, i32 %b, i32 %c"
1813         // %a EQ %b and %b NE %c then %x EQ true
1814         // %a EQ %c and %b NE %c then %x EQ false
1815
1816         Value *True  = SI->getTrueValue();
1817         Value *False = SI->getFalseValue();
1818         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1819           if (Canonical == VN.canonicalize(True, Top) ||
1820               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1821             add(SI->getCondition(), ConstantInt::getTrue(),
1822                 ICmpInst::ICMP_EQ, NewContext);
1823           else if (Canonical == VN.canonicalize(False, Top) ||
1824                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1825             add(SI->getCondition(), ConstantInt::getFalse(),
1826                 ICmpInst::ICMP_EQ, NewContext);
1827         }
1828       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1829         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1830              OE = GEPI->idx_end(); OI != OE; ++OI) {
1831           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1832           if (!Op || !Op->isZero()) return;
1833         }
1834         // TODO: The GEPI indices are all zero. Copy from definition to operand,
1835         // jumping the type plane as needed.
1836         if (isRelatedBy(GEPI, Context->getNullValue(GEPI->getType()),
1837                         ICmpInst::ICMP_NE)) {
1838           Value *Ptr = GEPI->getPointerOperand();
1839           add(Ptr, Context->getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1840               NewContext);
1841         }
1842       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1843         const Type *SrcTy = CI->getSrcTy();
1844
1845         unsigned ci = VN.getOrInsertVN(CI, Top);
1846         uint32_t W = VR.typeToWidth(SrcTy);
1847         if (!W) return;
1848         ConstantRange CR = VR.range(ci, Top);
1849
1850         if (CR.isFullSet()) return;
1851
1852         switch (CI->getOpcode()) {
1853           default: break;
1854           case Instruction::ZExt:
1855           case Instruction::SExt:
1856             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1857                           CR.truncate(W), Top, this);
1858             break;
1859           case Instruction::BitCast:
1860             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1861                           CR, Top, this);
1862             break;
1863         }
1864       }
1865     }
1866
1867     /// opsToDef - A new relationship was discovered involving one of this
1868     /// instruction's operands. Find any new relationship involving the
1869     /// definition, or another operand.
1870     void opsToDef(Instruction *I) {
1871       Instruction *NewContext = below(I) ? I : TopInst;
1872
1873       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1874         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1875         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1876
1877         if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1878           if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1879             add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1880                 ICmpInst::ICMP_EQ, NewContext);
1881             return;
1882           }
1883
1884         // "%y = and i1 true, %x" then %x EQ %y
1885         // "%y = or i1 false, %x" then %x EQ %y
1886         // "%x = add i32 %y, 0" then %x EQ %y
1887         // "%x = mul i32 %y, 0" then %x EQ 0
1888
1889         Instruction::BinaryOps Opcode = BO->getOpcode();
1890         const Type *Ty = BO->getType();
1891         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1892
1893         Constant *Zero = Context->getNullValue(Ty);
1894         Constant *One = ConstantInt::get(Ty, 1);
1895         ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
1896
1897         switch (Opcode) {
1898           default: break;
1899           case Instruction::LShr:
1900           case Instruction::AShr:
1901           case Instruction::Shl:
1902             if (Op1 == Zero) {
1903               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1904               return;
1905             }
1906             break;
1907           case Instruction::Sub:
1908             if (Op1 == Zero) {
1909               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1910               return;
1911             }
1912             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1913               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1914               ConstantRange CR = VR.range(n_ci0, Top);
1915               if (!CR.isFullSet()) {
1916                 CR.subtract(CI0->getValue());
1917                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1918                 VR.applyRange(n_bo, CR, Top, this);
1919                 return;
1920               }
1921             }
1922             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1923               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1924               ConstantRange CR = VR.range(n_ci1, Top);
1925               if (!CR.isFullSet()) {
1926                 CR.subtract(CI1->getValue());
1927                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1928                 VR.applyRange(n_bo, CR, Top, this);
1929                 return;
1930               }
1931             }
1932             break;
1933           case Instruction::Or:
1934             if (Op0 == AllOnes || Op1 == AllOnes) {
1935               add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1936               return;
1937             }
1938             if (Op0 == Zero) {
1939               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1940               return;
1941             } else if (Op1 == Zero) {
1942               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1943               return;
1944             }
1945             break;
1946           case Instruction::Add:
1947             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1948               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1949               ConstantRange CR = VR.range(n_ci0, Top);
1950               if (!CR.isFullSet()) {
1951                 CR.subtract(-CI0->getValue());
1952                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1953                 VR.applyRange(n_bo, CR, Top, this);
1954                 return;
1955               }
1956             }
1957             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1958               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1959               ConstantRange CR = VR.range(n_ci1, Top);
1960               if (!CR.isFullSet()) {
1961                 CR.subtract(-CI1->getValue());
1962                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1963                 VR.applyRange(n_bo, CR, Top, this);
1964                 return;
1965               }
1966             }
1967             // fall-through
1968           case Instruction::Xor:
1969             if (Op0 == Zero) {
1970               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1971               return;
1972             } else if (Op1 == Zero) {
1973               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1974               return;
1975             }
1976             break;
1977           case Instruction::And:
1978             if (Op0 == AllOnes) {
1979               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1980               return;
1981             } else if (Op1 == AllOnes) {
1982               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1983               return;
1984             }
1985             if (Op0 == Zero || Op1 == Zero) {
1986               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1987               return;
1988             }
1989             break;
1990           case Instruction::Mul:
1991             if (Op0 == Zero || Op1 == Zero) {
1992               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1993               return;
1994             }
1995             if (Op0 == One) {
1996               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1997               return;
1998             } else if (Op1 == One) {
1999               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2000               return;
2001             }
2002             break;
2003         }
2004
2005         // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
2006         // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
2007         // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
2008         // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
2009
2010         Value *Known = Op0, *Unknown = Op1,
2011               *TheBO = VN.canonicalize(BO, Top);
2012         if (Known != TheBO) std::swap(Known, Unknown);
2013         if (Known == TheBO) {
2014           switch (Opcode) {
2015             default: break;
2016             case Instruction::LShr:
2017             case Instruction::AShr:
2018             case Instruction::Shl:
2019               if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2020               // otherwise, fall-through.
2021             case Instruction::Sub:
2022               if (Unknown == Op0) break;
2023               // otherwise, fall-through.
2024             case Instruction::Xor:
2025             case Instruction::Add:
2026               add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
2027               break;
2028             case Instruction::UDiv:
2029             case Instruction::SDiv:
2030               if (Unknown == Op1) break;
2031               if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
2032                 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2033               break;
2034           }
2035         }
2036
2037         // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
2038
2039       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
2040         // "%a = icmp ult i32 %b, %c" and %b u<  %c then %a EQ true
2041         // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2042         // etc.
2043
2044         Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2045         Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2046
2047         ICmpInst::Predicate Pred = IC->getPredicate();
2048         if (isRelatedBy(Op0, Op1, Pred))
2049           add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
2050         else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2051           add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
2052
2053       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2054         if (I->getType()->isFPOrFPVector()) return;
2055
2056         // Given: "%a = select i1 %x, i32 %b, i32 %c"
2057         // %x EQ true  then %a EQ %b
2058         // %x EQ false then %a EQ %c
2059         // %b EQ %c then %a EQ %b
2060
2061         Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2062         if (Canonical == ConstantInt::getTrue()) {
2063           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2064         } else if (Canonical == ConstantInt::getFalse()) {
2065           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2066         } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2067                    VN.canonicalize(SI->getFalseValue(), Top)) {
2068           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2069         }
2070       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2071         const Type *DestTy = CI->getDestTy();
2072         if (DestTy->isFPOrFPVector()) return;
2073
2074         Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2075         Instruction::CastOps Opcode = CI->getOpcode();
2076
2077         if (Constant *C = dyn_cast<Constant>(Op)) {
2078           add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2079               ICmpInst::ICMP_EQ, NewContext);
2080         }
2081
2082         uint32_t W = VR.typeToWidth(DestTy);
2083         unsigned ci = VN.getOrInsertVN(CI, Top);
2084         ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2085
2086         if (!CR.isFullSet()) {
2087           switch (Opcode) {
2088             default: break;
2089             case Instruction::ZExt:
2090               VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2091               break;
2092             case Instruction::SExt:
2093               VR.applyRange(ci, CR.signExtend(W), Top, this);
2094               break;
2095             case Instruction::Trunc: {
2096               ConstantRange Result = CR.truncate(W);
2097               if (!Result.isFullSet())
2098                 VR.applyRange(ci, Result, Top, this);
2099             } break;
2100             case Instruction::BitCast:
2101               VR.applyRange(ci, CR, Top, this);
2102               break;
2103             // TODO: other casts?
2104           }
2105         }
2106       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2107         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2108              OE = GEPI->idx_end(); OI != OE; ++OI) {
2109           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2110           if (!Op || !Op->isZero()) return;
2111         }
2112         // TODO: The GEPI indices are all zero. Copy from operand to definition,
2113         // jumping the type plane as needed.
2114         Value *Ptr = GEPI->getPointerOperand();
2115         if (isRelatedBy(Ptr, Context->getNullValue(Ptr->getType()),
2116                         ICmpInst::ICMP_NE)) {
2117           add(GEPI, Context->getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2118               NewContext);
2119         }
2120       }
2121     }
2122
2123     /// solve - process the work queue
2124     void solve() {
2125       //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2126       while (!WorkList.empty()) {
2127         //DOUT << "WorkList size: " << WorkList.size() << "\n";
2128
2129         Operation &O = WorkList.front();
2130         TopInst = O.ContextInst;
2131         TopBB = O.ContextBB;
2132         Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2133
2134         O.LHS = VN.canonicalize(O.LHS, Top);
2135         O.RHS = VN.canonicalize(O.RHS, Top);
2136
2137         assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2138         assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2139
2140         DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2141         if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2142         else DOUT << " context block: " << O.ContextBB->getName();
2143         DOUT << "\n";
2144
2145         DEBUG(VN.dump());
2146         DEBUG(IG.dump());
2147         DEBUG(VR.dump());
2148
2149         // If they're both Constant, skip it. Check for contradiction and mark
2150         // the BB as unreachable if so.
2151         if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2152           if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2153             if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2154                 ConstantInt::getFalse())
2155               UB.mark(TopBB);
2156
2157             WorkList.pop_front();
2158             continue;
2159           }
2160         }
2161
2162         if (VN.compare(O.LHS, O.RHS)) {
2163           std::swap(O.LHS, O.RHS);
2164           O.Op = ICmpInst::getSwappedPredicate(O.Op);
2165         }
2166
2167         if (O.Op == ICmpInst::ICMP_EQ) {
2168           if (!makeEqual(O.RHS, O.LHS))
2169             UB.mark(TopBB);
2170         } else {
2171           LatticeVal LV = cmpInstToLattice(O.Op);
2172
2173           if ((LV & EQ_BIT) &&
2174               isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2175             if (!makeEqual(O.RHS, O.LHS))
2176               UB.mark(TopBB);
2177           } else {
2178             if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2179               UB.mark(TopBB);
2180               WorkList.pop_front();
2181               continue;
2182             }
2183
2184             unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2185             unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2186
2187             if (n1 == n2) {
2188               if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2189                   O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2190                 UB.mark(TopBB);
2191
2192               WorkList.pop_front();
2193               continue;
2194             }
2195
2196             if (VR.isRelatedBy(n1, n2, Top, LV) ||
2197                 IG.isRelatedBy(n1, n2, Top, LV)) {
2198               WorkList.pop_front();
2199               continue;
2200             }
2201
2202             VR.addInequality(n1, n2, Top, LV, this);
2203             if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2204                 LV == NE)
2205               IG.addInequality(n1, n2, Top, LV);
2206
2207             if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2208               if (aboveOrBelow(I1))
2209                 defToOps(I1);
2210             }
2211             if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2212               for (Value::use_iterator UI = O.LHS->use_begin(),
2213                    UE = O.LHS->use_end(); UI != UE;) {
2214                 Use &TheUse = UI.getUse();
2215                 ++UI;
2216                 Instruction *I = cast<Instruction>(TheUse.getUser());
2217                 if (aboveOrBelow(I))
2218                   opsToDef(I);
2219               }
2220             }
2221             if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2222               if (aboveOrBelow(I2))
2223               defToOps(I2);
2224             }
2225             if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2226               for (Value::use_iterator UI = O.RHS->use_begin(),
2227                    UE = O.RHS->use_end(); UI != UE;) {
2228                 Use &TheUse = UI.getUse();
2229                 ++UI;
2230                 Instruction *I = cast<Instruction>(TheUse.getUser());
2231                 if (aboveOrBelow(I))
2232                   opsToDef(I);
2233               }
2234             }
2235           }
2236         }
2237         WorkList.pop_front();
2238       }
2239     }
2240   };
2241
2242   void ValueRanges::addToWorklist(Value *V, Constant *C,
2243                                   ICmpInst::Predicate Pred, VRPSolver *VRP) {
2244     VRP->add(V, C, Pred, VRP->TopInst);
2245   }
2246
2247   void ValueRanges::markBlock(VRPSolver *VRP) {
2248     VRP->UB.mark(VRP->TopBB);
2249   }
2250
2251   /// PredicateSimplifier - This class is a simplifier that replaces
2252   /// one equivalent variable with another. It also tracks what
2253   /// can't be equal and will solve setcc instructions when possible.
2254   /// @brief Root of the predicate simplifier optimization.
2255   class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2256     DomTreeDFS *DTDFS;
2257     bool modified;
2258     ValueNumbering *VN;
2259     InequalityGraph *IG;
2260     UnreachableBlocks UB;
2261     ValueRanges *VR;
2262
2263     std::vector<DomTreeDFS::Node *> WorkList;
2264
2265   public:
2266     static char ID; // Pass identification, replacement for typeid
2267     PredicateSimplifier() : FunctionPass(&ID) {}
2268
2269     bool runOnFunction(Function &F);
2270
2271     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2272       AU.addRequiredID(BreakCriticalEdgesID);
2273       AU.addRequired<DominatorTree>();
2274       AU.addRequired<TargetData>();
2275       AU.addPreserved<TargetData>();
2276     }
2277
2278   private:
2279     /// Forwards - Adds new properties to VRPSolver and uses them to
2280     /// simplify instructions. Because new properties sometimes apply to
2281     /// a transition from one BasicBlock to another, this will use the
2282     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2283     /// basic block.
2284     /// @brief Performs abstract execution of the program.
2285     class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2286       friend class InstVisitor<Forwards>;
2287       PredicateSimplifier *PS;
2288       DomTreeDFS::Node *DTNode;
2289
2290     public:
2291       ValueNumbering &VN;
2292       InequalityGraph &IG;
2293       UnreachableBlocks &UB;
2294       ValueRanges &VR;
2295
2296       Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2297         : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2298           VR(*PS->VR) {}
2299
2300       void visitTerminatorInst(TerminatorInst &TI);
2301       void visitBranchInst(BranchInst &BI);
2302       void visitSwitchInst(SwitchInst &SI);
2303
2304       void visitAllocaInst(AllocaInst &AI);
2305       void visitLoadInst(LoadInst &LI);
2306       void visitStoreInst(StoreInst &SI);
2307
2308       void visitSExtInst(SExtInst &SI);
2309       void visitZExtInst(ZExtInst &ZI);
2310
2311       void visitBinaryOperator(BinaryOperator &BO);
2312       void visitICmpInst(ICmpInst &IC);
2313     };
2314   
2315     // Used by terminator instructions to proceed from the current basic
2316     // block to the next. Verifies that "current" dominates "next",
2317     // then calls visitBasicBlock.
2318     void proceedToSuccessors(DomTreeDFS::Node *Current) {
2319       for (DomTreeDFS::Node::iterator I = Current->begin(),
2320            E = Current->end(); I != E; ++I) {
2321         WorkList.push_back(*I);
2322       }
2323     }
2324
2325     void proceedToSuccessor(DomTreeDFS::Node *Next) {
2326       WorkList.push_back(Next);
2327     }
2328
2329     // Visits each instruction in the basic block.
2330     void visitBasicBlock(DomTreeDFS::Node *Node) {
2331       BasicBlock *BB = Node->getBlock();
2332       DOUT << "Entering Basic Block: " << BB->getName()
2333            << " (" << Node->getDFSNumIn() << ")\n";
2334       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2335         visitInstruction(I++, Node);
2336       }
2337     }
2338
2339     // Tries to simplify each Instruction and add new properties.
2340     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2341       DOUT << "Considering instruction " << *I << "\n";
2342       DEBUG(VN->dump());
2343       DEBUG(IG->dump());
2344       DEBUG(VR->dump());
2345
2346       // Sometimes instructions are killed in earlier analysis.
2347       if (isInstructionTriviallyDead(I)) {
2348         ++NumSimple;
2349         modified = true;
2350         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2351           if (VN->value(n) == I) IG->remove(n);
2352         VN->remove(I);
2353         I->eraseFromParent();
2354         return;
2355       }
2356
2357 #ifndef NDEBUG
2358       // Try to replace the whole instruction.
2359       Value *V = VN->canonicalize(I, DT);
2360       assert(V == I && "Late instruction canonicalization.");
2361       if (V != I) {
2362         modified = true;
2363         ++NumInstruction;
2364         DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
2365         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2366           if (VN->value(n) == I) IG->remove(n);
2367         VN->remove(I);
2368         I->replaceAllUsesWith(V);
2369         I->eraseFromParent();
2370         return;
2371       }
2372
2373       // Try to substitute operands.
2374       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2375         Value *Oper = I->getOperand(i);
2376         Value *V = VN->canonicalize(Oper, DT);
2377         assert(V == Oper && "Late operand canonicalization.");
2378         if (V != Oper) {
2379           modified = true;
2380           ++NumVarsReplaced;
2381           DOUT << "Resolving " << *I;
2382           I->setOperand(i, V);
2383           DOUT << " into " << *I;
2384         }
2385       }
2386 #endif
2387
2388       std::string name = I->getParent()->getName();
2389       DOUT << "push (%" << name << ")\n";
2390       Forwards visit(this, DT);
2391       visit.visit(*I);
2392       DOUT << "pop (%" << name << ")\n";
2393     }
2394   };
2395
2396   bool PredicateSimplifier::runOnFunction(Function &F) {
2397     DominatorTree *DT = &getAnalysis<DominatorTree>();
2398     DTDFS = new DomTreeDFS(DT);
2399     TargetData *TD = &getAnalysis<TargetData>();
2400
2401     DOUT << "Entering Function: " << F.getName() << "\n";
2402
2403     modified = false;
2404     DomTreeDFS::Node *Root = DTDFS->getRootNode();
2405     VN = new ValueNumbering(DTDFS);
2406     IG = new InequalityGraph(*VN, Root);
2407     VR = new ValueRanges(*VN, TD);
2408     WorkList.push_back(Root);
2409
2410     do {
2411       DomTreeDFS::Node *DTNode = WorkList.back();
2412       WorkList.pop_back();
2413       if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2414     } while (!WorkList.empty());
2415
2416     delete DTDFS;
2417     delete VR;
2418     delete IG;
2419     delete VN;
2420
2421     modified |= UB.kill();
2422
2423     return modified;
2424   }
2425
2426   void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2427     PS->proceedToSuccessors(DTNode);
2428   }
2429
2430   void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2431     if (BI.isUnconditional()) {
2432       PS->proceedToSuccessors(DTNode);
2433       return;
2434     }
2435
2436     Value *Condition = BI.getCondition();
2437     BasicBlock *TrueDest  = BI.getSuccessor(0);
2438     BasicBlock *FalseDest = BI.getSuccessor(1);
2439
2440     if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2441       PS->proceedToSuccessors(DTNode);
2442       return;
2443     }
2444
2445     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2446          I != E; ++I) {
2447       BasicBlock *Dest = (*I)->getBlock();
2448       DOUT << "Branch thinking about %" << Dest->getName()
2449            << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
2450
2451       if (Dest == TrueDest) {
2452         DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
2453         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2454         VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
2455         VRP.solve();
2456         DEBUG(VN.dump());
2457         DEBUG(IG.dump());
2458         DEBUG(VR.dump());
2459       } else if (Dest == FalseDest) {
2460         DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
2461         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2462         VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
2463         VRP.solve();
2464         DEBUG(VN.dump());
2465         DEBUG(IG.dump());
2466         DEBUG(VR.dump());
2467       }
2468
2469       PS->proceedToSuccessor(*I);
2470     }
2471   }
2472
2473   void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2474     Value *Condition = SI.getCondition();
2475
2476     // Set the EQProperty in each of the cases BBs, and the NEProperties
2477     // in the default BB.
2478
2479     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2480          I != E; ++I) {
2481       BasicBlock *BB = (*I)->getBlock();
2482       DOUT << "Switch thinking about BB %" << BB->getName()
2483            << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
2484
2485       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2486       if (BB == SI.getDefaultDest()) {
2487         for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2488           if (SI.getSuccessor(i) != BB)
2489             VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2490         VRP.solve();
2491       } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2492         VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2493         VRP.solve();
2494       }
2495       PS->proceedToSuccessor(*I);
2496     }
2497   }
2498
2499   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2500     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2501     VRP.add(AI.getParent()->getContext()->getNullValue(AI.getType()),
2502             &AI, ICmpInst::ICMP_NE);
2503     VRP.solve();
2504   }
2505
2506   void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2507     Value *Ptr = LI.getPointerOperand();
2508     // avoid "load i8* null" -> null NE null.
2509     if (isa<Constant>(Ptr)) return;
2510
2511     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2512     VRP.add(LI.getParent()->getContext()->getNullValue(Ptr->getType()),
2513             Ptr, ICmpInst::ICMP_NE);
2514     VRP.solve();
2515   }
2516
2517   void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2518     Value *Ptr = SI.getPointerOperand();
2519     if (isa<Constant>(Ptr)) return;
2520
2521     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2522     VRP.add(SI.getParent()->getContext()->getNullValue(Ptr->getType()),
2523             Ptr, ICmpInst::ICMP_NE);
2524     VRP.solve();
2525   }
2526
2527   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2528     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2529     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2530     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2531     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2532     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2533     VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2534     VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
2535     VRP.solve();
2536   }
2537
2538   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2539     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2540     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2541     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2542     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2543     VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
2544     VRP.solve();
2545   }
2546
2547   void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2548     Instruction::BinaryOps ops = BO.getOpcode();
2549
2550     switch (ops) {
2551     default: break;
2552       case Instruction::URem:
2553       case Instruction::SRem:
2554       case Instruction::UDiv:
2555       case Instruction::SDiv: {
2556         Value *Divisor = BO.getOperand(1);
2557         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2558         VRP.add(BO.getParent()->getContext()->getNullValue(Divisor->getType()), 
2559                 Divisor, ICmpInst::ICMP_NE);
2560         VRP.solve();
2561         break;
2562       }
2563     }
2564
2565     switch (ops) {
2566       default: break;
2567       case Instruction::Shl: {
2568         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2569         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2570         VRP.solve();
2571       } break;
2572       case Instruction::AShr: {
2573         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2574         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2575         VRP.solve();
2576       } break;
2577       case Instruction::LShr:
2578       case Instruction::UDiv: {
2579         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2580         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2581         VRP.solve();
2582       } break;
2583       case Instruction::URem: {
2584         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2585         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2586         VRP.solve();
2587       } break;
2588       case Instruction::And: {
2589         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2590         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2591         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2592         VRP.solve();
2593       } break;
2594       case Instruction::Or: {
2595         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2596         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2597         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2598         VRP.solve();
2599       } break;
2600     }
2601   }
2602
2603   void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2604     // If possible, squeeze the ICmp predicate into something simpler.
2605     // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2606     // the predicate to eq.
2607
2608     // XXX: once we do full PHI handling, modifying the instruction in the
2609     // Forwards visitor will cause missed optimizations.
2610
2611     ICmpInst::Predicate Pred = IC.getPredicate();
2612
2613     switch (Pred) {
2614       default: break;
2615       case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2616       case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2617       case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2618       case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2619     }
2620     if (Pred != IC.getPredicate()) {
2621       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2622       if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2623                           ICmpInst::ICMP_NE)) {
2624         ++NumSnuggle;
2625         PS->modified = true;
2626         IC.setPredicate(Pred);
2627       }
2628     }
2629
2630     Pred = IC.getPredicate();
2631
2632     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2633       ConstantInt *NextVal = 0;
2634       switch (Pred) {
2635         default: break;
2636         case ICmpInst::ICMP_SLT:
2637         case ICmpInst::ICMP_ULT:
2638           if (Op1->getValue() != 0)
2639             NextVal = ConstantInt::get(Op1->getValue()-1);
2640          break;
2641         case ICmpInst::ICMP_SGT:
2642         case ICmpInst::ICMP_UGT:
2643           if (!Op1->getValue().isAllOnesValue())
2644             NextVal = ConstantInt::get(Op1->getValue()+1);
2645          break;
2646       }
2647
2648       if (NextVal) {
2649         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2650         if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2651                             ICmpInst::getInversePredicate(Pred))) {
2652           ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ, 
2653                                          IC.getOperand(0), NextVal, "");
2654           NewIC->takeName(&IC);
2655           IC.replaceAllUsesWith(NewIC);
2656
2657           // XXX: prove this isn't necessary
2658           if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2659             if (VN.value(n) == &IC) IG.remove(n);
2660           VN.remove(&IC);
2661
2662           IC.eraseFromParent();
2663           ++NumSnuggle;
2664           PS->modified = true;
2665         }
2666       }
2667     }
2668   }
2669 }
2670
2671 char PredicateSimplifier::ID = 0;
2672 static RegisterPass<PredicateSimplifier>
2673 X("predsimplify", "Predicate Simplifier");
2674
2675 FunctionPass *llvm::createPredicateSimplifierPass() {
2676   return new PredicateSimplifier();
2677 }