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