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