blob: 972e875d4b0d04307b652eed3e4b1af836e4343a [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
714 if (J != E && J->To == n && J->Subtree->dominates(Subtree)) {
715 edge.LV = static_cast<LatticeVal>(J->LV & R);
716 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
717 if (edge.LV != J->LV) {
718
719 // We have to tighten any edge beneath our update.
720 for (iterator K = I; K->To == n; --K) {
721 if (K->Subtree->DominatedBy(Subtree)) {
722 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 assert(validPredicate(LV) && "Invalid union of lattice values");
Nick Lewyckydd38f8e2007-08-04 18:45:32 +0000724 K->LV = LV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 }
Nick Lewyckydd38f8e2007-08-04 18:45:32 +0000726 if (K == B) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 }
Nick Lewyckydd38f8e2007-08-04 18:45:32 +0000728
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 }
730 }
Nick Lewyckydd38f8e2007-08-04 18:45:32 +0000731
732 // Insert new edge at Subtree if it isn't already there.
733 if (I == E || I->To != n || Subtree != I->Subtree)
734 Relations.insert(I, edge);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 }
736 };
737
738 private:
739
740 std::vector<Node> Nodes;
741
742 public:
743 /// node - returns the node object at a given value number. The pointer
744 /// returned may be invalidated on the next call to node().
745 Node *node(unsigned index) {
746 assert(VN.value(index)); // This triggers the necessary checks.
747 if (Nodes.size() < index) Nodes.resize(index);
748 return &Nodes[index-1];
749 }
750
751 /// isRelatedBy - true iff n1 op n2
752 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
753 LatticeVal LV) {
754 if (n1 == n2) return LV & EQ_BIT;
755
756 Node *N1 = node(n1);
757 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
758 if (I != E) return (I->LV & LV) == I->LV;
759
760 return false;
761 }
762
763 // The add* methods assume that your input is logically valid and may
764 // assertion-fail or infinitely loop if you attempt a contradiction.
765
766 /// addInequality - Sets n1 op n2.
767 /// It is also an error to call this on an inequality that is already true.
768 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
769 LatticeVal LV1) {
770 assert(n1 != n2 && "A node can't be inequal to itself.");
771
772 if (LV1 != NE)
773 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
774 "Contradictory inequality.");
775
776 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
777 // add %a < %n2 too. This keeps the graph fully connected.
778 if (LV1 != NE) {
779 // Break up the relationship into signed and unsigned comparison parts.
780 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
781 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
782 // should have the EQ_BIT iff it's set for both op1 and op2.
783
784 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
785 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
786
787 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
788 if (I->LV != NE && I->To != n2) {
789
790 DomTreeDFS::Node *Local_Subtree = NULL;
791 if (Subtree->DominatedBy(I->Subtree))
792 Local_Subtree = Subtree;
793 else if (I->Subtree->DominatedBy(Subtree))
794 Local_Subtree = I->Subtree;
795
796 if (Local_Subtree) {
797 unsigned new_relationship = 0;
798 LatticeVal ILV = reversePredicate(I->LV);
799 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
800 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
801
802 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
803 new_relationship |= ILV_s;
804 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
805 new_relationship |= ILV_u;
806
807 if (new_relationship) {
808 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
809 new_relationship |= (SLT_BIT|SGT_BIT);
810 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
811 new_relationship |= (ULT_BIT|UGT_BIT);
812 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
813 new_relationship |= EQ_BIT;
814
815 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
816
817 node(I->To)->update(n2, NewLV, Local_Subtree);
818 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
819 }
820 }
821 }
822 }
823
824 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
825 if (I->LV != NE && I->To != n1) {
826 DomTreeDFS::Node *Local_Subtree = NULL;
827 if (Subtree->DominatedBy(I->Subtree))
828 Local_Subtree = Subtree;
829 else if (I->Subtree->DominatedBy(Subtree))
830 Local_Subtree = I->Subtree;
831
832 if (Local_Subtree) {
833 unsigned new_relationship = 0;
834 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
835 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
836
837 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
838 new_relationship |= ILV_s;
839
840 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
841 new_relationship |= ILV_u;
842
843 if (new_relationship) {
844 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
845 new_relationship |= (SLT_BIT|SGT_BIT);
846 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
847 new_relationship |= (ULT_BIT|UGT_BIT);
848 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
849 new_relationship |= EQ_BIT;
850
851 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
852
853 node(n1)->update(I->To, NewLV, Local_Subtree);
854 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
855 }
856 }
857 }
858 }
859 }
860
861 node(n1)->update(n2, LV1, Subtree);
862 node(n2)->update(n1, reversePredicate(LV1), Subtree);
863 }
864
865 /// remove - removes a node from the graph by removing all references to
866 /// and from it.
867 void remove(unsigned n) {
868 Node *N = node(n);
869 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
870 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
871 do {
872 node(NI->To)->Relations.erase(Iter);
873 Iter = node(NI->To)->find(n, TreeRoot);
874 } while (Iter != node(NI->To)->end());
875 }
876 N->Relations.clear();
877 }
878
879#ifndef NDEBUG
880 virtual ~InequalityGraph() {}
881 virtual void dump() {
882 dump(*cerr.stream());
883 }
884
885 void dump(std::ostream &os) {
886 for (unsigned i = 1; i <= Nodes.size(); ++i) {
887 os << i << " = {";
888 node(i)->dump(os);
889 os << "}\n";
890 }
891 }
892#endif
893 };
894
895 class VRPSolver;
896
897 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
898 /// in the InequalityGraph.
899 class VISIBILITY_HIDDEN ValueRanges {
900 ValueNumbering &VN;
901 TargetData *TD;
902
903 class VISIBILITY_HIDDEN ScopedRange {
904 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
905 RangeListType;
906 RangeListType RangeList;
907
908 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
909 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
910 return *LHS.first < *RHS.first;
911 }
912
913 public:
914#ifndef NDEBUG
915 virtual ~ScopedRange() {}
916 virtual void dump() const {
917 dump(*cerr.stream());
918 }
919
920 void dump(std::ostream &os) const {
921 os << "{";
922 for (const_iterator I = begin(), E = end(); I != E; ++I) {
923 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
924 }
925 os << "}";
926 }
927#endif
928
929 typedef RangeListType::iterator iterator;
930 typedef RangeListType::const_iterator const_iterator;
931
932 iterator begin() { return RangeList.begin(); }
933 iterator end() { return RangeList.end(); }
934 const_iterator begin() const { return RangeList.begin(); }
935 const_iterator end() const { return RangeList.end(); }
936
937 iterator find(DomTreeDFS::Node *Subtree) {
938 static ConstantRange empty(1, false);
939 iterator E = end();
940 iterator I = std::lower_bound(begin(), E,
941 std::make_pair(Subtree, empty), swo);
942
943 while (I != E && !I->first->dominates(Subtree)) ++I;
944 return I;
945 }
946
947 const_iterator find(DomTreeDFS::Node *Subtree) const {
948 static const ConstantRange empty(1, false);
949 const_iterator E = end();
950 const_iterator I = std::lower_bound(begin(), E,
951 std::make_pair(Subtree, empty), swo);
952
953 while (I != E && !I->first->dominates(Subtree)) ++I;
954 return I;
955 }
956
957 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
958 assert(!CR.isEmptySet() && "Empty ConstantRange.");
Nick Lewyckydd38f8e2007-08-04 18:45:32 +0000959 assert(!CR.isSingleElement() && "Refusing to store single element.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960
961 static ConstantRange empty(1, false);
962 iterator E = end();
963 iterator I =
964 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
965
966 if (I != end() && I->first == Subtree) {
967 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
968 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
969 "Invalid union of ranges.");
970 I->second = CR2;
971 } else
972 RangeList.insert(I, std::make_pair(Subtree, CR));
973 }
974 };
975
976 std::vector<ScopedRange> Ranges;
977
978 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
979 if (CR.isFullSet()) return;
980 if (Ranges.size() < n) Ranges.resize(n);
981 Ranges[n-1].update(CR, Subtree);
982 }
983
984 /// create - Creates a ConstantRange that matches the given LatticeVal
985 /// relation with a given integer.
986 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
987 assert(!CR.isEmptySet() && "Can't deal with empty set.");
988
989 if (LV == NE)
990 return makeConstantRange(ICmpInst::ICMP_NE, CR);
991
992 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
993 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
994 bool hasEQ = LV & EQ_BIT;
995
996 ConstantRange Range(CR.getBitWidth());
997
998 if (LV_s == SGT_BIT) {
999 Range = Range.maximalIntersectWith(makeConstantRange(
1000 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1001 } else if (LV_s == SLT_BIT) {
1002 Range = Range.maximalIntersectWith(makeConstantRange(
1003 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1004 }
1005
1006 if (LV_u == UGT_BIT) {
1007 Range = Range.maximalIntersectWith(makeConstantRange(
1008 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1009 } else if (LV_u == ULT_BIT) {
1010 Range = Range.maximalIntersectWith(makeConstantRange(
1011 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1012 }
1013
1014 return Range;
1015 }
1016
1017 /// makeConstantRange - Creates a ConstantRange representing the set of all
1018 /// value that match the ICmpInst::Predicate with any of the values in CR.
1019 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1020 const ConstantRange &CR) {
1021 uint32_t W = CR.getBitWidth();
1022 switch (ICmpOpcode) {
1023 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
1024 case ICmpInst::ICMP_EQ:
1025 return ConstantRange(CR.getLower(), CR.getUpper());
1026 case ICmpInst::ICMP_NE:
1027 if (CR.isSingleElement())
1028 return ConstantRange(CR.getUpper(), CR.getLower());
1029 return ConstantRange(W);
1030 case ICmpInst::ICMP_ULT:
1031 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1032 case ICmpInst::ICMP_SLT:
1033 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1034 case ICmpInst::ICMP_ULE: {
1035 APInt UMax(CR.getUnsignedMax());
1036 if (UMax.isMaxValue())
1037 return ConstantRange(W);
1038 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1039 }
1040 case ICmpInst::ICMP_SLE: {
1041 APInt SMax(CR.getSignedMax());
1042 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
1043 return ConstantRange(W);
1044 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1045 }
1046 case ICmpInst::ICMP_UGT:
1047 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
1048 case ICmpInst::ICMP_SGT:
1049 return ConstantRange(CR.getSignedMin() + 1,
1050 APInt::getSignedMinValue(W));
1051 case ICmpInst::ICMP_UGE: {
1052 APInt UMin(CR.getUnsignedMin());
1053 if (UMin.isMinValue())
1054 return ConstantRange(W);
1055 return ConstantRange(UMin, APInt::getNullValue(W));
1056 }
1057 case ICmpInst::ICMP_SGE: {
1058 APInt SMin(CR.getSignedMin());
1059 if (SMin.isMinSignedValue())
1060 return ConstantRange(W);
1061 return ConstantRange(SMin, APInt::getSignedMinValue(W));
1062 }
1063 }
1064 }
1065
1066#ifndef NDEBUG
1067 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1068 return V == VN.canonicalize(V, Subtree);
1069 }
1070#endif
1071
1072 public:
1073
1074 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
1075
1076#ifndef NDEBUG
1077 virtual ~ValueRanges() {}
1078
1079 virtual void dump() const {
1080 dump(*cerr.stream());
1081 }
1082
1083 void dump(std::ostream &os) const {
1084 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1085 os << (i+1) << " = ";
1086 Ranges[i].dump(os);
1087 os << "\n";
1088 }
1089 }
1090#endif
1091
1092 /// range - looks up the ConstantRange associated with a value number.
1093 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1094 assert(VN.value(n)); // performs range checks
1095
1096 if (n <= Ranges.size()) {
1097 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1098 if (I != Ranges[n-1].end()) return I->second;
1099 }
1100
1101 Value *V = VN.value(n);
1102 ConstantRange CR = range(V);
1103 return CR;
1104 }
1105
1106 /// range - determine a range from a Value without performing any lookups.
1107 ConstantRange range(Value *V) const {
1108 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1109 return ConstantRange(C->getValue());
1110 else if (isa<ConstantPointerNull>(V))
1111 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1112 else
1113 return typeToWidth(V->getType());
1114 }
1115
1116 // typeToWidth - returns the number of bits necessary to store a value of
1117 // this type, or zero if unknown.
1118 uint32_t typeToWidth(const Type *Ty) const {
1119 if (TD)
1120 return TD->getTypeSizeInBits(Ty);
1121
1122 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1123 return ITy->getBitWidth();
1124
1125 return 0;
1126 }
1127
1128 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1129 LatticeVal LV) {
1130 switch (LV) {
1131 default: assert(!"Impossible lattice value!");
1132 case NE:
1133 return CR1.maximalIntersectWith(CR2).isEmptySet();
1134 case ULT:
1135 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1136 case ULE:
1137 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1138 case UGT:
1139 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1140 case UGE:
1141 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1142 case SLT:
1143 return CR1.getSignedMax().slt(CR2.getSignedMin());
1144 case SLE:
1145 return CR1.getSignedMax().sle(CR2.getSignedMin());
1146 case SGT:
1147 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1148 case SGE:
1149 return CR1.getSignedMin().sge(CR2.getSignedMax());
1150 case LT:
1151 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1152 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1153 case LE:
1154 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1155 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1156 case GT:
1157 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1158 CR1.getSignedMin().sgt(CR2.getSignedMax());
1159 case GE:
1160 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1161 CR1.getSignedMin().sge(CR2.getSignedMax());
1162 case SLTUGT:
1163 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1164 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1165 case SLEUGE:
1166 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1167 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1168 case SGTULT:
1169 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1170 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1171 case SGEULE:
1172 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1173 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1174 }
1175 }
1176
1177 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1178 LatticeVal LV) {
1179 ConstantRange CR1 = range(n1, Subtree);
1180 ConstantRange CR2 = range(n2, Subtree);
1181
1182 // True iff all values in CR1 are LV to all values in CR2.
1183 return isRelatedBy(CR1, CR2, LV);
1184 }
1185
1186 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1187 VRPSolver *VRP);
1188 void markBlock(VRPSolver *VRP);
1189
1190 void mergeInto(Value **I, unsigned n, unsigned New,
1191 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1192 ConstantRange CR_New = range(New, Subtree);
1193 ConstantRange Merged = CR_New;
1194
1195 for (; n != 0; ++I, --n) {
1196 unsigned i = VN.valueNumber(*I, Subtree);
1197 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1198 if (CR_Kill.isFullSet()) continue;
1199 Merged = Merged.maximalIntersectWith(CR_Kill);
1200 }
1201
1202 if (Merged.isFullSet() || Merged == CR_New) return;
1203
1204 applyRange(New, Merged, Subtree, VRP);
1205 }
1206
1207 void applyRange(unsigned n, const ConstantRange &CR,
1208 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1209 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
1210 if (Merged.isEmptySet()) {
1211 markBlock(VRP);
1212 return;
1213 }
1214
1215 if (const APInt *I = Merged.getSingleElement()) {
1216 Value *V = VN.value(n); // XXX: redesign worklist.
1217 const Type *Ty = V->getType();
1218 if (Ty->isInteger()) {
1219 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1220 return;
1221 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1222 assert(*I == 0 && "Pointer is null but not zero?");
1223 addToWorklist(V, ConstantPointerNull::get(PTy),
1224 ICmpInst::ICMP_EQ, VRP);
1225 return;
1226 }
1227 }
1228
1229 update(n, Merged, Subtree);
1230 }
1231
1232 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1233 VRPSolver *VRP) {
1234 ConstantRange CR1 = range(n1, Subtree);
1235 ConstantRange CR2 = range(n2, Subtree);
1236
1237 uint32_t W = CR1.getBitWidth();
1238
1239 if (const APInt *I = CR1.getSingleElement()) {
1240 if (CR2.isFullSet()) {
1241 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1242 applyRange(n2, NewCR2, Subtree, VRP);
1243 } else if (*I == CR2.getLower()) {
1244 APInt NewLower(CR2.getLower() + 1),
1245 NewUpper(CR2.getUpper());
1246 if (NewLower == NewUpper)
1247 NewLower = NewUpper = APInt::getMinValue(W);
1248
1249 ConstantRange NewCR2(NewLower, NewUpper);
1250 applyRange(n2, NewCR2, Subtree, VRP);
1251 } else if (*I == CR2.getUpper() - 1) {
1252 APInt NewLower(CR2.getLower()),
1253 NewUpper(CR2.getUpper() - 1);
1254 if (NewLower == NewUpper)
1255 NewLower = NewUpper = APInt::getMinValue(W);
1256
1257 ConstantRange NewCR2(NewLower, NewUpper);
1258 applyRange(n2, NewCR2, Subtree, VRP);
1259 }
1260 }
1261
1262 if (const APInt *I = CR2.getSingleElement()) {
1263 if (CR1.isFullSet()) {
1264 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1265 applyRange(n1, NewCR1, Subtree, VRP);
1266 } else if (*I == CR1.getLower()) {
1267 APInt NewLower(CR1.getLower() + 1),
1268 NewUpper(CR1.getUpper());
1269 if (NewLower == NewUpper)
1270 NewLower = NewUpper = APInt::getMinValue(W);
1271
1272 ConstantRange NewCR1(NewLower, NewUpper);
1273 applyRange(n1, NewCR1, Subtree, VRP);
1274 } else if (*I == CR1.getUpper() - 1) {
1275 APInt NewLower(CR1.getLower()),
1276 NewUpper(CR1.getUpper() - 1);
1277 if (NewLower == NewUpper)
1278 NewLower = NewUpper = APInt::getMinValue(W);
1279
1280 ConstantRange NewCR1(NewLower, NewUpper);
1281 applyRange(n1, NewCR1, Subtree, VRP);
1282 }
1283 }
1284 }
1285
1286 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1287 LatticeVal LV, VRPSolver *VRP) {
1288 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1289
1290 if (LV == NE) {
1291 addNotEquals(n1, n2, Subtree, VRP);
1292 return;
1293 }
1294
1295 ConstantRange CR1 = range(n1, Subtree);
1296 ConstantRange CR2 = range(n2, Subtree);
1297
1298 if (!CR1.isSingleElement()) {
1299 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
1300 if (NewCR1 != CR1)
1301 applyRange(n1, NewCR1, Subtree, VRP);
1302 }
1303
1304 if (!CR2.isSingleElement()) {
1305 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1306 create(reversePredicate(LV), CR1));
1307 if (NewCR2 != CR2)
1308 applyRange(n2, NewCR2, Subtree, VRP);
1309 }
1310 }
1311 };
1312
1313 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1314 /// another discovered to be unreachable. This is used to cull the graph when
1315 /// analyzing instructions, and to mark blocks with the "unreachable"
1316 /// terminator instruction after the function has executed.
1317 class VISIBILITY_HIDDEN UnreachableBlocks {
1318 private:
1319 std::vector<BasicBlock *> DeadBlocks;
1320
1321 public:
1322 /// mark - mark a block as dead
1323 void mark(BasicBlock *BB) {
1324 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1325 std::vector<BasicBlock *>::iterator I =
1326 std::lower_bound(DeadBlocks.begin(), E, BB);
1327
1328 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1329 }
1330
1331 /// isDead - returns whether a block is known to be dead already
1332 bool isDead(BasicBlock *BB) {
1333 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1334 std::vector<BasicBlock *>::iterator I =
1335 std::lower_bound(DeadBlocks.begin(), E, BB);
1336
1337 return I != E && *I == BB;
1338 }
1339
1340 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1341 bool kill() {
1342 bool modified = false;
1343 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1344 E = DeadBlocks.end(); I != E; ++I) {
1345 BasicBlock *BB = *I;
1346
1347 DOUT << "unreachable block: " << BB->getName() << "\n";
1348
1349 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1350 SI != SE; ++SI) {
1351 BasicBlock *Succ = *SI;
1352 Succ->removePredecessor(BB);
1353 }
1354
1355 TerminatorInst *TI = BB->getTerminator();
1356 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1357 TI->eraseFromParent();
1358 new UnreachableInst(BB);
1359 ++NumBlocks;
1360 modified = true;
1361 }
1362 DeadBlocks.clear();
1363 return modified;
1364 }
1365 };
1366
1367 /// VRPSolver keeps track of how changes to one variable affect other
1368 /// variables, and forwards changes along to the InequalityGraph. It
1369 /// also maintains the correct choice for "canonical" in the IG.
1370 /// @brief VRPSolver calculates inferences from a new relationship.
1371 class VISIBILITY_HIDDEN VRPSolver {
1372 private:
1373 friend class ValueRanges;
1374
1375 struct Operation {
1376 Value *LHS, *RHS;
1377 ICmpInst::Predicate Op;
1378
1379 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1380 Instruction *ContextInst;
1381 };
1382 std::deque<Operation> WorkList;
1383
1384 ValueNumbering &VN;
1385 InequalityGraph &IG;
1386 UnreachableBlocks &UB;
1387 ValueRanges &VR;
1388 DomTreeDFS *DTDFS;
1389 DomTreeDFS::Node *Top;
1390 BasicBlock *TopBB;
1391 Instruction *TopInst;
1392 bool &modified;
1393
1394 typedef InequalityGraph::Node Node;
1395
1396 // below - true if the Instruction is dominated by the current context
1397 // block or instruction
1398 bool below(Instruction *I) {
1399 BasicBlock *BB = I->getParent();
1400 if (TopInst && TopInst->getParent() == BB) {
1401 if (isa<TerminatorInst>(TopInst)) return false;
1402 if (isa<TerminatorInst>(I)) return true;
1403 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1404 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1405
1406 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1407 Iter != E; ++Iter) {
1408 if (&*Iter == TopInst) return true;
1409 else if (&*Iter == I) return false;
1410 }
1411 assert(!"Instructions not found in parent BasicBlock?");
1412 } else {
1413 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1414 if (!Node) return false;
1415 return Top->dominates(Node);
1416 }
1417 }
1418
1419 // aboveOrBelow - true if the Instruction either dominates or is dominated
1420 // by the current context block or instruction
1421 bool aboveOrBelow(Instruction *I) {
1422 BasicBlock *BB = I->getParent();
1423 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1424 if (!Node) return false;
1425
1426 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1427 }
1428
1429 bool makeEqual(Value *V1, Value *V2) {
1430 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
1431 DOUT << "context is ";
1432 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1433 else DOUT << "BB: " << TopBB->getName()
1434 << "(" << Top->getDFSNumIn() << ")\n";
1435
1436 assert(V1->getType() == V2->getType() &&
1437 "Can't make two values with different types equal.");
1438
1439 if (V1 == V2) return true;
1440
1441 if (isa<Constant>(V1) && isa<Constant>(V2))
1442 return false;
1443
1444 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1445
1446 if (n1 && n2) {
1447 if (n1 == n2) return true;
1448 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1449 }
1450
1451 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1452 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1453
1454 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1455
1456 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1457
1458 SetVector<unsigned> Remove;
1459 if (n2) Remove.insert(n2);
1460
1461 if (n1 && n2) {
1462 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1463 // We can't just merge %x and %y because the relationship with %z would
1464 // be EQ and that's invalid. What we're doing is looking for any nodes
1465 // %z such that %x <= %z and %y >= %z, and vice versa.
1466
1467 Node::iterator end = IG.node(n2)->end();
1468
1469 // Find the intersection between N1 and N2 which is dominated by
1470 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1471 // Remove.
1472 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1473 I != E; ++I) {
1474 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1475
1476 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1477 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1478 Node::iterator NI = IG.node(n2)->find(I->To, Top);
1479 if (NI != end) {
1480 LatticeVal NILV = reversePredicate(NI->LV);
1481 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1482 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1483
1484 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1485 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1486 Remove.insert(I->To);
1487 }
1488 }
1489
1490 // See if one of the nodes about to be removed is actually a better
1491 // canonical choice than n1.
1492 unsigned orig_n1 = n1;
1493 SetVector<unsigned>::iterator DontRemove = Remove.end();
1494 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1495 E = Remove.end(); I != E; ++I) {
1496 unsigned n = *I;
1497 Value *V = VN.value(n);
1498 if (VN.compare(V, V1)) {
1499 V1 = V;
1500 n1 = n;
1501 DontRemove = I;
1502 }
1503 }
1504 if (DontRemove != Remove.end()) {
1505 unsigned n = *DontRemove;
1506 Remove.remove(n);
1507 Remove.insert(orig_n1);
1508 }
1509 }
1510
1511 // We'd like to allow makeEqual on two values to perform a simple
1512 // substitution without every creating nodes in the IG whenever possible.
1513 //
1514 // The first iteration through this loop operates on V2 before going
1515 // through the Remove list and operating on those too. If all of the
1516 // iterations performed simple replacements then we exit early.
1517 bool mergeIGNode = false;
1518 unsigned i = 0;
1519 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1520 if (i) R = VN.value(Remove[i]); // skip n2.
1521
1522 // Try to replace the whole instruction. If we can, we're done.
1523 Instruction *I2 = dyn_cast<Instruction>(R);
1524 if (I2 && below(I2)) {
1525 std::vector<Instruction *> ToNotify;
1526 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1527 UI != UE;) {
1528 Use &TheUse = UI.getUse();
1529 ++UI;
1530 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1531 ToNotify.push_back(I);
1532 }
1533
1534 DOUT << "Simply removing " << *I2
1535 << ", replacing with " << *V1 << "\n";
1536 I2->replaceAllUsesWith(V1);
1537 // leave it dead; it'll get erased later.
1538 ++NumInstruction;
1539 modified = true;
1540
1541 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1542 IE = ToNotify.end(); II != IE; ++II) {
1543 opsToDef(*II);
1544 }
1545
1546 continue;
1547 }
1548
1549 // Otherwise, replace all dominated uses.
1550 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1551 UI != UE;) {
1552 Use &TheUse = UI.getUse();
1553 ++UI;
1554 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1555 if (below(I)) {
1556 TheUse.set(V1);
1557 modified = true;
1558 ++NumVarsReplaced;
1559 opsToDef(I);
1560 }
1561 }
1562 }
1563
1564 // If that killed the instruction, stop here.
1565 if (I2 && isInstructionTriviallyDead(I2)) {
1566 DOUT << "Killed all uses of " << *I2
1567 << ", replacing with " << *V1 << "\n";
1568 continue;
1569 }
1570
1571 // If we make it to here, then we will need to create a node for N1.
1572 // Otherwise, we can skip out early!
1573 mergeIGNode = true;
1574 }
1575
1576 if (!isa<Constant>(V1)) {
1577 if (Remove.empty()) {
1578 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1579 } else {
1580 std::vector<Value*> RemoveVals;
1581 RemoveVals.reserve(Remove.size());
1582
1583 for (SetVector<unsigned>::iterator I = Remove.begin(),
1584 E = Remove.end(); I != E; ++I) {
1585 Value *V = VN.value(*I);
1586 if (!V->use_empty())
1587 RemoveVals.push_back(V);
1588 }
1589 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1590 VN.getOrInsertVN(V1, Top), Top, this);
1591 }
1592 }
1593
1594 if (mergeIGNode) {
1595 // Create N1.
1596 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1597
1598 // Migrate relationships from removed nodes to N1.
1599 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1600 I != E; ++I) {
1601 unsigned n = *I;
1602 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1603 NI != NE; ++NI) {
1604 if (NI->Subtree->DominatedBy(Top)) {
1605 if (NI->To == n1) {
1606 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1607 continue;
1608 }
1609 if (Remove.count(NI->To))
1610 continue;
1611
1612 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1613 IG.node(n1)->update(NI->To, NI->LV, Top);
1614 }
1615 }
1616 }
1617
1618 // Point V2 (and all items in Remove) to N1.
1619 if (!n2)
1620 VN.addEquality(n1, V2, Top);
1621 else {
1622 for (SetVector<unsigned>::iterator I = Remove.begin(),
1623 E = Remove.end(); I != E; ++I) {
1624 VN.addEquality(n1, VN.value(*I), Top);
1625 }
1626 }
1627
1628 // If !Remove.empty() then V2 = Remove[0]->getValue().
1629 // Even when Remove is empty, we still want to process V2.
1630 i = 0;
1631 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1632 if (i) R = VN.value(Remove[i]); // skip n2.
1633
1634 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1635 if (aboveOrBelow(I2))
1636 defToOps(I2);
1637 }
1638 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1639 UI != UE;) {
1640 Use &TheUse = UI.getUse();
1641 ++UI;
1642 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1643 if (aboveOrBelow(I))
1644 opsToDef(I);
1645 }
1646 }
1647 }
1648 }
1649
1650 // re-opsToDef all dominated users of V1.
1651 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1652 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1653 UI != UE;) {
1654 Use &TheUse = UI.getUse();
1655 ++UI;
1656 Value *V = TheUse.getUser();
1657 if (!V->use_empty()) {
1658 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
1659 if (aboveOrBelow(Inst))
1660 opsToDef(Inst);
1661 }
1662 }
1663 }
1664 }
1665
1666 return true;
1667 }
1668
1669 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1670 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1671 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1672 switch (Pred) {
1673 case ICmpInst::ICMP_EQ:
1674 assert(!"No matching lattice value.");
1675 return static_cast<LatticeVal>(EQ_BIT);
1676 default:
1677 assert(!"Invalid 'icmp' predicate.");
1678 case ICmpInst::ICMP_NE:
1679 return NE;
1680 case ICmpInst::ICMP_UGT:
1681 return UGT;
1682 case ICmpInst::ICMP_UGE:
1683 return UGE;
1684 case ICmpInst::ICMP_ULT:
1685 return ULT;
1686 case ICmpInst::ICMP_ULE:
1687 return ULE;
1688 case ICmpInst::ICMP_SGT:
1689 return SGT;
1690 case ICmpInst::ICMP_SGE:
1691 return SGE;
1692 case ICmpInst::ICMP_SLT:
1693 return SLT;
1694 case ICmpInst::ICMP_SLE:
1695 return SLE;
1696 }
1697 }
1698
1699 public:
1700 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1701 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1702 BasicBlock *TopBB)
1703 : VN(VN),
1704 IG(IG),
1705 UB(UB),
1706 VR(VR),
1707 DTDFS(DTDFS),
1708 Top(DTDFS->getNodeForBlock(TopBB)),
1709 TopBB(TopBB),
1710 TopInst(NULL),
1711 modified(modified)
1712 {
1713 assert(Top && "VRPSolver created for unreachable basic block.");
1714 }
1715
1716 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1717 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1718 Instruction *TopInst)
1719 : VN(VN),
1720 IG(IG),
1721 UB(UB),
1722 VR(VR),
1723 DTDFS(DTDFS),
1724 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1725 TopBB(TopInst->getParent()),
1726 TopInst(TopInst),
1727 modified(modified)
1728 {
1729 assert(Top && "VRPSolver created for unreachable basic block.");
1730 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1731 }
1732
1733 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1734 if (Constant *C1 = dyn_cast<Constant>(V1))
1735 if (Constant *C2 = dyn_cast<Constant>(V2))
1736 return ConstantExpr::getCompare(Pred, C1, C2) ==
1737 ConstantInt::getTrue();
1738
1739 unsigned n1 = VN.valueNumber(V1, Top);
1740 unsigned n2 = VN.valueNumber(V2, Top);
1741
1742 if (n1 && n2) {
1743 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1744 Pred == ICmpInst::ICMP_ULE ||
1745 Pred == ICmpInst::ICMP_UGE ||
1746 Pred == ICmpInst::ICMP_SLE ||
1747 Pred == ICmpInst::ICMP_SGE;
1748 if (Pred == ICmpInst::ICMP_EQ) return false;
1749 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1750 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1751 }
1752
1753 if ((n1 && !n2 && isa<Constant>(V2)) ||
1754 (n2 && !n1 && isa<Constant>(V1))) {
1755 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1756 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1757
1758 if (Pred == ICmpInst::ICMP_EQ)
1759 return CR1.isSingleElement() &&
1760 CR1.getSingleElement() == CR2.getSingleElement();
1761
1762 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1763 }
1764 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1765 return false;
1766 }
1767
1768 /// add - adds a new property to the work queue
1769 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1770 Instruction *I = NULL) {
1771 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1772 if (I) DOUT << " context: " << *I;
1773 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
1774 DOUT << "\n";
1775
1776 assert(V1->getType() == V2->getType() &&
1777 "Can't relate two values with different types.");
1778
1779 WorkList.push_back(Operation());
1780 Operation &O = WorkList.back();
1781 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1782 O.ContextBB = I ? I->getParent() : TopBB;
1783 }
1784
1785 /// defToOps - Given an instruction definition that we've learned something
1786 /// new about, find any new relationships between its operands.
1787 void defToOps(Instruction *I) {
1788 Instruction *NewContext = below(I) ? I : TopInst;
1789 Value *Canonical = VN.canonicalize(I, Top);
1790
1791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1792 const Type *Ty = BO->getType();
1793 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1794
1795 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1796 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1797
1798 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1799
1800 switch (BO->getOpcode()) {
1801 case Instruction::And: {
1802 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1803 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
1804 if (Canonical == CI) {
1805 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1806 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1807 }
1808 } break;
1809 case Instruction::Or: {
1810 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1811 Constant *Zero = Constant::getNullValue(Ty);
1812 if (Canonical == Zero) {
1813 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1814 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1815 }
1816 } break;
1817 case Instruction::Xor: {
1818 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1819 // "xor i32 %c, %a" EQ %c then %a EQ 0
1820 // "xor i32 %c, %a" NE %c then %a NE 0
1821 // Repeat the above, with order of operands reversed.
1822 Value *LHS = Op0;
1823 Value *RHS = Op1;
1824 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1825
1826 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1827 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1828 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
1829 ICmpInst::ICMP_EQ, NewContext);
1830 }
1831 }
1832 if (Canonical == LHS) {
1833 if (isa<ConstantInt>(Canonical))
1834 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1835 NewContext);
1836 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1837 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1838 NewContext);
1839 }
1840 } break;
1841 default:
1842 break;
1843 }
1844 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1845 // "icmp ult i32 %a, %y" EQ true then %a u< y
1846 // etc.
1847
1848 if (Canonical == ConstantInt::getTrue()) {
1849 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1850 NewContext);
1851 } else if (Canonical == ConstantInt::getFalse()) {
1852 add(IC->getOperand(0), IC->getOperand(1),
1853 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1854 }
1855 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1856 if (I->getType()->isFPOrFPVector()) return;
1857
1858 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1859 // %a EQ %b and %b NE %c then %x EQ true
1860 // %a EQ %c and %b NE %c then %x EQ false
1861
1862 Value *True = SI->getTrueValue();
1863 Value *False = SI->getFalseValue();
1864 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1865 if (Canonical == VN.canonicalize(True, Top) ||
1866 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1867 add(SI->getCondition(), ConstantInt::getTrue(),
1868 ICmpInst::ICMP_EQ, NewContext);
1869 else if (Canonical == VN.canonicalize(False, Top) ||
1870 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1871 add(SI->getCondition(), ConstantInt::getFalse(),
1872 ICmpInst::ICMP_EQ, NewContext);
1873 }
1874 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1875 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1876 OE = GEPI->idx_end(); OI != OE; ++OI) {
1877 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1878 if (!Op || !Op->isZero()) return;
1879 }
1880 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1881 // jumping the type plane as needed.
1882 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1883 ICmpInst::ICMP_NE)) {
1884 Value *Ptr = GEPI->getPointerOperand();
1885 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1886 NewContext);
1887 }
1888 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1889 const Type *SrcTy = CI->getSrcTy();
1890
1891 unsigned ci = VN.getOrInsertVN(CI, Top);
1892 uint32_t W = VR.typeToWidth(SrcTy);
1893 if (!W) return;
1894 ConstantRange CR = VR.range(ci, Top);
1895
1896 if (CR.isFullSet()) return;
1897
1898 switch (CI->getOpcode()) {
1899 default: break;
1900 case Instruction::ZExt:
1901 case Instruction::SExt:
1902 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1903 CR.truncate(W), Top, this);
1904 break;
1905 case Instruction::BitCast:
1906 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1907 CR, Top, this);
1908 break;
1909 }
1910 }
1911 }
1912
1913 /// opsToDef - A new relationship was discovered involving one of this
1914 /// instruction's operands. Find any new relationship involving the
1915 /// definition, or another operand.
1916 void opsToDef(Instruction *I) {
1917 Instruction *NewContext = below(I) ? I : TopInst;
1918
1919 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1920 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1921 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1922
1923 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1924 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1925 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1926 ICmpInst::ICMP_EQ, NewContext);
1927 return;
1928 }
1929
1930 // "%y = and i1 true, %x" then %x EQ %y
1931 // "%y = or i1 false, %x" then %x EQ %y
1932 // "%x = add i32 %y, 0" then %x EQ %y
1933 // "%x = mul i32 %y, 0" then %x EQ 0
1934
1935 Instruction::BinaryOps Opcode = BO->getOpcode();
1936 const Type *Ty = BO->getType();
1937 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1938
1939 Constant *Zero = Constant::getNullValue(Ty);
1940 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
1941
1942 switch (Opcode) {
1943 default: break;
1944 case Instruction::LShr:
1945 case Instruction::AShr:
1946 case Instruction::Shl:
1947 case Instruction::Sub:
1948 if (Op1 == Zero) {
1949 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1950 return;
1951 }
1952 break;
1953 case Instruction::Or:
1954 if (Op0 == AllOnes || Op1 == AllOnes) {
1955 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1956 return;
1957 } // fall-through
1958 case Instruction::Xor:
1959 case Instruction::Add:
1960 if (Op0 == Zero) {
1961 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1962 return;
1963 } else if (Op1 == Zero) {
1964 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1965 return;
1966 }
1967 break;
1968 case Instruction::And:
1969 if (Op0 == AllOnes) {
1970 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1971 return;
1972 } else if (Op1 == AllOnes) {
1973 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1974 return;
1975 }
1976 // fall-through
1977 case Instruction::Mul:
1978 if (Op0 == Zero || Op1 == Zero) {
1979 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1980 return;
1981 }
1982 break;
1983 }
1984
1985 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
1986 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1987 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
1988 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
1989
1990 Value *Known = Op0, *Unknown = Op1,
1991 *TheBO = VN.canonicalize(BO, Top);
1992 if (Known != TheBO) std::swap(Known, Unknown);
1993 if (Known == TheBO) {
1994 switch (Opcode) {
1995 default: break;
1996 case Instruction::LShr:
1997 case Instruction::AShr:
1998 case Instruction::Shl:
1999 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2000 // otherwise, fall-through.
2001 case Instruction::Sub:
2002 if (Unknown == Op1) break;
2003 // otherwise, fall-through.
2004 case Instruction::Xor:
2005 case Instruction::Add:
2006 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
2007 break;
2008 case Instruction::UDiv:
2009 case Instruction::SDiv:
2010 if (Unknown == Op1) break;
2011 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
2012 Constant *One = ConstantInt::get(Ty, 1);
2013 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2014 }
2015 break;
2016 }
2017 }
2018
2019 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
2020
2021 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
2022 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
2023 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2024 // etc.
2025
2026 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2027 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2028
2029 ICmpInst::Predicate Pred = IC->getPredicate();
2030 if (isRelatedBy(Op0, Op1, Pred))
2031 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
2032 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2033 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
2034
2035 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2036 if (I->getType()->isFPOrFPVector()) return;
2037
2038 // Given: "%a = select i1 %x, i32 %b, i32 %c"
2039 // %x EQ true then %a EQ %b
2040 // %x EQ false then %a EQ %c
2041 // %b EQ %c then %a EQ %b
2042
2043 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2044 if (Canonical == ConstantInt::getTrue()) {
2045 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2046 } else if (Canonical == ConstantInt::getFalse()) {
2047 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2048 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2049 VN.canonicalize(SI->getFalseValue(), Top)) {
2050 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2051 }
2052 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2053 const Type *DestTy = CI->getDestTy();
2054 if (DestTy->isFPOrFPVector()) return;
2055
2056 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2057 Instruction::CastOps Opcode = CI->getOpcode();
2058
2059 if (Constant *C = dyn_cast<Constant>(Op)) {
2060 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2061 ICmpInst::ICMP_EQ, NewContext);
2062 }
2063
2064 uint32_t W = VR.typeToWidth(DestTy);
2065 unsigned ci = VN.getOrInsertVN(CI, Top);
2066 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2067
2068 if (!CR.isFullSet()) {
2069 switch (Opcode) {
2070 default: break;
2071 case Instruction::ZExt:
2072 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2073 break;
2074 case Instruction::SExt:
2075 VR.applyRange(ci, CR.signExtend(W), Top, this);
2076 break;
2077 case Instruction::Trunc: {
2078 ConstantRange Result = CR.truncate(W);
2079 if (!Result.isFullSet())
2080 VR.applyRange(ci, Result, Top, this);
2081 } break;
2082 case Instruction::BitCast:
2083 VR.applyRange(ci, CR, Top, this);
2084 break;
2085 // TODO: other casts?
2086 }
2087 }
2088 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2089 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2090 OE = GEPI->idx_end(); OI != OE; ++OI) {
2091 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2092 if (!Op || !Op->isZero()) return;
2093 }
2094 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2095 // jumping the type plane as needed.
2096 Value *Ptr = GEPI->getPointerOperand();
2097 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2098 ICmpInst::ICMP_NE)) {
2099 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2100 NewContext);
2101 }
2102 }
2103 }
2104
2105 /// solve - process the work queue
2106 void solve() {
2107 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2108 while (!WorkList.empty()) {
2109 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2110
2111 Operation &O = WorkList.front();
2112 TopInst = O.ContextInst;
2113 TopBB = O.ContextBB;
2114 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2115
2116 O.LHS = VN.canonicalize(O.LHS, Top);
2117 O.RHS = VN.canonicalize(O.RHS, Top);
2118
2119 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2120 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2121
2122 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2123 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2124 else DOUT << " context block: " << O.ContextBB->getName();
2125 DOUT << "\n";
2126
2127 DEBUG(VN.dump());
2128 DEBUG(IG.dump());
2129 DEBUG(VR.dump());
2130
2131 // If they're both Constant, skip it. Check for contradiction and mark
2132 // the BB as unreachable if so.
2133 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2134 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2135 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2136 ConstantInt::getFalse())
2137 UB.mark(TopBB);
2138
2139 WorkList.pop_front();
2140 continue;
2141 }
2142 }
2143
2144 if (VN.compare(O.LHS, O.RHS)) {
2145 std::swap(O.LHS, O.RHS);
2146 O.Op = ICmpInst::getSwappedPredicate(O.Op);
2147 }
2148
2149 if (O.Op == ICmpInst::ICMP_EQ) {
2150 if (!makeEqual(O.RHS, O.LHS))
2151 UB.mark(TopBB);
2152 } else {
2153 LatticeVal LV = cmpInstToLattice(O.Op);
2154
2155 if ((LV & EQ_BIT) &&
2156 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2157 if (!makeEqual(O.RHS, O.LHS))
2158 UB.mark(TopBB);
2159 } else {
2160 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2161 UB.mark(TopBB);
2162 WorkList.pop_front();
2163 continue;
2164 }
2165
2166 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2167 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2168
2169 if (n1 == n2) {
2170 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2171 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2172 UB.mark(TopBB);
2173
2174 WorkList.pop_front();
2175 continue;
2176 }
2177
2178 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2179 IG.isRelatedBy(n1, n2, Top, LV)) {
2180 WorkList.pop_front();
2181 continue;
2182 }
2183
2184 VR.addInequality(n1, n2, Top, LV, this);
2185 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2186 LV == NE)
2187 IG.addInequality(n1, n2, Top, LV);
2188
2189 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2190 if (aboveOrBelow(I1))
2191 defToOps(I1);
2192 }
2193 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2194 for (Value::use_iterator UI = O.LHS->use_begin(),
2195 UE = O.LHS->use_end(); UI != UE;) {
2196 Use &TheUse = UI.getUse();
2197 ++UI;
2198 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2199 if (aboveOrBelow(I))
2200 opsToDef(I);
2201 }
2202 }
2203 }
2204 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2205 if (aboveOrBelow(I2))
2206 defToOps(I2);
2207 }
2208 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2209 for (Value::use_iterator UI = O.RHS->use_begin(),
2210 UE = O.RHS->use_end(); UI != UE;) {
2211 Use &TheUse = UI.getUse();
2212 ++UI;
2213 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2214 if (aboveOrBelow(I))
2215 opsToDef(I);
2216 }
2217 }
2218 }
2219 }
2220 }
2221 WorkList.pop_front();
2222 }
2223 }
2224 };
2225
2226 void ValueRanges::addToWorklist(Value *V, Constant *C,
2227 ICmpInst::Predicate Pred, VRPSolver *VRP) {
2228 VRP->add(V, C, Pred, VRP->TopInst);
2229 }
2230
2231 void ValueRanges::markBlock(VRPSolver *VRP) {
2232 VRP->UB.mark(VRP->TopBB);
2233 }
2234
2235 /// PredicateSimplifier - This class is a simplifier that replaces
2236 /// one equivalent variable with another. It also tracks what
2237 /// can't be equal and will solve setcc instructions when possible.
2238 /// @brief Root of the predicate simplifier optimization.
2239 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2240 DomTreeDFS *DTDFS;
2241 bool modified;
2242 ValueNumbering *VN;
2243 InequalityGraph *IG;
2244 UnreachableBlocks UB;
2245 ValueRanges *VR;
2246
2247 std::vector<DomTreeDFS::Node *> WorkList;
2248
2249 public:
2250 static char ID; // Pass identification, replacement for typeid
2251 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2252
2253 bool runOnFunction(Function &F);
2254
2255 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2256 AU.addRequiredID(BreakCriticalEdgesID);
2257 AU.addRequired<DominatorTree>();
2258 AU.addRequired<TargetData>();
2259 AU.addPreserved<TargetData>();
2260 }
2261
2262 private:
2263 /// Forwards - Adds new properties to VRPSolver and uses them to
2264 /// simplify instructions. Because new properties sometimes apply to
2265 /// a transition from one BasicBlock to another, this will use the
2266 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2267 /// basic block.
2268 /// @brief Performs abstract execution of the program.
2269 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2270 friend class InstVisitor<Forwards>;
2271 PredicateSimplifier *PS;
2272 DomTreeDFS::Node *DTNode;
2273
2274 public:
2275 ValueNumbering &VN;
2276 InequalityGraph &IG;
2277 UnreachableBlocks &UB;
2278 ValueRanges &VR;
2279
2280 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2281 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2282 VR(*PS->VR) {}
2283
2284 void visitTerminatorInst(TerminatorInst &TI);
2285 void visitBranchInst(BranchInst &BI);
2286 void visitSwitchInst(SwitchInst &SI);
2287
2288 void visitAllocaInst(AllocaInst &AI);
2289 void visitLoadInst(LoadInst &LI);
2290 void visitStoreInst(StoreInst &SI);
2291
2292 void visitSExtInst(SExtInst &SI);
2293 void visitZExtInst(ZExtInst &ZI);
2294
2295 void visitBinaryOperator(BinaryOperator &BO);
2296 void visitICmpInst(ICmpInst &IC);
2297 };
2298
2299 // Used by terminator instructions to proceed from the current basic
2300 // block to the next. Verifies that "current" dominates "next",
2301 // then calls visitBasicBlock.
2302 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2303 for (DomTreeDFS::Node::iterator I = Current->begin(),
2304 E = Current->end(); I != E; ++I) {
2305 WorkList.push_back(*I);
2306 }
2307 }
2308
2309 void proceedToSuccessor(DomTreeDFS::Node *Next) {
2310 WorkList.push_back(Next);
2311 }
2312
2313 // Visits each instruction in the basic block.
2314 void visitBasicBlock(DomTreeDFS::Node *Node) {
2315 BasicBlock *BB = Node->getBlock();
2316 DOUT << "Entering Basic Block: " << BB->getName()
2317 << " (" << Node->getDFSNumIn() << ")\n";
2318 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2319 visitInstruction(I++, Node);
2320 }
2321 }
2322
2323 // Tries to simplify each Instruction and add new properties.
2324 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2325 DOUT << "Considering instruction " << *I << "\n";
2326 DEBUG(VN->dump());
2327 DEBUG(IG->dump());
2328 DEBUG(VR->dump());
2329
2330 // Sometimes instructions are killed in earlier analysis.
2331 if (isInstructionTriviallyDead(I)) {
2332 ++NumSimple;
2333 modified = true;
2334 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2335 if (VN->value(n) == I) IG->remove(n);
2336 VN->remove(I);
2337 I->eraseFromParent();
2338 return;
2339 }
2340
2341#ifndef NDEBUG
2342 // Try to replace the whole instruction.
2343 Value *V = VN->canonicalize(I, DT);
2344 assert(V == I && "Late instruction canonicalization.");
2345 if (V != I) {
2346 modified = true;
2347 ++NumInstruction;
2348 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
2349 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2350 if (VN->value(n) == I) IG->remove(n);
2351 VN->remove(I);
2352 I->replaceAllUsesWith(V);
2353 I->eraseFromParent();
2354 return;
2355 }
2356
2357 // Try to substitute operands.
2358 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2359 Value *Oper = I->getOperand(i);
2360 Value *V = VN->canonicalize(Oper, DT);
2361 assert(V == Oper && "Late operand canonicalization.");
2362 if (V != Oper) {
2363 modified = true;
2364 ++NumVarsReplaced;
2365 DOUT << "Resolving " << *I;
2366 I->setOperand(i, V);
2367 DOUT << " into " << *I;
2368 }
2369 }
2370#endif
2371
2372 std::string name = I->getParent()->getName();
2373 DOUT << "push (%" << name << ")\n";
2374 Forwards visit(this, DT);
2375 visit.visit(*I);
2376 DOUT << "pop (%" << name << ")\n";
2377 }
2378 };
2379
2380 bool PredicateSimplifier::runOnFunction(Function &F) {
2381 DominatorTree *DT = &getAnalysis<DominatorTree>();
2382 DTDFS = new DomTreeDFS(DT);
2383 TargetData *TD = &getAnalysis<TargetData>();
2384
2385 DOUT << "Entering Function: " << F.getName() << "\n";
2386
2387 modified = false;
2388 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2389 VN = new ValueNumbering(DTDFS);
2390 IG = new InequalityGraph(*VN, Root);
2391 VR = new ValueRanges(*VN, TD);
2392 WorkList.push_back(Root);
2393
2394 do {
2395 DomTreeDFS::Node *DTNode = WorkList.back();
2396 WorkList.pop_back();
2397 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2398 } while (!WorkList.empty());
2399
2400 delete DTDFS;
2401 delete VR;
2402 delete IG;
2403
2404 modified |= UB.kill();
2405
2406 return modified;
2407 }
2408
2409 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2410 PS->proceedToSuccessors(DTNode);
2411 }
2412
2413 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2414 if (BI.isUnconditional()) {
2415 PS->proceedToSuccessors(DTNode);
2416 return;
2417 }
2418
2419 Value *Condition = BI.getCondition();
2420 BasicBlock *TrueDest = BI.getSuccessor(0);
2421 BasicBlock *FalseDest = BI.getSuccessor(1);
2422
2423 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2424 PS->proceedToSuccessors(DTNode);
2425 return;
2426 }
2427
2428 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2429 I != E; ++I) {
2430 BasicBlock *Dest = (*I)->getBlock();
2431 DOUT << "Branch thinking about %" << Dest->getName()
2432 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
2433
2434 if (Dest == TrueDest) {
2435 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
2436 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2437 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
2438 VRP.solve();
2439 DEBUG(VN.dump());
2440 DEBUG(IG.dump());
2441 DEBUG(VR.dump());
2442 } else if (Dest == FalseDest) {
2443 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
2444 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2445 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
2446 VRP.solve();
2447 DEBUG(VN.dump());
2448 DEBUG(IG.dump());
2449 DEBUG(VR.dump());
2450 }
2451
2452 PS->proceedToSuccessor(*I);
2453 }
2454 }
2455
2456 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2457 Value *Condition = SI.getCondition();
2458
2459 // Set the EQProperty in each of the cases BBs, and the NEProperties
2460 // in the default BB.
2461
2462 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2463 I != E; ++I) {
2464 BasicBlock *BB = (*I)->getBlock();
2465 DOUT << "Switch thinking about BB %" << BB->getName()
2466 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
2467
2468 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2469 if (BB == SI.getDefaultDest()) {
2470 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2471 if (SI.getSuccessor(i) != BB)
2472 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2473 VRP.solve();
2474 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2475 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2476 VRP.solve();
2477 }
2478 PS->proceedToSuccessor(*I);
2479 }
2480 }
2481
2482 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2483 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2484 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
2485 VRP.solve();
2486 }
2487
2488 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2489 Value *Ptr = LI.getPointerOperand();
2490 // avoid "load uint* null" -> null NE null.
2491 if (isa<Constant>(Ptr)) return;
2492
2493 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2494 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2495 VRP.solve();
2496 }
2497
2498 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2499 Value *Ptr = SI.getPointerOperand();
2500 if (isa<Constant>(Ptr)) return;
2501
2502 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2503 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2504 VRP.solve();
2505 }
2506
2507 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2508 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2509 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2510 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2511 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2512 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2513 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2514 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
2515 VRP.solve();
2516 }
2517
2518 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2519 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2520 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2521 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2522 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2523 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
2524 VRP.solve();
2525 }
2526
2527 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2528 Instruction::BinaryOps ops = BO.getOpcode();
2529
2530 switch (ops) {
2531 default: break;
2532 case Instruction::URem:
2533 case Instruction::SRem:
2534 case Instruction::UDiv:
2535 case Instruction::SDiv: {
2536 Value *Divisor = BO.getOperand(1);
2537 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2538 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2539 ICmpInst::ICMP_NE);
2540 VRP.solve();
2541 break;
2542 }
2543 }
2544
2545 switch (ops) {
2546 default: break;
2547 case Instruction::Shl: {
2548 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2549 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2550 VRP.solve();
2551 } break;
2552 case Instruction::AShr: {
2553 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2554 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2555 VRP.solve();
2556 } break;
2557 case Instruction::LShr:
2558 case Instruction::UDiv: {
2559 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2560 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2561 VRP.solve();
2562 } break;
2563 case Instruction::URem: {
2564 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2565 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2566 VRP.solve();
2567 } break;
2568 case Instruction::And: {
2569 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2570 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2571 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2572 VRP.solve();
2573 } break;
2574 case Instruction::Or: {
2575 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2576 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2577 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2578 VRP.solve();
2579 } break;
2580 }
2581 }
2582
2583 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2584 // If possible, squeeze the ICmp predicate into something simpler.
2585 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2586 // the predicate to eq.
2587
2588 // XXX: once we do full PHI handling, modifying the instruction in the
2589 // Forwards visitor will cause missed optimizations.
2590
2591 ICmpInst::Predicate Pred = IC.getPredicate();
2592
2593 switch (Pred) {
2594 default: break;
2595 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2596 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2597 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2598 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2599 }
2600 if (Pred != IC.getPredicate()) {
2601 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2602 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2603 ICmpInst::ICMP_NE)) {
2604 ++NumSnuggle;
2605 PS->modified = true;
2606 IC.setPredicate(Pred);
2607 }
2608 }
2609
2610 Pred = IC.getPredicate();
2611
2612 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2613 ConstantInt *NextVal = 0;
2614 switch (Pred) {
2615 default: break;
2616 case ICmpInst::ICMP_SLT:
2617 case ICmpInst::ICMP_ULT:
2618 if (Op1->getValue() != 0)
2619 NextVal = ConstantInt::get(Op1->getValue()-1);
2620 break;
2621 case ICmpInst::ICMP_SGT:
2622 case ICmpInst::ICMP_UGT:
2623 if (!Op1->getValue().isAllOnesValue())
2624 NextVal = ConstantInt::get(Op1->getValue()+1);
2625 break;
2626
2627 }
2628 if (NextVal) {
2629 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2630 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2631 ICmpInst::getInversePredicate(Pred))) {
2632 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2633 NextVal, "", &IC);
2634 NewIC->takeName(&IC);
2635 IC.replaceAllUsesWith(NewIC);
2636
2637 // XXX: prove this isn't necessary
2638 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2639 if (VN.value(n) == &IC) IG.remove(n);
2640 VN.remove(&IC);
2641
2642 IC.eraseFromParent();
2643 ++NumSnuggle;
2644 PS->modified = true;
2645 }
2646 }
2647 }
2648 }
2649
2650 char PredicateSimplifier::ID = 0;
2651 RegisterPass<PredicateSimplifier> X("predsimplify",
2652 "Predicate Simplifier");
2653}
2654
2655FunctionPass *llvm::createPredicateSimplifierPass() {
2656 return new PredicateSimplifier();
2657}