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