LLVM API Documentation

PredicateSimplifier.cpp

Go to the documentation of this file.
00001 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Path-sensitive optimizer. In a branch where x == y, replace uses of
00011 // x with y. Permits further optimization, such as the elimination of
00012 // the unreachable call:
00013 //
00014 // void test(int *p, int *q)
00015 // {
00016 //   if (p != q)
00017 //     return;
00018 // 
00019 //   if (*p != *q)
00020 //     foo(); // unreachable
00021 // }
00022 //
00023 //===----------------------------------------------------------------------===//
00024 //
00025 // The InequalityGraph focusses on four properties; equals, not equals,
00026 // less-than and less-than-or-equals-to. The greater-than forms are also held
00027 // just to allow walking from a lesser node to a greater one. These properties
00028 // are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
00029 //
00030 // These relationships define a graph between values of the same type. Each
00031 // Value is stored in a map table that retrieves the associated Node. This
00032 // is how EQ relationships are stored; the map contains pointers from equal
00033 // Value to the same node. The node contains a most canonical Value* form
00034 // and the list of known relationships with other nodes.
00035 //
00036 // If two nodes are known to be inequal, then they will contain pointers to
00037 // each other with an "NE" relationship. If node getNode(%x) is less than
00038 // getNode(%y), then the %x node will contain <%y, GT> and %y will contain
00039 // <%x, LT>. This allows us to tie nodes together into a graph like this:
00040 //
00041 //   %a < %b < %c < %d
00042 //
00043 // with four nodes representing the properties. The InequalityGraph provides
00044 // querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
00045 // To find a relationship, we start with one of the nodes any binary search
00046 // through its list to find where the relationships with the second node start.
00047 // Then we iterate through those to find the first relationship that dominates
00048 // our context node.
00049 //
00050 // To create these properties, we wait until a branch or switch instruction
00051 // implies that a particular value is true (or false). The VRPSolver is
00052 // responsible for analyzing the variable and seeing what new inferences
00053 // can be made from each property. For example:
00054 //
00055 //   %P = icmp ne i32* %ptr, null
00056 //   %a = and i1 %P, %Q
00057 //   br i1 %a label %cond_true, label %cond_false
00058 //
00059 // For the true branch, the VRPSolver will start with %a EQ true and look at
00060 // the definition of %a and find that it can infer that %P and %Q are both
00061 // true. From %P being true, it can infer that %ptr NE null. For the false
00062 // branch it can't infer anything from the "and" instruction.
00063 //
00064 // Besides branches, we can also infer properties from instruction that may
00065 // have undefined behaviour in certain cases. For example, the dividend of
00066 // a division may never be zero. After the division instruction, we may assume
00067 // that the dividend is not equal to zero.
00068 //
00069 //===----------------------------------------------------------------------===//
00070 //
00071 // The ValueRanges class stores the known integer bounds of a Value. When we
00072 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
00073 // %b = [0, 254].
00074 //
00075 // It never stores an empty range, because that means that the code is
00076 // unreachable. It never stores a single-element range since that's an equality
00077 // relationship and better stored in the InequalityGraph, nor an empty range
00078 // since that is better stored in UnreachableBlocks.
00079 //
00080 //===----------------------------------------------------------------------===//
00081 
00082 #define DEBUG_TYPE "predsimplify"
00083 #include "llvm/Transforms/Scalar.h"
00084 #include "llvm/Constants.h"
00085 #include "llvm/DerivedTypes.h"
00086 #include "llvm/Instructions.h"
00087 #include "llvm/Pass.h"
00088 #include "llvm/ADT/DepthFirstIterator.h"
00089 #include "llvm/ADT/SetOperations.h"
00090 #include "llvm/ADT/SetVector.h"
00091 #include "llvm/ADT/Statistic.h"
00092 #include "llvm/ADT/STLExtras.h"
00093 #include "llvm/Analysis/Dominators.h"
00094 #include "llvm/Assembly/Writer.h"
00095 #include "llvm/Support/CFG.h"
00096 #include "llvm/Support/Compiler.h"
00097 #include "llvm/Support/ConstantRange.h"
00098 #include "llvm/Support/Debug.h"
00099 #include "llvm/Support/InstVisitor.h"
00100 #include "llvm/Support/raw_ostream.h"
00101 #include "llvm/Target/TargetData.h"
00102 #include "llvm/Transforms/Utils/Local.h"
00103 #include <algorithm>
00104 #include <deque>
00105 #include <stack>
00106 using namespace llvm;
00107 
00108 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
00109 STATISTIC(NumInstruction , "Number of instructions removed");
00110 STATISTIC(NumSimple      , "Number of simple replacements");
00111 STATISTIC(NumBlocks      , "Number of blocks marked unreachable");
00112 STATISTIC(NumSnuggle     , "Number of comparisons snuggled");
00113 
00114 static const ConstantRange empty(1, false);
00115 
00116 namespace {
00117   class DomTreeDFS {
00118   public:
00119     class Node {
00120       friend class DomTreeDFS;
00121     public:
00122       typedef std::vector<Node *>::iterator       iterator;
00123       typedef std::vector<Node *>::const_iterator const_iterator;
00124 
00125       unsigned getDFSNumIn()  const { return DFSin;  }
00126       unsigned getDFSNumOut() const { return DFSout; }
00127 
00128       BasicBlock *getBlock() const { return BB; }
00129 
00130       iterator begin() { return Children.begin(); }
00131       iterator end()   { return Children.end();   }
00132 
00133       const_iterator begin() const { return Children.begin(); }
00134       const_iterator end()   const { return Children.end();   }
00135 
00136       bool dominates(const Node *N) const {
00137         return DFSin <= N->DFSin && DFSout >= N->DFSout;
00138       }
00139 
00140       bool DominatedBy(const Node *N) const {
00141         return N->dominates(this);
00142       }
00143 
00144       /// Sorts by the number of descendants. With this, you can iterate
00145       /// through a sorted list and the first matching entry is the most
00146       /// specific match for your basic block. The order provided is stable;
00147       /// DomTreeDFS::Nodes with the same number of descendants are sorted by
00148       /// DFS in number.
00149       bool operator<(const Node &N) const {
00150         unsigned   spread =   DFSout -   DFSin;
00151         unsigned N_spread = N.DFSout - N.DFSin;
00152         if (spread == N_spread) return DFSin < N.DFSin;
00153         return spread < N_spread;
00154       }
00155       bool operator>(const Node &N) const { return N < *this; }
00156 
00157     private:
00158       unsigned DFSin, DFSout;
00159       BasicBlock *BB;
00160 
00161       std::vector<Node *> Children;
00162     };
00163 
00164     // XXX: this may be slow. Instead of using "new" for each node, consider
00165     // putting them in a vector to keep them contiguous.
00166     explicit DomTreeDFS(DominatorTree *DT) {
00167       std::stack<std::pair<Node *, DomTreeNode *> > S;
00168 
00169       Entry = new Node;
00170       Entry->BB = DT->getRootNode()->getBlock();
00171       S.push(std::make_pair(Entry, DT->getRootNode()));
00172 
00173       NodeMap[Entry->BB] = Entry;
00174 
00175       while (!S.empty()) {
00176         std::pair<Node *, DomTreeNode *> &Pair = S.top();
00177         Node *N = Pair.first;
00178         DomTreeNode *DTNode = Pair.second;
00179         S.pop();
00180 
00181         for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
00182              I != E; ++I) {
00183           Node *NewNode = new Node;
00184           NewNode->BB = (*I)->getBlock();
00185           N->Children.push_back(NewNode);
00186           S.push(std::make_pair(NewNode, *I));
00187 
00188           NodeMap[NewNode->BB] = NewNode;
00189         }
00190       }
00191 
00192       renumber();
00193 
00194 #ifndef NDEBUG
00195       DEBUG(dump());
00196 #endif
00197     }
00198 
00199 #ifndef NDEBUG
00200     virtual
00201 #endif
00202     ~DomTreeDFS() {
00203       std::stack<Node *> S;
00204 
00205       S.push(Entry);
00206       while (!S.empty()) {
00207         Node *N = S.top(); S.pop();
00208 
00209         for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
00210           S.push(*I);
00211 
00212         delete N;
00213       }
00214     }
00215 
00216     /// getRootNode - This returns the entry node for the CFG of the function.
00217     Node *getRootNode() const { return Entry; }
00218 
00219     /// getNodeForBlock - return the node for the specified basic block.
00220     Node *getNodeForBlock(BasicBlock *BB) const {
00221       if (!NodeMap.count(BB)) return 0;
00222       return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
00223     }
00224 
00225     /// dominates - returns true if the basic block for I1 dominates that of
00226     /// the basic block for I2. If the instructions belong to the same basic
00227     /// block, the instruction first instruction sequentially in the block is
00228     /// considered dominating.
00229     bool dominates(Instruction *I1, Instruction *I2) {
00230       BasicBlock *BB1 = I1->getParent(),
00231                  *BB2 = I2->getParent();
00232       if (BB1 == BB2) {
00233         if (isa<TerminatorInst>(I1)) return false;
00234         if (isa<TerminatorInst>(I2)) return true;
00235         if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
00236         if (!isa<PHINode>(I1) &&  isa<PHINode>(I2)) return false;
00237 
00238         for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
00239              I != E; ++I) {
00240           if (&*I == I1) return true;
00241           else if (&*I == I2) return false;
00242         }
00243         assert(!"Instructions not found in parent BasicBlock?");
00244       } else {
00245         Node *Node1 = getNodeForBlock(BB1),
00246              *Node2 = getNodeForBlock(BB2);
00247         return Node1 && Node2 && Node1->dominates(Node2);
00248       }
00249       return false; // Not reached
00250     }
00251 
00252   private:
00253     /// renumber - calculates the depth first search numberings and applies
00254     /// them onto the nodes.
00255     void renumber() {
00256       std::stack<std::pair<Node *, Node::iterator> > S;
00257       unsigned n = 0;
00258 
00259       Entry->DFSin = ++n;
00260       S.push(std::make_pair(Entry, Entry->begin()));
00261 
00262       while (!S.empty()) {
00263         std::pair<Node *, Node::iterator> &Pair = S.top();
00264         Node *N = Pair.first;
00265         Node::iterator &I = Pair.second;
00266 
00267         if (I == N->end()) {
00268           N->DFSout = ++n;
00269           S.pop();
00270         } else {
00271           Node *Next = *I++;
00272           Next->DFSin = ++n;
00273           S.push(std::make_pair(Next, Next->begin()));
00274         }
00275       }
00276     }
00277 
00278 #ifndef NDEBUG
00279     virtual void dump() const {
00280       dump(*cerr.stream());
00281     }
00282 
00283     void dump(std::ostream &os) const {
00284       os << "Predicate simplifier DomTreeDFS: \n";
00285       dump(Entry, 0, os);
00286       os << "\n\n";
00287     }
00288 
00289     void dump(Node *N, int depth, std::ostream &os) const {
00290       ++depth;
00291       for (int i = 0; i < depth; ++i) { os << " "; }
00292       os << "[" << depth << "] ";
00293 
00294       os << N->getBlock()->getNameStr() << " (" << N->getDFSNumIn()
00295          << ", " << N->getDFSNumOut() << ")\n";
00296 
00297       for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
00298         dump(*I, depth, os);
00299     }
00300 #endif
00301 
00302     Node *Entry;
00303     std::map<BasicBlock *, Node *> NodeMap;
00304   };
00305 
00306   // SLT SGT ULT UGT EQ
00307   //   0   1   0   1  0 -- GT                  10
00308   //   0   1   0   1  1 -- GE                  11
00309   //   0   1   1   0  0 -- SGTULT              12
00310   //   0   1   1   0  1 -- SGEULE              13
00311   //   0   1   1   1  0 -- SGT                 14
00312   //   0   1   1   1  1 -- SGE                 15
00313   //   1   0   0   1  0 -- SLTUGT              18
00314   //   1   0   0   1  1 -- SLEUGE              19
00315   //   1   0   1   0  0 -- LT                  20
00316   //   1   0   1   0  1 -- LE                  21
00317   //   1   0   1   1  0 -- SLT                 22
00318   //   1   0   1   1  1 -- SLE                 23
00319   //   1   1   0   1  0 -- UGT                 26
00320   //   1   1   0   1  1 -- UGE                 27
00321   //   1   1   1   0  0 -- ULT                 28
00322   //   1   1   1   0  1 -- ULE                 29
00323   //   1   1   1   1  0 -- NE                  30
00324   enum LatticeBits {
00325     EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
00326   };
00327   enum LatticeVal {
00328     GT = SGT_BIT | UGT_BIT,
00329     GE = GT | EQ_BIT,
00330     LT = SLT_BIT | ULT_BIT,
00331     LE = LT | EQ_BIT,
00332     NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
00333     SGTULT = SGT_BIT | ULT_BIT,
00334     SGEULE = SGTULT | EQ_BIT,
00335     SLTUGT = SLT_BIT | UGT_BIT,
00336     SLEUGE = SLTUGT | EQ_BIT,
00337     ULT = SLT_BIT | SGT_BIT | ULT_BIT,
00338     UGT = SLT_BIT | SGT_BIT | UGT_BIT,
00339     SLT = SLT_BIT | ULT_BIT | UGT_BIT,
00340     SGT = SGT_BIT | ULT_BIT | UGT_BIT,
00341     SLE = SLT | EQ_BIT,
00342     SGE = SGT | EQ_BIT,
00343     ULE = ULT | EQ_BIT,
00344     UGE = UGT | EQ_BIT
00345   };
00346 
00347 #ifndef NDEBUG
00348   /// validPredicate - determines whether a given value is actually a lattice
00349   /// value. Only used in assertions or debugging.
00350   static bool validPredicate(LatticeVal LV) {
00351     switch (LV) {
00352       case GT: case GE: case LT: case LE: case NE:
00353       case SGTULT: case SGT: case SGEULE:
00354       case SLTUGT: case SLT: case SLEUGE:
00355       case ULT: case UGT:
00356       case SLE: case SGE: case ULE: case UGE:
00357         return true;
00358       default:
00359         return false;
00360     }
00361   }
00362 #endif
00363 
00364   /// reversePredicate - reverse the direction of the inequality
00365   static LatticeVal reversePredicate(LatticeVal LV) {
00366     unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
00367 
00368     if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
00369       reverse |= (SLT_BIT|SGT_BIT);
00370 
00371     if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
00372       reverse |= (ULT_BIT|UGT_BIT);
00373 
00374     LatticeVal Rev = static_cast<LatticeVal>(reverse);
00375     assert(validPredicate(Rev) && "Failed reversing predicate.");
00376     return Rev;
00377   }
00378 
00379   /// ValueNumbering stores the scope-specific value numbers for a given Value.
00380   class VISIBILITY_HIDDEN ValueNumbering {
00381 
00382     /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
00383     /// includes the comparison operators necessary to allow you to store it
00384     /// in a sorted vector.
00385     class VISIBILITY_HIDDEN VNPair {
00386     public:
00387       Value *V;
00388       unsigned index;
00389       DomTreeDFS::Node *Subtree;
00390 
00391       VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
00392         : V(V), index(index), Subtree(Subtree) {}
00393 
00394       bool operator==(const VNPair &RHS) const {
00395         return V == RHS.V && Subtree == RHS.Subtree;
00396       }
00397 
00398       bool operator<(const VNPair &RHS) const {
00399         if (V != RHS.V) return V < RHS.V;
00400         return *Subtree < *RHS.Subtree;
00401       }
00402 
00403       bool operator<(Value *RHS) const {
00404         return V < RHS;
00405       }
00406 
00407       bool operator>(Value *RHS) const {
00408         return V > RHS;
00409       }
00410 
00411       friend bool operator<(Value *RHS, const VNPair &pair) {
00412         return pair.operator>(RHS);
00413       }
00414     };
00415 
00416     typedef std::vector<VNPair> VNMapType;
00417     VNMapType VNMap;
00418 
00419     /// The canonical choice for value number at index.
00420     std::vector<Value *> Values;
00421 
00422     DomTreeDFS *DTDFS;
00423 
00424   public:
00425 #ifndef NDEBUG
00426     virtual ~ValueNumbering() {}
00427     virtual void dump() {
00428       dump(*cerr.stream());
00429     }
00430 
00431     void dump(std::ostream &os) {
00432       for (unsigned i = 1; i <= Values.size(); ++i) {
00433         os << i << " = ";
00434         WriteAsOperand(os, Values[i-1]);
00435         os << " {";
00436         for (unsigned j = 0; j < VNMap.size(); ++j) {
00437           if (VNMap[j].index == i) {
00438             WriteAsOperand(os, VNMap[j].V);
00439             os << " (" << VNMap[j].Subtree->getDFSNumIn() << ")  ";
00440           }
00441         }
00442         os << "}\n";
00443       }
00444     }
00445 #endif
00446 
00447     /// compare - returns true if V1 is a better canonical value than V2.
00448     bool compare(Value *V1, Value *V2) const {
00449       if (isa<Constant>(V1))
00450         return !isa<Constant>(V2);
00451       else if (isa<Constant>(V2))
00452         return false;
00453       else if (isa<Argument>(V1))
00454         return !isa<Argument>(V2);
00455       else if (isa<Argument>(V2))
00456         return false;
00457 
00458       Instruction *I1 = dyn_cast<Instruction>(V1);
00459       Instruction *I2 = dyn_cast<Instruction>(V2);
00460 
00461       if (!I1 || !I2)
00462         return V1->getNumUses() < V2->getNumUses();
00463 
00464       return DTDFS->dominates(I1, I2);
00465     }
00466 
00467     ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
00468 
00469     /// valueNumber - finds the value number for V under the Subtree. If
00470     /// there is no value number, returns zero.
00471     unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
00472       if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) || 
00473           V->getType() == Type::getVoidTy(V->getContext())) return 0;
00474 
00475       VNMapType::iterator E = VNMap.end();
00476       VNPair pair(V, 0, Subtree);
00477       VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
00478       while (I != E && I->V == V) {
00479         if (I->Subtree->dominates(Subtree))
00480           return I->index;
00481         ++I;
00482       }
00483       return 0;
00484     }
00485 
00486     /// getOrInsertVN - always returns a value number, creating it if necessary.
00487     unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
00488       if (unsigned n = valueNumber(V, Subtree))
00489         return n;
00490       else
00491         return newVN(V);
00492     }
00493 
00494     /// newVN - creates a new value number. Value V must not already have a
00495     /// value number assigned.
00496     unsigned newVN(Value *V) {
00497       assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
00498              "Bad Value for value numbering.");
00499       assert(V->getType() != Type::getVoidTy(V->getContext()) &&
00500              "Won't value number a void value");
00501 
00502       Values.push_back(V);
00503 
00504       VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
00505       VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
00506       assert((I == VNMap.end() || value(I->index) != V) &&
00507              "Attempt to create a duplicate value number.");
00508       VNMap.insert(I, pair);
00509 
00510       return Values.size();
00511     }
00512 
00513     /// value - returns the Value associated with a value number.
00514     Value *value(unsigned index) const {
00515       assert(index != 0 && "Zero index is reserved for not found.");
00516       assert(index <= Values.size() && "Index out of range.");
00517       return Values[index-1];
00518     }
00519 
00520     /// canonicalize - return a Value that is equal to V under Subtree.
00521     Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
00522       if (isa<Constant>(V)) return V;
00523 
00524       if (unsigned n = valueNumber(V, Subtree))
00525         return value(n);
00526       else
00527         return V;
00528     }
00529 
00530     /// addEquality - adds that value V belongs to the set of equivalent
00531     /// values defined by value number n under Subtree.
00532     void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
00533       assert(canonicalize(value(n), Subtree) == value(n) &&
00534              "Node's 'canonical' choice isn't best within this subtree.");
00535 
00536       // Suppose that we are given "%x -> node #1 (%y)". The problem is that
00537       // we may already have "%z -> node #2 (%x)" somewhere above us in the
00538       // graph. We need to find those edges and add "%z -> node #1 (%y)"
00539       // to keep the lookups canonical.
00540 
00541       std::vector<Value *> ToRepoint(1, V);
00542 
00543       if (unsigned Conflict = valueNumber(V, Subtree)) {
00544         for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
00545              I != E; ++I) {
00546           if (I->index == Conflict && I->Subtree->dominates(Subtree))
00547             ToRepoint.push_back(I->V);
00548         }
00549       }
00550 
00551       for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
00552            VE = ToRepoint.end(); VI != VE; ++VI) {
00553         Value *V = *VI;
00554 
00555         VNPair pair(V, n, Subtree);
00556         VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
00557         VNMapType::iterator I = std::lower_bound(B, E, pair);
00558         if (I != E && I->V == V && I->Subtree == Subtree)
00559           I->index = n; // Update best choice
00560         else
00561           VNMap.insert(I, pair); // New Value
00562 
00563         // XXX: we currently don't have to worry about updating values with
00564         // more specific Subtrees, but we will need to for PHI node support.
00565 
00566 #ifndef NDEBUG
00567         Value *V_n = value(n);
00568         if (isa<Constant>(V) && isa<Constant>(V_n)) {
00569           assert(V == V_n && "Constant equals different constant?");
00570         }
00571 #endif
00572       }
00573     }
00574 
00575     /// remove - removes all references to value V.
00576     void remove(Value *V) {
00577       VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
00578       VNPair pair(V, 0, DTDFS->getRootNode());
00579       VNMapType::iterator J = std::upper_bound(B, E, pair);
00580       VNMapType::iterator I = J;
00581 
00582       while (I != B && (I == E || I->V == V)) --I;
00583 
00584       VNMap.erase(I, J);
00585     }
00586   };
00587 
00588   /// The InequalityGraph stores the relationships between values.
00589   /// Each Value in the graph is assigned to a Node. Nodes are pointer
00590   /// comparable for equality. The caller is expected to maintain the logical
00591   /// consistency of the system.
00592   ///
00593   /// The InequalityGraph class may invalidate Node*s after any mutator call.
00594   /// @brief The InequalityGraph stores the relationships between values.
00595   class VISIBILITY_HIDDEN InequalityGraph {
00596     ValueNumbering &VN;
00597     DomTreeDFS::Node *TreeRoot;
00598 
00599     InequalityGraph();                  // DO NOT IMPLEMENT
00600     InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
00601   public:
00602     InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
00603       : VN(VN), TreeRoot(TreeRoot) {}
00604 
00605     class Node;
00606 
00607     /// An Edge is contained inside a Node making one end of the edge implicit
00608     /// and contains a pointer to the other end. The edge contains a lattice
00609     /// value specifying the relationship and an DomTreeDFS::Node specifying
00610     /// the root in the dominator tree to which this edge applies.
00611     class VISIBILITY_HIDDEN Edge {
00612     public:
00613       Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
00614         : To(T), LV(V), Subtree(ST) {}
00615 
00616       unsigned To;
00617       LatticeVal LV;
00618       DomTreeDFS::Node *Subtree;
00619 
00620       bool operator<(const Edge &edge) const {
00621         if (To != edge.To) return To < edge.To;
00622         return *Subtree < *edge.Subtree;
00623       }
00624 
00625       bool operator<(unsigned to) const {
00626         return To < to;
00627       }
00628 
00629       bool operator>(unsigned to) const {
00630         return To > to;
00631       }
00632 
00633       friend bool operator<(unsigned to, const Edge &edge) {
00634         return edge.operator>(to);
00635       }
00636     };
00637 
00638     /// A single node in the InequalityGraph. This stores the canonical Value
00639     /// for the node, as well as the relationships with the neighbours.
00640     ///
00641     /// @brief A single node in the InequalityGraph.
00642     class VISIBILITY_HIDDEN Node {
00643       friend class InequalityGraph;
00644 
00645       typedef SmallVector<Edge, 4> RelationsType;
00646       RelationsType Relations;
00647 
00648       // TODO: can this idea improve performance?
00649       //friend class std::vector<Node>;
00650       //Node(Node &N) { RelationsType.swap(N.RelationsType); }
00651 
00652     public:
00653       typedef RelationsType::iterator       iterator;
00654       typedef RelationsType::const_iterator const_iterator;
00655 
00656 #ifndef NDEBUG
00657       virtual ~Node() {}
00658       virtual void dump() const {
00659         dump(*cerr.stream());
00660       }
00661     private:
00662       void dump(std::ostream &os) const {
00663         static const std::string names[32] =
00664           { "000000", "000001", "000002", "000003", "000004", "000005",
00665             "000006", "000007", "000008", "000009", "     >", "    >=",
00666             "  s>u<", "s>=u<=", "    s>", "   s>=", "000016", "000017",
00667             "  s<u>", "s<=u>=", "     <", "    <=", "    s<", "   s<=",
00668             "000024", "000025", "    u>", "   u>=", "    u<", "   u<=",
00669             "    !=", "000031" };
00670         for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
00671           os << names[NI->LV] << " " << NI->To
00672              << " (" << NI->Subtree->getDFSNumIn() << "), ";
00673         }
00674       }
00675     public:
00676 #endif
00677 
00678       iterator begin()             { return Relations.begin(); }
00679       iterator end()               { return Relations.end();   }
00680       const_iterator begin() const { return Relations.begin(); }
00681       const_iterator end()   const { return Relations.end();   }
00682 
00683       iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
00684         iterator E = end();
00685         for (iterator I = std::lower_bound(begin(), E, n);
00686              I != E && I->To == n; ++I) {
00687           if (Subtree->DominatedBy(I->Subtree))
00688             return I;
00689         }
00690         return E;
00691       }
00692 
00693       const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
00694         const_iterator E = end();
00695         for (const_iterator I = std::lower_bound(begin(), E, n);
00696              I != E && I->To == n; ++I) {
00697           if (Subtree->DominatedBy(I->Subtree))
00698             return I;
00699         }
00700         return E;
00701       }
00702 
00703       /// update - updates the lattice value for a given node, creating a new
00704       /// entry if one doesn't exist. The new lattice value must not be
00705       /// inconsistent with any previously existing value.
00706       void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
00707         assert(validPredicate(R) && "Invalid predicate.");
00708 
00709         Edge edge(n, R, Subtree);
00710         iterator B = begin(), E = end();
00711         iterator I = std::lower_bound(B, E, edge);
00712 
00713         iterator J = I;
00714         while (J != E && J->To == n) {
00715           if (Subtree->DominatedBy(J->Subtree))
00716             break;
00717           ++J;
00718         }
00719 
00720         if (J != E && J->To == n) {
00721           edge.LV = static_cast<LatticeVal>(J->LV & R);
00722           assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
00723 
00724           if (edge.LV == J->LV)
00725             return; // This update adds nothing new.
00726         }
00727 
00728         if (I != B) {
00729           // We also have to tighten any edge beneath our update.
00730           for (iterator K = I - 1; K->To == n; --K) {
00731             if (K->Subtree->DominatedBy(Subtree)) {
00732               LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
00733               assert(validPredicate(LV) && "Invalid union of lattice values");
00734               K->LV = LV;
00735             }
00736             if (K == B) break;
00737           }
00738         }
00739 
00740         // Insert new edge at Subtree if it isn't already there.
00741         if (I == E || I->To != n || Subtree != I->Subtree)
00742           Relations.insert(I, edge);
00743       }
00744     };
00745 
00746   private:
00747 
00748     std::vector<Node> Nodes;
00749 
00750   public:
00751     /// node - returns the node object at a given value number. The pointer
00752     /// returned may be invalidated on the next call to node().
00753     Node *node(unsigned index) {
00754       assert(VN.value(index)); // This triggers the necessary checks.
00755       if (Nodes.size() < index) Nodes.resize(index);
00756       return &Nodes[index-1];
00757     }
00758 
00759     /// isRelatedBy - true iff n1 op n2
00760     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
00761                      LatticeVal LV) {
00762       if (n1 == n2) return LV & EQ_BIT;
00763 
00764       Node *N1 = node(n1);
00765       Node::iterator I = N1->find(n2, Subtree), E = N1->end();
00766       if (I != E) return (I->LV & LV) == I->LV;
00767 
00768       return false;
00769     }
00770 
00771     // The add* methods assume that your input is logically valid and may 
00772     // assertion-fail or infinitely loop if you attempt a contradiction.
00773 
00774     /// addInequality - Sets n1 op n2.
00775     /// It is also an error to call this on an inequality that is already true.
00776     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
00777                        LatticeVal LV1) {
00778       assert(n1 != n2 && "A node can't be inequal to itself.");
00779 
00780       if (LV1 != NE)
00781         assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
00782                "Contradictory inequality.");
00783 
00784       // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
00785       // add %a < %n2 too. This keeps the graph fully connected.
00786       if (LV1 != NE) {
00787         // Break up the relationship into signed and unsigned comparison parts.
00788         // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
00789         // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
00790         // should have the EQ_BIT iff it's set for both op1 and op2.
00791 
00792         unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
00793         unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
00794 
00795         for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
00796           if (I->LV != NE && I->To != n2) {
00797 
00798             DomTreeDFS::Node *Local_Subtree = NULL;
00799             if (Subtree->DominatedBy(I->Subtree))
00800               Local_Subtree = Subtree;
00801             else if (I->Subtree->DominatedBy(Subtree))
00802               Local_Subtree = I->Subtree;
00803 
00804             if (Local_Subtree) {
00805               unsigned new_relationship = 0;
00806               LatticeVal ILV = reversePredicate(I->LV);
00807               unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
00808               unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
00809 
00810               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
00811                 new_relationship |= ILV_s;
00812               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
00813                 new_relationship |= ILV_u;
00814 
00815               if (new_relationship) {
00816                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
00817                   new_relationship |= (SLT_BIT|SGT_BIT);
00818                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
00819                   new_relationship |= (ULT_BIT|UGT_BIT);
00820                 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
00821                   new_relationship |= EQ_BIT;
00822 
00823                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
00824 
00825                 node(I->To)->update(n2, NewLV, Local_Subtree);
00826                 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
00827               }
00828             }
00829           }
00830         }
00831 
00832         for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
00833           if (I->LV != NE && I->To != n1) {
00834             DomTreeDFS::Node *Local_Subtree = NULL;
00835             if (Subtree->DominatedBy(I->Subtree))
00836               Local_Subtree = Subtree;
00837             else if (I->Subtree->DominatedBy(Subtree))
00838               Local_Subtree = I->Subtree;
00839 
00840             if (Local_Subtree) {
00841               unsigned new_relationship = 0;
00842               unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
00843               unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
00844 
00845               if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
00846                 new_relationship |= ILV_s;
00847 
00848               if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
00849                 new_relationship |= ILV_u;
00850 
00851               if (new_relationship) {
00852                 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
00853                   new_relationship |= (SLT_BIT|SGT_BIT);
00854                 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
00855                   new_relationship |= (ULT_BIT|UGT_BIT);
00856                 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
00857                   new_relationship |= EQ_BIT;
00858 
00859                 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
00860 
00861                 node(n1)->update(I->To, NewLV, Local_Subtree);
00862                 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
00863               }
00864             }
00865           }
00866         }
00867       }
00868 
00869       node(n1)->update(n2, LV1, Subtree);
00870       node(n2)->update(n1, reversePredicate(LV1), Subtree);
00871     }
00872 
00873     /// remove - removes a node from the graph by removing all references to
00874     /// and from it.
00875     void remove(unsigned n) {
00876       Node *N = node(n);
00877       for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
00878         Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
00879         do {
00880           node(NI->To)->Relations.erase(Iter);
00881           Iter = node(NI->To)->find(n, TreeRoot);
00882         } while (Iter != node(NI->To)->end());
00883       }
00884       N->Relations.clear();
00885     }
00886 
00887 #ifndef NDEBUG
00888     virtual ~InequalityGraph() {}
00889     virtual void dump() {
00890       dump(*cerr.stream());
00891     }
00892 
00893     void dump(std::ostream &os) {
00894       for (unsigned i = 1; i <= Nodes.size(); ++i) {
00895         os << i << " = {";
00896         node(i)->dump(os);
00897         os << "}\n";
00898       }
00899     }
00900 #endif
00901   };
00902 
00903   class VRPSolver;
00904 
00905   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
00906   /// in the InequalityGraph.
00907   class VISIBILITY_HIDDEN ValueRanges {
00908     ValueNumbering &VN;
00909     TargetData *TD;
00910     LLVMContext *Context;
00911 
00912     class VISIBILITY_HIDDEN ScopedRange {
00913       typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
00914               RangeListType;
00915       RangeListType RangeList;
00916 
00917       static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
00918                       const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
00919         return *LHS.first < *RHS.first;
00920       }
00921 
00922     public:
00923 #ifndef NDEBUG
00924       virtual ~ScopedRange() {}
00925       virtual void dump() const {
00926         dump(*cerr.stream());
00927       }
00928 
00929       void dump(std::ostream &os) const {
00930         os << "{";
00931         for (const_iterator I = begin(), E = end(); I != E; ++I) {
00932           os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
00933         }
00934         os << "}";
00935       }
00936 #endif
00937 
00938       typedef RangeListType::iterator       iterator;
00939       typedef RangeListType::const_iterator const_iterator;
00940 
00941       iterator begin() { return RangeList.begin(); }
00942       iterator end()   { return RangeList.end(); }
00943       const_iterator begin() const { return RangeList.begin(); }
00944       const_iterator end()   const { return RangeList.end(); }
00945 
00946       iterator find(DomTreeDFS::Node *Subtree) {
00947         iterator E = end();
00948         iterator I = std::lower_bound(begin(), E,
00949                                       std::make_pair(Subtree, empty), swo);
00950 
00951         while (I != E && !I->first->dominates(Subtree)) ++I;
00952         return I;
00953       }
00954 
00955       const_iterator find(DomTreeDFS::Node *Subtree) const {
00956         const_iterator E = end();
00957         const_iterator I = std::lower_bound(begin(), E,
00958                                             std::make_pair(Subtree, empty), swo);
00959 
00960         while (I != E && !I->first->dominates(Subtree)) ++I;
00961         return I;
00962       }
00963 
00964       void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
00965         assert(!CR.isEmptySet() && "Empty ConstantRange.");
00966         assert(!CR.isSingleElement() && "Refusing to store single element.");
00967 
00968         iterator E = end();
00969         iterator I =
00970             std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
00971 
00972         if (I != end() && I->first == Subtree) {
00973           ConstantRange CR2 = I->second.intersectWith(CR);
00974           assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
00975                  "Invalid union of ranges.");
00976           I->second = CR2;
00977         } else
00978           RangeList.insert(I, std::make_pair(Subtree, CR));
00979       }
00980     };
00981 
00982     std::vector<ScopedRange> Ranges;
00983 
00984     void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
00985       if (CR.isFullSet()) return;
00986       if (Ranges.size() < n) Ranges.resize(n);
00987       Ranges[n-1].update(CR, Subtree);
00988     }
00989 
00990     /// create - Creates a ConstantRange that matches the given LatticeVal
00991     /// relation with a given integer.
00992     ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
00993       assert(!CR.isEmptySet() && "Can't deal with empty set.");
00994 
00995       if (LV == NE)
00996         return ConstantRange::makeICmpRegion(ICmpInst::ICMP_NE, CR);
00997 
00998       unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
00999       unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
01000       bool hasEQ = LV & EQ_BIT;
01001 
01002       ConstantRange Range(CR.getBitWidth());
01003 
01004       if (LV_s == SGT_BIT) {
01005         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
01006                     hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
01007       } else if (LV_s == SLT_BIT) {
01008         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
01009                     hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
01010       }
01011 
01012       if (LV_u == UGT_BIT) {
01013         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
01014                     hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
01015       } else if (LV_u == ULT_BIT) {
01016         Range = Range.intersectWith(ConstantRange::makeICmpRegion(
01017                     hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
01018       }
01019 
01020       return Range;
01021     }
01022 
01023 #ifndef NDEBUG
01024     bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
01025       return V == VN.canonicalize(V, Subtree);
01026     }
01027 #endif
01028 
01029   public:
01030 
01031     ValueRanges(ValueNumbering &VN, TargetData *TD, LLVMContext *C) :
01032       VN(VN), TD(TD), Context(C) {}
01033 
01034 #ifndef NDEBUG
01035     virtual ~ValueRanges() {}
01036 
01037     virtual void dump() const {
01038       dump(*cerr.stream());
01039     }
01040 
01041     void dump(std::ostream &os) const {
01042       for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
01043         os << (i+1) << " = ";
01044         Ranges[i].dump(os);
01045         os << "\n";
01046       }
01047     }
01048 #endif
01049 
01050     /// range - looks up the ConstantRange associated with a value number.
01051     ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
01052       assert(VN.value(n)); // performs range checks
01053 
01054       if (n <= Ranges.size()) {
01055         ScopedRange::iterator I = Ranges[n-1].find(Subtree);
01056         if (I != Ranges[n-1].end()) return I->second;
01057       }
01058 
01059       Value *V = VN.value(n);
01060       ConstantRange CR = range(V);
01061       return CR;
01062     }
01063 
01064     /// range - determine a range from a Value without performing any lookups.
01065     ConstantRange range(Value *V) const {
01066       if (ConstantInt *C = dyn_cast<ConstantInt>(V))
01067         return ConstantRange(C->getValue());
01068       else if (isa<ConstantPointerNull>(V))
01069         return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
01070       else
01071         return ConstantRange(typeToWidth(V->getType()));
01072     }
01073 
01074     // typeToWidth - returns the number of bits necessary to store a value of
01075     // this type, or zero if unknown.
01076     uint32_t typeToWidth(const Type *Ty) const {
01077       if (TD)
01078         return TD->getTypeSizeInBits(Ty);
01079       else
01080         return Ty->getPrimitiveSizeInBits();
01081     }
01082 
01083     static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
01084                             LatticeVal LV) {
01085       switch (LV) {
01086       default: assert(!"Impossible lattice value!");
01087       case NE:
01088         return CR1.intersectWith(CR2).isEmptySet();
01089       case ULT:
01090         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
01091       case ULE:
01092         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
01093       case UGT:
01094         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
01095       case UGE:
01096         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
01097       case SLT:
01098         return CR1.getSignedMax().slt(CR2.getSignedMin());
01099       case SLE:
01100         return CR1.getSignedMax().sle(CR2.getSignedMin());
01101       case SGT:
01102         return CR1.getSignedMin().sgt(CR2.getSignedMax());
01103       case SGE:
01104         return CR1.getSignedMin().sge(CR2.getSignedMax());
01105       case LT:
01106         return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
01107                CR1.getSignedMax().slt(CR2.getUnsignedMin());
01108       case LE:
01109         return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
01110                CR1.getSignedMax().sle(CR2.getUnsignedMin());
01111       case GT:
01112         return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
01113                CR1.getSignedMin().sgt(CR2.getSignedMax());
01114       case GE:
01115         return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
01116                CR1.getSignedMin().sge(CR2.getSignedMax());
01117       case SLTUGT:
01118         return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
01119                CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
01120       case SLEUGE:
01121         return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
01122                CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
01123       case SGTULT:
01124         return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
01125                CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
01126       case SGEULE:
01127         return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
01128                CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
01129       }
01130     }
01131 
01132     bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
01133                      LatticeVal LV) {
01134       ConstantRange CR1 = range(n1, Subtree);
01135       ConstantRange CR2 = range(n2, Subtree);
01136 
01137       // True iff all values in CR1 are LV to all values in CR2.
01138       return isRelatedBy(CR1, CR2, LV);
01139     }
01140 
01141     void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
01142                        VRPSolver *VRP);
01143     void markBlock(VRPSolver *VRP);
01144 
01145     void mergeInto(Value **I, unsigned n, unsigned New,
01146                    DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
01147       ConstantRange CR_New = range(New, Subtree);
01148       ConstantRange Merged = CR_New;
01149 
01150       for (; n != 0; ++I, --n) {
01151         unsigned i = VN.valueNumber(*I, Subtree);
01152         ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
01153         if (CR_Kill.isFullSet()) continue;
01154         Merged = Merged.intersectWith(CR_Kill);
01155       }
01156 
01157       if (Merged.isFullSet() || Merged == CR_New) return;
01158 
01159       applyRange(New, Merged, Subtree, VRP);
01160     }
01161 
01162     void applyRange(unsigned n, const ConstantRange &CR,
01163                     DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
01164       ConstantRange Merged = CR.intersectWith(range(n, Subtree));
01165       if (Merged.isEmptySet()) {
01166         markBlock(VRP);
01167         return;
01168       }
01169 
01170       if (const APInt *I = Merged.getSingleElement()) {
01171         Value *V = VN.value(n); // XXX: redesign worklist.
01172         const Type *Ty = V->getType();
01173         if (Ty->isInteger()) {
01174           addToWorklist(V, ConstantInt::get(*Context, *I),
01175                         ICmpInst::ICMP_EQ, VRP);
01176           return;
01177         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
01178           assert(*I == 0 && "Pointer is null but not zero?");
01179           addToWorklist(V, ConstantPointerNull::get(PTy),
01180                         ICmpInst::ICMP_EQ, VRP);
01181           return;
01182         }
01183       }
01184 
01185       update(n, Merged, Subtree);
01186     }
01187 
01188     void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
01189                       VRPSolver *VRP) {
01190       ConstantRange CR1 = range(n1, Subtree);
01191       ConstantRange CR2 = range(n2, Subtree);
01192 
01193       uint32_t W = CR1.getBitWidth();
01194 
01195       if (const APInt *I = CR1.getSingleElement()) {
01196         if (CR2.isFullSet()) {
01197           ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
01198           applyRange(n2, NewCR2, Subtree, VRP);
01199         } else if (*I == CR2.getLower()) {
01200           APInt NewLower(CR2.getLower() + 1),
01201                 NewUpper(CR2.getUpper());
01202           if (NewLower == NewUpper)
01203             NewLower = NewUpper = APInt::getMinValue(W);
01204 
01205           ConstantRange NewCR2(NewLower, NewUpper);
01206           applyRange(n2, NewCR2, Subtree, VRP);
01207         } else if (*I == CR2.getUpper() - 1) {
01208           APInt NewLower(CR2.getLower()),
01209                 NewUpper(CR2.getUpper() - 1);
01210           if (NewLower == NewUpper)
01211             NewLower = NewUpper = APInt::getMinValue(W);
01212 
01213           ConstantRange NewCR2(NewLower, NewUpper);
01214           applyRange(n2, NewCR2, Subtree, VRP);
01215         }
01216       }
01217 
01218       if (const APInt *I = CR2.getSingleElement()) {
01219         if (CR1.isFullSet()) {
01220           ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
01221           applyRange(n1, NewCR1, Subtree, VRP);
01222         } else if (*I == CR1.getLower()) {
01223           APInt NewLower(CR1.getLower() + 1),
01224                 NewUpper(CR1.getUpper());
01225           if (NewLower == NewUpper)
01226             NewLower = NewUpper = APInt::getMinValue(W);
01227 
01228           ConstantRange NewCR1(NewLower, NewUpper);
01229           applyRange(n1, NewCR1, Subtree, VRP);
01230         } else if (*I == CR1.getUpper() - 1) {
01231           APInt NewLower(CR1.getLower()),
01232                 NewUpper(CR1.getUpper() - 1);
01233           if (NewLower == NewUpper)
01234             NewLower = NewUpper = APInt::getMinValue(W);
01235 
01236           ConstantRange NewCR1(NewLower, NewUpper);
01237           applyRange(n1, NewCR1, Subtree, VRP);
01238         }
01239       }
01240     }
01241 
01242     void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
01243                        LatticeVal LV, VRPSolver *VRP) {
01244       assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
01245 
01246       if (LV == NE) {
01247         addNotEquals(n1, n2, Subtree, VRP);
01248         return;
01249       }
01250 
01251       ConstantRange CR1 = range(n1, Subtree);
01252       ConstantRange CR2 = range(n2, Subtree);
01253 
01254       if (!CR1.isSingleElement()) {
01255         ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
01256         if (NewCR1 != CR1)
01257           applyRange(n1, NewCR1, Subtree, VRP);
01258       }
01259 
01260       if (!CR2.isSingleElement()) {
01261         ConstantRange NewCR2 = CR2.intersectWith(
01262                                        create(reversePredicate(LV), CR1));
01263         if (NewCR2 != CR2)
01264           applyRange(n2, NewCR2, Subtree, VRP);
01265       }
01266     }
01267   };
01268 
01269   /// UnreachableBlocks keeps tracks of blocks that are for one reason or
01270   /// another discovered to be unreachable. This is used to cull the graph when
01271   /// analyzing instructions, and to mark blocks with the "unreachable"
01272   /// terminator instruction after the function has executed.
01273   class VISIBILITY_HIDDEN UnreachableBlocks {
01274   private:
01275     std::vector<BasicBlock *> DeadBlocks;
01276 
01277   public:
01278     /// mark - mark a block as dead
01279     void mark(BasicBlock *BB) {
01280       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
01281       std::vector<BasicBlock *>::iterator I =
01282         std::lower_bound(DeadBlocks.begin(), E, BB);
01283 
01284       if (I == E || *I != BB) DeadBlocks.insert(I, BB);
01285     }
01286 
01287     /// isDead - returns whether a block is known to be dead already
01288     bool isDead(BasicBlock *BB) {
01289       std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
01290       std::vector<BasicBlock *>::iterator I =
01291         std::lower_bound(DeadBlocks.begin(), E, BB);
01292 
01293       return I != E && *I == BB;
01294     }
01295 
01296     /// kill - replace the dead blocks' terminator with an UnreachableInst.
01297     bool kill() {
01298       bool modified = false;
01299       for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
01300            E = DeadBlocks.end(); I != E; ++I) {
01301         BasicBlock *BB = *I;
01302 
01303         DEBUG(errs() << "unreachable block: " << BB->getName() << "\n");
01304 
01305         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
01306              SI != SE; ++SI) {
01307           BasicBlock *Succ = *SI;
01308           Succ->removePredecessor(BB);
01309         }
01310 
01311         TerminatorInst *TI = BB->getTerminator();
01312         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
01313         TI->eraseFromParent();
01314         new UnreachableInst(BB->getContext(), BB);
01315         ++NumBlocks;
01316         modified = true;
01317       }
01318       DeadBlocks.clear();
01319       return modified;
01320     }
01321   };
01322 
01323   /// VRPSolver keeps track of how changes to one variable affect other
01324   /// variables, and forwards changes along to the InequalityGraph. It
01325   /// also maintains the correct choice for "canonical" in the IG.
01326   /// @brief VRPSolver calculates inferences from a new relationship.
01327   class VISIBILITY_HIDDEN VRPSolver {
01328   private:
01329     friend class ValueRanges;
01330 
01331     struct Operation {
01332       Value *LHS, *RHS;
01333       ICmpInst::Predicate Op;
01334 
01335       BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
01336       Instruction *ContextInst;
01337     };
01338     std::deque<Operation> WorkList;
01339 
01340     ValueNumbering &VN;
01341     InequalityGraph &IG;
01342     UnreachableBlocks &UB;
01343     ValueRanges &VR;
01344     DomTreeDFS *DTDFS;
01345     DomTreeDFS::Node *Top;
01346     BasicBlock *TopBB;
01347     Instruction *TopInst;
01348     bool &modified;
01349     LLVMContext *Context;
01350 
01351     typedef InequalityGraph::Node Node;
01352 
01353     // below - true if the Instruction is dominated by the current context
01354     // block or instruction
01355     bool below(Instruction *I) {
01356       BasicBlock *BB = I->getParent();
01357       if (TopInst && TopInst->getParent() == BB) {
01358         if (isa<TerminatorInst>(TopInst)) return false;
01359         if (isa<TerminatorInst>(I)) return true;
01360         if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
01361         if (!isa<PHINode>(TopInst) &&  isa<PHINode>(I)) return false;
01362 
01363         for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
01364              Iter != E; ++Iter) {
01365           if (&*Iter == TopInst) return true;
01366           else if (&*Iter == I) return false;
01367         }
01368         assert(!"Instructions not found in parent BasicBlock?");
01369       } else {
01370         DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
01371         if (!Node) return false;
01372         return Top->dominates(Node);
01373       }
01374       return false; // Not reached
01375     }
01376 
01377     // aboveOrBelow - true if the Instruction either dominates or is dominated
01378     // by the current context block or instruction
01379     bool aboveOrBelow(Instruction *I) {
01380       BasicBlock *BB = I->getParent();
01381       DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
01382       if (!Node) return false;
01383 
01384       return Top == Node || Top->dominates(Node) || Node->dominates(Top);
01385     }
01386 
01387     bool makeEqual(Value *V1, Value *V2) {
01388       DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
01389       DOUT << "context is ";
01390       DEBUG(if (TopInst) 
01391               errs() << "I: " << *TopInst << "\n";
01392             else 
01393               errs() << "BB: " << TopBB->getName()
01394                      << "(" << Top->getDFSNumIn() << ")\n");
01395 
01396       assert(V1->getType() == V2->getType() &&
01397              "Can't make two values with different types equal.");
01398 
01399       if (V1 == V2) return true;
01400 
01401       if (isa<Constant>(V1) && isa<Constant>(V2))
01402         return false;
01403 
01404       unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
01405 
01406       if (n1 && n2) {
01407         if (n1 == n2) return true;
01408         if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
01409       }
01410 
01411       if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
01412       if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
01413 
01414       assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
01415 
01416       assert(!isa<Constant>(V2) && "Tried to remove a constant.");
01417 
01418       SetVector<unsigned> Remove;
01419       if (n2) Remove.insert(n2);
01420 
01421       if (n1 && n2) {
01422         // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
01423         // We can't just merge %x and %y because the relationship with %z would
01424         // be EQ and that's invalid. What we're doing is looking for any nodes
01425         // %z such that %x <= %z and %y >= %z, and vice versa.
01426 
01427         Node::iterator end = IG.node(n2)->end();
01428 
01429         // Find the intersection between N1 and N2 which is dominated by
01430         // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
01431         // Remove.
01432         for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
01433              I != E; ++I) {
01434           if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
01435 
01436           unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
01437           unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
01438           Node::iterator NI = IG.node(n2)->find(I->To, Top);
01439           if (NI != end) {
01440             LatticeVal NILV = reversePredicate(NI->LV);
01441             unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
01442             unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
01443 
01444             if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
01445                 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
01446               Remove.insert(I->To);
01447           }
01448         }
01449 
01450         // See if one of the nodes about to be removed is actually a better
01451         // canonical choice than n1.
01452         unsigned orig_n1 = n1;
01453         SetVector<unsigned>::iterator DontRemove = Remove.end();
01454         for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
01455              E = Remove.end(); I != E; ++I) {
01456           unsigned n = *I;
01457           Value *V = VN.value(n);
01458           if (VN.compare(V, V1)) {
01459             V1 = V;
01460             n1 = n;
01461             DontRemove = I;
01462           }
01463         }
01464         if (DontRemove != Remove.end()) {
01465           unsigned n = *DontRemove;
01466           Remove.remove(n);
01467           Remove.insert(orig_n1);
01468         }
01469       }
01470 
01471       // We'd like to allow makeEqual on two values to perform a simple
01472       // substitution without creating nodes in the IG whenever possible.
01473       //
01474       // The first iteration through this loop operates on V2 before going
01475       // through the Remove list and operating on those too. If all of the
01476       // iterations performed simple replacements then we exit early.
01477       bool mergeIGNode = false;
01478       unsigned i = 0;
01479       for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
01480         if (i) R = VN.value(Remove[i]); // skip n2.
01481 
01482         // Try to replace the whole instruction. If we can, we're done.
01483         Instruction *I2 = dyn_cast<Instruction>(R);
01484         if (I2 && below(I2)) {
01485           std::vector<Instruction *> ToNotify;
01486           for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
01487                UI != UE;) {
01488             Use &TheUse = UI.getUse();
01489             ++UI;
01490             Instruction *I = cast<Instruction>(TheUse.getUser());
01491             ToNotify.push_back(I);
01492           }
01493 
01494           DOUT << "Simply removing " << *I2
01495                << ", replacing with " << *V1 << "\n";
01496           I2->replaceAllUsesWith(V1);
01497           // leave it dead; it'll get erased later.
01498           ++NumInstruction;
01499           modified = true;
01500 
01501           for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
01502                IE = ToNotify.end(); II != IE; ++II) {
01503             opsToDef(*II);
01504           }
01505 
01506           continue;
01507         }
01508 
01509         // Otherwise, replace all dominated uses.
01510         for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
01511              UI != UE;) {
01512           Use &TheUse = UI.getUse();
01513           ++UI;
01514           if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
01515             if (below(I)) {
01516               TheUse.set(V1);
01517               modified = true;
01518               ++NumVarsReplaced;
01519               opsToDef(I);
01520             }
01521           }
01522         }
01523 
01524         // If that killed the instruction, stop here.
01525         if (I2 && isInstructionTriviallyDead(I2)) {
01526           DOUT << "Killed all uses of " << *I2
01527                << ", replacing with " << *V1 << "\n";
01528           continue;
01529         }
01530 
01531         // If we make it to here, then we will need to create a node for N1.
01532         // Otherwise, we can skip out early!
01533         mergeIGNode = true;
01534       }
01535 
01536       if (!isa<Constant>(V1)) {
01537         if (Remove.empty()) {
01538           VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
01539         } else {
01540           std::vector<Value*> RemoveVals;
01541           RemoveVals.reserve(Remove.size());
01542 
01543           for (SetVector<unsigned>::iterator I = Remove.begin(),
01544                E = Remove.end(); I != E; ++I) {
01545             Value *V = VN.value(*I);
01546             if (!V->use_empty())
01547               RemoveVals.push_back(V);
01548           }
01549           VR.mergeInto(&RemoveVals[0], RemoveVals.size(), 
01550                        VN.getOrInsertVN(V1, Top), Top, this);
01551         }
01552       }
01553 
01554       if (mergeIGNode) {
01555         // Create N1.
01556         if (!n1) n1 = VN.getOrInsertVN(V1, Top);
01557         IG.node(n1); // Ensure that IG.Nodes won't get resized
01558 
01559         // Migrate relationships from removed nodes to N1.
01560         for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
01561              I != E; ++I) {
01562           unsigned n = *I;
01563           for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
01564                NI != NE; ++NI) {
01565             if (NI->Subtree->DominatedBy(Top)) {
01566               if (NI->To == n1) {
01567                 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
01568                 continue;
01569               }
01570               if (Remove.count(NI->To))
01571                 continue;
01572 
01573               IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
01574               IG.node(n1)->update(NI->To, NI->LV, Top);
01575             }
01576           }
01577         }
01578 
01579         // Point V2 (and all items in Remove) to N1.
01580         if (!n2)
01581           VN.addEquality(n1, V2, Top);
01582         else {
01583           for (SetVector<unsigned>::iterator I = Remove.begin(),
01584                E = Remove.end(); I != E; ++I) {
01585             VN.addEquality(n1, VN.value(*I), Top);
01586           }
01587         }
01588 
01589         // If !Remove.empty() then V2 = Remove[0]->getValue().
01590         // Even when Remove is empty, we still want to process V2.
01591         i = 0;
01592         for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
01593           if (i) R = VN.value(Remove[i]); // skip n2.
01594 
01595           if (Instruction *I2 = dyn_cast<Instruction>(R)) {
01596             if (aboveOrBelow(I2))
01597             defToOps(I2);
01598           }
01599           for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
01600                UI != UE;) {
01601             Use &TheUse = UI.getUse();
01602             ++UI;
01603             if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
01604               if (aboveOrBelow(I))
01605                 opsToDef(I);
01606             }
01607           }
01608         }
01609       }
01610 
01611       // re-opsToDef all dominated users of V1.
01612       if (Instruction *I = dyn_cast<Instruction>(V1)) {
01613         for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
01614              UI != UE;) {
01615           Use &TheUse = UI.getUse();
01616           ++UI;
01617           Value *V = TheUse.getUser();
01618           if (!V->use_empty()) {
01619             Instruction *Inst = cast<Instruction>(V);
01620             if (aboveOrBelow(Inst))
01621               opsToDef(Inst);
01622           }
01623         }
01624       }
01625 
01626       return true;
01627     }
01628 
01629     /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
01630     /// Requires that the lattice value be valid; does not accept ICMP_EQ.
01631     static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
01632       switch (Pred) {
01633         case ICmpInst::ICMP_EQ:
01634           assert(!"No matching lattice value.");
01635           return static_cast<LatticeVal>(EQ_BIT);
01636         default:
01637           assert(!"Invalid 'icmp' predicate.");
01638         case ICmpInst::ICMP_NE:
01639           return NE;
01640         case ICmpInst::ICMP_UGT:
01641           return UGT;
01642         case ICmpInst::ICMP_UGE:
01643           return UGE;
01644         case ICmpInst::ICMP_ULT:
01645           return ULT;
01646         case ICmpInst::ICMP_ULE:
01647           return ULE;
01648         case ICmpInst::ICMP_SGT:
01649           return SGT;
01650         case ICmpInst::ICMP_SGE:
01651           return SGE;
01652         case ICmpInst::ICMP_SLT:
01653           return SLT;
01654         case ICmpInst::ICMP_SLE:
01655           return SLE;
01656       }
01657     }
01658 
01659   public:
01660     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
01661               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
01662               BasicBlock *TopBB)
01663       : VN(VN),
01664         IG(IG),
01665         UB(UB),
01666         VR(VR),
01667         DTDFS(DTDFS),
01668         Top(DTDFS->getNodeForBlock(TopBB)),
01669         TopBB(TopBB),
01670         TopInst(NULL),
01671         modified(modified),
01672         Context(&TopBB->getContext())
01673     {
01674       assert(Top && "VRPSolver created for unreachable basic block.");
01675     }
01676 
01677     VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
01678               ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
01679               Instruction *TopInst)
01680       : VN(VN),
01681         IG(IG),
01682         UB(UB),
01683         VR(VR),
01684         DTDFS(DTDFS),
01685         Top(DTDFS->getNodeForBlock(TopInst->getParent())),
01686         TopBB(TopInst->getParent()),
01687         TopInst(TopInst),
01688         modified(modified),
01689         Context(&TopInst->getContext())
01690     {
01691       assert(Top && "VRPSolver created for unreachable basic block.");
01692       assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
01693     }
01694 
01695     bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
01696       if (Constant *C1 = dyn_cast<Constant>(V1))
01697         if (Constant *C2 = dyn_cast<Constant>(V2))
01698           return ConstantExpr::getCompare(Pred, C1, C2) ==
01699                  ConstantInt::getTrue(*Context);
01700 
01701       unsigned n1 = VN.valueNumber(V1, Top);
01702       unsigned n2 = VN.valueNumber(V2, Top);
01703 
01704       if (n1 && n2) {
01705         if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
01706                              Pred == ICmpInst::ICMP_ULE ||
01707                              Pred == ICmpInst::ICMP_UGE ||
01708                              Pred == ICmpInst::ICMP_SLE ||
01709                              Pred == ICmpInst::ICMP_SGE;
01710         if (Pred == ICmpInst::ICMP_EQ) return false;
01711         if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
01712         if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
01713       }
01714 
01715       if ((n1 && !n2 && isa<Constant>(V2)) ||
01716           (n2 && !n1 && isa<Constant>(V1))) {
01717         ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
01718         ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
01719 
01720         if (Pred == ICmpInst::ICMP_EQ)
01721           return CR1.isSingleElement() &&
01722                  CR1.getSingleElement() == CR2.getSingleElement();
01723 
01724         return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
01725       }
01726       if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
01727       return false;
01728     }
01729 
01730     /// add - adds a new property to the work queue
01731     void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
01732              Instruction *I = NULL) {
01733       DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
01734       if (I) DOUT << " context: " << *I;
01735       else DOUT << " default context (" << Top->getDFSNumIn() << ")";
01736       DOUT << "\n";
01737 
01738       assert(V1->getType() == V2->getType() &&
01739              "Can't relate two values with different types.");
01740 
01741       WorkList.push_back(Operation());
01742       Operation &O = WorkList.back();
01743       O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
01744       O.ContextBB = I ? I->getParent() : TopBB;
01745     }
01746 
01747     /// defToOps - Given an instruction definition that we've learned something
01748     /// new about, find any new relationships between its operands.
01749     void defToOps(Instruction *I) {
01750       Instruction *NewContext = below(I) ? I : TopInst;
01751       Value *Canonical = VN.canonicalize(I, Top);
01752 
01753       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
01754         const Type *Ty = BO->getType();
01755         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
01756 
01757         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
01758         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
01759 
01760         // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
01761 
01762         switch (BO->getOpcode()) {
01763           case Instruction::And: {
01764             // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
01765             ConstantInt *CI = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
01766             if (Canonical == CI) {
01767               add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
01768               add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
01769             }
01770           } break;
01771           case Instruction::Or: {
01772             // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
01773             Constant *Zero = Constant::getNullValue(Ty);
01774             if (Canonical == Zero) {
01775               add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
01776               add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
01777             }
01778           } break;
01779           case Instruction::Xor: {
01780             // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
01781             // "xor i32 %c, %a" EQ %c then %a EQ 0
01782             // "xor i32 %c, %a" NE %c then %a NE 0
01783             // Repeat the above, with order of operands reversed.
01784             Value *LHS = Op0;
01785             Value *RHS = Op1;
01786             if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
01787 
01788             if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
01789               if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
01790                 add(RHS,
01791                   ConstantInt::get(*Context, CI->getValue() ^ Arg->getValue()),
01792                     ICmpInst::ICMP_EQ, NewContext);
01793               }
01794             }
01795             if (Canonical == LHS) {
01796               if (isa<ConstantInt>(Canonical))
01797                 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
01798                     NewContext);
01799             } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
01800               add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
01801                   NewContext);
01802             }
01803           } break;
01804           default:
01805             break;
01806         }
01807       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
01808         // "icmp ult i32 %a, %y" EQ true then %a u< y
01809         // etc.
01810 
01811         if (Canonical == ConstantInt::getTrue(*Context)) {
01812           add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
01813               NewContext);
01814         } else if (Canonical == ConstantInt::getFalse(*Context)) {
01815           add(IC->getOperand(0), IC->getOperand(1),
01816               ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
01817         }
01818       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
01819         if (I->getType()->isFPOrFPVector()) return;
01820 
01821         // Given: "%a = select i1 %x, i32 %b, i32 %c"
01822         // %a EQ %b and %b NE %c then %x EQ true
01823         // %a EQ %c and %b NE %c then %x EQ false
01824 
01825         Value *True  = SI->getTrueValue();
01826         Value *False = SI->getFalseValue();
01827         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
01828           if (Canonical == VN.canonicalize(True, Top) ||
01829               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
01830             add(SI->getCondition(), ConstantInt::getTrue(*Context),
01831                 ICmpInst::ICMP_EQ, NewContext);
01832           else if (Canonical == VN.canonicalize(False, Top) ||
01833                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
01834             add(SI->getCondition(), ConstantInt::getFalse(*Context),
01835                 ICmpInst::ICMP_EQ, NewContext);
01836         }
01837       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
01838         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
01839              OE = GEPI->idx_end(); OI != OE; ++OI) {
01840           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
01841           if (!Op || !Op->isZero()) return;
01842         }
01843         // TODO: The GEPI indices are all zero. Copy from definition to operand,
01844         // jumping the type plane as needed.
01845         if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
01846                         ICmpInst::ICMP_NE)) {
01847           Value *Ptr = GEPI->getPointerOperand();
01848           add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
01849               NewContext);
01850         }
01851       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
01852         const Type *SrcTy = CI->getSrcTy();
01853 
01854         unsigned ci = VN.getOrInsertVN(CI, Top);
01855         uint32_t W = VR.typeToWidth(SrcTy);
01856         if (!W) return;
01857         ConstantRange CR = VR.range(ci, Top);
01858 
01859         if (CR.isFullSet()) return;
01860 
01861         switch (CI->getOpcode()) {
01862           default: break;
01863           case Instruction::ZExt:
01864           case Instruction::SExt:
01865             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
01866                           CR.truncate(W), Top, this);
01867             break;
01868           case Instruction::BitCast:
01869             VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
01870                           CR, Top, this);
01871             break;
01872         }
01873       }
01874     }
01875 
01876     /// opsToDef - A new relationship was discovered involving one of this
01877     /// instruction's operands. Find any new relationship involving the
01878     /// definition, or another operand.
01879     void opsToDef(Instruction *I) {
01880       Instruction *NewContext = below(I) ? I : TopInst;
01881 
01882       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
01883         Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
01884         Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
01885 
01886         if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
01887           if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
01888             add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
01889                 ICmpInst::ICMP_EQ, NewContext);
01890             return;
01891           }
01892 
01893         // "%y = and i1 true, %x" then %x EQ %y
01894         // "%y = or i1 false, %x" then %x EQ %y
01895         // "%x = add i32 %y, 0" then %x EQ %y
01896         // "%x = mul i32 %y, 0" then %x EQ 0
01897 
01898         Instruction::BinaryOps Opcode = BO->getOpcode();
01899         const Type *Ty = BO->getType();
01900         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
01901 
01902         Constant *Zero = Constant::getNullValue(Ty);
01903         Constant *One = ConstantInt::get(Ty, 1);
01904         ConstantInt *AllOnes = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
01905 
01906         switch (Opcode) {
01907           default: break;
01908           case Instruction::LShr:
01909           case Instruction::AShr:
01910           case Instruction::Shl:
01911             if (Op1 == Zero) {
01912               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01913               return;
01914             }
01915             break;
01916           case Instruction::Sub:
01917             if (Op1 == Zero) {
01918               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01919               return;
01920             }
01921             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
01922               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
01923               ConstantRange CR = VR.range(n_ci0, Top);
01924               if (!CR.isFullSet()) {
01925                 CR.subtract(CI0->getValue());
01926                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
01927                 VR.applyRange(n_bo, CR, Top, this);
01928                 return;
01929               }
01930             }
01931             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
01932               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
01933               ConstantRange CR = VR.range(n_ci1, Top);
01934               if (!CR.isFullSet()) {
01935                 CR.subtract(CI1->getValue());
01936                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
01937                 VR.applyRange(n_bo, CR, Top, this);
01938                 return;
01939               }
01940             }
01941             break;
01942           case Instruction::Or:
01943             if (Op0 == AllOnes || Op1 == AllOnes) {
01944               add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
01945               return;
01946             }
01947             if (Op0 == Zero) {
01948               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
01949               return;
01950             } else if (Op1 == Zero) {
01951               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01952               return;
01953             }
01954             break;
01955           case Instruction::Add:
01956             if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
01957               unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
01958               ConstantRange CR = VR.range(n_ci0, Top);
01959               if (!CR.isFullSet()) {
01960                 CR.subtract(-CI0->getValue());
01961                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
01962                 VR.applyRange(n_bo, CR, Top, this);
01963                 return;
01964               }
01965             }
01966             if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
01967               unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
01968               ConstantRange CR = VR.range(n_ci1, Top);
01969               if (!CR.isFullSet()) {
01970                 CR.subtract(-CI1->getValue());
01971                 unsigned n_bo = VN.getOrInsertVN(BO, Top);
01972                 VR.applyRange(n_bo, CR, Top, this);
01973                 return;
01974               }
01975             }
01976             // fall-through
01977           case Instruction::Xor:
01978             if (Op0 == Zero) {
01979               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
01980               return;
01981             } else if (Op1 == Zero) {
01982               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01983               return;
01984             }
01985             break;
01986           case Instruction::And:
01987             if (Op0 == AllOnes) {
01988               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
01989               return;
01990             } else if (Op1 == AllOnes) {
01991               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
01992               return;
01993             }
01994             if (Op0 == Zero || Op1 == Zero) {
01995               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
01996               return;
01997             }
01998             break;
01999           case Instruction::Mul:
02000             if (Op0 == Zero || Op1 == Zero) {
02001               add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
02002               return;
02003             }
02004             if (Op0 == One) {
02005               add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
02006               return;
02007             } else if (Op1 == One) {
02008               add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
02009               return;
02010             }
02011             break;
02012         }
02013 
02014         // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
02015         // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
02016         // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
02017         // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
02018 
02019         Value *Known = Op0, *Unknown = Op1,
02020               *TheBO = VN.canonicalize(BO, Top);
02021         if (Known != TheBO) std::swap(Known, Unknown);
02022         if (Known == TheBO) {
02023           switch (Opcode) {
02024             default: break;
02025             case Instruction::LShr:
02026             case Instruction::AShr:
02027             case Instruction::Shl:
02028               if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
02029               // otherwise, fall-through.
02030             case Instruction::Sub:
02031               if (Unknown == Op0) break;
02032               // otherwise, fall-through.
02033             case Instruction::Xor:
02034             case Instruction::Add:
02035               add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
02036               break;
02037             case Instruction::UDiv:
02038             case Instruction::SDiv:
02039               if (Unknown == Op1) break;
02040               if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
02041                 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
02042               break;
02043           }
02044         }
02045 
02046         // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
02047 
02048       } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
02049         // "%a = icmp ult i32 %b, %c" and %b u<  %c then %a EQ true
02050         // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
02051         // etc.
02052 
02053         Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
02054         Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
02055 
02056         ICmpInst::Predicate Pred = IC->getPredicate();
02057         if (isRelatedBy(Op0, Op1, Pred))
02058           add(IC, ConstantInt::getTrue(*Context), ICmpInst::ICMP_EQ, NewContext);
02059         else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
02060           add(IC, ConstantInt::getFalse(*Context),
02061               ICmpInst::ICMP_EQ, NewContext);
02062 
02063       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
02064         if (I->getType()->isFPOrFPVector()) return;
02065 
02066         // Given: "%a = select i1 %x, i32 %b, i32 %c"
02067         // %x EQ true  then %a EQ %b
02068         // %x EQ false then %a EQ %c
02069         // %b EQ %c then %a EQ %b
02070 
02071         Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
02072         if (Canonical == ConstantInt::getTrue(*Context)) {
02073           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
02074         } else if (Canonical == ConstantInt::getFalse(*Context)) {
02075           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
02076         } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
02077                    VN.canonicalize(SI->getFalseValue(), Top)) {
02078           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
02079         }
02080       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
02081         const Type *DestTy = CI->getDestTy();
02082         if (DestTy->isFPOrFPVector()) return;
02083 
02084         Value *Op = VN.canonicalize(CI->getOperand(0), Top);
02085         Instruction::CastOps Opcode = CI->getOpcode();
02086 
02087         if (Constant *C = dyn_cast<Constant>(Op)) {
02088           add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
02089               ICmpInst::ICMP_EQ, NewContext);
02090         }
02091 
02092         uint32_t W = VR.typeToWidth(DestTy);
02093         unsigned ci = VN.getOrInsertVN(CI, Top);
02094         ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
02095 
02096         if (!CR.isFullSet()) {
02097           switch (Opcode) {
02098             default: break;
02099             case Instruction::ZExt:
02100               VR.applyRange(ci, CR.zeroExtend(W), Top, this);
02101               break;
02102             case Instruction::SExt:
02103               VR.applyRange(ci, CR.signExtend(W), Top, this);
02104               break;
02105             case Instruction::Trunc: {
02106               ConstantRange Result = CR.truncate(W);
02107               if (!Result.isFullSet())
02108                 VR.applyRange(ci, Result, Top, this);
02109             } break;
02110             case Instruction::BitCast:
02111               VR.applyRange(ci, CR, Top, this);
02112               break;
02113             // TODO: other casts?
02114           }
02115         }
02116       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
02117         for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
02118              OE = GEPI->idx_end(); OI != OE; ++OI) {
02119           ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
02120           if (!Op || !Op->isZero()) return;
02121         }
02122         // TODO: The GEPI indices are all zero. Copy from operand to definition,
02123         // jumping the type plane as needed.
02124         Value *Ptr = GEPI->getPointerOperand();
02125         if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
02126                         ICmpInst::ICMP_NE)) {
02127           add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
02128               NewContext);
02129         }
02130       }
02131     }
02132 
02133     /// solve - process the work queue
02134     void solve() {
02135       //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
02136       while (!WorkList.empty()) {
02137         //DOUT << "WorkList size: " << WorkList.size() << "\n";
02138 
02139         Operation &O = WorkList.front();
02140         TopInst = O.ContextInst;
02141         TopBB = O.ContextBB;
02142         Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
02143 
02144         O.LHS = VN.canonicalize(O.LHS, Top);
02145         O.RHS = VN.canonicalize(O.RHS, Top);
02146 
02147         assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
02148         assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
02149 
02150         DEBUG(errs() << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
02151               if (O.ContextInst) 
02152                 errs() << " context inst: " << *O.ContextInst;
02153               else
02154                 errs() << " context block: " << O.ContextBB->getName();
02155               errs() << "\n";
02156 
02157               VN.dump();
02158               IG.dump();
02159               VR.dump(););
02160 
02161         // If they're both Constant, skip it. Check for contradiction and mark
02162         // the BB as unreachable if so.
02163         if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
02164           if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
02165             if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
02166                 ConstantInt::getFalse(*Context))
02167               UB.mark(TopBB);
02168 
02169             WorkList.pop_front();
02170             continue;
02171           }
02172         }
02173 
02174         if (VN.compare(O.LHS, O.RHS)) {
02175           std::swap(O.LHS, O.RHS);
02176           O.Op = ICmpInst::getSwappedPredicate(O.Op);
02177         }
02178 
02179         if (O.Op == ICmpInst::ICMP_EQ) {
02180           if (!makeEqual(O.RHS, O.LHS))
02181             UB.mark(TopBB);
02182         } else {
02183           LatticeVal LV = cmpInstToLattice(O.Op);
02184 
02185           if ((LV & EQ_BIT) &&
02186               isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
02187             if (!makeEqual(O.RHS, O.LHS))
02188               UB.mark(TopBB);
02189           } else {
02190             if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
02191               UB.mark(TopBB);
02192               WorkList.pop_front();
02193               continue;
02194             }
02195 
02196             unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
02197             unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
02198 
02199             if (n1 == n2) {
02200               if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
02201                   O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
02202                 UB.mark(TopBB);
02203 
02204               WorkList.pop_front();
02205               continue;
02206             }
02207 
02208             if (VR.isRelatedBy(n1, n2, Top, LV) ||
02209                 IG.isRelatedBy(n1, n2, Top, LV)) {
02210               WorkList.pop_front();
02211               continue;
02212             }
02213 
02214             VR.addInequality(n1, n2, Top, LV, this);
02215             if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
02216                 LV == NE)
02217               IG.addInequality(n1, n2, Top, LV);
02218 
02219             if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
02220               if (aboveOrBelow(I1))
02221                 defToOps(I1);
02222             }
02223             if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
02224               for (Value::use_iterator UI = O.LHS->use_begin(),
02225                    UE = O.LHS->use_end(); UI != UE;) {
02226                 Use &TheUse = UI.getUse();
02227                 ++UI;
02228                 Instruction *I = cast<Instruction>(TheUse.getUser());
02229                 if (aboveOrBelow(I))
02230                   opsToDef(I);
02231               }
02232             }
02233             if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
02234               if (aboveOrBelow(I2))
02235               defToOps(I2);
02236             }
02237             if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
02238               for (Value::use_iterator UI = O.RHS->use_begin(),
02239                    UE = O.RHS->use_end(); UI != UE;) {
02240                 Use &TheUse = UI.getUse();
02241                 ++UI;
02242                 Instruction *I = cast<Instruction>(TheUse.getUser());
02243                 if (aboveOrBelow(I))
02244                   opsToDef(I);
02245               }
02246             }
02247           }
02248         }
02249         WorkList.pop_front();
02250       }
02251     }
02252   };
02253 
02254   void ValueRanges::addToWorklist(Value *V, Constant *C,
02255                                   ICmpInst::Predicate Pred, VRPSolver *VRP) {
02256     VRP->add(V, C, Pred, VRP->TopInst);
02257   }
02258 
02259   void ValueRanges::markBlock(VRPSolver *VRP) {
02260     VRP->UB.mark(VRP->TopBB);
02261   }
02262 
02263   /// PredicateSimplifier - This class is a simplifier that replaces
02264   /// one equivalent variable with another. It also tracks what
02265   /// can't be equal and will solve setcc instructions when possible.
02266   /// @brief Root of the predicate simplifier optimization.
02267   class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
02268     DomTreeDFS *DTDFS;
02269     bool modified;
02270     ValueNumbering *VN;
02271     InequalityGraph *IG;
02272     UnreachableBlocks UB;
02273     ValueRanges *VR;
02274 
02275     std::vector<DomTreeDFS::Node *> WorkList;
02276 
02277     LLVMContext *Context;
02278   public:
02279     static char ID; // Pass identification, replacement for typeid
02280     PredicateSimplifier() : FunctionPass(&ID) {}
02281 
02282     bool runOnFunction(Function &F);
02283 
02284     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
02285       AU.addRequiredID(BreakCriticalEdgesID);
02286       AU.addRequired<DominatorTree>();
02287     }
02288 
02289   private:
02290     /// Forwards - Adds new properties to VRPSolver and uses them to
02291     /// simplify instructions. Because new properties sometimes apply to
02292     /// a transition from one BasicBlock to another, this will use the
02293     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
02294     /// basic block.
02295     /// @brief Performs abstract execution of the program.
02296     class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
02297       friend class InstVisitor<Forwards>;
02298       PredicateSimplifier *PS;
02299       DomTreeDFS::Node *DTNode;
02300 
02301     public:
02302       ValueNumbering &VN;
02303       InequalityGraph &IG;
02304       UnreachableBlocks &UB;
02305       ValueRanges &VR;
02306 
02307       Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
02308         : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
02309           VR(*PS->VR) {}
02310 
02311       void visitTerminatorInst(TerminatorInst &TI);
02312       void visitBranchInst(BranchInst &BI);
02313       void visitSwitchInst(SwitchInst &SI);
02314 
02315       void visitAllocaInst(AllocaInst &AI);
02316       void visitLoadInst(LoadInst &LI);
02317       void visitStoreInst(StoreInst &SI);
02318 
02319       void visitSExtInst(SExtInst &SI);
02320       void visitZExtInst(ZExtInst &ZI);
02321 
02322       void visitBinaryOperator(BinaryOperator &BO);
02323       void visitICmpInst(ICmpInst &IC);
02324     };
02325   
02326     // Used by terminator instructions to proceed from the current basic
02327     // block to the next. Verifies that "current" dominates "next",
02328     // then calls visitBasicBlock.
02329     void proceedToSuccessors(DomTreeDFS::Node *Current) {
02330       for (DomTreeDFS::Node::iterator I = Current->begin(),
02331            E = Current->end(); I != E; ++I) {
02332         WorkList.push_back(*I);
02333       }
02334     }
02335 
02336     void proceedToSuccessor(DomTreeDFS::Node *Next) {
02337       WorkList.push_back(Next);
02338     }
02339 
02340     // Visits each instruction in the basic block.
02341     void visitBasicBlock(DomTreeDFS::Node *Node) {
02342       BasicBlock *BB = Node->getBlock();
02343       DEBUG(errs() << "Entering Basic Block: " << BB->getName()
02344             << " (" << Node->getDFSNumIn() << ")\n");
02345       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
02346         visitInstruction(I++, Node);
02347       }
02348     }
02349 
02350     // Tries to simplify each Instruction and add new properties.
02351     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
02352       DOUT << "Considering instruction " << *I << "\n";
02353       DEBUG(VN->dump());
02354       DEBUG(IG->dump());
02355       DEBUG(VR->dump());
02356 
02357       // Sometimes instructions are killed in earlier analysis.
02358       if (isInstructionTriviallyDead(I)) {
02359         ++NumSimple;
02360         modified = true;
02361         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
02362           if (VN->value(n) == I) IG->remove(n);
02363         VN->remove(I);
02364         I->eraseFromParent();
02365         return;
02366       }
02367 
02368 #ifndef NDEBUG
02369       // Try to replace the whole instruction.
02370       Value *V = VN->canonicalize(I, DT);
02371       assert(V == I && "Late instruction canonicalization.");
02372       if (V != I) {
02373         modified = true;
02374         ++NumInstruction;
02375         DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
02376         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
02377           if (VN->value(n) == I) IG->remove(n);
02378         VN->remove(I);
02379         I->replaceAllUsesWith(V);
02380         I->eraseFromParent();
02381         return;
02382       }
02383 
02384       // Try to substitute operands.
02385       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
02386         Value *Oper = I->getOperand(i);
02387         Value *V = VN->canonicalize(Oper, DT);
02388         assert(V == Oper && "Late operand canonicalization.");
02389         if (V != Oper) {
02390           modified = true;
02391           ++NumVarsReplaced;
02392           DOUT << "Resolving " << *I;
02393           I->setOperand(i, V);
02394           DOUT << " into " << *I;
02395         }
02396       }
02397 #endif
02398 
02399       std::string name = I->getParent()->getName();
02400       DOUT << "push (%" << name << ")\n";
02401       Forwards visit(this, DT);
02402       visit.visit(*I);
02403       DOUT << "pop (%" << name << ")\n";
02404     }
02405   };
02406 
02407   bool PredicateSimplifier::runOnFunction(Function &F) {
02408     DominatorTree *DT = &getAnalysis<DominatorTree>();
02409     DTDFS = new DomTreeDFS(DT);
02410     TargetData *TD = getAnalysisIfAvailable<TargetData>();
02411 
02412     // FIXME: PredicateSimplifier should still be able to do basic
02413     // optimizations without TargetData. But for now, just exit if
02414     // it's not available.
02415     if (!TD) return false;
02416 
02417     Context = &F.getContext();
02418 
02419     DEBUG(errs() << "Entering Function: " << F.getName() << "\n");
02420 
02421     modified = false;
02422     DomTreeDFS::Node *Root = DTDFS->getRootNode();
02423     VN = new ValueNumbering(DTDFS);
02424     IG = new InequalityGraph(*VN, Root);
02425     VR = new ValueRanges(*VN, TD, Context);
02426     WorkList.push_back(Root);
02427 
02428     do {
02429       DomTreeDFS::Node *DTNode = WorkList.back();
02430       WorkList.pop_back();
02431       if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
02432     } while (!WorkList.empty());
02433 
02434     delete DTDFS;
02435     delete VR;
02436     delete IG;
02437     delete VN;
02438 
02439     modified |= UB.kill();
02440 
02441     return modified;
02442   }
02443 
02444   void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
02445     PS->proceedToSuccessors(DTNode);
02446   }
02447 
02448   void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
02449     if (BI.isUnconditional()) {
02450       PS->proceedToSuccessors(DTNode);
02451       return;
02452     }
02453 
02454     Value *Condition = BI.getCondition();
02455     BasicBlock *TrueDest  = BI.getSuccessor(0);
02456     BasicBlock *FalseDest = BI.getSuccessor(1);
02457 
02458     if (isa<Constant>(Condition) || TrueDest == FalseDest) {
02459       PS->proceedToSuccessors(DTNode);
02460       return;
02461     }
02462 
02463     LLVMContext *Context = &BI.getContext();
02464 
02465     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
02466          I != E; ++I) {
02467       BasicBlock *Dest = (*I)->getBlock();
02468       DEBUG(errs() << "Branch thinking about %" << Dest->getName()
02469             << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n");
02470 
02471       if (Dest == TrueDest) {
02472         DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
02473               << ") true set:\n");
02474         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
02475         VRP.add(ConstantInt::getTrue(*Context), Condition, ICmpInst::ICMP_EQ);
02476         VRP.solve();
02477         DEBUG(VN.dump());
02478         DEBUG(IG.dump());
02479         DEBUG(VR.dump());
02480       } else if (Dest == FalseDest) {
02481         DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
02482               << ") false set:\n");
02483         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
02484         VRP.add(ConstantInt::getFalse(*Context), Condition, ICmpInst::ICMP_EQ);
02485         VRP.solve();
02486         DEBUG(VN.dump());
02487         DEBUG(IG.dump());
02488         DEBUG(VR.dump());
02489       }
02490 
02491       PS->proceedToSuccessor(*I);
02492     }
02493   }
02494 
02495   void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
02496     Value *Condition = SI.getCondition();
02497 
02498     // Set the EQProperty in each of the cases BBs, and the NEProperties
02499     // in the default BB.
02500 
02501     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
02502          I != E; ++I) {
02503       BasicBlock *BB = (*I)->getBlock();
02504       DEBUG(errs() << "Switch thinking about BB %" << BB->getName()
02505             << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n");
02506 
02507       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
02508       if (BB == SI.getDefaultDest()) {
02509         for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
02510           if (SI.getSuccessor(i) != BB)
02511             VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
02512         VRP.solve();
02513       } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
02514         VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
02515         VRP.solve();
02516       }
02517       PS->proceedToSuccessor(*I);
02518     }
02519   }
02520 
02521   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
02522     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
02523     VRP.add(Constant::getNullValue(AI.getType()),
02524             &AI, ICmpInst::ICMP_NE);
02525     VRP.solve();
02526   }
02527 
02528   void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
02529     Value *Ptr = LI.getPointerOperand();
02530     // avoid "load i8* null" -> null NE null.
02531     if (isa<Constant>(Ptr)) return;
02532 
02533     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
02534     VRP.add(Constant::getNullValue(Ptr->getType()),
02535             Ptr, ICmpInst::ICMP_NE);
02536     VRP.solve();
02537   }
02538 
02539   void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
02540     Value *Ptr = SI.getPointerOperand();
02541     if (isa<Constant>(Ptr)) return;
02542 
02543     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
02544     VRP.add(Constant::getNullValue(Ptr->getType()),
02545             Ptr, ICmpInst::ICMP_NE);
02546     VRP.solve();
02547   }
02548 
02549   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
02550     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
02551     LLVMContext &Context = SI.getContext();
02552     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
02553     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
02554     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
02555     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
02556     VRP.add(ConstantInt::get(Context, Min), &SI, ICmpInst::ICMP_SLE);
02557     VRP.add(ConstantInt::get(Context, Max), &SI, ICmpInst::ICMP_SGE);
02558     VRP.solve();
02559   }
02560 
02561   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
02562     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
02563     LLVMContext &Context = ZI.getContext();
02564     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
02565     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
02566     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
02567     VRP.add(ConstantInt::get(Context, Max), &ZI, ICmpInst::ICMP_UGE);
02568     VRP.solve();
02569   }
02570 
02571   void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
02572     Instruction::BinaryOps ops = BO.getOpcode();
02573 
02574     switch (ops) {
02575     default: break;
02576       case Instruction::URem:
02577       case Instruction::SRem:
02578       case Instruction::UDiv:
02579       case Instruction::SDiv: {
02580         Value *Divisor = BO.getOperand(1);
02581         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02582         VRP.add(Constant::getNullValue(Divisor->getType()), 
02583                 Divisor, ICmpInst::ICMP_NE);
02584         VRP.solve();
02585         break;
02586       }
02587     }
02588 
02589     switch (ops) {
02590       default: break;
02591       case Instruction::Shl: {
02592         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02593         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
02594         VRP.solve();
02595       } break;
02596       case Instruction::AShr: {
02597         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02598         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
02599         VRP.solve();
02600       } break;
02601       case Instruction::LShr:
02602       case Instruction::UDiv: {
02603         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02604         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
02605         VRP.solve();
02606       } break;
02607       case Instruction::URem: {
02608         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02609         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
02610         VRP.solve();
02611       } break;
02612       case Instruction::And: {
02613         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02614         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
02615         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
02616         VRP.solve();
02617       } break;
02618       case Instruction::Or: {
02619         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
02620         VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
02621         VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
02622         VRP.solve();
02623       } break;
02624     }
02625   }
02626 
02627   void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
02628     // If possible, squeeze the ICmp predicate into something simpler.
02629     // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
02630     // the predicate to eq.
02631 
02632     // XXX: once we do full PHI handling, modifying the instruction in the
02633     // Forwards visitor will cause missed optimizations.
02634 
02635     ICmpInst::Predicate Pred = IC.getPredicate();
02636 
02637     switch (Pred) {
02638       default: break;
02639       case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
02640       case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
02641       case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
02642       case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
02643     }
02644     if (Pred != IC.getPredicate()) {
02645       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
02646       if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
02647                           ICmpInst::ICMP_NE)) {
02648         ++NumSnuggle;
02649         PS->modified = true;
02650         IC.setPredicate(Pred);
02651       }
02652     }
02653 
02654     Pred = IC.getPredicate();
02655 
02656     LLVMContext &Context = IC.getContext();
02657 
02658     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
02659       ConstantInt *NextVal = 0;
02660       switch (Pred) {
02661         default: break;
02662         case ICmpInst::ICMP_SLT:
02663         case ICmpInst::ICMP_ULT:
02664           if (Op1->getValue() != 0)
02665             NextVal = ConstantInt::get(Context, Op1->getValue()-1);
02666          break;
02667         case ICmpInst::ICMP_SGT:
02668         case ICmpInst::ICMP_UGT:
02669           if (!Op1->getValue().isAllOnesValue())
02670             NextVal = ConstantInt::get(Context, Op1->getValue()+1);
02671          break;
02672       }
02673 
02674       if (NextVal) {
02675         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
02676         if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
02677                             ICmpInst::getInversePredicate(Pred))) {
02678           ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ, 
02679                                          IC.getOperand(0), NextVal, "");
02680           NewIC->takeName(&IC);
02681           IC.replaceAllUsesWith(NewIC);
02682 
02683           // XXX: prove this isn't necessary
02684           if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
02685             if (VN.value(n) == &IC) IG.remove(n);
02686           VN.remove(&IC);
02687 
02688           IC.eraseFromParent();
02689           ++NumSnuggle;
02690           PS->modified = true;
02691         }
02692       }
02693     }
02694   }
02695 }
02696 
02697 char PredicateSimplifier::ID = 0;
02698 static RegisterPass<PredicateSimplifier>
02699 X("predsimplify", "Predicate Simplifier");
02700 
02701 FunctionPass *llvm::createPredicateSimplifierPass() {
02702   return new PredicateSimplifier();
02703 }