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