1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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
75 // It never stores an empty range, because that means that the code is
76 // unreachable. It never stores a single-element range since that's an equality
77 // relationship and better stored in the InequalityGraph, nor an empty range
78 // since that is better stored in UnreachableBlocks.
80 //===----------------------------------------------------------------------===//
82 #define DEBUG_TYPE "predsimplify"
83 #include "llvm/Transforms/Scalar.h"
84 #include "llvm/Constants.h"
85 #include "llvm/DerivedTypes.h"
86 #include "llvm/Instructions.h"
87 #include "llvm/Pass.h"
88 #include "llvm/ADT/DepthFirstIterator.h"
89 #include "llvm/ADT/SetOperations.h"
90 #include "llvm/ADT/SetVector.h"
91 #include "llvm/ADT/Statistic.h"
92 #include "llvm/ADT/STLExtras.h"
93 #include "llvm/Analysis/Dominators.h"
94 #include "llvm/Assembly/Writer.h"
95 #include "llvm/Support/CFG.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/ConstantRange.h"
98 #include "llvm/Support/Debug.h"
99 #include "llvm/Support/InstVisitor.h"
100 #include "llvm/Target/TargetData.h"
101 #include "llvm/Transforms/Utils/Local.h"
105 using namespace llvm;
107 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
108 STATISTIC(NumInstruction , "Number of instructions removed");
109 STATISTIC(NumSimple , "Number of simple replacements");
110 STATISTIC(NumBlocks , "Number of blocks marked unreachable");
111 STATISTIC(NumSnuggle , "Number of comparisons snuggled");
113 static const ConstantRange empty(1, false);
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);
248 return false; // Not reached
252 /// renumber - calculates the depth first search numberings and applies
253 /// them onto the nodes.
255 std::stack<std::pair<Node *, Node::iterator> > S;
259 S.push(std::make_pair(Entry, Entry->begin()));
262 std::pair<Node *, Node::iterator> &Pair = S.top();
263 Node *N = Pair.first;
264 Node::iterator &I = Pair.second;
272 S.push(std::make_pair(Next, Next->begin()));
278 virtual void dump() const {
279 dump(*cerr.stream());
282 void dump(std::ostream &os) const {
283 os << "Predicate simplifier DomTreeDFS: \n";
288 void dump(Node *N, int depth, std::ostream &os) const {
290 for (int i = 0; i < depth; ++i) { os << " "; }
291 os << "[" << depth << "] ";
293 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
294 << ", " << N->getDFSNumOut() << ")\n";
296 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
302 std::map<BasicBlock *, Node *> NodeMap;
305 // SLT SGT ULT UGT EQ
306 // 0 1 0 1 0 -- GT 10
307 // 0 1 0 1 1 -- GE 11
308 // 0 1 1 0 0 -- SGTULT 12
309 // 0 1 1 0 1 -- SGEULE 13
310 // 0 1 1 1 0 -- SGT 14
311 // 0 1 1 1 1 -- SGE 15
312 // 1 0 0 1 0 -- SLTUGT 18
313 // 1 0 0 1 1 -- SLEUGE 19
314 // 1 0 1 0 0 -- LT 20
315 // 1 0 1 0 1 -- LE 21
316 // 1 0 1 1 0 -- SLT 22
317 // 1 0 1 1 1 -- SLE 23
318 // 1 1 0 1 0 -- UGT 26
319 // 1 1 0 1 1 -- UGE 27
320 // 1 1 1 0 0 -- ULT 28
321 // 1 1 1 0 1 -- ULE 29
322 // 1 1 1 1 0 -- NE 30
324 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
327 GT = SGT_BIT | UGT_BIT,
329 LT = SLT_BIT | ULT_BIT,
331 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
332 SGTULT = SGT_BIT | ULT_BIT,
333 SGEULE = SGTULT | EQ_BIT,
334 SLTUGT = SLT_BIT | UGT_BIT,
335 SLEUGE = SLTUGT | EQ_BIT,
336 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
337 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
338 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
339 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
347 /// validPredicate - determines whether a given value is actually a lattice
348 /// value. Only used in assertions or debugging.
349 static bool validPredicate(LatticeVal LV) {
351 case GT: case GE: case LT: case LE: case NE:
352 case SGTULT: case SGT: case SGEULE:
353 case SLTUGT: case SLT: case SLEUGE:
355 case SLE: case SGE: case ULE: case UGE:
363 /// reversePredicate - reverse the direction of the inequality
364 static LatticeVal reversePredicate(LatticeVal LV) {
365 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
367 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
368 reverse |= (SLT_BIT|SGT_BIT);
370 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
371 reverse |= (ULT_BIT|UGT_BIT);
373 LatticeVal Rev = static_cast<LatticeVal>(reverse);
374 assert(validPredicate(Rev) && "Failed reversing predicate.");
378 /// ValueNumbering stores the scope-specific value numbers for a given Value.
379 class VISIBILITY_HIDDEN ValueNumbering {
381 /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
382 /// includes the comparison operators necessary to allow you to store it
383 /// in a sorted vector.
384 class VISIBILITY_HIDDEN VNPair {
388 DomTreeDFS::Node *Subtree;
390 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
391 : V(V), index(index), Subtree(Subtree) {}
393 bool operator==(const VNPair &RHS) const {
394 return V == RHS.V && Subtree == RHS.Subtree;
397 bool operator<(const VNPair &RHS) const {
398 if (V != RHS.V) return V < RHS.V;
399 return *Subtree < *RHS.Subtree;
402 bool operator<(Value *RHS) const {
406 bool operator>(Value *RHS) const {
410 friend bool operator<(Value *RHS, const VNPair &pair) {
411 return pair.operator>(RHS);
415 typedef std::vector<VNPair> VNMapType;
418 /// The canonical choice for value number at index.
419 std::vector<Value *> Values;
425 virtual ~ValueNumbering() {}
426 virtual void dump() {
427 dump(*cerr.stream());
430 void dump(std::ostream &os) {
431 for (unsigned i = 1; i <= Values.size(); ++i) {
433 WriteAsOperand(os, Values[i-1]);
435 for (unsigned j = 0; j < VNMap.size(); ++j) {
436 if (VNMap[j].index == i) {
437 WriteAsOperand(os, VNMap[j].V);
438 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
446 /// compare - returns true if V1 is a better canonical value than V2.
447 bool compare(Value *V1, Value *V2) const {
448 if (isa<Constant>(V1))
449 return !isa<Constant>(V2);
450 else if (isa<Constant>(V2))
452 else if (isa<Argument>(V1))
453 return !isa<Argument>(V2);
454 else if (isa<Argument>(V2))
457 Instruction *I1 = dyn_cast<Instruction>(V1);
458 Instruction *I2 = dyn_cast<Instruction>(V2);
461 return V1->getNumUses() < V2->getNumUses();
463 return DTDFS->dominates(I1, I2);
466 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
468 /// valueNumber - finds the value number for V under the Subtree. If
469 /// there is no value number, returns zero.
470 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
471 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
472 || V->getType() == Type::VoidTy) return 0;
474 VNMapType::iterator E = VNMap.end();
475 VNPair pair(V, 0, Subtree);
476 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
477 while (I != E && I->V == V) {
478 if (I->Subtree->dominates(Subtree))
485 /// getOrInsertVN - always returns a value number, creating it if necessary.
486 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
487 if (unsigned n = valueNumber(V, Subtree))
493 /// newVN - creates a new value number. Value V must not already have a
494 /// value number assigned.
495 unsigned newVN(Value *V) {
496 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
497 "Bad Value for value numbering.");
498 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
502 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
503 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
504 assert((I == VNMap.end() || value(I->index) != V) &&
505 "Attempt to create a duplicate value number.");
506 VNMap.insert(I, pair);
508 return Values.size();
511 /// value - returns the Value associated with a value number.
512 Value *value(unsigned index) const {
513 assert(index != 0 && "Zero index is reserved for not found.");
514 assert(index <= Values.size() && "Index out of range.");
515 return Values[index-1];
518 /// canonicalize - return a Value that is equal to V under Subtree.
519 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
520 if (isa<Constant>(V)) return V;
522 if (unsigned n = valueNumber(V, Subtree))
528 /// addEquality - adds that value V belongs to the set of equivalent
529 /// values defined by value number n under Subtree.
530 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
531 assert(canonicalize(value(n), Subtree) == value(n) &&
532 "Node's 'canonical' choice isn't best within this subtree.");
534 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
535 // we may already have "%z -> node #2 (%x)" somewhere above us in the
536 // graph. We need to find those edges and add "%z -> node #1 (%y)"
537 // to keep the lookups canonical.
539 std::vector<Value *> ToRepoint(1, V);
541 if (unsigned Conflict = valueNumber(V, Subtree)) {
542 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
544 if (I->index == Conflict && I->Subtree->dominates(Subtree))
545 ToRepoint.push_back(I->V);
549 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
550 VE = ToRepoint.end(); VI != VE; ++VI) {
553 VNPair pair(V, n, Subtree);
554 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
555 VNMapType::iterator I = std::lower_bound(B, E, pair);
556 if (I != E && I->V == V && I->Subtree == Subtree)
557 I->index = n; // Update best choice
559 VNMap.insert(I, pair); // New Value
561 // XXX: we currently don't have to worry about updating values with
562 // more specific Subtrees, but we will need to for PHI node support.
565 Value *V_n = value(n);
566 if (isa<Constant>(V) && isa<Constant>(V_n)) {
567 assert(V == V_n && "Constant equals different constant?");
573 /// remove - removes all references to value V.
574 void remove(Value *V) {
575 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
576 VNPair pair(V, 0, DTDFS->getRootNode());
577 VNMapType::iterator J = std::upper_bound(B, E, pair);
578 VNMapType::iterator I = J;
580 while (I != B && (I == E || I->V == V)) --I;
586 /// The InequalityGraph stores the relationships between values.
587 /// Each Value in the graph is assigned to a Node. Nodes are pointer
588 /// comparable for equality. The caller is expected to maintain the logical
589 /// consistency of the system.
591 /// The InequalityGraph class may invalidate Node*s after any mutator call.
592 /// @brief The InequalityGraph stores the relationships between values.
593 class VISIBILITY_HIDDEN InequalityGraph {
595 DomTreeDFS::Node *TreeRoot;
597 InequalityGraph(); // DO NOT IMPLEMENT
598 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
600 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
601 : VN(VN), TreeRoot(TreeRoot) {}
605 /// An Edge is contained inside a Node making one end of the edge implicit
606 /// and contains a pointer to the other end. The edge contains a lattice
607 /// value specifying the relationship and an DomTreeDFS::Node specifying
608 /// the root in the dominator tree to which this edge applies.
609 class VISIBILITY_HIDDEN Edge {
611 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
612 : To(T), LV(V), Subtree(ST) {}
616 DomTreeDFS::Node *Subtree;
618 bool operator<(const Edge &edge) const {
619 if (To != edge.To) return To < edge.To;
620 return *Subtree < *edge.Subtree;
623 bool operator<(unsigned to) const {
627 bool operator>(unsigned to) const {
631 friend bool operator<(unsigned to, const Edge &edge) {
632 return edge.operator>(to);
636 /// A single node in the InequalityGraph. This stores the canonical Value
637 /// for the node, as well as the relationships with the neighbours.
639 /// @brief A single node in the InequalityGraph.
640 class VISIBILITY_HIDDEN Node {
641 friend class InequalityGraph;
643 typedef SmallVector<Edge, 4> RelationsType;
644 RelationsType Relations;
646 // TODO: can this idea improve performance?
647 //friend class std::vector<Node>;
648 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
651 typedef RelationsType::iterator iterator;
652 typedef RelationsType::const_iterator const_iterator;
656 virtual void dump() const {
657 dump(*cerr.stream());
660 void dump(std::ostream &os) const {
661 static const std::string names[32] =
662 { "000000", "000001", "000002", "000003", "000004", "000005",
663 "000006", "000007", "000008", "000009", " >", " >=",
664 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
665 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
666 "000024", "000025", " u>", " u>=", " u<", " u<=",
668 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
669 os << names[NI->LV] << " " << NI->To
670 << " (" << NI->Subtree->getDFSNumIn() << "), ";
676 iterator begin() { return Relations.begin(); }
677 iterator end() { return Relations.end(); }
678 const_iterator begin() const { return Relations.begin(); }
679 const_iterator end() const { return Relations.end(); }
681 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
683 for (iterator I = std::lower_bound(begin(), E, n);
684 I != E && I->To == n; ++I) {
685 if (Subtree->DominatedBy(I->Subtree))
691 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
692 const_iterator E = end();
693 for (const_iterator I = std::lower_bound(begin(), E, n);
694 I != E && I->To == n; ++I) {
695 if (Subtree->DominatedBy(I->Subtree))
701 /// update - updates the lattice value for a given node, creating a new
702 /// entry if one doesn't exist. The new lattice value must not be
703 /// inconsistent with any previously existing value.
704 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
705 assert(validPredicate(R) && "Invalid predicate.");
707 Edge edge(n, R, Subtree);
708 iterator B = begin(), E = end();
709 iterator I = std::lower_bound(B, E, edge);
712 while (J != E && J->To == n) {
713 if (Subtree->DominatedBy(J->Subtree))
718 if (J != E && J->To == n) {
719 edge.LV = static_cast<LatticeVal>(J->LV & R);
720 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
722 if (edge.LV == J->LV)
723 return; // This update adds nothing new.
727 // We also have to tighten any edge beneath our update.
728 for (iterator K = I - 1; K->To == n; --K) {
729 if (K->Subtree->DominatedBy(Subtree)) {
730 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
731 assert(validPredicate(LV) && "Invalid union of lattice values");
738 // Insert new edge at Subtree if it isn't already there.
739 if (I == E || I->To != n || Subtree != I->Subtree)
740 Relations.insert(I, edge);
746 std::vector<Node> Nodes;
749 /// node - returns the node object at a given value number. The pointer
750 /// returned may be invalidated on the next call to node().
751 Node *node(unsigned index) {
752 assert(VN.value(index)); // This triggers the necessary checks.
753 if (Nodes.size() < index) Nodes.resize(index);
754 return &Nodes[index-1];
757 /// isRelatedBy - true iff n1 op n2
758 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
760 if (n1 == n2) return LV & EQ_BIT;
763 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
764 if (I != E) return (I->LV & LV) == I->LV;
769 // The add* methods assume that your input is logically valid and may
770 // assertion-fail or infinitely loop if you attempt a contradiction.
772 /// addInequality - Sets n1 op n2.
773 /// It is also an error to call this on an inequality that is already true.
774 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
776 assert(n1 != n2 && "A node can't be inequal to itself.");
779 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
780 "Contradictory inequality.");
782 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
783 // add %a < %n2 too. This keeps the graph fully connected.
785 // Break up the relationship into signed and unsigned comparison parts.
786 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
787 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
788 // should have the EQ_BIT iff it's set for both op1 and op2.
790 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
791 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
793 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
794 if (I->LV != NE && I->To != n2) {
796 DomTreeDFS::Node *Local_Subtree = NULL;
797 if (Subtree->DominatedBy(I->Subtree))
798 Local_Subtree = Subtree;
799 else if (I->Subtree->DominatedBy(Subtree))
800 Local_Subtree = I->Subtree;
803 unsigned new_relationship = 0;
804 LatticeVal ILV = reversePredicate(I->LV);
805 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
806 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
808 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
809 new_relationship |= ILV_s;
810 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
811 new_relationship |= ILV_u;
813 if (new_relationship) {
814 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
815 new_relationship |= (SLT_BIT|SGT_BIT);
816 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
817 new_relationship |= (ULT_BIT|UGT_BIT);
818 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
819 new_relationship |= EQ_BIT;
821 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
823 node(I->To)->update(n2, NewLV, Local_Subtree);
824 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
830 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
831 if (I->LV != NE && I->To != n1) {
832 DomTreeDFS::Node *Local_Subtree = NULL;
833 if (Subtree->DominatedBy(I->Subtree))
834 Local_Subtree = Subtree;
835 else if (I->Subtree->DominatedBy(Subtree))
836 Local_Subtree = I->Subtree;
839 unsigned new_relationship = 0;
840 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
841 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
843 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
844 new_relationship |= ILV_s;
846 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
847 new_relationship |= ILV_u;
849 if (new_relationship) {
850 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
851 new_relationship |= (SLT_BIT|SGT_BIT);
852 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
853 new_relationship |= (ULT_BIT|UGT_BIT);
854 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
855 new_relationship |= EQ_BIT;
857 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
859 node(n1)->update(I->To, NewLV, Local_Subtree);
860 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
867 node(n1)->update(n2, LV1, Subtree);
868 node(n2)->update(n1, reversePredicate(LV1), Subtree);
871 /// remove - removes a node from the graph by removing all references to
873 void remove(unsigned n) {
875 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
876 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
878 node(NI->To)->Relations.erase(Iter);
879 Iter = node(NI->To)->find(n, TreeRoot);
880 } while (Iter != node(NI->To)->end());
882 N->Relations.clear();
886 virtual ~InequalityGraph() {}
887 virtual void dump() {
888 dump(*cerr.stream());
891 void dump(std::ostream &os) {
892 for (unsigned i = 1; i <= Nodes.size(); ++i) {
903 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
904 /// in the InequalityGraph.
905 class VISIBILITY_HIDDEN ValueRanges {
909 class VISIBILITY_HIDDEN ScopedRange {
910 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
912 RangeListType RangeList;
914 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
915 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
916 return *LHS.first < *RHS.first;
921 virtual ~ScopedRange() {}
922 virtual void dump() const {
923 dump(*cerr.stream());
926 void dump(std::ostream &os) const {
928 for (const_iterator I = begin(), E = end(); I != E; ++I) {
929 os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
935 typedef RangeListType::iterator iterator;
936 typedef RangeListType::const_iterator const_iterator;
938 iterator begin() { return RangeList.begin(); }
939 iterator end() { return RangeList.end(); }
940 const_iterator begin() const { return RangeList.begin(); }
941 const_iterator end() const { return RangeList.end(); }
943 iterator find(DomTreeDFS::Node *Subtree) {
945 iterator I = std::lower_bound(begin(), E,
946 std::make_pair(Subtree, empty), swo);
948 while (I != E && !I->first->dominates(Subtree)) ++I;
952 const_iterator find(DomTreeDFS::Node *Subtree) const {
953 const_iterator E = end();
954 const_iterator I = std::lower_bound(begin(), E,
955 std::make_pair(Subtree, empty), swo);
957 while (I != E && !I->first->dominates(Subtree)) ++I;
961 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
962 assert(!CR.isEmptySet() && "Empty ConstantRange.");
963 assert(!CR.isSingleElement() && "Refusing to store single element.");
967 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
969 if (I != end() && I->first == Subtree) {
970 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
971 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
972 "Invalid union of ranges.");
975 RangeList.insert(I, std::make_pair(Subtree, CR));
979 std::vector<ScopedRange> Ranges;
981 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
982 if (CR.isFullSet()) return;
983 if (Ranges.size() < n) Ranges.resize(n);
984 Ranges[n-1].update(CR, Subtree);
987 /// create - Creates a ConstantRange that matches the given LatticeVal
988 /// relation with a given integer.
989 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
990 assert(!CR.isEmptySet() && "Can't deal with empty set.");
993 return makeConstantRange(ICmpInst::ICMP_NE, CR);
995 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
996 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
997 bool hasEQ = LV & EQ_BIT;
999 ConstantRange Range(CR.getBitWidth());
1001 if (LV_s == SGT_BIT) {
1002 Range = Range.maximalIntersectWith(makeConstantRange(
1003 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1004 } else if (LV_s == SLT_BIT) {
1005 Range = Range.maximalIntersectWith(makeConstantRange(
1006 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1009 if (LV_u == UGT_BIT) {
1010 Range = Range.maximalIntersectWith(makeConstantRange(
1011 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1012 } else if (LV_u == ULT_BIT) {
1013 Range = Range.maximalIntersectWith(makeConstantRange(
1014 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1020 /// makeConstantRange - Creates a ConstantRange representing the set of all
1021 /// value that match the ICmpInst::Predicate with any of the values in CR.
1022 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1023 const ConstantRange &CR) {
1024 uint32_t W = CR.getBitWidth();
1025 switch (ICmpOpcode) {
1026 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
1027 case ICmpInst::ICMP_EQ:
1028 return ConstantRange(CR.getLower(), CR.getUpper());
1029 case ICmpInst::ICMP_NE:
1030 if (CR.isSingleElement())
1031 return ConstantRange(CR.getUpper(), CR.getLower());
1032 return ConstantRange(W);
1033 case ICmpInst::ICMP_ULT:
1034 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1035 case ICmpInst::ICMP_SLT:
1036 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1037 case ICmpInst::ICMP_ULE: {
1038 APInt UMax(CR.getUnsignedMax());
1039 if (UMax.isMaxValue())
1040 return ConstantRange(W);
1041 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1043 case ICmpInst::ICMP_SLE: {
1044 APInt SMax(CR.getSignedMax());
1045 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
1046 return ConstantRange(W);
1047 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1049 case ICmpInst::ICMP_UGT:
1050 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
1051 case ICmpInst::ICMP_SGT:
1052 return ConstantRange(CR.getSignedMin() + 1,
1053 APInt::getSignedMinValue(W));
1054 case ICmpInst::ICMP_UGE: {
1055 APInt UMin(CR.getUnsignedMin());
1056 if (UMin.isMinValue())
1057 return ConstantRange(W);
1058 return ConstantRange(UMin, APInt::getNullValue(W));
1060 case ICmpInst::ICMP_SGE: {
1061 APInt SMin(CR.getSignedMin());
1062 if (SMin.isMinSignedValue())
1063 return ConstantRange(W);
1064 return ConstantRange(SMin, APInt::getSignedMinValue(W));
1070 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1071 return V == VN.canonicalize(V, Subtree);
1077 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
1080 virtual ~ValueRanges() {}
1082 virtual void dump() const {
1083 dump(*cerr.stream());
1086 void dump(std::ostream &os) const {
1087 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1088 os << (i+1) << " = ";
1095 /// range - looks up the ConstantRange associated with a value number.
1096 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1097 assert(VN.value(n)); // performs range checks
1099 if (n <= Ranges.size()) {
1100 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1101 if (I != Ranges[n-1].end()) return I->second;
1104 Value *V = VN.value(n);
1105 ConstantRange CR = range(V);
1109 /// range - determine a range from a Value without performing any lookups.
1110 ConstantRange range(Value *V) const {
1111 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1112 return ConstantRange(C->getValue());
1113 else if (isa<ConstantPointerNull>(V))
1114 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1116 return ConstantRange(typeToWidth(V->getType()));
1119 // typeToWidth - returns the number of bits necessary to store a value of
1120 // this type, or zero if unknown.
1121 uint32_t typeToWidth(const Type *Ty) const {
1123 return TD->getTypeSizeInBits(Ty);
1125 return Ty->getPrimitiveSizeInBits();
1128 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1131 default: assert(!"Impossible lattice value!");
1133 return CR1.maximalIntersectWith(CR2).isEmptySet();
1135 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1137 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1139 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1141 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1143 return CR1.getSignedMax().slt(CR2.getSignedMin());
1145 return CR1.getSignedMax().sle(CR2.getSignedMin());
1147 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1149 return CR1.getSignedMin().sge(CR2.getSignedMax());
1151 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1152 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1154 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1155 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1157 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1158 CR1.getSignedMin().sgt(CR2.getSignedMax());
1160 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1161 CR1.getSignedMin().sge(CR2.getSignedMax());
1163 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1164 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1166 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1167 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1169 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1170 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1172 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1173 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1177 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1179 ConstantRange CR1 = range(n1, Subtree);
1180 ConstantRange CR2 = range(n2, Subtree);
1182 // True iff all values in CR1 are LV to all values in CR2.
1183 return isRelatedBy(CR1, CR2, LV);
1186 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1188 void markBlock(VRPSolver *VRP);
1190 void mergeInto(Value **I, unsigned n, unsigned New,
1191 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1192 ConstantRange CR_New = range(New, Subtree);
1193 ConstantRange Merged = CR_New;
1195 for (; n != 0; ++I, --n) {
1196 unsigned i = VN.valueNumber(*I, Subtree);
1197 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1198 if (CR_Kill.isFullSet()) continue;
1199 Merged = Merged.maximalIntersectWith(CR_Kill);
1202 if (Merged.isFullSet() || Merged == CR_New) return;
1204 applyRange(New, Merged, Subtree, VRP);
1207 void applyRange(unsigned n, const ConstantRange &CR,
1208 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1209 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
1210 if (Merged.isEmptySet()) {
1215 if (const APInt *I = Merged.getSingleElement()) {
1216 Value *V = VN.value(n); // XXX: redesign worklist.
1217 const Type *Ty = V->getType();
1218 if (Ty->isInteger()) {
1219 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1221 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1222 assert(*I == 0 && "Pointer is null but not zero?");
1223 addToWorklist(V, ConstantPointerNull::get(PTy),
1224 ICmpInst::ICMP_EQ, VRP);
1229 update(n, Merged, Subtree);
1232 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1234 ConstantRange CR1 = range(n1, Subtree);
1235 ConstantRange CR2 = range(n2, Subtree);
1237 uint32_t W = CR1.getBitWidth();
1239 if (const APInt *I = CR1.getSingleElement()) {
1240 if (CR2.isFullSet()) {
1241 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1242 applyRange(n2, NewCR2, Subtree, VRP);
1243 } else if (*I == CR2.getLower()) {
1244 APInt NewLower(CR2.getLower() + 1),
1245 NewUpper(CR2.getUpper());
1246 if (NewLower == NewUpper)
1247 NewLower = NewUpper = APInt::getMinValue(W);
1249 ConstantRange NewCR2(NewLower, NewUpper);
1250 applyRange(n2, NewCR2, Subtree, VRP);
1251 } else if (*I == CR2.getUpper() - 1) {
1252 APInt NewLower(CR2.getLower()),
1253 NewUpper(CR2.getUpper() - 1);
1254 if (NewLower == NewUpper)
1255 NewLower = NewUpper = APInt::getMinValue(W);
1257 ConstantRange NewCR2(NewLower, NewUpper);
1258 applyRange(n2, NewCR2, Subtree, VRP);
1262 if (const APInt *I = CR2.getSingleElement()) {
1263 if (CR1.isFullSet()) {
1264 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1265 applyRange(n1, NewCR1, Subtree, VRP);
1266 } else if (*I == CR1.getLower()) {
1267 APInt NewLower(CR1.getLower() + 1),
1268 NewUpper(CR1.getUpper());
1269 if (NewLower == NewUpper)
1270 NewLower = NewUpper = APInt::getMinValue(W);
1272 ConstantRange NewCR1(NewLower, NewUpper);
1273 applyRange(n1, NewCR1, Subtree, VRP);
1274 } else if (*I == CR1.getUpper() - 1) {
1275 APInt NewLower(CR1.getLower()),
1276 NewUpper(CR1.getUpper() - 1);
1277 if (NewLower == NewUpper)
1278 NewLower = NewUpper = APInt::getMinValue(W);
1280 ConstantRange NewCR1(NewLower, NewUpper);
1281 applyRange(n1, NewCR1, Subtree, VRP);
1286 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1287 LatticeVal LV, VRPSolver *VRP) {
1288 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1291 addNotEquals(n1, n2, Subtree, VRP);
1295 ConstantRange CR1 = range(n1, Subtree);
1296 ConstantRange CR2 = range(n2, Subtree);
1298 if (!CR1.isSingleElement()) {
1299 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
1301 applyRange(n1, NewCR1, Subtree, VRP);
1304 if (!CR2.isSingleElement()) {
1305 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1306 create(reversePredicate(LV), CR1));
1308 applyRange(n2, NewCR2, Subtree, VRP);
1313 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1314 /// another discovered to be unreachable. This is used to cull the graph when
1315 /// analyzing instructions, and to mark blocks with the "unreachable"
1316 /// terminator instruction after the function has executed.
1317 class VISIBILITY_HIDDEN UnreachableBlocks {
1319 std::vector<BasicBlock *> DeadBlocks;
1322 /// mark - mark a block as dead
1323 void mark(BasicBlock *BB) {
1324 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1325 std::vector<BasicBlock *>::iterator I =
1326 std::lower_bound(DeadBlocks.begin(), E, BB);
1328 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1331 /// isDead - returns whether a block is known to be dead already
1332 bool isDead(BasicBlock *BB) {
1333 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1334 std::vector<BasicBlock *>::iterator I =
1335 std::lower_bound(DeadBlocks.begin(), E, BB);
1337 return I != E && *I == BB;
1340 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1342 bool modified = false;
1343 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1344 E = DeadBlocks.end(); I != E; ++I) {
1345 BasicBlock *BB = *I;
1347 DOUT << "unreachable block: " << BB->getName() << "\n";
1349 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1351 BasicBlock *Succ = *SI;
1352 Succ->removePredecessor(BB);
1355 TerminatorInst *TI = BB->getTerminator();
1356 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1357 TI->eraseFromParent();
1358 new UnreachableInst(BB);
1367 /// VRPSolver keeps track of how changes to one variable affect other
1368 /// variables, and forwards changes along to the InequalityGraph. It
1369 /// also maintains the correct choice for "canonical" in the IG.
1370 /// @brief VRPSolver calculates inferences from a new relationship.
1371 class VISIBILITY_HIDDEN VRPSolver {
1373 friend class ValueRanges;
1377 ICmpInst::Predicate Op;
1379 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1380 Instruction *ContextInst;
1382 std::deque<Operation> WorkList;
1385 InequalityGraph &IG;
1386 UnreachableBlocks &UB;
1389 DomTreeDFS::Node *Top;
1391 Instruction *TopInst;
1394 typedef InequalityGraph::Node Node;
1396 // below - true if the Instruction is dominated by the current context
1397 // block or instruction
1398 bool below(Instruction *I) {
1399 BasicBlock *BB = I->getParent();
1400 if (TopInst && TopInst->getParent() == BB) {
1401 if (isa<TerminatorInst>(TopInst)) return false;
1402 if (isa<TerminatorInst>(I)) return true;
1403 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1404 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1406 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1407 Iter != E; ++Iter) {
1408 if (&*Iter == TopInst) return true;
1409 else if (&*Iter == I) return false;
1411 assert(!"Instructions not found in parent BasicBlock?");
1413 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1414 if (!Node) return false;
1415 return Top->dominates(Node);
1417 return false; // Not reached
1420 // aboveOrBelow - true if the Instruction either dominates or is dominated
1421 // by the current context block or instruction
1422 bool aboveOrBelow(Instruction *I) {
1423 BasicBlock *BB = I->getParent();
1424 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1425 if (!Node) return false;
1427 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1430 bool makeEqual(Value *V1, Value *V2) {
1431 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
1432 DOUT << "context is ";
1433 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1434 else DOUT << "BB: " << TopBB->getName()
1435 << "(" << Top->getDFSNumIn() << ")\n";
1437 assert(V1->getType() == V2->getType() &&
1438 "Can't make two values with different types equal.");
1440 if (V1 == V2) return true;
1442 if (isa<Constant>(V1) && isa<Constant>(V2))
1445 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1448 if (n1 == n2) return true;
1449 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1452 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1453 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1455 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1457 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1459 SetVector<unsigned> Remove;
1460 if (n2) Remove.insert(n2);
1463 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1464 // We can't just merge %x and %y because the relationship with %z would
1465 // be EQ and that's invalid. What we're doing is looking for any nodes
1466 // %z such that %x <= %z and %y >= %z, and vice versa.
1468 Node::iterator end = IG.node(n2)->end();
1470 // Find the intersection between N1 and N2 which is dominated by
1471 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1473 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1475 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1477 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1478 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1479 Node::iterator NI = IG.node(n2)->find(I->To, Top);
1481 LatticeVal NILV = reversePredicate(NI->LV);
1482 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1483 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1485 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1486 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1487 Remove.insert(I->To);
1491 // See if one of the nodes about to be removed is actually a better
1492 // canonical choice than n1.
1493 unsigned orig_n1 = n1;
1494 SetVector<unsigned>::iterator DontRemove = Remove.end();
1495 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1496 E = Remove.end(); I != E; ++I) {
1498 Value *V = VN.value(n);
1499 if (VN.compare(V, V1)) {
1505 if (DontRemove != Remove.end()) {
1506 unsigned n = *DontRemove;
1508 Remove.insert(orig_n1);
1512 // We'd like to allow makeEqual on two values to perform a simple
1513 // substitution without creating nodes in the IG whenever possible.
1515 // The first iteration through this loop operates on V2 before going
1516 // through the Remove list and operating on those too. If all of the
1517 // iterations performed simple replacements then we exit early.
1518 bool mergeIGNode = false;
1520 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1521 if (i) R = VN.value(Remove[i]); // skip n2.
1523 // Try to replace the whole instruction. If we can, we're done.
1524 Instruction *I2 = dyn_cast<Instruction>(R);
1525 if (I2 && below(I2)) {
1526 std::vector<Instruction *> ToNotify;
1527 for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
1529 Use &TheUse = UI.getUse();
1531 Instruction *I = cast<Instruction>(TheUse.getUser());
1532 ToNotify.push_back(I);
1535 DOUT << "Simply removing " << *I2
1536 << ", replacing with " << *V1 << "\n";
1537 I2->replaceAllUsesWith(V1);
1538 // leave it dead; it'll get erased later.
1542 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1543 IE = ToNotify.end(); II != IE; ++II) {
1550 // Otherwise, replace all dominated uses.
1551 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1553 Use &TheUse = UI.getUse();
1555 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1565 // If that killed the instruction, stop here.
1566 if (I2 && isInstructionTriviallyDead(I2)) {
1567 DOUT << "Killed all uses of " << *I2
1568 << ", replacing with " << *V1 << "\n";
1572 // If we make it to here, then we will need to create a node for N1.
1573 // Otherwise, we can skip out early!
1577 if (!isa<Constant>(V1)) {
1578 if (Remove.empty()) {
1579 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1581 std::vector<Value*> RemoveVals;
1582 RemoveVals.reserve(Remove.size());
1584 for (SetVector<unsigned>::iterator I = Remove.begin(),
1585 E = Remove.end(); I != E; ++I) {
1586 Value *V = VN.value(*I);
1587 if (!V->use_empty())
1588 RemoveVals.push_back(V);
1590 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1591 VN.getOrInsertVN(V1, Top), Top, this);
1597 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1598 IG.node(n1); // Ensure that IG.Nodes won't get resized
1600 // Migrate relationships from removed nodes to N1.
1601 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1604 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1606 if (NI->Subtree->DominatedBy(Top)) {
1608 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1611 if (Remove.count(NI->To))
1614 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1615 IG.node(n1)->update(NI->To, NI->LV, Top);
1620 // Point V2 (and all items in Remove) to N1.
1622 VN.addEquality(n1, V2, Top);
1624 for (SetVector<unsigned>::iterator I = Remove.begin(),
1625 E = Remove.end(); I != E; ++I) {
1626 VN.addEquality(n1, VN.value(*I), Top);
1630 // If !Remove.empty() then V2 = Remove[0]->getValue().
1631 // Even when Remove is empty, we still want to process V2.
1633 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1634 if (i) R = VN.value(Remove[i]); // skip n2.
1636 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1637 if (aboveOrBelow(I2))
1640 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1642 Use &TheUse = UI.getUse();
1644 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1645 if (aboveOrBelow(I))
1652 // re-opsToDef all dominated users of V1.
1653 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1654 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1656 Use &TheUse = UI.getUse();
1658 Value *V = TheUse.getUser();
1659 if (!V->use_empty()) {
1660 Instruction *Inst = cast<Instruction>(V);
1661 if (aboveOrBelow(Inst))
1670 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1671 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1672 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1674 case ICmpInst::ICMP_EQ:
1675 assert(!"No matching lattice value.");
1676 return static_cast<LatticeVal>(EQ_BIT);
1678 assert(!"Invalid 'icmp' predicate.");
1679 case ICmpInst::ICMP_NE:
1681 case ICmpInst::ICMP_UGT:
1683 case ICmpInst::ICMP_UGE:
1685 case ICmpInst::ICMP_ULT:
1687 case ICmpInst::ICMP_ULE:
1689 case ICmpInst::ICMP_SGT:
1691 case ICmpInst::ICMP_SGE:
1693 case ICmpInst::ICMP_SLT:
1695 case ICmpInst::ICMP_SLE:
1701 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1702 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1709 Top(DTDFS->getNodeForBlock(TopBB)),
1714 assert(Top && "VRPSolver created for unreachable basic block.");
1717 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1718 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1719 Instruction *TopInst)
1725 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1726 TopBB(TopInst->getParent()),
1730 assert(Top && "VRPSolver created for unreachable basic block.");
1731 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1734 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1735 if (Constant *C1 = dyn_cast<Constant>(V1))
1736 if (Constant *C2 = dyn_cast<Constant>(V2))
1737 return ConstantExpr::getCompare(Pred, C1, C2) ==
1738 ConstantInt::getTrue();
1740 unsigned n1 = VN.valueNumber(V1, Top);
1741 unsigned n2 = VN.valueNumber(V2, Top);
1744 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1745 Pred == ICmpInst::ICMP_ULE ||
1746 Pred == ICmpInst::ICMP_UGE ||
1747 Pred == ICmpInst::ICMP_SLE ||
1748 Pred == ICmpInst::ICMP_SGE;
1749 if (Pred == ICmpInst::ICMP_EQ) return false;
1750 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1751 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1754 if ((n1 && !n2 && isa<Constant>(V2)) ||
1755 (n2 && !n1 && isa<Constant>(V1))) {
1756 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1757 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1759 if (Pred == ICmpInst::ICMP_EQ)
1760 return CR1.isSingleElement() &&
1761 CR1.getSingleElement() == CR2.getSingleElement();
1763 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1765 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1769 /// add - adds a new property to the work queue
1770 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1771 Instruction *I = NULL) {
1772 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1773 if (I) DOUT << " context: " << *I;
1774 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
1777 assert(V1->getType() == V2->getType() &&
1778 "Can't relate two values with different types.");
1780 WorkList.push_back(Operation());
1781 Operation &O = WorkList.back();
1782 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1783 O.ContextBB = I ? I->getParent() : TopBB;
1786 /// defToOps - Given an instruction definition that we've learned something
1787 /// new about, find any new relationships between its operands.
1788 void defToOps(Instruction *I) {
1789 Instruction *NewContext = below(I) ? I : TopInst;
1790 Value *Canonical = VN.canonicalize(I, Top);
1792 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1793 const Type *Ty = BO->getType();
1794 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1796 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1797 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1799 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1801 switch (BO->getOpcode()) {
1802 case Instruction::And: {
1803 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1804 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
1805 if (Canonical == CI) {
1806 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1807 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1810 case Instruction::Or: {
1811 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1812 Constant *Zero = Constant::getNullValue(Ty);
1813 if (Canonical == Zero) {
1814 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1815 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1818 case Instruction::Xor: {
1819 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1820 // "xor i32 %c, %a" EQ %c then %a EQ 0
1821 // "xor i32 %c, %a" NE %c then %a NE 0
1822 // Repeat the above, with order of operands reversed.
1825 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1827 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1828 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1829 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
1830 ICmpInst::ICMP_EQ, NewContext);
1833 if (Canonical == LHS) {
1834 if (isa<ConstantInt>(Canonical))
1835 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1837 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1838 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1845 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1846 // "icmp ult i32 %a, %y" EQ true then %a u< y
1849 if (Canonical == ConstantInt::getTrue()) {
1850 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1852 } else if (Canonical == ConstantInt::getFalse()) {
1853 add(IC->getOperand(0), IC->getOperand(1),
1854 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1856 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1857 if (I->getType()->isFPOrFPVector()) return;
1859 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1860 // %a EQ %b and %b NE %c then %x EQ true
1861 // %a EQ %c and %b NE %c then %x EQ false
1863 Value *True = SI->getTrueValue();
1864 Value *False = SI->getFalseValue();
1865 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1866 if (Canonical == VN.canonicalize(True, Top) ||
1867 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1868 add(SI->getCondition(), ConstantInt::getTrue(),
1869 ICmpInst::ICMP_EQ, NewContext);
1870 else if (Canonical == VN.canonicalize(False, Top) ||
1871 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1872 add(SI->getCondition(), ConstantInt::getFalse(),
1873 ICmpInst::ICMP_EQ, NewContext);
1875 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1876 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1877 OE = GEPI->idx_end(); OI != OE; ++OI) {
1878 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1879 if (!Op || !Op->isZero()) return;
1881 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1882 // jumping the type plane as needed.
1883 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1884 ICmpInst::ICMP_NE)) {
1885 Value *Ptr = GEPI->getPointerOperand();
1886 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1889 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1890 const Type *SrcTy = CI->getSrcTy();
1892 unsigned ci = VN.getOrInsertVN(CI, Top);
1893 uint32_t W = VR.typeToWidth(SrcTy);
1895 ConstantRange CR = VR.range(ci, Top);
1897 if (CR.isFullSet()) return;
1899 switch (CI->getOpcode()) {
1901 case Instruction::ZExt:
1902 case Instruction::SExt:
1903 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1904 CR.truncate(W), Top, this);
1906 case Instruction::BitCast:
1907 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1914 /// opsToDef - A new relationship was discovered involving one of this
1915 /// instruction's operands. Find any new relationship involving the
1916 /// definition, or another operand.
1917 void opsToDef(Instruction *I) {
1918 Instruction *NewContext = below(I) ? I : TopInst;
1920 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1921 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1922 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1924 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1925 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1926 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1927 ICmpInst::ICMP_EQ, NewContext);
1931 // "%y = and i1 true, %x" then %x EQ %y
1932 // "%y = or i1 false, %x" then %x EQ %y
1933 // "%x = add i32 %y, 0" then %x EQ %y
1934 // "%x = mul i32 %y, 0" then %x EQ 0
1936 Instruction::BinaryOps Opcode = BO->getOpcode();
1937 const Type *Ty = BO->getType();
1938 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1940 Constant *Zero = Constant::getNullValue(Ty);
1941 Constant *One = ConstantInt::get(Ty, 1);
1942 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
1946 case Instruction::LShr:
1947 case Instruction::AShr:
1948 case Instruction::Shl:
1950 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1954 case Instruction::Sub:
1956 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1959 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1960 unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1961 ConstantRange CR = VR.range(n_ci0, Top);
1962 if (!CR.isFullSet()) {
1963 CR.subtract(CI0->getValue());
1964 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1965 VR.applyRange(n_bo, CR, Top, this);
1969 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1970 unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1971 ConstantRange CR = VR.range(n_ci1, Top);
1972 if (!CR.isFullSet()) {
1973 CR.subtract(CI1->getValue());
1974 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1975 VR.applyRange(n_bo, CR, Top, this);
1980 case Instruction::Or:
1981 if (Op0 == AllOnes || Op1 == AllOnes) {
1982 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1986 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1988 } else if (Op1 == Zero) {
1989 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1993 case Instruction::Add:
1994 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1995 unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1996 ConstantRange CR = VR.range(n_ci0, Top);
1997 if (!CR.isFullSet()) {
1998 CR.subtract(-CI0->getValue());
1999 unsigned n_bo = VN.getOrInsertVN(BO, Top);
2000 VR.applyRange(n_bo, CR, Top, this);
2004 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
2005 unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
2006 ConstantRange CR = VR.range(n_ci1, Top);
2007 if (!CR.isFullSet()) {
2008 CR.subtract(-CI1->getValue());
2009 unsigned n_bo = VN.getOrInsertVN(BO, Top);
2010 VR.applyRange(n_bo, CR, Top, this);
2015 case Instruction::Xor:
2017 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
2019 } else if (Op1 == Zero) {
2020 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2024 case Instruction::And:
2025 if (Op0 == AllOnes) {
2026 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
2028 } else if (Op1 == AllOnes) {
2029 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2032 if (Op0 == Zero || Op1 == Zero) {
2033 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
2037 case Instruction::Mul:
2038 if (Op0 == Zero || Op1 == Zero) {
2039 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
2043 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
2045 } else if (Op1 == One) {
2046 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2052 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
2053 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
2054 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
2055 // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
2057 Value *Known = Op0, *Unknown = Op1,
2058 *TheBO = VN.canonicalize(BO, Top);
2059 if (Known != TheBO) std::swap(Known, Unknown);
2060 if (Known == TheBO) {
2063 case Instruction::LShr:
2064 case Instruction::AShr:
2065 case Instruction::Shl:
2066 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2067 // otherwise, fall-through.
2068 case Instruction::Sub:
2069 if (Unknown == Op0) break;
2070 // otherwise, fall-through.
2071 case Instruction::Xor:
2072 case Instruction::Add:
2073 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
2075 case Instruction::UDiv:
2076 case Instruction::SDiv:
2077 if (Unknown == Op1) break;
2078 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
2079 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2084 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
2086 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
2087 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
2088 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2091 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2092 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2094 ICmpInst::Predicate Pred = IC->getPredicate();
2095 if (isRelatedBy(Op0, Op1, Pred))
2096 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
2097 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2098 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
2100 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2101 if (I->getType()->isFPOrFPVector()) return;
2103 // Given: "%a = select i1 %x, i32 %b, i32 %c"
2104 // %x EQ true then %a EQ %b
2105 // %x EQ false then %a EQ %c
2106 // %b EQ %c then %a EQ %b
2108 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2109 if (Canonical == ConstantInt::getTrue()) {
2110 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2111 } else if (Canonical == ConstantInt::getFalse()) {
2112 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2113 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2114 VN.canonicalize(SI->getFalseValue(), Top)) {
2115 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2117 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2118 const Type *DestTy = CI->getDestTy();
2119 if (DestTy->isFPOrFPVector()) return;
2121 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2122 Instruction::CastOps Opcode = CI->getOpcode();
2124 if (Constant *C = dyn_cast<Constant>(Op)) {
2125 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2126 ICmpInst::ICMP_EQ, NewContext);
2129 uint32_t W = VR.typeToWidth(DestTy);
2130 unsigned ci = VN.getOrInsertVN(CI, Top);
2131 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2133 if (!CR.isFullSet()) {
2136 case Instruction::ZExt:
2137 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2139 case Instruction::SExt:
2140 VR.applyRange(ci, CR.signExtend(W), Top, this);
2142 case Instruction::Trunc: {
2143 ConstantRange Result = CR.truncate(W);
2144 if (!Result.isFullSet())
2145 VR.applyRange(ci, Result, Top, this);
2147 case Instruction::BitCast:
2148 VR.applyRange(ci, CR, Top, this);
2150 // TODO: other casts?
2153 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2154 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2155 OE = GEPI->idx_end(); OI != OE; ++OI) {
2156 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2157 if (!Op || !Op->isZero()) return;
2159 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2160 // jumping the type plane as needed.
2161 Value *Ptr = GEPI->getPointerOperand();
2162 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2163 ICmpInst::ICMP_NE)) {
2164 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2170 /// solve - process the work queue
2172 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2173 while (!WorkList.empty()) {
2174 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2176 Operation &O = WorkList.front();
2177 TopInst = O.ContextInst;
2178 TopBB = O.ContextBB;
2179 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2181 O.LHS = VN.canonicalize(O.LHS, Top);
2182 O.RHS = VN.canonicalize(O.RHS, Top);
2184 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2185 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2187 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2188 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2189 else DOUT << " context block: " << O.ContextBB->getName();
2196 // If they're both Constant, skip it. Check for contradiction and mark
2197 // the BB as unreachable if so.
2198 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2199 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2200 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2201 ConstantInt::getFalse())
2204 WorkList.pop_front();
2209 if (VN.compare(O.LHS, O.RHS)) {
2210 std::swap(O.LHS, O.RHS);
2211 O.Op = ICmpInst::getSwappedPredicate(O.Op);
2214 if (O.Op == ICmpInst::ICMP_EQ) {
2215 if (!makeEqual(O.RHS, O.LHS))
2218 LatticeVal LV = cmpInstToLattice(O.Op);
2220 if ((LV & EQ_BIT) &&
2221 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2222 if (!makeEqual(O.RHS, O.LHS))
2225 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2227 WorkList.pop_front();
2231 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2232 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2235 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2236 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2239 WorkList.pop_front();
2243 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2244 IG.isRelatedBy(n1, n2, Top, LV)) {
2245 WorkList.pop_front();
2249 VR.addInequality(n1, n2, Top, LV, this);
2250 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2252 IG.addInequality(n1, n2, Top, LV);
2254 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2255 if (aboveOrBelow(I1))
2258 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2259 for (Value::use_iterator UI = O.LHS->use_begin(),
2260 UE = O.LHS->use_end(); UI != UE;) {
2261 Use &TheUse = UI.getUse();
2263 Instruction *I = cast<Instruction>(TheUse.getUser());
2264 if (aboveOrBelow(I))
2268 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2269 if (aboveOrBelow(I2))
2272 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2273 for (Value::use_iterator UI = O.RHS->use_begin(),
2274 UE = O.RHS->use_end(); UI != UE;) {
2275 Use &TheUse = UI.getUse();
2277 Instruction *I = cast<Instruction>(TheUse.getUser());
2278 if (aboveOrBelow(I))
2284 WorkList.pop_front();
2289 void ValueRanges::addToWorklist(Value *V, Constant *C,
2290 ICmpInst::Predicate Pred, VRPSolver *VRP) {
2291 VRP->add(V, C, Pred, VRP->TopInst);
2294 void ValueRanges::markBlock(VRPSolver *VRP) {
2295 VRP->UB.mark(VRP->TopBB);
2298 /// PredicateSimplifier - This class is a simplifier that replaces
2299 /// one equivalent variable with another. It also tracks what
2300 /// can't be equal and will solve setcc instructions when possible.
2301 /// @brief Root of the predicate simplifier optimization.
2302 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2306 InequalityGraph *IG;
2307 UnreachableBlocks UB;
2310 std::vector<DomTreeDFS::Node *> WorkList;
2313 static char ID; // Pass identification, replacement for typeid
2314 PredicateSimplifier() : FunctionPass(&ID) {}
2316 bool runOnFunction(Function &F);
2318 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2319 AU.addRequiredID(BreakCriticalEdgesID);
2320 AU.addRequired<DominatorTree>();
2321 AU.addRequired<TargetData>();
2322 AU.addPreserved<TargetData>();
2326 /// Forwards - Adds new properties to VRPSolver and uses them to
2327 /// simplify instructions. Because new properties sometimes apply to
2328 /// a transition from one BasicBlock to another, this will use the
2329 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2331 /// @brief Performs abstract execution of the program.
2332 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2333 friend class InstVisitor<Forwards>;
2334 PredicateSimplifier *PS;
2335 DomTreeDFS::Node *DTNode;
2339 InequalityGraph &IG;
2340 UnreachableBlocks &UB;
2343 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2344 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2347 void visitTerminatorInst(TerminatorInst &TI);
2348 void visitBranchInst(BranchInst &BI);
2349 void visitSwitchInst(SwitchInst &SI);
2351 void visitAllocaInst(AllocaInst &AI);
2352 void visitLoadInst(LoadInst &LI);
2353 void visitStoreInst(StoreInst &SI);
2355 void visitSExtInst(SExtInst &SI);
2356 void visitZExtInst(ZExtInst &ZI);
2358 void visitBinaryOperator(BinaryOperator &BO);
2359 void visitICmpInst(ICmpInst &IC);
2362 // Used by terminator instructions to proceed from the current basic
2363 // block to the next. Verifies that "current" dominates "next",
2364 // then calls visitBasicBlock.
2365 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2366 for (DomTreeDFS::Node::iterator I = Current->begin(),
2367 E = Current->end(); I != E; ++I) {
2368 WorkList.push_back(*I);
2372 void proceedToSuccessor(DomTreeDFS::Node *Next) {
2373 WorkList.push_back(Next);
2376 // Visits each instruction in the basic block.
2377 void visitBasicBlock(DomTreeDFS::Node *Node) {
2378 BasicBlock *BB = Node->getBlock();
2379 DOUT << "Entering Basic Block: " << BB->getName()
2380 << " (" << Node->getDFSNumIn() << ")\n";
2381 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2382 visitInstruction(I++, Node);
2386 // Tries to simplify each Instruction and add new properties.
2387 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2388 DOUT << "Considering instruction " << *I << "\n";
2393 // Sometimes instructions are killed in earlier analysis.
2394 if (isInstructionTriviallyDead(I)) {
2397 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2398 if (VN->value(n) == I) IG->remove(n);
2400 I->eraseFromParent();
2405 // Try to replace the whole instruction.
2406 Value *V = VN->canonicalize(I, DT);
2407 assert(V == I && "Late instruction canonicalization.");
2411 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
2412 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2413 if (VN->value(n) == I) IG->remove(n);
2415 I->replaceAllUsesWith(V);
2416 I->eraseFromParent();
2420 // Try to substitute operands.
2421 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2422 Value *Oper = I->getOperand(i);
2423 Value *V = VN->canonicalize(Oper, DT);
2424 assert(V == Oper && "Late operand canonicalization.");
2428 DOUT << "Resolving " << *I;
2429 I->setOperand(i, V);
2430 DOUT << " into " << *I;
2435 std::string name = I->getParent()->getName();
2436 DOUT << "push (%" << name << ")\n";
2437 Forwards visit(this, DT);
2439 DOUT << "pop (%" << name << ")\n";
2443 bool PredicateSimplifier::runOnFunction(Function &F) {
2444 DominatorTree *DT = &getAnalysis<DominatorTree>();
2445 DTDFS = new DomTreeDFS(DT);
2446 TargetData *TD = &getAnalysis<TargetData>();
2448 DOUT << "Entering Function: " << F.getName() << "\n";
2451 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2452 VN = new ValueNumbering(DTDFS);
2453 IG = new InequalityGraph(*VN, Root);
2454 VR = new ValueRanges(*VN, TD);
2455 WorkList.push_back(Root);
2458 DomTreeDFS::Node *DTNode = WorkList.back();
2459 WorkList.pop_back();
2460 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2461 } while (!WorkList.empty());
2468 modified |= UB.kill();
2473 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2474 PS->proceedToSuccessors(DTNode);
2477 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2478 if (BI.isUnconditional()) {
2479 PS->proceedToSuccessors(DTNode);
2483 Value *Condition = BI.getCondition();
2484 BasicBlock *TrueDest = BI.getSuccessor(0);
2485 BasicBlock *FalseDest = BI.getSuccessor(1);
2487 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2488 PS->proceedToSuccessors(DTNode);
2492 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2494 BasicBlock *Dest = (*I)->getBlock();
2495 DOUT << "Branch thinking about %" << Dest->getName()
2496 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
2498 if (Dest == TrueDest) {
2499 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
2500 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2501 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
2506 } else if (Dest == FalseDest) {
2507 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
2508 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2509 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
2516 PS->proceedToSuccessor(*I);
2520 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2521 Value *Condition = SI.getCondition();
2523 // Set the EQProperty in each of the cases BBs, and the NEProperties
2524 // in the default BB.
2526 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2528 BasicBlock *BB = (*I)->getBlock();
2529 DOUT << "Switch thinking about BB %" << BB->getName()
2530 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
2532 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2533 if (BB == SI.getDefaultDest()) {
2534 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2535 if (SI.getSuccessor(i) != BB)
2536 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2538 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2539 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2542 PS->proceedToSuccessor(*I);
2546 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2547 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2548 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
2552 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2553 Value *Ptr = LI.getPointerOperand();
2554 // avoid "load i8* null" -> null NE null.
2555 if (isa<Constant>(Ptr)) return;
2557 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2558 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2562 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2563 Value *Ptr = SI.getPointerOperand();
2564 if (isa<Constant>(Ptr)) return;
2566 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2567 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2571 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2572 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2573 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2574 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2575 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2576 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2577 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2578 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
2582 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2583 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2584 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2585 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2586 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2587 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
2591 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2592 Instruction::BinaryOps ops = BO.getOpcode();
2596 case Instruction::URem:
2597 case Instruction::SRem:
2598 case Instruction::UDiv:
2599 case Instruction::SDiv: {
2600 Value *Divisor = BO.getOperand(1);
2601 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2602 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2611 case Instruction::Shl: {
2612 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2613 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2616 case Instruction::AShr: {
2617 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2618 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2621 case Instruction::LShr:
2622 case Instruction::UDiv: {
2623 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2624 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2627 case Instruction::URem: {
2628 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2629 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2632 case Instruction::And: {
2633 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2634 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2635 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2638 case Instruction::Or: {
2639 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2640 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2641 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2647 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2648 // If possible, squeeze the ICmp predicate into something simpler.
2649 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2650 // the predicate to eq.
2652 // XXX: once we do full PHI handling, modifying the instruction in the
2653 // Forwards visitor will cause missed optimizations.
2655 ICmpInst::Predicate Pred = IC.getPredicate();
2659 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2660 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2661 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2662 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2664 if (Pred != IC.getPredicate()) {
2665 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2666 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2667 ICmpInst::ICMP_NE)) {
2669 PS->modified = true;
2670 IC.setPredicate(Pred);
2674 Pred = IC.getPredicate();
2676 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2677 ConstantInt *NextVal = 0;
2680 case ICmpInst::ICMP_SLT:
2681 case ICmpInst::ICMP_ULT:
2682 if (Op1->getValue() != 0)
2683 NextVal = ConstantInt::get(Op1->getValue()-1);
2685 case ICmpInst::ICMP_SGT:
2686 case ICmpInst::ICMP_UGT:
2687 if (!Op1->getValue().isAllOnesValue())
2688 NextVal = ConstantInt::get(Op1->getValue()+1);
2693 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2694 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2695 ICmpInst::getInversePredicate(Pred))) {
2696 ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ,
2697 IC.getOperand(0), NextVal, "");
2698 NewIC->takeName(&IC);
2699 IC.replaceAllUsesWith(NewIC);
2701 // XXX: prove this isn't necessary
2702 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2703 if (VN.value(n) == &IC) IG.remove(n);
2706 IC.eraseFromParent();
2708 PS->modified = true;
2715 char PredicateSimplifier::ID = 0;
2716 static RegisterPass<PredicateSimplifier>
2717 X("predsimplify", "Predicate Simplifier");
2719 FunctionPass *llvm::createPredicateSimplifierPass() {
2720 return new PredicateSimplifier();