1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nick Lewycky and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Path-sensitive optimizer. In a branch where x == y, replace uses of
11 // x with y. Permits further optimization, such as the elimination of
12 // the unreachable call:
14 // void test(int *p, int *q)
20 // foo(); // unreachable
23 //===----------------------------------------------------------------------===//
25 // The InequalityGraph focusses on four properties; equals, not equals,
26 // less-than and less-than-or-equals-to. The greater-than forms are also held
27 // just to allow walking from a lesser node to a greater one. These properties
28 // are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
30 // These relationships define a graph between values of the same type. Each
31 // Value is stored in a map table that retrieves the associated Node. This
32 // is how EQ relationships are stored; the map contains pointers from equal
33 // Value to the same node. The node contains a most canonical Value* form
34 // and the list of known relationships with other nodes.
36 // If two nodes are known to be inequal, then they will contain pointers to
37 // each other with an "NE" relationship. If node getNode(%x) is less than
38 // getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39 // <%x, LT>. This allows us to tie nodes together into a graph like this:
43 // with four nodes representing the properties. The InequalityGraph provides
44 // querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
45 // To find a relationship, we start with one of the nodes any binary search
46 // through its list to find where the relationships with the second node start.
47 // Then we iterate through those to find the first relationship that dominates
50 // To create these properties, we wait until a branch or switch instruction
51 // implies that a particular value is true (or false). The VRPSolver is
52 // responsible for analyzing the variable and seeing what new inferences
53 // can be made from each property. For example:
55 // %P = icmp ne i32* %ptr, null
57 // br i1 %a label %cond_true, label %cond_false
59 // For the true branch, the VRPSolver will start with %a EQ true and look at
60 // the definition of %a and find that it can infer that %P and %Q are both
61 // true. From %P being true, it can infer that %ptr NE null. For the false
62 // branch it can't infer anything from the "and" instruction.
64 // Besides branches, we can also infer properties from instruction that may
65 // have undefined behaviour in certain cases. For example, the dividend of
66 // a division may never be zero. After the division instruction, we may assume
67 // that the dividend is not equal to zero.
69 //===----------------------------------------------------------------------===//
71 // The ValueRanges class stores the known integer bounds of a Value. When we
72 // encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
73 // %b = [0, 254]. Because we store these by Value*, you should always
74 // canonicalize through the InequalityGraph first.
76 // It never stores an empty range, because that means that the code is
77 // unreachable. It never stores a single-element range since that's an equality
78 // relationship and better stored in the InequalityGraph, nor an empty range
79 // since that is better stored in UnreachableBlocks.
81 //===----------------------------------------------------------------------===//
83 #define DEBUG_TYPE "predsimplify"
84 #include "llvm/Transforms/Scalar.h"
85 #include "llvm/Constants.h"
86 #include "llvm/DerivedTypes.h"
87 #include "llvm/Instructions.h"
88 #include "llvm/Pass.h"
89 #include "llvm/ADT/DepthFirstIterator.h"
90 #include "llvm/ADT/SetOperations.h"
91 #include "llvm/ADT/SetVector.h"
92 #include "llvm/ADT/Statistic.h"
93 #include "llvm/ADT/STLExtras.h"
94 #include "llvm/Analysis/Dominators.h"
95 #include "llvm/Assembly/Writer.h"
96 #include "llvm/Support/CFG.h"
97 #include "llvm/Support/Compiler.h"
98 #include "llvm/Support/ConstantRange.h"
99 #include "llvm/Support/Debug.h"
100 #include "llvm/Support/InstVisitor.h"
101 #include "llvm/Target/TargetData.h"
102 #include "llvm/Transforms/Utils/Local.h"
107 using namespace llvm;
109 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
110 STATISTIC(NumInstruction , "Number of instructions removed");
111 STATISTIC(NumSimple , "Number of simple replacements");
112 STATISTIC(NumBlocks , "Number of blocks marked unreachable");
113 STATISTIC(NumSnuggle , "Number of comparisons snuggled");
119 friend class DomTreeDFS;
121 typedef std::vector<Node *>::iterator iterator;
122 typedef std::vector<Node *>::const_iterator const_iterator;
124 unsigned getDFSNumIn() const { return DFSin; }
125 unsigned getDFSNumOut() const { return DFSout; }
127 BasicBlock *getBlock() const { return BB; }
129 iterator begin() { return Children.begin(); }
130 iterator end() { return Children.end(); }
132 const_iterator begin() const { return Children.begin(); }
133 const_iterator end() const { return Children.end(); }
135 bool dominates(const Node *N) const {
136 return DFSin <= N->DFSin && DFSout >= N->DFSout;
139 bool DominatedBy(const Node *N) const {
140 return N->dominates(this);
143 /// Sorts by the number of descendants. With this, you can iterate
144 /// through a sorted list and the first matching entry is the most
145 /// specific match for your basic block. The order provided is stable;
146 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
148 bool operator<(const Node &N) const {
149 unsigned spread = DFSout - DFSin;
150 unsigned N_spread = N.DFSout - N.DFSin;
151 if (spread == N_spread) return DFSin < N.DFSin;
152 return spread < N_spread;
154 bool operator>(const Node &N) const { return N < *this; }
157 unsigned DFSin, DFSout;
160 std::vector<Node *> Children;
163 // XXX: this may be slow. Instead of using "new" for each node, consider
164 // putting them in a vector to keep them contiguous.
165 explicit DomTreeDFS(DominatorTree *DT) {
166 std::stack<std::pair<Node *, DomTreeNode *> > S;
169 Entry->BB = DT->getRootNode()->getBlock();
170 S.push(std::make_pair(Entry, DT->getRootNode()));
172 NodeMap[Entry->BB] = Entry;
175 std::pair<Node *, DomTreeNode *> &Pair = S.top();
176 Node *N = Pair.first;
177 DomTreeNode *DTNode = Pair.second;
180 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
182 Node *NewNode = new Node;
183 NewNode->BB = (*I)->getBlock();
184 N->Children.push_back(NewNode);
185 S.push(std::make_pair(NewNode, *I));
187 NodeMap[NewNode->BB] = NewNode;
202 std::stack<Node *> S;
206 Node *N = S.top(); S.pop();
208 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
215 /// getRootNode - This returns the entry node for the CFG of the function.
216 Node *getRootNode() const { return Entry; }
218 /// getNodeForBlock - return the node for the specified basic block.
219 Node *getNodeForBlock(BasicBlock *BB) const {
220 if (!NodeMap.count(BB)) return 0;
221 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
224 /// dominates - returns true if the basic block for I1 dominates that of
225 /// the basic block for I2. If the instructions belong to the same basic
226 /// block, the instruction first instruction sequentially in the block is
227 /// considered dominating.
228 bool dominates(Instruction *I1, Instruction *I2) {
229 BasicBlock *BB1 = I1->getParent(),
230 *BB2 = I2->getParent();
232 if (isa<TerminatorInst>(I1)) return false;
233 if (isa<TerminatorInst>(I2)) return true;
234 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
235 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
237 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
239 if (&*I == I1) return true;
240 else if (&*I == I2) return false;
242 assert(!"Instructions not found in parent BasicBlock?");
244 Node *Node1 = getNodeForBlock(BB1),
245 *Node2 = getNodeForBlock(BB2);
246 return Node1 && Node2 && Node1->dominates(Node2);
251 /// renumber - calculates the depth first search numberings and applies
252 /// them onto the nodes.
254 std::stack<std::pair<Node *, Node::iterator> > S;
258 S.push(std::make_pair(Entry, Entry->begin()));
261 std::pair<Node *, Node::iterator> &Pair = S.top();
262 Node *N = Pair.first;
263 Node::iterator &I = Pair.second;
271 S.push(std::make_pair(Next, Next->begin()));
277 virtual void dump() const {
278 dump(*cerr.stream());
281 void dump(std::ostream &os) const {
282 os << "Predicate simplifier DomTreeDFS: \n";
287 void dump(Node *N, int depth, std::ostream &os) const {
289 for (int i = 0; i < depth; ++i) { os << " "; }
290 os << "[" << depth << "] ";
292 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
293 << ", " << N->getDFSNumOut() << ")\n";
295 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
301 std::map<BasicBlock *, Node *> NodeMap;
304 // SLT SGT ULT UGT EQ
305 // 0 1 0 1 0 -- GT 10
306 // 0 1 0 1 1 -- GE 11
307 // 0 1 1 0 0 -- SGTULT 12
308 // 0 1 1 0 1 -- SGEULE 13
309 // 0 1 1 1 0 -- SGT 14
310 // 0 1 1 1 1 -- SGE 15
311 // 1 0 0 1 0 -- SLTUGT 18
312 // 1 0 0 1 1 -- SLEUGE 19
313 // 1 0 1 0 0 -- LT 20
314 // 1 0 1 0 1 -- LE 21
315 // 1 0 1 1 0 -- SLT 22
316 // 1 0 1 1 1 -- SLE 23
317 // 1 1 0 1 0 -- UGT 26
318 // 1 1 0 1 1 -- UGE 27
319 // 1 1 1 0 0 -- ULT 28
320 // 1 1 1 0 1 -- ULE 29
321 // 1 1 1 1 0 -- NE 30
323 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
326 GT = SGT_BIT | UGT_BIT,
328 LT = SLT_BIT | ULT_BIT,
330 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
331 SGTULT = SGT_BIT | ULT_BIT,
332 SGEULE = SGTULT | EQ_BIT,
333 SLTUGT = SLT_BIT | UGT_BIT,
334 SLEUGE = SLTUGT | EQ_BIT,
335 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
336 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
337 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
338 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
345 static bool validPredicate(LatticeVal LV) {
347 case GT: case GE: case LT: case LE: case NE:
348 case SGTULT: case SGT: case SGEULE:
349 case SLTUGT: case SLT: case SLEUGE:
351 case SLE: case SGE: case ULE: case UGE:
358 /// reversePredicate - reverse the direction of the inequality
359 static LatticeVal reversePredicate(LatticeVal LV) {
360 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
362 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
363 reverse |= (SLT_BIT|SGT_BIT);
365 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
366 reverse |= (ULT_BIT|UGT_BIT);
368 LatticeVal Rev = static_cast<LatticeVal>(reverse);
369 assert(validPredicate(Rev) && "Failed reversing predicate.");
373 /// ValueNumbering stores the scope-specific value numbers for a given Value.
374 class VISIBILITY_HIDDEN ValueNumbering {
375 class VISIBILITY_HIDDEN VNPair {
379 DomTreeDFS::Node *Subtree;
381 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
382 : V(V), index(index), Subtree(Subtree) {}
384 bool operator==(const VNPair &RHS) const {
385 return V == RHS.V && Subtree == RHS.Subtree;
388 bool operator<(const VNPair &RHS) const {
389 if (V != RHS.V) return V < RHS.V;
390 return *Subtree < *RHS.Subtree;
393 bool operator<(Value *RHS) const {
398 typedef std::vector<VNPair> VNMapType;
401 std::vector<Value *> Values;
407 virtual ~ValueNumbering() {}
408 virtual void dump() {
409 dump(*cerr.stream());
412 void dump(std::ostream &os) {
413 for (unsigned i = 1; i <= Values.size(); ++i) {
415 WriteAsOperand(os, Values[i-1]);
417 for (unsigned j = 0; j < VNMap.size(); ++j) {
418 if (VNMap[j].index == i) {
419 WriteAsOperand(os, VNMap[j].V);
420 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
428 /// compare - returns true if V1 is a better canonical value than V2.
429 bool compare(Value *V1, Value *V2) const {
430 if (isa<Constant>(V1))
431 return !isa<Constant>(V2);
432 else if (isa<Constant>(V2))
434 else if (isa<Argument>(V1))
435 return !isa<Argument>(V2);
436 else if (isa<Argument>(V2))
439 Instruction *I1 = dyn_cast<Instruction>(V1);
440 Instruction *I2 = dyn_cast<Instruction>(V2);
443 return V1->getNumUses() < V2->getNumUses();
445 return DTDFS->dominates(I1, I2);
448 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
450 /// valueNumber - finds the value number for V under the Subtree. If
451 /// there is no value number, returns zero.
452 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
453 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
454 || V->getType() == Type::VoidTy) return 0;
456 VNMapType::iterator E = VNMap.end();
457 VNPair pair(V, 0, Subtree);
458 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
459 while (I != E && I->V == V) {
460 if (I->Subtree->dominates(Subtree))
467 /// getOrInsertVN - always returns a value number, creating it if necessary.
468 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
469 if (unsigned n = valueNumber(V, Subtree))
475 /// newVN - creates a new value number. Value V must not already have a
476 /// value number assigned.
477 unsigned newVN(Value *V) {
478 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
479 "Bad Value for value numbering.");
480 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
484 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
485 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
486 assert((I == VNMap.end() || value(I->index) != V) &&
487 "Attempt to create a duplicate value number.");
488 VNMap.insert(I, pair);
490 return Values.size();
493 /// value - returns the Value associated with a value number.
494 Value *value(unsigned index) const {
495 assert(index != 0 && "Zero index is reserved for not found.");
496 assert(index <= Values.size() && "Index out of range.");
497 return Values[index-1];
500 /// canonicalize - return a Value that is equal to V under Subtree.
501 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
502 if (isa<Constant>(V)) return V;
504 if (unsigned n = valueNumber(V, Subtree))
510 /// addEquality - adds that value V belongs to the set of equivalent
511 /// values defined by value number n under Subtree.
512 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
513 assert(canonicalize(value(n), Subtree) == value(n) &&
514 "Node's 'canonical' choice isn't best within this subtree.");
516 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
517 // we may already have "%z -> node #2 (%x)" somewhere above us in the
518 // graph. We need to find those edges and add "%z -> node #1 (%y)"
519 // to keep the lookups canonical.
521 std::vector<Value *> ToRepoint(1, V);
523 if (unsigned Conflict = valueNumber(V, Subtree)) {
524 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
526 if (I->index == Conflict && I->Subtree->dominates(Subtree))
527 ToRepoint.push_back(I->V);
531 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
532 VE = ToRepoint.end(); VI != VE; ++VI) {
535 VNPair pair(V, n, Subtree);
536 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
537 VNMapType::iterator I = std::lower_bound(B, E, pair);
538 if (I != E && I->V == V && I->Subtree == Subtree)
539 I->index = n; // Update best choice
541 VNMap.insert(I, pair); // New Value
543 // XXX: we currently don't have to worry about updating values with
544 // more specific Subtrees, but we will need to for PHI node support.
547 Value *V_n = value(n);
548 if (isa<Constant>(V) && isa<Constant>(V_n)) {
549 assert(V == V_n && "Constant equals different constant?");
555 /// remove - removes all references to value V.
556 void remove(Value *V) {
557 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
558 VNPair pair(V, 0, DTDFS->getRootNode());
559 VNMapType::iterator J = std::upper_bound(B, E, pair);
560 VNMapType::iterator I = J;
562 while (I != B && (I == E || I->V == V)) --I;
568 /// The InequalityGraph stores the relationships between values.
569 /// Each Value in the graph is assigned to a Node. Nodes are pointer
570 /// comparable for equality. The caller is expected to maintain the logical
571 /// consistency of the system.
573 /// The InequalityGraph class may invalidate Node*s after any mutator call.
574 /// @brief The InequalityGraph stores the relationships between values.
575 class VISIBILITY_HIDDEN InequalityGraph {
577 DomTreeDFS::Node *TreeRoot;
579 InequalityGraph(); // DO NOT IMPLEMENT
580 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
582 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
583 : VN(VN), TreeRoot(TreeRoot) {}
587 /// An Edge is contained inside a Node making one end of the edge implicit
588 /// and contains a pointer to the other end. The edge contains a lattice
589 /// value specifying the relationship and an DomTreeDFS::Node specifying
590 /// the root in the dominator tree to which this edge applies.
591 class VISIBILITY_HIDDEN Edge {
593 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
594 : To(T), LV(V), Subtree(ST) {}
598 DomTreeDFS::Node *Subtree;
600 bool operator<(const Edge &edge) const {
601 if (To != edge.To) return To < edge.To;
602 return *Subtree < *edge.Subtree;
605 bool operator<(unsigned to) const {
609 bool operator>(unsigned to) const {
613 friend bool operator<(unsigned to, const Edge &edge) {
614 return edge.operator>(to);
618 /// A single node in the InequalityGraph. This stores the canonical Value
619 /// for the node, as well as the relationships with the neighbours.
621 /// @brief A single node in the InequalityGraph.
622 class VISIBILITY_HIDDEN Node {
623 friend class InequalityGraph;
625 typedef SmallVector<Edge, 4> RelationsType;
626 RelationsType Relations;
628 // TODO: can this idea improve performance?
629 //friend class std::vector<Node>;
630 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
633 typedef RelationsType::iterator iterator;
634 typedef RelationsType::const_iterator const_iterator;
638 virtual void dump() const {
639 dump(*cerr.stream());
642 void dump(std::ostream &os) const {
643 static const std::string names[32] =
644 { "000000", "000001", "000002", "000003", "000004", "000005",
645 "000006", "000007", "000008", "000009", " >", " >=",
646 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
647 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
648 "000024", "000025", " u>", " u>=", " u<", " u<=",
650 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
651 os << names[NI->LV] << " " << NI->To
652 << " (" << NI->Subtree->getDFSNumIn() << "), ";
658 iterator begin() { return Relations.begin(); }
659 iterator end() { return Relations.end(); }
660 const_iterator begin() const { return Relations.begin(); }
661 const_iterator end() const { return Relations.end(); }
663 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
665 for (iterator I = std::lower_bound(begin(), E, n);
666 I != E && I->To == n; ++I) {
667 if (Subtree->DominatedBy(I->Subtree))
673 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
674 const_iterator E = end();
675 for (const_iterator I = std::lower_bound(begin(), E, n);
676 I != E && I->To == n; ++I) {
677 if (Subtree->DominatedBy(I->Subtree))
683 /// Updates the lattice value for a given node. Create a new entry if
684 /// one doesn't exist, otherwise it merges the values. The new lattice
685 /// value must not be inconsistent with any previously existing value.
686 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
687 assert(validPredicate(R) && "Invalid predicate.");
688 iterator I = find(n, Subtree);
690 Edge edge(n, R, Subtree);
691 iterator Insert = std::lower_bound(begin(), end(), edge);
692 Relations.insert(Insert, edge);
694 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
695 assert(validPredicate(LV) && "Invalid union of lattice values.");
697 if (Subtree != I->Subtree) {
698 assert(Subtree->DominatedBy(I->Subtree) &&
699 "Find returned subtree that doesn't apply.");
701 Edge edge(n, R, Subtree);
702 iterator Insert = std::lower_bound(begin(), end(), edge);
703 Relations.insert(Insert, edge); // invalidates I
704 I = find(n, Subtree);
707 // Also, we have to tighten any edge that Subtree dominates.
708 for (iterator B = begin(); I->To == n; --I) {
709 if (I->Subtree->DominatedBy(Subtree)) {
710 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
711 assert(validPredicate(LV) && "Invalid union of lattice values");
723 std::vector<Node> Nodes;
726 /// node - returns the node object at a given value number. The pointer
727 /// returned may be invalidated on the next call to node().
728 Node *node(unsigned index) {
729 assert(VN.value(index)); // This triggers the necessary checks.
730 if (Nodes.size() < index) Nodes.resize(index);
731 return &Nodes[index-1];
734 /// isRelatedBy - true iff n1 op n2
735 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
737 if (n1 == n2) return LV & EQ_BIT;
740 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
741 if (I != E) return (I->LV & LV) == I->LV;
746 // The add* methods assume that your input is logically valid and may
747 // assertion-fail or infinitely loop if you attempt a contradiction.
749 /// addInequality - Sets n1 op n2.
750 /// It is also an error to call this on an inequality that is already true.
751 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
753 assert(n1 != n2 && "A node can't be inequal to itself.");
756 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
757 "Contradictory inequality.");
759 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
760 // add %a < %n2 too. This keeps the graph fully connected.
762 // Break up the relationship into signed and unsigned comparison parts.
763 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
764 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
765 // should have the EQ_BIT iff it's set for both op1 and op2.
767 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
768 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
770 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
771 if (I->LV != NE && I->To != n2) {
773 DomTreeDFS::Node *Local_Subtree = NULL;
774 if (Subtree->DominatedBy(I->Subtree))
775 Local_Subtree = Subtree;
776 else if (I->Subtree->DominatedBy(Subtree))
777 Local_Subtree = I->Subtree;
780 unsigned new_relationship = 0;
781 LatticeVal ILV = reversePredicate(I->LV);
782 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
783 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
785 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
786 new_relationship |= ILV_s;
787 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
788 new_relationship |= ILV_u;
790 if (new_relationship) {
791 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
792 new_relationship |= (SLT_BIT|SGT_BIT);
793 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
794 new_relationship |= (ULT_BIT|UGT_BIT);
795 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
796 new_relationship |= EQ_BIT;
798 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
800 node(I->To)->update(n2, NewLV, Local_Subtree);
801 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
807 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
808 if (I->LV != NE && I->To != n1) {
809 DomTreeDFS::Node *Local_Subtree = NULL;
810 if (Subtree->DominatedBy(I->Subtree))
811 Local_Subtree = Subtree;
812 else if (I->Subtree->DominatedBy(Subtree))
813 Local_Subtree = I->Subtree;
816 unsigned new_relationship = 0;
817 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
818 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
820 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
821 new_relationship |= ILV_s;
823 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
824 new_relationship |= ILV_u;
826 if (new_relationship) {
827 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
828 new_relationship |= (SLT_BIT|SGT_BIT);
829 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
830 new_relationship |= (ULT_BIT|UGT_BIT);
831 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
832 new_relationship |= EQ_BIT;
834 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
836 node(n1)->update(I->To, NewLV, Local_Subtree);
837 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
844 node(n1)->update(n2, LV1, Subtree);
845 node(n2)->update(n1, reversePredicate(LV1), Subtree);
848 /// remove - removes a node from the graph by removing all references to
850 void remove(unsigned n) {
852 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
853 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
855 node(NI->To)->Relations.erase(Iter);
856 Iter = node(NI->To)->find(n, TreeRoot);
857 } while (Iter != node(NI->To)->end());
859 N->Relations.clear();
863 virtual ~InequalityGraph() {}
864 virtual void dump() {
865 dump(*cerr.stream());
868 void dump(std::ostream &os) {
869 for (unsigned i = 1; i <= Nodes.size(); ++i) {
880 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
881 /// in the InequalityGraph.
882 class VISIBILITY_HIDDEN ValueRanges {
886 class VISIBILITY_HIDDEN ScopedRange {
887 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
889 RangeListType RangeList;
891 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
892 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
893 return *LHS.first < *RHS.first;
898 virtual ~ScopedRange() {}
899 virtual void dump() const {
900 dump(*cerr.stream());
903 void dump(std::ostream &os) const {
905 for (const_iterator I = begin(), E = end(); I != E; ++I) {
906 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
912 typedef RangeListType::iterator iterator;
913 typedef RangeListType::const_iterator const_iterator;
915 iterator begin() { return RangeList.begin(); }
916 iterator end() { return RangeList.end(); }
917 const_iterator begin() const { return RangeList.begin(); }
918 const_iterator end() const { return RangeList.end(); }
920 iterator find(DomTreeDFS::Node *Subtree) {
921 static ConstantRange empty(1, false);
923 iterator I = std::lower_bound(begin(), E,
924 std::make_pair(Subtree, empty), swo);
926 while (I != E && !I->first->dominates(Subtree)) ++I;
930 const_iterator find(DomTreeDFS::Node *Subtree) const {
931 static const ConstantRange empty(1, false);
932 const_iterator E = end();
933 const_iterator I = std::lower_bound(begin(), E,
934 std::make_pair(Subtree, empty), swo);
936 while (I != E && !I->first->dominates(Subtree)) ++I;
940 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
941 assert(!CR.isEmptySet() && "Empty ConstantRange.");
942 assert(!CR.isSingleElement() && "Won't store single element.");
944 static ConstantRange empty(1, false);
947 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
949 if (I != end() && I->first == Subtree) {
950 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
951 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
952 "Invalid union of ranges.");
955 RangeList.insert(I, std::make_pair(Subtree, CR));
959 std::vector<ScopedRange> Ranges;
961 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
962 if (CR.isFullSet()) return;
963 if (Ranges.size() < n) Ranges.resize(n);
964 Ranges[n-1].update(CR, Subtree);
967 /// create - Creates a ConstantRange that matches the given LatticeVal
968 /// relation with a given integer.
969 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
970 assert(!CR.isEmptySet() && "Can't deal with empty set.");
973 return makeConstantRange(ICmpInst::ICMP_NE, CR);
975 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
976 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
977 bool hasEQ = LV & EQ_BIT;
979 ConstantRange Range(CR.getBitWidth());
981 if (LV_s == SGT_BIT) {
982 Range = Range.maximalIntersectWith(makeConstantRange(
983 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
984 } else if (LV_s == SLT_BIT) {
985 Range = Range.maximalIntersectWith(makeConstantRange(
986 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
989 if (LV_u == UGT_BIT) {
990 Range = Range.maximalIntersectWith(makeConstantRange(
991 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
992 } else if (LV_u == ULT_BIT) {
993 Range = Range.maximalIntersectWith(makeConstantRange(
994 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1000 /// makeConstantRange - Creates a ConstantRange representing the set of all
1001 /// value that match the ICmpInst::Predicate with any of the values in CR.
1002 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1003 const ConstantRange &CR) {
1004 uint32_t W = CR.getBitWidth();
1005 switch (ICmpOpcode) {
1006 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
1007 case ICmpInst::ICMP_EQ:
1008 return ConstantRange(CR.getLower(), CR.getUpper());
1009 case ICmpInst::ICMP_NE:
1010 if (CR.isSingleElement())
1011 return ConstantRange(CR.getUpper(), CR.getLower());
1012 return ConstantRange(W);
1013 case ICmpInst::ICMP_ULT:
1014 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1015 case ICmpInst::ICMP_SLT:
1016 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1017 case ICmpInst::ICMP_ULE: {
1018 APInt UMax(CR.getUnsignedMax());
1019 if (UMax.isMaxValue())
1020 return ConstantRange(W);
1021 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1023 case ICmpInst::ICMP_SLE: {
1024 APInt SMax(CR.getSignedMax());
1025 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
1026 return ConstantRange(W);
1027 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1029 case ICmpInst::ICMP_UGT:
1030 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
1031 case ICmpInst::ICMP_SGT:
1032 return ConstantRange(CR.getSignedMin() + 1,
1033 APInt::getSignedMinValue(W));
1034 case ICmpInst::ICMP_UGE: {
1035 APInt UMin(CR.getUnsignedMin());
1036 if (UMin.isMinValue())
1037 return ConstantRange(W);
1038 return ConstantRange(UMin, APInt::getNullValue(W));
1040 case ICmpInst::ICMP_SGE: {
1041 APInt SMin(CR.getSignedMin());
1042 if (SMin.isMinSignedValue())
1043 return ConstantRange(W);
1044 return ConstantRange(SMin, APInt::getSignedMinValue(W));
1050 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1051 return V == VN.canonicalize(V, Subtree);
1057 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
1060 virtual ~ValueRanges() {}
1062 virtual void dump() const {
1063 dump(*cerr.stream());
1066 void dump(std::ostream &os) const {
1067 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1068 os << (i+1) << " = ";
1075 /// range - looks up the ConstantRange associated with a value number.
1076 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1077 assert(VN.value(n)); // performs range checks
1079 if (n <= Ranges.size()) {
1080 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1081 if (I != Ranges[n-1].end()) return I->second;
1084 Value *V = VN.value(n);
1085 ConstantRange CR = range(V);
1089 /// range - determine a range from a Value without performing any lookups.
1090 ConstantRange range(Value *V) const {
1091 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1092 return ConstantRange(C->getValue());
1093 else if (isa<ConstantPointerNull>(V))
1094 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1096 return typeToWidth(V->getType());
1099 // typeToWidth - returns the number of bits necessary to store a value of
1100 // this type, or zero if unknown.
1101 uint32_t typeToWidth(const Type *Ty) const {
1103 return TD->getTypeSizeInBits(Ty);
1105 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1106 return ITy->getBitWidth();
1111 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1114 default: assert(!"Impossible lattice value!");
1116 return CR1.maximalIntersectWith(CR2).isEmptySet();
1118 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1120 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1122 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1124 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1126 return CR1.getSignedMax().slt(CR2.getSignedMin());
1128 return CR1.getSignedMax().sle(CR2.getSignedMin());
1130 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1132 return CR1.getSignedMin().sge(CR2.getSignedMax());
1134 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1135 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1137 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1138 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1140 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1141 CR1.getSignedMin().sgt(CR2.getSignedMax());
1143 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1144 CR1.getSignedMin().sge(CR2.getSignedMax());
1146 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1147 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1149 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1150 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1152 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1153 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1155 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1156 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1160 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1162 ConstantRange CR1 = range(n1, Subtree);
1163 ConstantRange CR2 = range(n2, Subtree);
1165 // True iff all values in CR1 are LV to all values in CR2.
1166 return isRelatedBy(CR1, CR2, LV);
1169 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1171 void markBlock(VRPSolver *VRP);
1173 void mergeInto(Value **I, unsigned n, unsigned New,
1174 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1175 ConstantRange CR_New = range(New, Subtree);
1176 ConstantRange Merged = CR_New;
1178 for (; n != 0; ++I, --n) {
1179 unsigned i = VN.valueNumber(*I, Subtree);
1180 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1181 if (CR_Kill.isFullSet()) continue;
1182 Merged = Merged.maximalIntersectWith(CR_Kill);
1185 if (Merged.isFullSet() || Merged == CR_New) return;
1187 applyRange(New, Merged, Subtree, VRP);
1190 void applyRange(unsigned n, const ConstantRange &CR,
1191 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1192 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
1193 if (Merged.isEmptySet()) {
1198 if (const APInt *I = Merged.getSingleElement()) {
1199 Value *V = VN.value(n); // XXX: redesign worklist.
1200 const Type *Ty = V->getType();
1201 if (Ty->isInteger()) {
1202 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1204 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1205 assert(*I == 0 && "Pointer is null but not zero?");
1206 addToWorklist(V, ConstantPointerNull::get(PTy),
1207 ICmpInst::ICMP_EQ, VRP);
1212 update(n, Merged, Subtree);
1215 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1217 ConstantRange CR1 = range(n1, Subtree);
1218 ConstantRange CR2 = range(n2, Subtree);
1220 uint32_t W = CR1.getBitWidth();
1222 if (const APInt *I = CR1.getSingleElement()) {
1223 if (CR2.isFullSet()) {
1224 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1225 applyRange(n2, NewCR2, Subtree, VRP);
1226 } else if (*I == CR2.getLower()) {
1227 APInt NewLower(CR2.getLower() + 1),
1228 NewUpper(CR2.getUpper());
1229 if (NewLower == NewUpper)
1230 NewLower = NewUpper = APInt::getMinValue(W);
1232 ConstantRange NewCR2(NewLower, NewUpper);
1233 applyRange(n2, NewCR2, Subtree, VRP);
1234 } else if (*I == CR2.getUpper() - 1) {
1235 APInt NewLower(CR2.getLower()),
1236 NewUpper(CR2.getUpper() - 1);
1237 if (NewLower == NewUpper)
1238 NewLower = NewUpper = APInt::getMinValue(W);
1240 ConstantRange NewCR2(NewLower, NewUpper);
1241 applyRange(n2, NewCR2, Subtree, VRP);
1245 if (const APInt *I = CR2.getSingleElement()) {
1246 if (CR1.isFullSet()) {
1247 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1248 applyRange(n1, NewCR1, Subtree, VRP);
1249 } else if (*I == CR1.getLower()) {
1250 APInt NewLower(CR1.getLower() + 1),
1251 NewUpper(CR1.getUpper());
1252 if (NewLower == NewUpper)
1253 NewLower = NewUpper = APInt::getMinValue(W);
1255 ConstantRange NewCR1(NewLower, NewUpper);
1256 applyRange(n1, NewCR1, Subtree, VRP);
1257 } else if (*I == CR1.getUpper() - 1) {
1258 APInt NewLower(CR1.getLower()),
1259 NewUpper(CR1.getUpper() - 1);
1260 if (NewLower == NewUpper)
1261 NewLower = NewUpper = APInt::getMinValue(W);
1263 ConstantRange NewCR1(NewLower, NewUpper);
1264 applyRange(n1, NewCR1, Subtree, VRP);
1269 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1270 LatticeVal LV, VRPSolver *VRP) {
1271 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1274 addNotEquals(n1, n2, Subtree, VRP);
1278 ConstantRange CR1 = range(n1, Subtree);
1279 ConstantRange CR2 = range(n2, Subtree);
1281 if (!CR1.isSingleElement()) {
1282 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
1284 applyRange(n1, NewCR1, Subtree, VRP);
1287 if (!CR2.isSingleElement()) {
1288 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1289 create(reversePredicate(LV), CR1));
1291 applyRange(n2, NewCR2, Subtree, VRP);
1296 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1297 /// another discovered to be unreachable. This is used to cull the graph when
1298 /// analyzing instructions, and to mark blocks with the "unreachable"
1299 /// terminator instruction after the function has executed.
1300 class VISIBILITY_HIDDEN UnreachableBlocks {
1302 std::vector<BasicBlock *> DeadBlocks;
1305 /// mark - mark a block as dead
1306 void mark(BasicBlock *BB) {
1307 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1308 std::vector<BasicBlock *>::iterator I =
1309 std::lower_bound(DeadBlocks.begin(), E, BB);
1311 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1314 /// isDead - returns whether a block is known to be dead already
1315 bool isDead(BasicBlock *BB) {
1316 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1317 std::vector<BasicBlock *>::iterator I =
1318 std::lower_bound(DeadBlocks.begin(), E, BB);
1320 return I != E && *I == BB;
1323 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1325 bool modified = false;
1326 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1327 E = DeadBlocks.end(); I != E; ++I) {
1328 BasicBlock *BB = *I;
1330 DOUT << "unreachable block: " << BB->getName() << "\n";
1332 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1334 BasicBlock *Succ = *SI;
1335 Succ->removePredecessor(BB);
1338 TerminatorInst *TI = BB->getTerminator();
1339 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1340 TI->eraseFromParent();
1341 new UnreachableInst(BB);
1350 /// VRPSolver keeps track of how changes to one variable affect other
1351 /// variables, and forwards changes along to the InequalityGraph. It
1352 /// also maintains the correct choice for "canonical" in the IG.
1353 /// @brief VRPSolver calculates inferences from a new relationship.
1354 class VISIBILITY_HIDDEN VRPSolver {
1356 friend class ValueRanges;
1360 ICmpInst::Predicate Op;
1362 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1363 Instruction *ContextInst;
1365 std::deque<Operation> WorkList;
1368 InequalityGraph &IG;
1369 UnreachableBlocks &UB;
1372 DomTreeDFS::Node *Top;
1374 Instruction *TopInst;
1377 typedef InequalityGraph::Node Node;
1379 // below - true if the Instruction is dominated by the current context
1380 // block or instruction
1381 bool below(Instruction *I) {
1382 BasicBlock *BB = I->getParent();
1383 if (TopInst && TopInst->getParent() == BB) {
1384 if (isa<TerminatorInst>(TopInst)) return false;
1385 if (isa<TerminatorInst>(I)) return true;
1386 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1387 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1389 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1390 Iter != E; ++Iter) {
1391 if (&*Iter == TopInst) return true;
1392 else if (&*Iter == I) return false;
1394 assert(!"Instructions not found in parent BasicBlock?");
1396 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1397 if (!Node) return false;
1398 return Top->dominates(Node);
1402 // aboveOrBelow - true if the Instruction either dominates or is dominated
1403 // by the current context block or instruction
1404 bool aboveOrBelow(Instruction *I) {
1405 BasicBlock *BB = I->getParent();
1406 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1407 if (!Node) return false;
1409 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1412 bool makeEqual(Value *V1, Value *V2) {
1413 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
1414 DOUT << "context is ";
1415 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1416 else DOUT << "BB: " << TopBB->getName()
1417 << "(" << Top->getDFSNumIn() << ")\n";
1419 assert(V1->getType() == V2->getType() &&
1420 "Can't make two values with different types equal.");
1422 if (V1 == V2) return true;
1424 if (isa<Constant>(V1) && isa<Constant>(V2))
1427 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1430 if (n1 == n2) return true;
1431 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1434 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1435 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1437 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1439 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1441 SetVector<unsigned> Remove;
1442 if (n2) Remove.insert(n2);
1445 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1446 // We can't just merge %x and %y because the relationship with %z would
1447 // be EQ and that's invalid. What we're doing is looking for any nodes
1448 // %z such that %x <= %z and %y >= %z, and vice versa.
1450 Node::iterator end = IG.node(n2)->end();
1452 // Find the intersection between N1 and N2 which is dominated by
1453 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1455 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1457 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1459 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1460 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1461 Node::iterator NI = IG.node(n2)->find(I->To, Top);
1463 LatticeVal NILV = reversePredicate(NI->LV);
1464 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1465 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1467 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1468 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1469 Remove.insert(I->To);
1473 // See if one of the nodes about to be removed is actually a better
1474 // canonical choice than n1.
1475 unsigned orig_n1 = n1;
1476 SetVector<unsigned>::iterator DontRemove = Remove.end();
1477 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1478 E = Remove.end(); I != E; ++I) {
1480 Value *V = VN.value(n);
1481 if (VN.compare(V, V1)) {
1487 if (DontRemove != Remove.end()) {
1488 unsigned n = *DontRemove;
1490 Remove.insert(orig_n1);
1494 // We'd like to allow makeEqual on two values to perform a simple
1495 // substitution without every creating nodes in the IG whenever possible.
1497 // The first iteration through this loop operates on V2 before going
1498 // through the Remove list and operating on those too. If all of the
1499 // iterations performed simple replacements then we exit early.
1500 bool mergeIGNode = false;
1502 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1503 if (i) R = VN.value(Remove[i]); // skip n2.
1505 // Try to replace the whole instruction. If we can, we're done.
1506 Instruction *I2 = dyn_cast<Instruction>(R);
1507 if (I2 && below(I2)) {
1508 std::vector<Instruction *> ToNotify;
1509 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1511 Use &TheUse = UI.getUse();
1513 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1514 ToNotify.push_back(I);
1517 DOUT << "Simply removing " << *I2
1518 << ", replacing with " << *V1 << "\n";
1519 I2->replaceAllUsesWith(V1);
1520 // leave it dead; it'll get erased later.
1524 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1525 IE = ToNotify.end(); II != IE; ++II) {
1532 // Otherwise, replace all dominated uses.
1533 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1535 Use &TheUse = UI.getUse();
1537 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1547 // If that killed the instruction, stop here.
1548 if (I2 && isInstructionTriviallyDead(I2)) {
1549 DOUT << "Killed all uses of " << *I2
1550 << ", replacing with " << *V1 << "\n";
1554 // If we make it to here, then we will need to create a node for N1.
1555 // Otherwise, we can skip out early!
1559 if (!isa<Constant>(V1)) {
1560 if (Remove.empty()) {
1561 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1563 std::vector<Value*> RemoveVals;
1564 RemoveVals.reserve(Remove.size());
1566 for (SetVector<unsigned>::iterator I = Remove.begin(),
1567 E = Remove.end(); I != E; ++I) {
1568 Value *V = VN.value(*I);
1569 if (!V->use_empty())
1570 RemoveVals.push_back(V);
1572 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1573 VN.getOrInsertVN(V1, Top), Top, this);
1579 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1581 // Migrate relationships from removed nodes to N1.
1582 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1585 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1587 if (NI->Subtree->DominatedBy(Top)) {
1589 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1592 if (Remove.count(NI->To))
1595 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1596 IG.node(n1)->update(NI->To, NI->LV, Top);
1601 // Point V2 (and all items in Remove) to N1.
1603 VN.addEquality(n1, V2, Top);
1605 for (SetVector<unsigned>::iterator I = Remove.begin(),
1606 E = Remove.end(); I != E; ++I) {
1607 VN.addEquality(n1, VN.value(*I), Top);
1611 // If !Remove.empty() then V2 = Remove[0]->getValue().
1612 // Even when Remove is empty, we still want to process V2.
1614 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1615 if (i) R = VN.value(Remove[i]); // skip n2.
1617 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1618 if (aboveOrBelow(I2))
1621 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1623 Use &TheUse = UI.getUse();
1625 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1626 if (aboveOrBelow(I))
1633 // re-opsToDef all dominated users of V1.
1634 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1635 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1637 Use &TheUse = UI.getUse();
1639 Value *V = TheUse.getUser();
1640 if (!V->use_empty()) {
1641 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
1642 if (aboveOrBelow(Inst))
1652 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1653 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1654 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1656 case ICmpInst::ICMP_EQ:
1657 assert(!"No matching lattice value.");
1658 return static_cast<LatticeVal>(EQ_BIT);
1660 assert(!"Invalid 'icmp' predicate.");
1661 case ICmpInst::ICMP_NE:
1663 case ICmpInst::ICMP_UGT:
1665 case ICmpInst::ICMP_UGE:
1667 case ICmpInst::ICMP_ULT:
1669 case ICmpInst::ICMP_ULE:
1671 case ICmpInst::ICMP_SGT:
1673 case ICmpInst::ICMP_SGE:
1675 case ICmpInst::ICMP_SLT:
1677 case ICmpInst::ICMP_SLE:
1683 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1684 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1691 Top(DTDFS->getNodeForBlock(TopBB)),
1696 assert(Top && "VRPSolver created for unreachable basic block.");
1699 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1700 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1701 Instruction *TopInst)
1707 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1708 TopBB(TopInst->getParent()),
1712 assert(Top && "VRPSolver created for unreachable basic block.");
1713 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1716 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1717 if (Constant *C1 = dyn_cast<Constant>(V1))
1718 if (Constant *C2 = dyn_cast<Constant>(V2))
1719 return ConstantExpr::getCompare(Pred, C1, C2) ==
1720 ConstantInt::getTrue();
1722 unsigned n1 = VN.valueNumber(V1, Top);
1723 unsigned n2 = VN.valueNumber(V2, Top);
1726 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1727 Pred == ICmpInst::ICMP_ULE ||
1728 Pred == ICmpInst::ICMP_UGE ||
1729 Pred == ICmpInst::ICMP_SLE ||
1730 Pred == ICmpInst::ICMP_SGE;
1731 if (Pred == ICmpInst::ICMP_EQ) return false;
1732 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1733 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1736 if ((n1 && !n2 && isa<Constant>(V2)) ||
1737 (n2 && !n1 && isa<Constant>(V1))) {
1738 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1739 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1741 if (Pred == ICmpInst::ICMP_EQ)
1742 return CR1.isSingleElement() &&
1743 CR1.getSingleElement() == CR2.getSingleElement();
1745 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1747 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1751 /// add - adds a new property to the work queue
1752 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1753 Instruction *I = NULL) {
1754 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1755 if (I) DOUT << " context: " << *I;
1756 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
1759 assert(V1->getType() == V2->getType() &&
1760 "Can't relate two values with different types.");
1762 WorkList.push_back(Operation());
1763 Operation &O = WorkList.back();
1764 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1765 O.ContextBB = I ? I->getParent() : TopBB;
1768 /// defToOps - Given an instruction definition that we've learned something
1769 /// new about, find any new relationships between its operands.
1770 void defToOps(Instruction *I) {
1771 Instruction *NewContext = below(I) ? I : TopInst;
1772 Value *Canonical = VN.canonicalize(I, Top);
1774 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1775 const Type *Ty = BO->getType();
1776 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1778 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1779 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1781 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1783 switch (BO->getOpcode()) {
1784 case Instruction::And: {
1785 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1786 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
1787 if (Canonical == CI) {
1788 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1789 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1792 case Instruction::Or: {
1793 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1794 Constant *Zero = Constant::getNullValue(Ty);
1795 if (Canonical == Zero) {
1796 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1797 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1800 case Instruction::Xor: {
1801 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1802 // "xor i32 %c, %a" EQ %c then %a EQ 0
1803 // "xor i32 %c, %a" NE %c then %a NE 0
1804 // Repeat the above, with order of operands reversed.
1807 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1809 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1810 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1811 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
1812 ICmpInst::ICMP_EQ, NewContext);
1815 if (Canonical == LHS) {
1816 if (isa<ConstantInt>(Canonical))
1817 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1819 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1820 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1827 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1828 // "icmp ult i32 %a, %y" EQ true then %a u< y
1831 if (Canonical == ConstantInt::getTrue()) {
1832 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1834 } else if (Canonical == ConstantInt::getFalse()) {
1835 add(IC->getOperand(0), IC->getOperand(1),
1836 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1838 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1839 if (I->getType()->isFPOrFPVector()) return;
1841 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1842 // %a EQ %b and %b NE %c then %x EQ true
1843 // %a EQ %c and %b NE %c then %x EQ false
1845 Value *True = SI->getTrueValue();
1846 Value *False = SI->getFalseValue();
1847 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1848 if (Canonical == VN.canonicalize(True, Top) ||
1849 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1850 add(SI->getCondition(), ConstantInt::getTrue(),
1851 ICmpInst::ICMP_EQ, NewContext);
1852 else if (Canonical == VN.canonicalize(False, Top) ||
1853 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1854 add(SI->getCondition(), ConstantInt::getFalse(),
1855 ICmpInst::ICMP_EQ, NewContext);
1857 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1858 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1859 OE = GEPI->idx_end(); OI != OE; ++OI) {
1860 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1861 if (!Op || !Op->isZero()) return;
1863 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1864 // jumping the type plane as needed.
1865 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1866 ICmpInst::ICMP_NE)) {
1867 Value *Ptr = GEPI->getPointerOperand();
1868 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1871 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1872 const Type *SrcTy = CI->getSrcTy();
1874 unsigned ci = VN.getOrInsertVN(CI, Top);
1875 uint32_t W = VR.typeToWidth(SrcTy);
1877 ConstantRange CR = VR.range(ci, Top);
1879 if (CR.isFullSet()) return;
1881 switch (CI->getOpcode()) {
1883 case Instruction::ZExt:
1884 case Instruction::SExt:
1885 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1886 CR.truncate(W), Top, this);
1888 case Instruction::BitCast:
1889 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1896 /// opsToDef - A new relationship was discovered involving one of this
1897 /// instruction's operands. Find any new relationship involving the
1898 /// definition, or another operand.
1899 void opsToDef(Instruction *I) {
1900 Instruction *NewContext = below(I) ? I : TopInst;
1902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1903 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1904 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1906 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1907 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1908 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1909 ICmpInst::ICMP_EQ, NewContext);
1913 // "%y = and i1 true, %x" then %x EQ %y
1914 // "%y = or i1 false, %x" then %x EQ %y
1915 // "%x = add i32 %y, 0" then %x EQ %y
1916 // "%x = mul i32 %y, 0" then %x EQ 0
1918 Instruction::BinaryOps Opcode = BO->getOpcode();
1919 const Type *Ty = BO->getType();
1920 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1922 Constant *Zero = Constant::getNullValue(Ty);
1923 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
1927 case Instruction::LShr:
1928 case Instruction::AShr:
1929 case Instruction::Shl:
1930 case Instruction::Sub:
1932 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1936 case Instruction::Or:
1937 if (Op0 == AllOnes || Op1 == AllOnes) {
1938 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1941 case Instruction::Xor:
1942 case Instruction::Add:
1944 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1946 } else if (Op1 == Zero) {
1947 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1951 case Instruction::And:
1952 if (Op0 == AllOnes) {
1953 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1955 } else if (Op1 == AllOnes) {
1956 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1960 case Instruction::Mul:
1961 if (Op0 == Zero || Op1 == Zero) {
1962 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1968 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
1969 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1970 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
1971 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
1973 Value *Known = Op0, *Unknown = Op1,
1974 *TheBO = VN.canonicalize(BO, Top);
1975 if (Known != TheBO) std::swap(Known, Unknown);
1976 if (Known == TheBO) {
1979 case Instruction::LShr:
1980 case Instruction::AShr:
1981 case Instruction::Shl:
1982 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1983 // otherwise, fall-through.
1984 case Instruction::Sub:
1985 if (Unknown == Op1) break;
1986 // otherwise, fall-through.
1987 case Instruction::Xor:
1988 case Instruction::Add:
1989 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
1991 case Instruction::UDiv:
1992 case Instruction::SDiv:
1993 if (Unknown == Op1) break;
1994 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
1995 Constant *One = ConstantInt::get(Ty, 1);
1996 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2002 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
2004 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
2005 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
2006 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2009 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2010 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2012 ICmpInst::Predicate Pred = IC->getPredicate();
2013 if (isRelatedBy(Op0, Op1, Pred))
2014 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
2015 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2016 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
2018 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2019 if (I->getType()->isFPOrFPVector()) return;
2021 // Given: "%a = select i1 %x, i32 %b, i32 %c"
2022 // %x EQ true then %a EQ %b
2023 // %x EQ false then %a EQ %c
2024 // %b EQ %c then %a EQ %b
2026 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2027 if (Canonical == ConstantInt::getTrue()) {
2028 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2029 } else if (Canonical == ConstantInt::getFalse()) {
2030 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2031 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2032 VN.canonicalize(SI->getFalseValue(), Top)) {
2033 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2035 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2036 const Type *DestTy = CI->getDestTy();
2037 if (DestTy->isFPOrFPVector()) return;
2039 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2040 Instruction::CastOps Opcode = CI->getOpcode();
2042 if (Constant *C = dyn_cast<Constant>(Op)) {
2043 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2044 ICmpInst::ICMP_EQ, NewContext);
2047 uint32_t W = VR.typeToWidth(DestTy);
2048 unsigned ci = VN.getOrInsertVN(CI, Top);
2049 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2051 if (!CR.isFullSet()) {
2054 case Instruction::ZExt:
2055 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2057 case Instruction::SExt:
2058 VR.applyRange(ci, CR.signExtend(W), Top, this);
2060 case Instruction::Trunc: {
2061 ConstantRange Result = CR.truncate(W);
2062 if (!Result.isFullSet())
2063 VR.applyRange(ci, Result, Top, this);
2065 case Instruction::BitCast:
2066 VR.applyRange(ci, CR, Top, this);
2068 // TODO: other casts?
2071 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2072 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2073 OE = GEPI->idx_end(); OI != OE; ++OI) {
2074 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2075 if (!Op || !Op->isZero()) return;
2077 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2078 // jumping the type plane as needed.
2079 Value *Ptr = GEPI->getPointerOperand();
2080 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2081 ICmpInst::ICMP_NE)) {
2082 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2088 /// solve - process the work queue
2090 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2091 while (!WorkList.empty()) {
2092 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2094 Operation &O = WorkList.front();
2095 TopInst = O.ContextInst;
2096 TopBB = O.ContextBB;
2097 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2099 O.LHS = VN.canonicalize(O.LHS, Top);
2100 O.RHS = VN.canonicalize(O.RHS, Top);
2102 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2103 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2105 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2106 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2107 else DOUT << " context block: " << O.ContextBB->getName();
2114 // If they're both Constant, skip it. Check for contradiction and mark
2115 // the BB as unreachable if so.
2116 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2117 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2118 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2119 ConstantInt::getFalse())
2122 WorkList.pop_front();
2127 if (VN.compare(O.LHS, O.RHS)) {
2128 std::swap(O.LHS, O.RHS);
2129 O.Op = ICmpInst::getSwappedPredicate(O.Op);
2132 if (O.Op == ICmpInst::ICMP_EQ) {
2133 if (!makeEqual(O.RHS, O.LHS))
2136 LatticeVal LV = cmpInstToLattice(O.Op);
2138 if ((LV & EQ_BIT) &&
2139 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2140 if (!makeEqual(O.RHS, O.LHS))
2143 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2145 WorkList.pop_front();
2149 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2150 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2153 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2154 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2157 WorkList.pop_front();
2161 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2162 IG.isRelatedBy(n1, n2, Top, LV)) {
2163 WorkList.pop_front();
2167 VR.addInequality(n1, n2, Top, LV, this);
2168 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2170 IG.addInequality(n1, n2, Top, LV);
2172 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2173 if (aboveOrBelow(I1))
2176 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2177 for (Value::use_iterator UI = O.LHS->use_begin(),
2178 UE = O.LHS->use_end(); UI != UE;) {
2179 Use &TheUse = UI.getUse();
2181 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2182 if (aboveOrBelow(I))
2187 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2188 if (aboveOrBelow(I2))
2191 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2192 for (Value::use_iterator UI = O.RHS->use_begin(),
2193 UE = O.RHS->use_end(); UI != UE;) {
2194 Use &TheUse = UI.getUse();
2196 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2197 if (aboveOrBelow(I))
2204 WorkList.pop_front();
2209 void ValueRanges::addToWorklist(Value *V, Constant *C,
2210 ICmpInst::Predicate Pred, VRPSolver *VRP) {
2211 VRP->add(V, C, Pred, VRP->TopInst);
2214 void ValueRanges::markBlock(VRPSolver *VRP) {
2215 VRP->UB.mark(VRP->TopBB);
2218 /// PredicateSimplifier - This class is a simplifier that replaces
2219 /// one equivalent variable with another. It also tracks what
2220 /// can't be equal and will solve setcc instructions when possible.
2221 /// @brief Root of the predicate simplifier optimization.
2222 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2226 InequalityGraph *IG;
2227 UnreachableBlocks UB;
2230 std::vector<DomTreeDFS::Node *> WorkList;
2233 static char ID; // Pass identification, replacement for typeid
2234 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2236 bool runOnFunction(Function &F);
2238 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2239 AU.addRequiredID(BreakCriticalEdgesID);
2240 AU.addRequired<DominatorTree>();
2241 AU.addRequired<TargetData>();
2242 AU.addPreserved<TargetData>();
2246 /// Forwards - Adds new properties to VRPSolver and uses them to
2247 /// simplify instructions. Because new properties sometimes apply to
2248 /// a transition from one BasicBlock to another, this will use the
2249 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2251 /// @brief Performs abstract execution of the program.
2252 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2253 friend class InstVisitor<Forwards>;
2254 PredicateSimplifier *PS;
2255 DomTreeDFS::Node *DTNode;
2259 InequalityGraph &IG;
2260 UnreachableBlocks &UB;
2263 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2264 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2267 void visitTerminatorInst(TerminatorInst &TI);
2268 void visitBranchInst(BranchInst &BI);
2269 void visitSwitchInst(SwitchInst &SI);
2271 void visitAllocaInst(AllocaInst &AI);
2272 void visitLoadInst(LoadInst &LI);
2273 void visitStoreInst(StoreInst &SI);
2275 void visitSExtInst(SExtInst &SI);
2276 void visitZExtInst(ZExtInst &ZI);
2278 void visitBinaryOperator(BinaryOperator &BO);
2279 void visitICmpInst(ICmpInst &IC);
2282 // Used by terminator instructions to proceed from the current basic
2283 // block to the next. Verifies that "current" dominates "next",
2284 // then calls visitBasicBlock.
2285 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2286 for (DomTreeDFS::Node::iterator I = Current->begin(),
2287 E = Current->end(); I != E; ++I) {
2288 WorkList.push_back(*I);
2292 void proceedToSuccessor(DomTreeDFS::Node *Next) {
2293 WorkList.push_back(Next);
2296 // Visits each instruction in the basic block.
2297 void visitBasicBlock(DomTreeDFS::Node *Node) {
2298 BasicBlock *BB = Node->getBlock();
2299 DOUT << "Entering Basic Block: " << BB->getName()
2300 << " (" << Node->getDFSNumIn() << ")\n";
2301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2302 visitInstruction(I++, Node);
2306 // Tries to simplify each Instruction and add new properties.
2307 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2308 DOUT << "Considering instruction " << *I << "\n";
2313 // Sometimes instructions are killed in earlier analysis.
2314 if (isInstructionTriviallyDead(I)) {
2317 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2318 if (VN->value(n) == I) IG->remove(n);
2320 I->eraseFromParent();
2325 // Try to replace the whole instruction.
2326 Value *V = VN->canonicalize(I, DT);
2327 assert(V == I && "Late instruction canonicalization.");
2331 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
2332 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2333 if (VN->value(n) == I) IG->remove(n);
2335 I->replaceAllUsesWith(V);
2336 I->eraseFromParent();
2340 // Try to substitute operands.
2341 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2342 Value *Oper = I->getOperand(i);
2343 Value *V = VN->canonicalize(Oper, DT);
2344 assert(V == Oper && "Late operand canonicalization.");
2348 DOUT << "Resolving " << *I;
2349 I->setOperand(i, V);
2350 DOUT << " into " << *I;
2355 std::string name = I->getParent()->getName();
2356 DOUT << "push (%" << name << ")\n";
2357 Forwards visit(this, DT);
2359 DOUT << "pop (%" << name << ")\n";
2363 bool PredicateSimplifier::runOnFunction(Function &F) {
2364 DominatorTree *DT = &getAnalysis<DominatorTree>();
2365 DTDFS = new DomTreeDFS(DT);
2366 TargetData *TD = &getAnalysis<TargetData>();
2368 DOUT << "Entering Function: " << F.getName() << "\n";
2371 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2372 VN = new ValueNumbering(DTDFS);
2373 IG = new InequalityGraph(*VN, Root);
2374 VR = new ValueRanges(*VN, TD);
2375 WorkList.push_back(Root);
2378 DomTreeDFS::Node *DTNode = WorkList.back();
2379 WorkList.pop_back();
2380 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2381 } while (!WorkList.empty());
2387 modified |= UB.kill();
2392 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2393 PS->proceedToSuccessors(DTNode);
2396 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2397 if (BI.isUnconditional()) {
2398 PS->proceedToSuccessors(DTNode);
2402 Value *Condition = BI.getCondition();
2403 BasicBlock *TrueDest = BI.getSuccessor(0);
2404 BasicBlock *FalseDest = BI.getSuccessor(1);
2406 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2407 PS->proceedToSuccessors(DTNode);
2411 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2413 BasicBlock *Dest = (*I)->getBlock();
2414 DOUT << "Branch thinking about %" << Dest->getName()
2415 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
2417 if (Dest == TrueDest) {
2418 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
2419 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2420 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
2425 } else if (Dest == FalseDest) {
2426 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
2427 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2428 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
2435 PS->proceedToSuccessor(*I);
2439 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2440 Value *Condition = SI.getCondition();
2442 // Set the EQProperty in each of the cases BBs, and the NEProperties
2443 // in the default BB.
2445 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2447 BasicBlock *BB = (*I)->getBlock();
2448 DOUT << "Switch thinking about BB %" << BB->getName()
2449 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
2451 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2452 if (BB == SI.getDefaultDest()) {
2453 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2454 if (SI.getSuccessor(i) != BB)
2455 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2457 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2458 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2461 PS->proceedToSuccessor(*I);
2465 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2466 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2467 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
2471 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2472 Value *Ptr = LI.getPointerOperand();
2473 // avoid "load uint* null" -> null NE null.
2474 if (isa<Constant>(Ptr)) return;
2476 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2477 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2481 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2482 Value *Ptr = SI.getPointerOperand();
2483 if (isa<Constant>(Ptr)) return;
2485 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2486 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2490 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2491 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2492 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2493 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2494 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2495 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2496 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2497 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
2501 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2502 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2503 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2504 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2505 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2506 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
2510 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2511 Instruction::BinaryOps ops = BO.getOpcode();
2515 case Instruction::URem:
2516 case Instruction::SRem:
2517 case Instruction::UDiv:
2518 case Instruction::SDiv: {
2519 Value *Divisor = BO.getOperand(1);
2520 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2521 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2530 case Instruction::Shl: {
2531 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2532 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2535 case Instruction::AShr: {
2536 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2537 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2540 case Instruction::LShr:
2541 case Instruction::UDiv: {
2542 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2543 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2546 case Instruction::URem: {
2547 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2548 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2551 case Instruction::And: {
2552 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2553 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2554 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2557 case Instruction::Or: {
2558 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2559 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2560 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2566 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2567 // If possible, squeeze the ICmp predicate into something simpler.
2568 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2569 // the predicate to eq.
2571 // XXX: once we do full PHI handling, modifying the instruction in the
2572 // Forwards visitor will cause missed optimizations.
2574 ICmpInst::Predicate Pred = IC.getPredicate();
2578 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2579 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2580 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2581 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2583 if (Pred != IC.getPredicate()) {
2584 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2585 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2586 ICmpInst::ICMP_NE)) {
2588 PS->modified = true;
2589 IC.setPredicate(Pred);
2593 Pred = IC.getPredicate();
2595 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2596 ConstantInt *NextVal = 0;
2599 case ICmpInst::ICMP_SLT:
2600 case ICmpInst::ICMP_ULT:
2601 if (Op1->getValue() != 0)
2602 NextVal = ConstantInt::get(Op1->getValue()-1);
2604 case ICmpInst::ICMP_SGT:
2605 case ICmpInst::ICMP_UGT:
2606 if (!Op1->getValue().isAllOnesValue())
2607 NextVal = ConstantInt::get(Op1->getValue()+1);
2612 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2613 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2614 ICmpInst::getInversePredicate(Pred))) {
2615 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2617 NewIC->takeName(&IC);
2618 IC.replaceAllUsesWith(NewIC);
2620 // XXX: prove this isn't necessary
2621 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2622 if (VN.value(n) == &IC) IG.remove(n);
2625 IC.eraseFromParent();
2627 PS->modified = true;
2633 char PredicateSimplifier::ID = 0;
2634 RegisterPass<PredicateSimplifier> X("predsimplify",
2635 "Predicate Simplifier");
2638 FunctionPass *llvm::createPredicateSimplifierPass() {
2639 return new PredicateSimplifier();