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/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"
106 using namespace llvm;
108 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
109 STATISTIC(NumInstruction , "Number of instructions removed");
110 STATISTIC(NumSimple , "Number of simple replacements");
111 STATISTIC(NumBlocks , "Number of blocks marked unreachable");
112 STATISTIC(NumSnuggle , "Number of comparisons snuggled");
118 friend class DomTreeDFS;
120 typedef std::vector<Node *>::iterator iterator;
121 typedef std::vector<Node *>::const_iterator const_iterator;
123 unsigned getDFSNumIn() const { return DFSin; }
124 unsigned getDFSNumOut() const { return DFSout; }
126 BasicBlock *getBlock() const { return BB; }
128 iterator begin() { return Children.begin(); }
129 iterator end() { return Children.end(); }
131 const_iterator begin() const { return Children.begin(); }
132 const_iterator end() const { return Children.end(); }
134 bool dominates(const Node *N) const {
135 return DFSin <= N->DFSin && DFSout >= N->DFSout;
138 bool DominatedBy(const Node *N) const {
139 return N->dominates(this);
142 /// Sorts by the number of descendants. With this, you can iterate
143 /// through a sorted list and the first matching entry is the most
144 /// specific match for your basic block. The order provided is stable;
145 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
147 bool operator<(const Node &N) const {
148 unsigned spread = DFSout - DFSin;
149 unsigned N_spread = N.DFSout - N.DFSin;
150 if (spread == N_spread) return DFSin < N.DFSin;
151 else return DFSout - DFSin < N.DFSout - N.DFSin;
153 bool operator>(const Node &N) const { return N < *this; }
156 unsigned DFSin, DFSout;
159 std::vector<Node *> Children;
162 // XXX: this may be slow. Instead of using "new" for each node, consider
163 // putting them in a vector to keep them contiguous.
164 explicit DomTreeDFS(DominatorTree *DT) {
165 std::stack<std::pair<Node *, DomTreeNode *> > S;
168 Entry->BB = DT->getRootNode()->getBlock();
169 S.push(std::make_pair(Entry, DT->getRootNode()));
171 NodeMap[Entry->BB] = Entry;
174 std::pair<Node *, DomTreeNode *> &Pair = S.top();
175 Node *N = Pair.first;
176 DomTreeNode *DTNode = Pair.second;
179 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
181 Node *NewNode = new Node;
182 NewNode->BB = (*I)->getBlock();
183 N->Children.push_back(NewNode);
184 S.push(std::make_pair(NewNode, *I));
186 NodeMap[NewNode->BB] = NewNode;
201 std::stack<Node *> S;
205 Node *N = S.top(); S.pop();
207 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
214 Node *getRootNode() const { return Entry; }
216 Node *getNodeForBlock(BasicBlock *BB) const {
217 if (!NodeMap.count(BB)) return 0;
218 else return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
221 bool dominates(Instruction *I1, Instruction *I2) {
222 BasicBlock *BB1 = I1->getParent(),
223 *BB2 = I2->getParent();
225 if (isa<TerminatorInst>(I1)) return false;
226 if (isa<TerminatorInst>(I2)) return true;
227 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
228 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
230 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
232 if (&*I == I1) return true;
233 else if (&*I == I2) return false;
235 assert(!"Instructions not found in parent BasicBlock?");
237 Node *Node1 = getNodeForBlock(BB1),
238 *Node2 = getNodeForBlock(BB2);
239 if (!Node1 || !Node2) return false;
240 return Node1->dominates(Node2);
245 std::stack<std::pair<Node *, Node::iterator> > S;
249 S.push(std::make_pair(Entry, Entry->begin()));
252 std::pair<Node *, Node::iterator> &Pair = S.top();
253 Node *N = Pair.first;
254 Node::iterator &I = Pair.second;
262 S.push(std::make_pair(Next, Next->begin()));
268 virtual void dump() const {
269 dump(*cerr.stream());
272 void dump(std::ostream &os) const {
273 os << "Predicate simplifier DomTreeDFS: \n";
278 void dump(Node *N, int depth, std::ostream &os) const {
280 for (int i = 0; i < depth; ++i) { os << " "; }
281 os << "[" << depth << "] ";
283 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
284 << ", " << N->getDFSNumOut() << ")\n";
286 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
292 std::map<BasicBlock *, Node *> NodeMap;
295 // SLT SGT ULT UGT EQ
296 // 0 1 0 1 0 -- GT 10
297 // 0 1 0 1 1 -- GE 11
298 // 0 1 1 0 0 -- SGTULT 12
299 // 0 1 1 0 1 -- SGEULE 13
300 // 0 1 1 1 0 -- SGT 14
301 // 0 1 1 1 1 -- SGE 15
302 // 1 0 0 1 0 -- SLTUGT 18
303 // 1 0 0 1 1 -- SLEUGE 19
304 // 1 0 1 0 0 -- LT 20
305 // 1 0 1 0 1 -- LE 21
306 // 1 0 1 1 0 -- SLT 22
307 // 1 0 1 1 1 -- SLE 23
308 // 1 1 0 1 0 -- UGT 26
309 // 1 1 0 1 1 -- UGE 27
310 // 1 1 1 0 0 -- ULT 28
311 // 1 1 1 0 1 -- ULE 29
312 // 1 1 1 1 0 -- NE 30
314 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
317 GT = SGT_BIT | UGT_BIT,
319 LT = SLT_BIT | ULT_BIT,
321 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
322 SGTULT = SGT_BIT | ULT_BIT,
323 SGEULE = SGTULT | EQ_BIT,
324 SLTUGT = SLT_BIT | UGT_BIT,
325 SLEUGE = SLTUGT | EQ_BIT,
326 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
327 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
328 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
329 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
336 static bool validPredicate(LatticeVal LV) {
338 case GT: case GE: case LT: case LE: case NE:
339 case SGTULT: case SGT: case SGEULE:
340 case SLTUGT: case SLT: case SLEUGE:
342 case SLE: case SGE: case ULE: case UGE:
349 /// reversePredicate - reverse the direction of the inequality
350 static LatticeVal reversePredicate(LatticeVal LV) {
351 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
353 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
354 reverse |= (SLT_BIT|SGT_BIT);
356 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
357 reverse |= (ULT_BIT|UGT_BIT);
359 LatticeVal Rev = static_cast<LatticeVal>(reverse);
360 assert(validPredicate(Rev) && "Failed reversing predicate.");
364 /// The InequalityGraph stores the relationships between values.
365 /// Each Value in the graph is assigned to a Node. Nodes are pointer
366 /// comparable for equality. The caller is expected to maintain the logical
367 /// consistency of the system.
369 /// The InequalityGraph class may invalidate Node*s after any mutator call.
370 /// @brief The InequalityGraph stores the relationships between values.
371 class VISIBILITY_HIDDEN InequalityGraph {
372 DomTreeDFS::Node *TreeRoot;
374 InequalityGraph(); // DO NOT IMPLEMENT
375 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
377 explicit InequalityGraph(DomTreeDFS::Node *TreeRoot) : TreeRoot(TreeRoot){}
381 /// An Edge is contained inside a Node making one end of the edge implicit
382 /// and contains a pointer to the other end. The edge contains a lattice
383 /// value specifying the relationship and an DomTreeDFS::Node specifying
384 /// the root in the dominator tree to which this edge applies.
385 class VISIBILITY_HIDDEN Edge {
387 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
388 : To(T), LV(V), Subtree(ST) {}
392 DomTreeDFS::Node *Subtree;
394 bool operator<(const Edge &edge) const {
395 if (To != edge.To) return To < edge.To;
396 else return *Subtree < *edge.Subtree;
399 bool operator<(unsigned to) const {
403 bool operator>(unsigned to) const {
407 friend bool operator<(unsigned to, const Edge &edge) {
408 return edge.operator>(to);
412 /// A single node in the InequalityGraph. This stores the canonical Value
413 /// for the node, as well as the relationships with the neighbours.
415 /// @brief A single node in the InequalityGraph.
416 class VISIBILITY_HIDDEN Node {
417 friend class InequalityGraph;
419 typedef SmallVector<Edge, 4> RelationsType;
420 RelationsType Relations;
424 // TODO: can this idea improve performance?
425 //friend class std::vector<Node>;
426 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
429 typedef RelationsType::iterator iterator;
430 typedef RelationsType::const_iterator const_iterator;
432 Node(Value *V) : Canonical(V) {}
438 virtual void dump() const {
439 dump(*cerr.stream());
442 void dump(std::ostream &os) const {
443 os << *getValue() << ":\n";
444 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
445 static const std::string names[32] =
446 { "000000", "000001", "000002", "000003", "000004", "000005",
447 "000006", "000007", "000008", "000009", " >", " >=",
448 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
449 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
450 "000024", "000025", " u>", " u>=", " u<", " u<=",
452 os << " " << names[NI->LV] << " " << NI->To
453 << " (" << NI->Subtree->getDFSNumIn() << ")\n";
459 iterator begin() { return Relations.begin(); }
460 iterator end() { return Relations.end(); }
461 const_iterator begin() const { return Relations.begin(); }
462 const_iterator end() const { return Relations.end(); }
464 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
466 for (iterator I = std::lower_bound(begin(), E, n);
467 I != E && I->To == n; ++I) {
468 if (Subtree->DominatedBy(I->Subtree))
474 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
475 const_iterator E = end();
476 for (const_iterator I = std::lower_bound(begin(), E, n);
477 I != E && I->To == n; ++I) {
478 if (Subtree->DominatedBy(I->Subtree))
484 Value *getValue() const
489 /// Updates the lattice value for a given node. Create a new entry if
490 /// one doesn't exist, otherwise it merges the values. The new lattice
491 /// value must not be inconsistent with any previously existing value.
492 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
493 assert(validPredicate(R) && "Invalid predicate.");
494 iterator I = find(n, Subtree);
496 Edge edge(n, R, Subtree);
497 iterator Insert = std::lower_bound(begin(), end(), edge);
498 Relations.insert(Insert, edge);
500 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
501 assert(validPredicate(LV) && "Invalid union of lattice values.");
503 if (Subtree != I->Subtree) {
504 assert(Subtree->DominatedBy(I->Subtree) &&
505 "Find returned subtree that doesn't apply.");
507 Edge edge(n, R, Subtree);
508 iterator Insert = std::lower_bound(begin(), end(), edge);
509 Relations.insert(Insert, edge); // invalidates I
510 I = find(n, Subtree);
513 // Also, we have to tighten any edge that Subtree dominates.
514 for (iterator B = begin(); I->To == n; --I) {
515 if (I->Subtree->DominatedBy(Subtree)) {
516 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
517 assert(validPredicate(LV) && "Invalid union of lattice values");
528 struct VISIBILITY_HIDDEN NodeMapEdge {
531 DomTreeDFS::Node *Subtree;
533 NodeMapEdge(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
534 : V(V), index(index), Subtree(Subtree) {}
536 bool operator==(const NodeMapEdge &RHS) const {
538 Subtree == RHS.Subtree;
541 bool operator<(const NodeMapEdge &RHS) const {
542 if (V != RHS.V) return V < RHS.V;
543 else return *Subtree < *RHS.Subtree;
546 bool operator<(Value *RHS) const {
551 typedef std::vector<NodeMapEdge> NodeMapType;
554 std::vector<Node> Nodes;
557 /// node - returns the node object at a given index retrieved from getNode.
558 /// Index zero is reserved and may not be passed in here. The pointer
559 /// returned is valid until the next call to newNode or getOrInsertNode.
560 Node *node(unsigned index) {
561 assert(index != 0 && "Zero index is reserved for not found.");
562 assert(index <= Nodes.size() && "Index out of range.");
563 return &Nodes[index-1];
566 /// Returns the node currently representing Value V, or zero if no such
568 unsigned getNode(Value *V, DomTreeDFS::Node *Subtree) {
569 NodeMapType::iterator E = NodeMap.end();
570 NodeMapEdge Edge(V, 0, Subtree);
571 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
572 while (I != E && I->V == V) {
573 if (Subtree->DominatedBy(I->Subtree))
580 /// getOrInsertNode - always returns a valid node index, creating a node
581 /// to match the Value if needed.
582 unsigned getOrInsertNode(Value *V, DomTreeDFS::Node *Subtree) {
583 if (unsigned n = getNode(V, Subtree))
589 /// newNode - creates a new node for a given Value and returns the index.
590 unsigned newNode(Value *V) {
591 assert(!isa<BasicBlock>(V) && "BBs may not be nodes.");
592 assert(V->getType() != Type::VoidTy && "Void node?");
594 Nodes.push_back(Node(V));
596 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
597 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
598 "Attempt to create a duplicate Node.");
599 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
600 MapEntry), MapEntry);
601 return MapEntry.index;
604 /// If the Value is in the graph, return the canonical form. Otherwise,
605 /// return the original Value.
606 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
607 if (isa<Constant>(V)) return V;
609 if (unsigned n = getNode(V, Subtree))
610 return node(n)->getValue();
615 /// isRelatedBy - true iff n1 op n2
616 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
618 if (n1 == n2) return LV & EQ_BIT;
621 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
622 if (I != E) return (I->LV & LV) == I->LV;
627 // The add* methods assume that your input is logically valid and may
628 // assertion-fail or infinitely loop if you attempt a contradiction.
630 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
631 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
632 && "Node's 'canonical' choice isn't best within this subtree.");
634 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
635 // we may already have "%z -> node #2 (%x)" somewhere above us in the
636 // graph. We need to find those edges and add "%z -> node #1 (%y)"
637 // to keep the lookups canonical.
639 std::vector<Value *> ToRepoint;
640 ToRepoint.push_back(V);
642 if (unsigned Conflict = getNode(V, Subtree)) {
643 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
645 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
646 ToRepoint.push_back(I->V);
650 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
651 VE = ToRepoint.end(); VI != VE; ++VI) {
654 // XXX: review this code. This may be doing too many insertions.
655 NodeMapEdge Edge(V, n, Subtree);
656 NodeMapType::iterator E = NodeMap.end();
657 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
658 if (I == E || I->V != V || I->Subtree != Subtree) {
660 NodeMap.insert(I, Edge);
661 } else if (I != E && I->V == V && I->Subtree == Subtree) {
662 // Update best choice
668 if (isa<Constant>(V)) {
669 if (isa<Constant>(N->getValue())) {
670 assert(V == N->getValue() && "Constant equals different constant?");
677 /// addInequality - Sets n1 op n2.
678 /// It is also an error to call this on an inequality that is already true.
679 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
681 assert(n1 != n2 && "A node can't be inequal to itself.");
684 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
685 "Contradictory inequality.");
690 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
691 // add %a < %n2 too. This keeps the graph fully connected.
693 // Break up the relationship into signed and unsigned comparison parts.
694 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
695 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
696 // should have the EQ_BIT iff it's set for both op1 and op2.
698 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
699 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
701 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
702 if (I->LV != NE && I->To != n2) {
704 DomTreeDFS::Node *Local_Subtree = NULL;
705 if (Subtree->DominatedBy(I->Subtree))
706 Local_Subtree = Subtree;
707 else if (I->Subtree->DominatedBy(Subtree))
708 Local_Subtree = I->Subtree;
711 unsigned new_relationship = 0;
712 LatticeVal ILV = reversePredicate(I->LV);
713 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
714 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
716 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
717 new_relationship |= ILV_s;
718 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
719 new_relationship |= ILV_u;
721 if (new_relationship) {
722 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
723 new_relationship |= (SLT_BIT|SGT_BIT);
724 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
725 new_relationship |= (ULT_BIT|UGT_BIT);
726 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
727 new_relationship |= EQ_BIT;
729 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
731 node(I->To)->update(n2, NewLV, Local_Subtree);
732 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
738 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
739 if (I->LV != NE && I->To != n1) {
740 DomTreeDFS::Node *Local_Subtree = NULL;
741 if (Subtree->DominatedBy(I->Subtree))
742 Local_Subtree = Subtree;
743 else if (I->Subtree->DominatedBy(Subtree))
744 Local_Subtree = I->Subtree;
747 unsigned new_relationship = 0;
748 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
749 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
751 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
752 new_relationship |= ILV_s;
754 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
755 new_relationship |= ILV_u;
757 if (new_relationship) {
758 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
759 new_relationship |= (SLT_BIT|SGT_BIT);
760 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
761 new_relationship |= (ULT_BIT|UGT_BIT);
762 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
763 new_relationship |= EQ_BIT;
765 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
767 N1->update(I->To, NewLV, Local_Subtree);
768 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
775 N1->update(n2, LV1, Subtree);
776 N2->update(n1, reversePredicate(LV1), Subtree);
779 /// remove - Removes a Value from the graph. If the value is the canonical
780 /// choice for a Node, destroys the Node from the graph deleting all edges
781 /// to and from it. This method does not renumber the nodes.
782 void remove(Value *V) {
783 for (unsigned i = 0; i < NodeMap.size();) {
784 NodeMapType::iterator I = NodeMap.begin()+i;
786 Node *N = node(I->index);
787 if (node(I->index)->getValue() == V) {
788 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI){
789 Node::iterator Iter = node(NI->To)->find(I->index, TreeRoot);
791 node(NI->To)->Relations.erase(Iter);
792 Iter = node(NI->To)->find(I->index, TreeRoot);
793 } while (Iter != node(NI->To)->end());
797 N->Relations.clear();
804 virtual ~InequalityGraph() {}
805 virtual void dump() {
806 dump(*cerr.stream());
809 void dump(std::ostream &os) {
810 std::set<Node *> VisitedNodes;
811 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
813 Node *N = node(I->index);
814 os << *I->V << " == " << I->index
815 << "(" << I->Subtree->getDFSNumIn() << ")\n";
816 if (VisitedNodes.insert(N).second) {
817 os << I->index << ". ";
818 if (!N->getValue()) os << "(deleted node)\n";
828 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
829 /// in the InequalityGraph.
830 class VISIBILITY_HIDDEN ValueRanges {
832 /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
833 /// the scope of a rooted subtree in the dominator tree.
834 class VISIBILITY_HIDDEN ScopedRange {
836 ScopedRange(Value *V, ConstantRange CR, DomTreeDFS::Node *ST)
837 : V(V), CR(CR), Subtree(ST) {}
841 DomTreeDFS::Node *Subtree;
843 bool operator<(const ScopedRange &range) const {
844 if (V != range.V) return V < range.V;
845 else return Subtree < range.Subtree;
848 bool operator<(const Value *value) const {
852 bool operator>(const Value *value) const {
856 friend bool operator<(const Value *value, const ScopedRange &range) {
857 return range.operator>(value);
863 std::vector<ScopedRange> Ranges;
864 typedef std::vector<ScopedRange>::iterator iterator;
866 // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
867 // intrusive domtree-scoped container is in order?
869 iterator begin() { return Ranges.begin(); }
870 iterator end() { return Ranges.end(); }
872 iterator find(Value *V, DomTreeDFS::Node *Subtree) {
874 for (iterator I = std::lower_bound(begin(), E, V);
875 I != E && I->V == V; ++I) {
876 if (Subtree->DominatedBy(I->Subtree))
882 void update(Value *V, ConstantRange CR, DomTreeDFS::Node *Subtree) {
883 assert(!CR.isEmptySet() && "Empty ConstantRange!");
884 if (CR.isFullSet()) return;
886 iterator I = find(V, Subtree);
888 ScopedRange range(V, CR, Subtree);
889 iterator Insert = std::lower_bound(begin(), end(), range);
890 Ranges.insert(Insert, range);
892 CR = CR.intersectWith(I->CR);
893 assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
896 if (Subtree != I->Subtree) {
897 assert(Subtree->DominatedBy(I->Subtree) &&
898 "Find returned subtree that doesn't apply.");
900 ScopedRange range(V, CR, Subtree);
901 iterator Insert = std::lower_bound(begin(), end(), range);
902 Ranges.insert(Insert, range); // invalidates I
903 I = find(V, Subtree);
906 // Also, we have to tighten any edge that Subtree dominates.
907 for (iterator B = begin(); I->V == V; --I) {
908 if (I->Subtree->DominatedBy(Subtree)) {
909 I->CR = CR.intersectWith(I->CR);
910 assert(!I->CR.isEmptySet() &&
911 "Empty intersection of ConstantRanges!");
919 /// range - Creates a ConstantRange representing the set of all values
920 /// that match the ICmpInst::Predicate with any of the values in CR.
921 ConstantRange range(ICmpInst::Predicate ICmpOpcode,
922 const ConstantRange &CR) {
923 uint32_t W = CR.getBitWidth();
924 switch (ICmpOpcode) {
925 default: assert(!"Invalid ICmp opcode to range()");
926 case ICmpInst::ICMP_EQ:
927 return ConstantRange(CR.getLower(), CR.getUpper());
928 case ICmpInst::ICMP_NE:
929 if (CR.isSingleElement())
930 return ConstantRange(CR.getUpper(), CR.getLower());
931 return ConstantRange(W);
932 case ICmpInst::ICMP_ULT:
933 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
934 case ICmpInst::ICMP_SLT:
935 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
936 case ICmpInst::ICMP_ULE: {
937 APInt UMax(CR.getUnsignedMax());
938 if (UMax.isMaxValue())
939 return ConstantRange(W);
940 return ConstantRange(APInt::getMinValue(W), UMax + 1);
942 case ICmpInst::ICMP_SLE: {
943 APInt SMax(CR.getSignedMax());
944 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
945 return ConstantRange(W);
946 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
948 case ICmpInst::ICMP_UGT:
949 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
950 case ICmpInst::ICMP_SGT:
951 return ConstantRange(CR.getSignedMin() + 1,
952 APInt::getSignedMinValue(W));
953 case ICmpInst::ICMP_UGE: {
954 APInt UMin(CR.getUnsignedMin());
955 if (UMin.isMinValue())
956 return ConstantRange(W);
957 return ConstantRange(UMin, APInt::getNullValue(W));
959 case ICmpInst::ICMP_SGE: {
960 APInt SMin(CR.getSignedMin());
961 if (SMin.isMinSignedValue())
962 return ConstantRange(W);
963 return ConstantRange(SMin, APInt::getSignedMinValue(W));
968 /// create - Creates a ConstantRange that matches the given LatticeVal
969 /// relation with a given integer.
970 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
971 assert(!CR.isEmptySet() && "Can't deal with empty set.");
974 return range(ICmpInst::ICMP_NE, CR);
976 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
977 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
978 bool hasEQ = LV & EQ_BIT;
980 ConstantRange Range(CR.getBitWidth());
982 if (LV_s == SGT_BIT) {
983 Range = Range.intersectWith(range(
984 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
985 } else if (LV_s == SLT_BIT) {
986 Range = Range.intersectWith(range(
987 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
990 if (LV_u == UGT_BIT) {
991 Range = Range.intersectWith(range(
992 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
993 } else if (LV_u == ULT_BIT) {
994 Range = Range.intersectWith(range(
995 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1002 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree, VRPSolver *VRP);
1007 explicit ValueRanges(TargetData *TD) : TD(TD) {}
1009 // rangeFromValue - converts a Value into a range. If the value is a
1010 // constant it constructs the single element range, otherwise it performs
1011 // a lookup. The width W must be retrieved from typeToWidth and may not
1013 ConstantRange rangeFromValue(Value *V, DomTreeDFS::Node *Subtree,
1015 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
1016 return ConstantRange(C->getValue());
1017 } else if (isa<ConstantPointerNull>(V)) {
1018 return ConstantRange(APInt::getNullValue(W));
1020 iterator I = find(V, Subtree);
1024 return ConstantRange(W);
1027 // typeToWidth - returns the number of bits necessary to store a value of
1028 // this type, or zero if unknown.
1029 uint32_t typeToWidth(const Type *Ty) const {
1031 return TD->getTypeSizeInBits(Ty);
1033 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1034 return ITy->getBitWidth();
1039 bool isRelatedBy(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1041 uint32_t W = typeToWidth(V1->getType());
1042 if (!W) return false;
1044 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1045 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1047 // True iff all values in CR1 are LV to all values in CR2.
1049 default: assert(!"Impossible lattice value!");
1051 return CR1.intersectWith(CR2).isEmptySet();
1053 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1055 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1057 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1059 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1061 return CR1.getSignedMax().slt(CR2.getSignedMin());
1063 return CR1.getSignedMax().sle(CR2.getSignedMin());
1065 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1067 return CR1.getSignedMin().sge(CR2.getSignedMax());
1069 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1070 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1072 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1073 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1075 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1076 CR1.getSignedMin().sgt(CR2.getSignedMax());
1078 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1079 CR1.getSignedMin().sge(CR2.getSignedMax());
1081 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1082 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1084 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1085 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1087 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1088 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1090 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1091 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1095 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1097 void markBlock(VRPSolver *VRP);
1099 void mergeInto(Value **I, unsigned n, Value *New,
1100 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1101 assert(isCanonical(New, Subtree, VRP) && "Best choice not canonical?");
1103 uint32_t W = typeToWidth(New->getType());
1106 ConstantRange CR_New = rangeFromValue(New, Subtree, W);
1107 ConstantRange Merged = CR_New;
1109 for (; n != 0; ++I, --n) {
1110 ConstantRange CR_Kill = rangeFromValue(*I, Subtree, W);
1111 if (CR_Kill.isFullSet()) continue;
1112 Merged = Merged.intersectWith(CR_Kill);
1115 if (Merged.isFullSet() || Merged == CR_New) return;
1117 applyRange(New, Merged, Subtree, VRP);
1120 void applyRange(Value *V, const ConstantRange &CR,
1121 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1122 assert(isCanonical(V, Subtree, VRP) && "Value not canonical.");
1124 if (const APInt *I = CR.getSingleElement()) {
1125 const Type *Ty = V->getType();
1126 if (Ty->isInteger()) {
1127 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1129 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1130 assert(*I == 0 && "Pointer is null but not zero?");
1131 addToWorklist(V, ConstantPointerNull::get(PTy),
1132 ICmpInst::ICMP_EQ, VRP);
1137 ConstantRange Merged = CR.intersectWith(
1138 rangeFromValue(V, Subtree, CR.getBitWidth()));
1139 if (Merged.isEmptySet()) {
1144 update(V, Merged, Subtree);
1147 void addNotEquals(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1149 uint32_t W = typeToWidth(V1->getType());
1152 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1153 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1155 if (const APInt *I = CR1.getSingleElement()) {
1156 if (CR2.isFullSet()) {
1157 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1158 applyRange(V2, NewCR2, Subtree, VRP);
1159 } else if (*I == CR2.getLower()) {
1160 APInt NewLower(CR2.getLower() + 1),
1161 NewUpper(CR2.getUpper());
1162 if (NewLower == NewUpper)
1163 NewLower = NewUpper = APInt::getMinValue(W);
1165 ConstantRange NewCR2(NewLower, NewUpper);
1166 applyRange(V2, NewCR2, Subtree, VRP);
1167 } else if (*I == CR2.getUpper() - 1) {
1168 APInt NewLower(CR2.getLower()),
1169 NewUpper(CR2.getUpper() - 1);
1170 if (NewLower == NewUpper)
1171 NewLower = NewUpper = APInt::getMinValue(W);
1173 ConstantRange NewCR2(NewLower, NewUpper);
1174 applyRange(V2, NewCR2, Subtree, VRP);
1178 if (const APInt *I = CR2.getSingleElement()) {
1179 if (CR1.isFullSet()) {
1180 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1181 applyRange(V1, NewCR1, Subtree, VRP);
1182 } else if (*I == CR1.getLower()) {
1183 APInt NewLower(CR1.getLower() + 1),
1184 NewUpper(CR1.getUpper());
1185 if (NewLower == NewUpper)
1186 NewLower = NewUpper = APInt::getMinValue(W);
1188 ConstantRange NewCR1(NewLower, NewUpper);
1189 applyRange(V1, NewCR1, Subtree, VRP);
1190 } else if (*I == CR1.getUpper() - 1) {
1191 APInt NewLower(CR1.getLower()),
1192 NewUpper(CR1.getUpper() - 1);
1193 if (NewLower == NewUpper)
1194 NewLower = NewUpper = APInt::getMinValue(W);
1196 ConstantRange NewCR1(NewLower, NewUpper);
1197 applyRange(V1, NewCR1, Subtree, VRP);
1202 void addInequality(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1203 LatticeVal LV, VRPSolver *VRP) {
1204 assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
1206 assert(isCanonical(V1, Subtree, VRP) && "Value not canonical.");
1207 assert(isCanonical(V2, Subtree, VRP) && "Value not canonical.");
1210 addNotEquals(V1, V2, Subtree, VRP);
1214 uint32_t W = typeToWidth(V1->getType());
1217 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1218 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1220 if (!CR1.isSingleElement()) {
1221 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
1223 applyRange(V1, NewCR1, Subtree, VRP);
1226 if (!CR2.isSingleElement()) {
1227 ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
1230 applyRange(V2, NewCR2, Subtree, VRP);
1235 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1236 /// another discovered to be unreachable. This is used to cull the graph when
1237 /// analyzing instructions, and to mark blocks with the "unreachable"
1238 /// terminator instruction after the function has executed.
1239 class VISIBILITY_HIDDEN UnreachableBlocks {
1241 std::vector<BasicBlock *> DeadBlocks;
1244 /// mark - mark a block as dead
1245 void mark(BasicBlock *BB) {
1246 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1247 std::vector<BasicBlock *>::iterator I =
1248 std::lower_bound(DeadBlocks.begin(), E, BB);
1250 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1253 /// isDead - returns whether a block is known to be dead already
1254 bool isDead(BasicBlock *BB) {
1255 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1256 std::vector<BasicBlock *>::iterator I =
1257 std::lower_bound(DeadBlocks.begin(), E, BB);
1259 return I != E && *I == BB;
1262 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1264 bool modified = false;
1265 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1266 E = DeadBlocks.end(); I != E; ++I) {
1267 BasicBlock *BB = *I;
1269 DOUT << "unreachable block: " << BB->getName() << "\n";
1271 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1273 BasicBlock *Succ = *SI;
1274 Succ->removePredecessor(BB);
1277 TerminatorInst *TI = BB->getTerminator();
1278 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1279 TI->eraseFromParent();
1280 new UnreachableInst(BB);
1289 /// VRPSolver keeps track of how changes to one variable affect other
1290 /// variables, and forwards changes along to the InequalityGraph. It
1291 /// also maintains the correct choice for "canonical" in the IG.
1292 /// @brief VRPSolver calculates inferences from a new relationship.
1293 class VISIBILITY_HIDDEN VRPSolver {
1295 friend class ValueRanges;
1299 ICmpInst::Predicate Op;
1301 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1302 Instruction *ContextInst;
1304 std::deque<Operation> WorkList;
1306 InequalityGraph &IG;
1307 UnreachableBlocks &UB;
1310 DomTreeDFS::Node *Top;
1312 Instruction *TopInst;
1315 typedef InequalityGraph::Node Node;
1317 /// Returns true if V1 is a better canonical value than V2.
1318 bool compare(Value *V1, Value *V2) const {
1319 if (isa<Constant>(V1))
1320 return !isa<Constant>(V2);
1321 else if (isa<Constant>(V2))
1323 else if (isa<Argument>(V1))
1324 return !isa<Argument>(V2);
1325 else if (isa<Argument>(V2))
1328 Instruction *I1 = dyn_cast<Instruction>(V1);
1329 Instruction *I2 = dyn_cast<Instruction>(V2);
1332 return V1->getNumUses() < V2->getNumUses();
1334 return DTDFS->dominates(I1, I2);
1337 // below - true if the Instruction is dominated by the current context
1338 // block or instruction
1339 bool below(Instruction *I) {
1340 BasicBlock *BB = I->getParent();
1341 if (TopInst && TopInst->getParent() == BB) {
1342 if (isa<TerminatorInst>(TopInst)) return false;
1343 if (isa<TerminatorInst>(I)) return true;
1344 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1345 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1347 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1348 Iter != E; ++Iter) {
1349 if (&*Iter == TopInst) return true;
1350 else if (&*Iter == I) return false;
1352 assert(!"Instructions not found in parent BasicBlock?");
1354 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1355 if (!Node) return false;
1356 return Top->dominates(Node);
1360 // aboveOrBelow - true if the Instruction either dominates or is dominated
1361 // by the current context block or instruction
1362 bool aboveOrBelow(Instruction *I) {
1363 BasicBlock *BB = I->getParent();
1364 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1365 if (!Node) return false;
1367 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1370 bool makeEqual(Value *V1, Value *V2) {
1371 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
1372 DOUT << "context is ";
1373 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1374 else DOUT << "BB: " << TopBB->getName()
1375 << "(" << Top->getDFSNumIn() << ")\n";
1377 assert(V1->getType() == V2->getType() &&
1378 "Can't make two values with different types equal.");
1380 if (V1 == V2) return true;
1382 if (isa<Constant>(V1) && isa<Constant>(V2))
1385 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
1388 if (n1 == n2) return true;
1389 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1392 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
1393 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
1395 assert(!compare(V2, V1) && "Please order parameters to makeEqual.");
1397 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1399 SetVector<unsigned> Remove;
1400 if (n2) Remove.insert(n2);
1403 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1404 // We can't just merge %x and %y because the relationship with %z would
1405 // be EQ and that's invalid. What we're doing is looking for any nodes
1406 // %z such that %x <= %z and %y >= %z, and vice versa.
1408 Node *N1 = IG.node(n1);
1409 Node *N2 = IG.node(n2);
1410 Node::iterator end = N2->end();
1412 // Find the intersection between N1 and N2 which is dominated by
1413 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1415 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
1416 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1418 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1419 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1420 Node::iterator NI = N2->find(I->To, Top);
1422 LatticeVal NILV = reversePredicate(NI->LV);
1423 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1424 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1426 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1427 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1428 Remove.insert(I->To);
1432 // See if one of the nodes about to be removed is actually a better
1433 // canonical choice than n1.
1434 unsigned orig_n1 = n1;
1435 SetVector<unsigned>::iterator DontRemove = Remove.end();
1436 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1437 E = Remove.end(); I != E; ++I) {
1439 Value *V = IG.node(n)->getValue();
1440 if (compare(V, V1)) {
1446 if (DontRemove != Remove.end()) {
1447 unsigned n = *DontRemove;
1449 Remove.insert(orig_n1);
1453 // We'd like to allow makeEqual on two values to perform a simple
1454 // substitution without every creating nodes in the IG whenever possible.
1456 // The first iteration through this loop operates on V2 before going
1457 // through the Remove list and operating on those too. If all of the
1458 // iterations performed simple replacements then we exit early.
1459 bool mergeIGNode = false;
1461 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1462 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1464 // Try to replace the whole instruction. If we can, we're done.
1465 Instruction *I2 = dyn_cast<Instruction>(R);
1466 if (I2 && below(I2)) {
1467 std::vector<Instruction *> ToNotify;
1468 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1470 Use &TheUse = UI.getUse();
1472 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1473 ToNotify.push_back(I);
1476 DOUT << "Simply removing " << *I2
1477 << ", replacing with " << *V1 << "\n";
1478 I2->replaceAllUsesWith(V1);
1479 // leave it dead; it'll get erased later.
1483 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1484 IE = ToNotify.end(); II != IE; ++II) {
1491 // Otherwise, replace all dominated uses.
1492 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1494 Use &TheUse = UI.getUse();
1496 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1506 // If that killed the instruction, stop here.
1507 if (I2 && isInstructionTriviallyDead(I2)) {
1508 DOUT << "Killed all uses of " << *I2
1509 << ", replacing with " << *V1 << "\n";
1513 // If we make it to here, then we will need to create a node for N1.
1514 // Otherwise, we can skip out early!
1518 if (!isa<Constant>(V1)) {
1519 if (Remove.empty()) {
1520 VR.mergeInto(&V2, 1, V1, Top, this);
1522 std::vector<Value*> RemoveVals;
1523 RemoveVals.reserve(Remove.size());
1525 for (SetVector<unsigned>::iterator I = Remove.begin(),
1526 E = Remove.end(); I != E; ++I) {
1527 Value *V = IG.node(*I)->getValue();
1528 if (!V->use_empty())
1529 RemoveVals.push_back(V);
1531 VR.mergeInto(&RemoveVals[0], RemoveVals.size(), V1, Top, this);
1537 if (!n1) n1 = IG.newNode(V1);
1539 // Migrate relationships from removed nodes to N1.
1540 Node *N1 = IG.node(n1);
1541 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1544 Node *N = IG.node(n);
1545 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
1546 if (NI->Subtree->DominatedBy(Top)) {
1548 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1551 if (Remove.count(NI->To))
1554 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1555 N1->update(NI->To, NI->LV, Top);
1560 // Point V2 (and all items in Remove) to N1.
1562 IG.addEquality(n1, V2, Top);
1564 for (SetVector<unsigned>::iterator I = Remove.begin(),
1565 E = Remove.end(); I != E; ++I) {
1566 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
1570 // If !Remove.empty() then V2 = Remove[0]->getValue().
1571 // Even when Remove is empty, we still want to process V2.
1573 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1574 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1576 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1577 if (aboveOrBelow(I2))
1580 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1582 Use &TheUse = UI.getUse();
1584 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1585 if (aboveOrBelow(I))
1592 // re-opsToDef all dominated users of V1.
1593 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1594 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1596 Use &TheUse = UI.getUse();
1598 Value *V = TheUse.getUser();
1599 if (!V->use_empty()) {
1600 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
1601 if (aboveOrBelow(Inst))
1611 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1612 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1613 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1615 case ICmpInst::ICMP_EQ:
1616 assert(!"No matching lattice value.");
1617 return static_cast<LatticeVal>(EQ_BIT);
1619 assert(!"Invalid 'icmp' predicate.");
1620 case ICmpInst::ICMP_NE:
1622 case ICmpInst::ICMP_UGT:
1624 case ICmpInst::ICMP_UGE:
1626 case ICmpInst::ICMP_ULT:
1628 case ICmpInst::ICMP_ULE:
1630 case ICmpInst::ICMP_SGT:
1632 case ICmpInst::ICMP_SGE:
1634 case ICmpInst::ICMP_SLT:
1636 case ICmpInst::ICMP_SLE:
1642 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
1643 DomTreeDFS *DTDFS, bool &modified, BasicBlock *TopBB)
1648 Top(DTDFS->getNodeForBlock(TopBB)),
1653 assert(Top && "VRPSolver created for unreachable basic block.");
1656 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
1657 DomTreeDFS *DTDFS, bool &modified, Instruction *TopInst)
1662 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1663 TopBB(TopInst->getParent()),
1667 assert(Top && "VRPSolver created for unreachable basic block.");
1668 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1671 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1672 if (Constant *C1 = dyn_cast<Constant>(V1))
1673 if (Constant *C2 = dyn_cast<Constant>(V2))
1674 return ConstantExpr::getCompare(Pred, C1, C2) ==
1675 ConstantInt::getTrue();
1677 if (unsigned n1 = IG.getNode(V1, Top))
1678 if (unsigned n2 = IG.getNode(V2, Top)) {
1679 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1680 Pred == ICmpInst::ICMP_ULE ||
1681 Pred == ICmpInst::ICMP_UGE ||
1682 Pred == ICmpInst::ICMP_SLE ||
1683 Pred == ICmpInst::ICMP_SGE;
1684 if (Pred == ICmpInst::ICMP_EQ) return false;
1685 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1688 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1689 return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
1692 /// add - adds a new property to the work queue
1693 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1694 Instruction *I = NULL) {
1695 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1696 if (I) DOUT << " context: " << *I;
1697 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
1700 assert(V1->getType() == V2->getType() &&
1701 "Can't relate two values with different types.");
1703 WorkList.push_back(Operation());
1704 Operation &O = WorkList.back();
1705 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1706 O.ContextBB = I ? I->getParent() : TopBB;
1709 /// defToOps - Given an instruction definition that we've learned something
1710 /// new about, find any new relationships between its operands.
1711 void defToOps(Instruction *I) {
1712 Instruction *NewContext = below(I) ? I : TopInst;
1713 Value *Canonical = IG.canonicalize(I, Top);
1715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1716 const Type *Ty = BO->getType();
1717 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1719 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1720 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1722 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1724 switch (BO->getOpcode()) {
1725 case Instruction::And: {
1726 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1727 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
1728 if (Canonical == CI) {
1729 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1730 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1733 case Instruction::Or: {
1734 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1735 Constant *Zero = Constant::getNullValue(Ty);
1736 if (Canonical == Zero) {
1737 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1738 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1741 case Instruction::Xor: {
1742 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1743 // "xor i32 %c, %a" EQ %c then %a EQ 0
1744 // "xor i32 %c, %a" NE %c then %a NE 0
1745 // Repeat the above, with order of operands reversed.
1748 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1750 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1751 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1752 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
1753 ICmpInst::ICMP_EQ, NewContext);
1756 if (Canonical == LHS) {
1757 if (isa<ConstantInt>(Canonical))
1758 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1760 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1761 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1768 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1769 // "icmp ult i32 %a, %y" EQ true then %a u< y
1772 if (Canonical == ConstantInt::getTrue()) {
1773 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1775 } else if (Canonical == ConstantInt::getFalse()) {
1776 add(IC->getOperand(0), IC->getOperand(1),
1777 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1779 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1780 if (I->getType()->isFPOrFPVector()) return;
1782 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1783 // %a EQ %b and %b NE %c then %x EQ true
1784 // %a EQ %c and %b NE %c then %x EQ false
1786 Value *True = SI->getTrueValue();
1787 Value *False = SI->getFalseValue();
1788 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1789 if (Canonical == IG.canonicalize(True, Top) ||
1790 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1791 add(SI->getCondition(), ConstantInt::getTrue(),
1792 ICmpInst::ICMP_EQ, NewContext);
1793 else if (Canonical == IG.canonicalize(False, Top) ||
1794 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1795 add(SI->getCondition(), ConstantInt::getFalse(),
1796 ICmpInst::ICMP_EQ, NewContext);
1798 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1799 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1800 OE = GEPI->idx_end(); OI != OE; ++OI) {
1801 ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
1802 if (!Op || !Op->isZero()) return;
1804 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1805 // jumping the type plane as needed.
1806 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1807 ICmpInst::ICMP_NE)) {
1808 Value *Ptr = GEPI->getPointerOperand();
1809 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1812 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1813 const Type *SrcTy = CI->getSrcTy();
1815 Value *TheCI = IG.canonicalize(CI, Top);
1816 uint32_t W = VR.typeToWidth(SrcTy);
1818 ConstantRange CR = VR.rangeFromValue(TheCI, Top, W);
1820 if (CR.isFullSet()) return;
1822 switch (CI->getOpcode()) {
1824 case Instruction::ZExt:
1825 case Instruction::SExt:
1826 VR.applyRange(IG.canonicalize(CI->getOperand(0), Top),
1827 CR.truncate(W), Top, this);
1829 case Instruction::BitCast:
1830 VR.applyRange(IG.canonicalize(CI->getOperand(0), Top),
1837 /// opsToDef - A new relationship was discovered involving one of this
1838 /// instruction's operands. Find any new relationship involving the
1839 /// definition, or another operand.
1840 void opsToDef(Instruction *I) {
1841 Instruction *NewContext = below(I) ? I : TopInst;
1843 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1844 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1845 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1847 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1848 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1849 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1850 ICmpInst::ICMP_EQ, NewContext);
1854 // "%y = and i1 true, %x" then %x EQ %y
1855 // "%y = or i1 false, %x" then %x EQ %y
1856 // "%x = add i32 %y, 0" then %x EQ %y
1857 // "%x = mul i32 %y, 0" then %x EQ 0
1859 Instruction::BinaryOps Opcode = BO->getOpcode();
1860 const Type *Ty = BO->getType();
1861 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1863 Constant *Zero = Constant::getNullValue(Ty);
1864 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
1868 case Instruction::LShr:
1869 case Instruction::AShr:
1870 case Instruction::Shl:
1871 case Instruction::Sub:
1873 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1877 case Instruction::Or:
1878 if (Op0 == AllOnes || Op1 == AllOnes) {
1879 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1882 case Instruction::Xor:
1883 case Instruction::Add:
1885 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1887 } else if (Op1 == Zero) {
1888 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1892 case Instruction::And:
1893 if (Op0 == AllOnes) {
1894 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1896 } else if (Op1 == AllOnes) {
1897 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1901 case Instruction::Mul:
1902 if (Op0 == Zero || Op1 == Zero) {
1903 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1909 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
1910 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1911 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
1912 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
1914 Value *Known = Op0, *Unknown = Op1,
1915 *TheBO = IG.canonicalize(BO, Top);
1916 if (Known != TheBO) std::swap(Known, Unknown);
1917 if (Known == TheBO) {
1920 case Instruction::LShr:
1921 case Instruction::AShr:
1922 case Instruction::Shl:
1923 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1924 // otherwise, fall-through.
1925 case Instruction::Sub:
1926 if (Unknown == Op1) break;
1927 // otherwise, fall-through.
1928 case Instruction::Xor:
1929 case Instruction::Add:
1930 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
1932 case Instruction::UDiv:
1933 case Instruction::SDiv:
1934 if (Unknown == Op1) break;
1935 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
1936 Constant *One = ConstantInt::get(Ty, 1);
1937 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1943 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
1945 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1946 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
1947 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
1950 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1951 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1953 ICmpInst::Predicate Pred = IC->getPredicate();
1954 if (isRelatedBy(Op0, Op1, Pred)) {
1955 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
1956 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
1957 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
1960 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1961 if (I->getType()->isFPOrFPVector()) return;
1963 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1964 // %x EQ true then %a EQ %b
1965 // %x EQ false then %a EQ %c
1966 // %b EQ %c then %a EQ %b
1968 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
1969 if (Canonical == ConstantInt::getTrue()) {
1970 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1971 } else if (Canonical == ConstantInt::getFalse()) {
1972 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1973 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1974 IG.canonicalize(SI->getFalseValue(), Top)) {
1975 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1977 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1978 const Type *DestTy = CI->getDestTy();
1979 if (DestTy->isFPOrFPVector()) return;
1981 Value *Op = IG.canonicalize(CI->getOperand(0), Top);
1982 Instruction::CastOps Opcode = CI->getOpcode();
1984 if (Constant *C = dyn_cast<Constant>(Op)) {
1985 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
1986 ICmpInst::ICMP_EQ, NewContext);
1989 uint32_t W = VR.typeToWidth(DestTy);
1990 Value *TheCI = IG.canonicalize(CI, Top);
1991 ConstantRange CR = VR.rangeFromValue(Op, Top, W);
1993 if (!CR.isFullSet()) {
1996 case Instruction::ZExt:
1997 VR.applyRange(TheCI, CR.zeroExtend(W), Top, this);
1999 case Instruction::SExt:
2000 VR.applyRange(TheCI, CR.signExtend(W), Top, this);
2002 case Instruction::Trunc: {
2003 ConstantRange Result = CR.truncate(W);
2004 if (!Result.isFullSet())
2005 VR.applyRange(TheCI, Result, Top, this);
2007 case Instruction::BitCast:
2008 VR.applyRange(TheCI, CR, Top, this);
2010 // TODO: other casts?
2013 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2014 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2015 OE = GEPI->idx_end(); OI != OE; ++OI) {
2016 ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
2017 if (!Op || !Op->isZero()) return;
2019 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2020 // jumping the type plane as needed.
2021 Value *Ptr = GEPI->getPointerOperand();
2022 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2023 ICmpInst::ICMP_NE)) {
2024 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2030 /// solve - process the work queue
2032 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2033 while (!WorkList.empty()) {
2034 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2036 Operation &O = WorkList.front();
2037 TopInst = O.ContextInst;
2038 TopBB = O.ContextBB;
2039 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2041 O.LHS = IG.canonicalize(O.LHS, Top);
2042 O.RHS = IG.canonicalize(O.RHS, Top);
2044 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2045 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2047 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2048 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2049 else DOUT << " context block: " << O.ContextBB->getName();
2054 // If they're both Constant, skip it. Check for contradiction and mark
2055 // the BB as unreachable if so.
2056 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2057 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2058 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2059 ConstantInt::getFalse())
2062 WorkList.pop_front();
2067 if (compare(O.LHS, O.RHS)) {
2068 std::swap(O.LHS, O.RHS);
2069 O.Op = ICmpInst::getSwappedPredicate(O.Op);
2072 if (O.Op == ICmpInst::ICMP_EQ) {
2073 if (!makeEqual(O.RHS, O.LHS))
2076 LatticeVal LV = cmpInstToLattice(O.Op);
2078 if ((LV & EQ_BIT) &&
2079 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2080 if (!makeEqual(O.RHS, O.LHS))
2083 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2085 WorkList.pop_front();
2089 unsigned n1 = IG.getNode(O.LHS, Top);
2090 unsigned n2 = IG.getNode(O.RHS, Top);
2092 if (n1 && n1 == n2) {
2093 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2094 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2097 WorkList.pop_front();
2101 if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
2102 (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
2103 WorkList.pop_front();
2107 VR.addInequality(O.LHS, O.RHS, Top, LV, this);
2108 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2110 if (!n1) n1 = IG.newNode(O.LHS);
2111 if (!n2) n2 = IG.newNode(O.RHS);
2112 IG.addInequality(n1, n2, Top, LV);
2115 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2116 if (aboveOrBelow(I1))
2119 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2120 for (Value::use_iterator UI = O.LHS->use_begin(),
2121 UE = O.LHS->use_end(); UI != UE;) {
2122 Use &TheUse = UI.getUse();
2124 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2125 if (aboveOrBelow(I))
2130 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2131 if (aboveOrBelow(I2))
2134 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2135 for (Value::use_iterator UI = O.RHS->use_begin(),
2136 UE = O.RHS->use_end(); UI != UE;) {
2137 Use &TheUse = UI.getUse();
2139 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2140 if (aboveOrBelow(I))
2147 WorkList.pop_front();
2152 void ValueRanges::addToWorklist(Value *V, Constant *C,
2153 ICmpInst::Predicate Pred, VRPSolver *VRP) {
2154 VRP->add(V, C, Pred, VRP->TopInst);
2157 void ValueRanges::markBlock(VRPSolver *VRP) {
2158 VRP->UB.mark(VRP->TopBB);
2162 bool ValueRanges::isCanonical(Value *V, DomTreeDFS::Node *Subtree,
2164 return V == VRP->IG.canonicalize(V, Subtree);
2168 /// PredicateSimplifier - This class is a simplifier that replaces
2169 /// one equivalent variable with another. It also tracks what
2170 /// can't be equal and will solve setcc instructions when possible.
2171 /// @brief Root of the predicate simplifier optimization.
2172 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2175 InequalityGraph *IG;
2176 UnreachableBlocks UB;
2179 std::vector<DomTreeDFS::Node *> WorkList;
2182 static char ID; // Pass identification, replacement for typeid
2183 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2185 bool runOnFunction(Function &F);
2187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2188 AU.addRequiredID(BreakCriticalEdgesID);
2189 AU.addRequired<DominatorTree>();
2190 AU.addRequired<TargetData>();
2191 AU.addPreserved<TargetData>();
2195 /// Forwards - Adds new properties into PropertySet and uses them to
2196 /// simplify instructions. Because new properties sometimes apply to
2197 /// a transition from one BasicBlock to another, this will use the
2198 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2199 /// basic block with the new PropertySet.
2200 /// @brief Performs abstract execution of the program.
2201 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2202 friend class InstVisitor<Forwards>;
2203 PredicateSimplifier *PS;
2204 DomTreeDFS::Node *DTNode;
2207 InequalityGraph &IG;
2208 UnreachableBlocks &UB;
2211 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2212 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB), VR(*PS->VR) {}
2214 void visitTerminatorInst(TerminatorInst &TI);
2215 void visitBranchInst(BranchInst &BI);
2216 void visitSwitchInst(SwitchInst &SI);
2218 void visitAllocaInst(AllocaInst &AI);
2219 void visitLoadInst(LoadInst &LI);
2220 void visitStoreInst(StoreInst &SI);
2222 void visitSExtInst(SExtInst &SI);
2223 void visitZExtInst(ZExtInst &ZI);
2225 void visitBinaryOperator(BinaryOperator &BO);
2226 void visitICmpInst(ICmpInst &IC);
2229 // Used by terminator instructions to proceed from the current basic
2230 // block to the next. Verifies that "current" dominates "next",
2231 // then calls visitBasicBlock.
2232 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2233 for (DomTreeDFS::Node::iterator I = Current->begin(),
2234 E = Current->end(); I != E; ++I) {
2235 WorkList.push_back(*I);
2239 void proceedToSuccessor(DomTreeDFS::Node *Next) {
2240 WorkList.push_back(Next);
2243 // Visits each instruction in the basic block.
2244 void visitBasicBlock(DomTreeDFS::Node *Node) {
2245 BasicBlock *BB = Node->getBlock();
2246 DOUT << "Entering Basic Block: " << BB->getName()
2247 << " (" << Node->getDFSNumIn() << ")\n";
2248 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2249 visitInstruction(I++, Node);
2253 // Tries to simplify each Instruction and add new properties to
2255 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2256 DOUT << "Considering instruction " << *I << "\n";
2259 // Sometimes instructions are killed in earlier analysis.
2260 if (isInstructionTriviallyDead(I)) {
2264 I->eraseFromParent();
2269 // Try to replace the whole instruction.
2270 Value *V = IG->canonicalize(I, DT);
2271 assert(V == I && "Late instruction canonicalization.");
2275 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
2277 I->replaceAllUsesWith(V);
2278 I->eraseFromParent();
2282 // Try to substitute operands.
2283 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2284 Value *Oper = I->getOperand(i);
2285 Value *V = IG->canonicalize(Oper, DT);
2286 assert(V == Oper && "Late operand canonicalization.");
2290 DOUT << "Resolving " << *I;
2291 I->setOperand(i, V);
2292 DOUT << " into " << *I;
2297 std::string name = I->getParent()->getName();
2298 DOUT << "push (%" << name << ")\n";
2299 Forwards visit(this, DT);
2301 DOUT << "pop (%" << name << ")\n";
2305 bool PredicateSimplifier::runOnFunction(Function &F) {
2306 DominatorTree *DT = &getAnalysis<DominatorTree>();
2307 DTDFS = new DomTreeDFS(DT);
2308 TargetData *TD = &getAnalysis<TargetData>();
2310 DOUT << "Entering Function: " << F.getName() << "\n";
2313 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2314 IG = new InequalityGraph(Root);
2315 VR = new ValueRanges(TD);
2316 WorkList.push_back(Root);
2319 DomTreeDFS::Node *DTNode = WorkList.back();
2320 WorkList.pop_back();
2321 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2322 } while (!WorkList.empty());
2328 modified |= UB.kill();
2333 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2334 PS->proceedToSuccessors(DTNode);
2337 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2338 if (BI.isUnconditional()) {
2339 PS->proceedToSuccessors(DTNode);
2343 Value *Condition = BI.getCondition();
2344 BasicBlock *TrueDest = BI.getSuccessor(0);
2345 BasicBlock *FalseDest = BI.getSuccessor(1);
2347 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2348 PS->proceedToSuccessors(DTNode);
2352 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2354 BasicBlock *Dest = (*I)->getBlock();
2355 DOUT << "Branch thinking about %" << Dest->getName()
2356 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
2358 if (Dest == TrueDest) {
2359 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
2360 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2361 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
2364 } else if (Dest == FalseDest) {
2365 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
2366 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2367 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
2372 PS->proceedToSuccessor(*I);
2376 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2377 Value *Condition = SI.getCondition();
2379 // Set the EQProperty in each of the cases BBs, and the NEProperties
2380 // in the default BB.
2382 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2384 BasicBlock *BB = (*I)->getBlock();
2385 DOUT << "Switch thinking about BB %" << BB->getName()
2386 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
2388 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, BB);
2389 if (BB == SI.getDefaultDest()) {
2390 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2391 if (SI.getSuccessor(i) != BB)
2392 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2394 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2395 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2398 PS->proceedToSuccessor(*I);
2402 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2403 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2404 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
2408 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2409 Value *Ptr = LI.getPointerOperand();
2410 // avoid "load uint* null" -> null NE null.
2411 if (isa<Constant>(Ptr)) return;
2413 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2414 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2418 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2419 Value *Ptr = SI.getPointerOperand();
2420 if (isa<Constant>(Ptr)) return;
2422 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2423 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2427 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2428 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2429 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2430 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2431 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2432 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2433 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2434 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
2438 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2439 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2440 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2441 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2442 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2443 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
2447 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2448 Instruction::BinaryOps ops = BO.getOpcode();
2452 case Instruction::URem:
2453 case Instruction::SRem:
2454 case Instruction::UDiv:
2455 case Instruction::SDiv: {
2456 Value *Divisor = BO.getOperand(1);
2457 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2458 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2467 case Instruction::Shl: {
2468 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2469 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2472 case Instruction::AShr: {
2473 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2474 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2477 case Instruction::LShr:
2478 case Instruction::UDiv: {
2479 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2480 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2483 case Instruction::URem: {
2484 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2485 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2488 case Instruction::And: {
2489 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2490 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2491 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2494 case Instruction::Or: {
2495 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2496 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2497 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2503 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2504 // If possible, squeeze the ICmp predicate into something simpler.
2505 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2506 // the predicate to eq.
2508 // XXX: once we do full PHI handling, modifying the instruction in the
2509 // Forwards visitor will cause missed optimizations.
2511 ICmpInst::Predicate Pred = IC.getPredicate();
2515 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2516 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2517 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2518 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2520 if (Pred != IC.getPredicate()) {
2521 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2522 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2523 ICmpInst::ICMP_NE)) {
2525 PS->modified = true;
2526 IC.setPredicate(Pred);
2530 Pred = IC.getPredicate();
2532 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2533 ConstantInt *NextVal = 0;
2536 case ICmpInst::ICMP_SLT:
2537 case ICmpInst::ICMP_ULT:
2538 if (Op1->getValue() != 0)
2539 NextVal = ConstantInt::get(Op1->getValue()-1);
2541 case ICmpInst::ICMP_SGT:
2542 case ICmpInst::ICMP_UGT:
2543 if (!Op1->getValue().isAllOnesValue())
2544 NextVal = ConstantInt::get(Op1->getValue()+1);
2549 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2550 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2551 ICmpInst::getInversePredicate(Pred))) {
2552 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2554 NewIC->takeName(&IC);
2555 IC.replaceAllUsesWith(NewIC);
2556 IG.remove(&IC); // XXX: prove this isn't necessary
2557 IC.eraseFromParent();
2559 PS->modified = true;
2565 char PredicateSimplifier::ID = 0;
2566 RegisterPass<PredicateSimplifier> X("predsimplify",
2567 "Predicate Simplifier");
2570 FunctionPass *llvm::createPredicateSimplifierPass() {
2571 return new PredicateSimplifier();