blob: 2672e4e762a6fc9dedf2bdf15d1ef9cbecc67125 [file] [log] [blame]
Nick Lewycky565706b2006-11-22 23:49:16 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nick Lewycky05450ae2006-08-28 22:44:55 +00007//
Nick Lewycky565706b2006-11-22 23:49:16 +00008//===----------------------------------------------------------------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +00009//
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//
Nick Lewycky565706b2006-11-22 23:49:16 +000023//===----------------------------------------------------------------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +000024//
Nick Lewycky4c708752007-03-16 02:37:39 +000025// 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
Nick Lewycky565706b2006-11-22 23:49:16 +000028// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
Nick Lewycky05450ae2006-08-28 22:44:55 +000029//
Nick Lewycky565706b2006-11-22 23:49:16 +000030// 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
Nick Lewyckye677a0b2007-03-10 18:12:48 +000032// 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.
Nick Lewycky565706b2006-11-22 23:49:16 +000035//
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
Nick Lewycky419c6f52007-01-11 02:32:38 +000044// 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.
Nick Lewycky565706b2006-11-22 23:49:16 +000049//
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//
Nick Lewyckye677a0b2007-03-10 18:12:48 +000055// %P = icmp ne i32* %ptr, null
56// %a = and i1 %P, %Q
57// br i1 %a label %cond_true, label %cond_false
Nick Lewycky565706b2006-11-22 23:49:16 +000058//
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
Nick Lewycky6a08f912007-01-29 02:56:54 +000062// branch it can't infer anything from the "and" instruction.
Nick Lewycky565706b2006-11-22 23:49:16 +000063//
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//===----------------------------------------------------------------------===//
Nick Lewycky4c708752007-03-16 02:37:39 +000070//
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 Lewycky7956dae2007-08-04 18:45:32 +000073// %b = [0, 254].
Nick Lewycky4c708752007-03-16 02:37:39 +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
Nick Lewyckyb01c77e2007-04-07 03:16:12 +000077// relationship and better stored in the InequalityGraph, nor an empty range
78// since that is better stored in UnreachableBlocks.
Nick Lewycky4c708752007-03-16 02:37:39 +000079//
80//===----------------------------------------------------------------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +000081
Nick Lewycky05450ae2006-08-28 22:44:55 +000082#define DEBUG_TYPE "predsimplify"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Constants.h"
Nick Lewycky802fe272006-10-22 19:53:27 +000085#include "llvm/DerivedTypes.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000086#include "llvm/Instructions.h"
87#include "llvm/Pass.h"
Nick Lewycky419c6f52007-01-11 02:32:38 +000088#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky565706b2006-11-22 23:49:16 +000089#include "llvm/ADT/SetOperations.h"
Reid Spencer6734b572007-02-04 00:40:42 +000090#include "llvm/ADT/SetVector.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000091#include "llvm/ADT/Statistic.h"
92#include "llvm/ADT/STLExtras.h"
93#include "llvm/Analysis/Dominators.h"
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +000094#include "llvm/Assembly/Writer.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000095#include "llvm/Support/CFG.h"
Chris Lattner02fc40e2006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckye677a0b2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky078ff412006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewyckyb01c77e2007-04-07 03:16:12 +0000100#include "llvm/Target/TargetData.h"
Nick Lewycky565706b2006-11-22 23:49:16 +0000101#include "llvm/Transforms/Utils/Local.h"
102#include <algorithm>
103#include <deque>
Nick Lewycky984504b2007-06-24 04:36:20 +0000104#include <stack>
Nick Lewycky05450ae2006-08-28 22:44:55 +0000105using namespace llvm;
106
Chris Lattner438e08e2006-12-19 21:49:03 +0000107STATISTIC(NumVarsReplaced, "Number of argument substitutions");
108STATISTIC(NumInstruction , "Number of instructions removed");
109STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky419c6f52007-01-11 02:32:38 +0000110STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4c708752007-03-16 02:37:39 +0000111STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewycky05450ae2006-08-28 22:44:55 +0000112
Chris Lattner438e08e2006-12-19 21:49:03 +0000113namespace {
Nick Lewycky984504b2007-06-24 04:36:20 +0000114 class DomTreeDFS {
115 public:
116 class Node {
117 friend class DomTreeDFS;
118 public:
119 typedef std::vector<Node *>::iterator iterator;
120 typedef std::vector<Node *>::const_iterator const_iterator;
121
122 unsigned getDFSNumIn() const { return DFSin; }
123 unsigned getDFSNumOut() const { return DFSout; }
124
125 BasicBlock *getBlock() const { return BB; }
126
127 iterator begin() { return Children.begin(); }
128 iterator end() { return Children.end(); }
129
130 const_iterator begin() const { return Children.begin(); }
131 const_iterator end() const { return Children.end(); }
132
133 bool dominates(const Node *N) const {
134 return DFSin <= N->DFSin && DFSout >= N->DFSout;
135 }
136
137 bool DominatedBy(const Node *N) const {
138 return N->dominates(this);
139 }
140
141 /// Sorts by the number of descendants. With this, you can iterate
142 /// through a sorted list and the first matching entry is the most
143 /// specific match for your basic block. The order provided is stable;
144 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
145 /// DFS in number.
146 bool operator<(const Node &N) const {
147 unsigned spread = DFSout - DFSin;
148 unsigned N_spread = N.DFSout - N.DFSin;
149 if (spread == N_spread) return DFSin < N.DFSin;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000150 return spread < N_spread;
Nick Lewycky984504b2007-06-24 04:36:20 +0000151 }
152 bool operator>(const Node &N) const { return N < *this; }
153
154 private:
155 unsigned DFSin, DFSout;
156 BasicBlock *BB;
157
158 std::vector<Node *> Children;
159 };
160
161 // XXX: this may be slow. Instead of using "new" for each node, consider
162 // putting them in a vector to keep them contiguous.
163 explicit DomTreeDFS(DominatorTree *DT) {
164 std::stack<std::pair<Node *, DomTreeNode *> > S;
165
166 Entry = new Node;
167 Entry->BB = DT->getRootNode()->getBlock();
168 S.push(std::make_pair(Entry, DT->getRootNode()));
169
170 NodeMap[Entry->BB] = Entry;
171
172 while (!S.empty()) {
173 std::pair<Node *, DomTreeNode *> &Pair = S.top();
174 Node *N = Pair.first;
175 DomTreeNode *DTNode = Pair.second;
176 S.pop();
177
178 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
179 I != E; ++I) {
180 Node *NewNode = new Node;
181 NewNode->BB = (*I)->getBlock();
182 N->Children.push_back(NewNode);
183 S.push(std::make_pair(NewNode, *I));
184
185 NodeMap[NewNode->BB] = NewNode;
186 }
187 }
188
189 renumber();
190
191#ifndef NDEBUG
192 DEBUG(dump());
193#endif
194 }
195
196#ifndef NDEBUG
197 virtual
198#endif
199 ~DomTreeDFS() {
200 std::stack<Node *> S;
201
202 S.push(Entry);
203 while (!S.empty()) {
204 Node *N = S.top(); S.pop();
205
206 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
207 S.push(*I);
208
209 delete N;
210 }
211 }
212
Nick Lewycky5380e942007-07-16 02:58:37 +0000213 /// getRootNode - This returns the entry node for the CFG of the function.
Nick Lewycky984504b2007-06-24 04:36:20 +0000214 Node *getRootNode() const { return Entry; }
215
Nick Lewycky5380e942007-07-16 02:58:37 +0000216 /// getNodeForBlock - return the node for the specified basic block.
Nick Lewycky984504b2007-06-24 04:36:20 +0000217 Node *getNodeForBlock(BasicBlock *BB) const {
218 if (!NodeMap.count(BB)) return 0;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000219 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
Nick Lewycky984504b2007-06-24 04:36:20 +0000220 }
221
Nick Lewycky5380e942007-07-16 02:58:37 +0000222 /// dominates - returns true if the basic block for I1 dominates that of
223 /// the basic block for I2. If the instructions belong to the same basic
224 /// block, the instruction first instruction sequentially in the block is
225 /// considered dominating.
Nick Lewycky984504b2007-06-24 04:36:20 +0000226 bool dominates(Instruction *I1, Instruction *I2) {
227 BasicBlock *BB1 = I1->getParent(),
228 *BB2 = I2->getParent();
229 if (BB1 == BB2) {
230 if (isa<TerminatorInst>(I1)) return false;
231 if (isa<TerminatorInst>(I2)) return true;
232 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
233 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
234
235 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
236 I != E; ++I) {
237 if (&*I == I1) return true;
238 else if (&*I == I2) return false;
239 }
240 assert(!"Instructions not found in parent BasicBlock?");
241 } else {
Nick Lewyckydea25262007-06-24 04:40:16 +0000242 Node *Node1 = getNodeForBlock(BB1),
Nick Lewycky984504b2007-06-24 04:36:20 +0000243 *Node2 = getNodeForBlock(BB2);
Nick Lewycky29a05b62007-07-05 03:15:00 +0000244 return Node1 && Node2 && Node1->dominates(Node2);
Nick Lewycky984504b2007-06-24 04:36:20 +0000245 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000246 return false; // Not reached
Nick Lewycky984504b2007-06-24 04:36:20 +0000247 }
Nick Lewycky5380e942007-07-16 02:58:37 +0000248
Nick Lewycky984504b2007-06-24 04:36:20 +0000249 private:
Nick Lewycky5380e942007-07-16 02:58:37 +0000250 /// renumber - calculates the depth first search numberings and applies
251 /// them onto the nodes.
Nick Lewycky984504b2007-06-24 04:36:20 +0000252 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
Nick Lewycky419c6f52007-01-11 02:32:38 +0000303 // 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
Nick Lewycky6a08f912007-01-29 02:56:54 +0000308 // 0 1 1 1 0 -- SGT 14
309 // 0 1 1 1 1 -- SGE 15
Nick Lewycky419c6f52007-01-11 02:32:38 +0000310 // 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
Nick Lewycky6a08f912007-01-29 02:56:54 +0000314 // 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
Nick Lewycky419c6f52007-01-11 02:32:38 +0000320 // 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,
Nick Lewycky6a08f912007-01-29 02:56:54 +0000334 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
Nick Lewycky419c6f52007-01-11 02:32:38 +0000342 };
343
Nick Lewycky7956dae2007-08-04 18:45:32 +0000344 /// validPredicate - determines whether a given value is actually a lattice
345 /// value. Only used in assertions or debugging.
Nick Lewycky419c6f52007-01-11 02:32:38 +0000346 static bool validPredicate(LatticeVal LV) {
347 switch (LV) {
Nick Lewycky45351752007-02-04 23:43:05 +0000348 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;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000356 }
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
Nick Lewycky4c708752007-03-16 02:37:39 +0000362
Nick Lewycky419c6f52007-01-11 02:32:38 +0000363 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
Nick Lewycky29a05b62007-07-05 03:15:00 +0000374 /// ValueNumbering stores the scope-specific value numbers for a given Value.
375 class VISIBILITY_HIDDEN ValueNumbering {
Nick Lewycky7956dae2007-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.
Nick Lewycky29a05b62007-07-05 03:15:00 +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 Lewycky7956dae2007-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 }
Nick Lewycky29a05b62007-07-05 03:15:00 +0000409 };
410
411 typedef std::vector<VNPair> VNMapType;
412 VNMapType VNMap;
413
Nick Lewycky7956dae2007-08-04 18:45:32 +0000414 /// The canonical choice for value number at index.
Nick Lewycky29a05b62007-07-05 03:15:00 +0000415 std::vector<Value *> Values;
416
417 DomTreeDFS *DTDFS;
418
419 public:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000420#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
Nick Lewycky29a05b62007-07-05 03:15:00 +0000442 /// 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) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000467 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
468 || V->getType() == Type::VoidTy) return 0;
469
Nick Lewycky29a05b62007-07-05 03:15:00 +0000470 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
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000481 /// 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
Nick Lewycky29a05b62007-07-05 03:15:00 +0000489 /// newVN - creates a new value number. Value V must not already have a
490 /// value number assigned.
491 unsigned newVN(Value *V) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000492 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
Nick Lewycky29a05b62007-07-05 03:15:00 +0000496 Values.push_back(V);
497
498 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000499 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
500 assert((I == VNMap.end() || value(I->index) != V) &&
Nick Lewycky29a05b62007-07-05 03:15:00 +0000501 "Attempt to create a duplicate value number.");
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000502 VNMap.insert(I, pair);
Nick Lewycky29a05b62007-07-05 03:15:00 +0000503
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
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000554 else
Nick Lewycky29a05b62007-07-05 03:15:00 +0000555 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) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000571 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
Nick Lewycky29a05b62007-07-05 03:15:00 +0000572 VNPair pair(V, 0, DTDFS->getRootNode());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000573 VNMapType::iterator J = std::upper_bound(B, E, pair);
Nick Lewycky29a05b62007-07-05 03:15:00 +0000574 VNMapType::iterator I = J;
575
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000576 while (I != B && (I == E || I->V == V)) --I;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000577
578 VNMap.erase(I, J);
579 }
580 };
581
Nick Lewycky565706b2006-11-22 23:49:16 +0000582 /// 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 {
Nick Lewycky29a05b62007-07-05 03:15:00 +0000590 ValueNumbering &VN;
Nick Lewycky984504b2007-06-24 04:36:20 +0000591 DomTreeDFS::Node *TreeRoot;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000592
593 InequalityGraph(); // DO NOT IMPLEMENT
594 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky565706b2006-11-22 23:49:16 +0000595 public:
Nick Lewycky29a05b62007-07-05 03:15:00 +0000596 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
597 : VN(VN), TreeRoot(TreeRoot) {}
Nick Lewycky419c6f52007-01-11 02:32:38 +0000598
Nick Lewycky565706b2006-11-22 23:49:16 +0000599 class Node;
Nick Lewycky05450ae2006-08-28 22:44:55 +0000600
Nick Lewycky419c6f52007-01-11 02:32:38 +0000601 /// 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
Nick Lewycky984504b2007-06-24 04:36:20 +0000603 /// value specifying the relationship and an DomTreeDFS::Node specifying
604 /// the root in the dominator tree to which this edge applies.
Nick Lewycky419c6f52007-01-11 02:32:38 +0000605 class VISIBILITY_HIDDEN Edge {
606 public:
Nick Lewycky984504b2007-06-24 04:36:20 +0000607 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky419c6f52007-01-11 02:32:38 +0000608 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky565706b2006-11-22 23:49:16 +0000609
Nick Lewycky419c6f52007-01-11 02:32:38 +0000610 unsigned To;
611 LatticeVal LV;
Nick Lewycky984504b2007-06-24 04:36:20 +0000612 DomTreeDFS::Node *Subtree;
Nick Lewycky565706b2006-11-22 23:49:16 +0000613
Nick Lewycky419c6f52007-01-11 02:32:38 +0000614 bool operator<(const Edge &edge) const {
615 if (To != edge.To) return To < edge.To;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000616 return *Subtree < *edge.Subtree;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000617 }
Nick Lewycky984504b2007-06-24 04:36:20 +0000618
Nick Lewycky419c6f52007-01-11 02:32:38 +0000619 bool operator<(unsigned to) const {
620 return To < to;
621 }
Nick Lewycky984504b2007-06-24 04:36:20 +0000622
Bill Wendling851879c2007-06-04 23:52:59 +0000623 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 }
Nick Lewycky419c6f52007-01-11 02:32:38 +0000630 };
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000631
Nick Lewycky565706b2006-11-22 23:49:16 +0000632 /// A single node in the InequalityGraph. This stores the canonical Value
633 /// for the node, as well as the relationships with the neighbours.
634 ///
Nick Lewycky565706b2006-11-22 23:49:16 +0000635 /// @brief A single node in the InequalityGraph.
636 class VISIBILITY_HIDDEN Node {
637 friend class InequalityGraph;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000638
Nick Lewycky419c6f52007-01-11 02:32:38 +0000639 typedef SmallVector<Edge, 4> RelationsType;
640 RelationsType Relations;
641
Nick Lewycky419c6f52007-01-11 02:32:38 +0000642 // TODO: can this idea improve performance?
643 //friend class std::vector<Node>;
644 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
645
Nick Lewycky565706b2006-11-22 23:49:16 +0000646 public:
647 typedef RelationsType::iterator iterator;
648 typedef RelationsType::const_iterator const_iterator;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000649
Nick Lewycky419c6f52007-01-11 02:32:38 +0000650#ifndef NDEBUG
Nick Lewyckybc00fec2007-01-11 02:38:21 +0000651 virtual ~Node() {}
Nick Lewycky419c6f52007-01-11 02:32:38 +0000652 virtual void dump() const {
653 dump(*cerr.stream());
654 }
655 private:
Nick Lewycky29a05b62007-07-05 03:15:00 +0000656 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" };
Nick Lewycky419c6f52007-01-11 02:32:38 +0000664 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +0000665 os << names[NI->LV] << " " << NI->To
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000666 << " (" << NI->Subtree->getDFSNumIn() << "), ";
Nick Lewycky419c6f52007-01-11 02:32:38 +0000667 }
668 }
Nick Lewycky29a05b62007-07-05 03:15:00 +0000669 public:
Nick Lewycky419c6f52007-01-11 02:32:38 +0000670#endif
671
Nick Lewycky419c6f52007-01-11 02:32:38 +0000672 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
Nick Lewycky984504b2007-06-24 04:36:20 +0000677 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000678 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
Nick Lewycky984504b2007-06-24 04:36:20 +0000687 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000688 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 Lewycky7956dae2007-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.
Nick Lewycky984504b2007-06-24 04:36:20 +0000700 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000701 assert(validPredicate(R) && "Invalid predicate.");
Nick Lewycky419c6f52007-01-11 02:32:38 +0000702
Nick Lewycky7956dae2007-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);
Nick Lewyckydd402582007-01-15 14:30:07 +0000706
Nick Lewycky7956dae2007-08-04 18:45:32 +0000707 iterator J = I;
708 while (J != E && J->To == n) {
709 if (Subtree->DominatedBy(J->Subtree))
710 break;
711 ++J;
712 }
713
Nick Lewyckyc7212232007-08-18 23:18:03 +0000714 if (J != E && J->To == n) {
Nick Lewycky7956dae2007-08-04 18:45:32 +0000715 edge.LV = static_cast<LatticeVal>(J->LV & R);
716 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
Nick Lewycky7956dae2007-08-04 18:45:32 +0000717
Nick Lewyckyc7212232007-08-18 23:18:03 +0000718 if (edge.LV == J->LV)
719 return; // This update adds nothing new.
Bill Wendling587c01d2008-02-26 10:53:30 +0000720 }
Nick Lewyckyc7212232007-08-18 23:18:03 +0000721
722 if (I != B) {
723 // We also have to tighten any edge beneath our update.
724 for (iterator K = I - 1; K->To == n; --K) {
725 if (K->Subtree->DominatedBy(Subtree)) {
726 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
727 assert(validPredicate(LV) && "Invalid union of lattice values");
728 K->LV = LV;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000729 }
Nick Lewyckyc7212232007-08-18 23:18:03 +0000730 if (K == B) break;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000731 }
Bill Wendling587c01d2008-02-26 10:53:30 +0000732 }
Nick Lewycky7956dae2007-08-04 18:45:32 +0000733
734 // Insert new edge at Subtree if it isn't already there.
735 if (I == E || I->To != n || Subtree != I->Subtree)
736 Relations.insert(I, edge);
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000737 }
Nick Lewycky565706b2006-11-22 23:49:16 +0000738 };
739
Nick Lewycky565706b2006-11-22 23:49:16 +0000740 private:
Nick Lewycky419c6f52007-01-11 02:32:38 +0000741
742 std::vector<Node> Nodes;
743
Nick Lewycky565706b2006-11-22 23:49:16 +0000744 public:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000745 /// node - returns the node object at a given value number. The pointer
746 /// returned may be invalidated on the next call to node().
Nick Lewycky419c6f52007-01-11 02:32:38 +0000747 Node *node(unsigned index) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000748 assert(VN.value(index)); // This triggers the necessary checks.
749 if (Nodes.size() < index) Nodes.resize(index);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000750 return &Nodes[index-1];
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000751 }
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000752
Nick Lewycky419c6f52007-01-11 02:32:38 +0000753 /// isRelatedBy - true iff n1 op n2
Nick Lewycky984504b2007-06-24 04:36:20 +0000754 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
755 LatticeVal LV) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000756 if (n1 == n2) return LV & EQ_BIT;
757
758 Node *N1 = node(n1);
759 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
760 if (I != E) return (I->LV & LV) == I->LV;
761
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000762 return false;
763 }
764
Nick Lewycky565706b2006-11-22 23:49:16 +0000765 // The add* methods assume that your input is logically valid and may
766 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewyckye63bf952006-10-25 23:48:24 +0000767
Nick Lewycky419c6f52007-01-11 02:32:38 +0000768 /// addInequality - Sets n1 op n2.
769 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky984504b2007-06-24 04:36:20 +0000770 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky419c6f52007-01-11 02:32:38 +0000771 LatticeVal LV1) {
772 assert(n1 != n2 && "A node can't be inequal to itself.");
773
774 if (LV1 != NE)
775 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
776 "Contradictory inequality.");
777
Nick Lewycky419c6f52007-01-11 02:32:38 +0000778 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
779 // add %a < %n2 too. This keeps the graph fully connected.
780 if (LV1 != NE) {
Nick Lewyckyf3a9e362007-04-07 03:36:51 +0000781 // Break up the relationship into signed and unsigned comparison parts.
782 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
783 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
784 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky419c6f52007-01-11 02:32:38 +0000785
786 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
787 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewyckyf3a9e362007-04-07 03:36:51 +0000788
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000789 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000790 if (I->LV != NE && I->To != n2) {
Nick Lewyckyf3a9e362007-04-07 03:36:51 +0000791
Nick Lewycky984504b2007-06-24 04:36:20 +0000792 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000793 if (Subtree->DominatedBy(I->Subtree))
794 Local_Subtree = Subtree;
795 else if (I->Subtree->DominatedBy(Subtree))
796 Local_Subtree = I->Subtree;
797
798 if (Local_Subtree) {
799 unsigned new_relationship = 0;
800 LatticeVal ILV = reversePredicate(I->LV);
801 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
802 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
803
804 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
805 new_relationship |= ILV_s;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000806 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
807 new_relationship |= ILV_u;
808
809 if (new_relationship) {
810 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
811 new_relationship |= (SLT_BIT|SGT_BIT);
812 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
813 new_relationship |= (ULT_BIT|UGT_BIT);
814 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
815 new_relationship |= EQ_BIT;
816
817 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
818
819 node(I->To)->update(n2, NewLV, Local_Subtree);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000820 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000821 }
822 }
823 }
824 }
825
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000826 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000827 if (I->LV != NE && I->To != n1) {
Nick Lewycky984504b2007-06-24 04:36:20 +0000828 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000829 if (Subtree->DominatedBy(I->Subtree))
830 Local_Subtree = Subtree;
831 else if (I->Subtree->DominatedBy(Subtree))
832 Local_Subtree = I->Subtree;
833
834 if (Local_Subtree) {
835 unsigned new_relationship = 0;
836 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
837 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
838
839 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
840 new_relationship |= ILV_s;
841
842 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
843 new_relationship |= ILV_u;
844
845 if (new_relationship) {
846 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
847 new_relationship |= (SLT_BIT|SGT_BIT);
848 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
849 new_relationship |= (ULT_BIT|UGT_BIT);
850 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
851 new_relationship |= EQ_BIT;
852
853 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
854
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000855 node(n1)->update(I->To, NewLV, Local_Subtree);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000856 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
857 }
858 }
859 }
860 }
861 }
862
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000863 node(n1)->update(n2, LV1, Subtree);
864 node(n2)->update(n1, reversePredicate(LV1), Subtree);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000865 }
Nick Lewycky977be252006-09-13 19:24:01 +0000866
Nick Lewycky29a05b62007-07-05 03:15:00 +0000867 /// remove - removes a node from the graph by removing all references to
868 /// and from it.
869 void remove(unsigned n) {
870 Node *N = node(n);
871 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
872 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
873 do {
874 node(NI->To)->Relations.erase(Iter);
875 Iter = node(NI->To)->find(n, TreeRoot);
876 } while (Iter != node(NI->To)->end());
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000877 }
Nick Lewycky29a05b62007-07-05 03:15:00 +0000878 N->Relations.clear();
Nick Lewycky565706b2006-11-22 23:49:16 +0000879 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000880
Nick Lewycky565706b2006-11-22 23:49:16 +0000881#ifndef NDEBUG
Nick Lewyckybc00fec2007-01-11 02:38:21 +0000882 virtual ~InequalityGraph() {}
Nick Lewycky419c6f52007-01-11 02:32:38 +0000883 virtual void dump() {
884 dump(*cerr.stream());
885 }
886
887 void dump(std::ostream &os) {
Nick Lewycky29a05b62007-07-05 03:15:00 +0000888 for (unsigned i = 1; i <= Nodes.size(); ++i) {
889 os << i << " = {";
890 node(i)->dump(os);
891 os << "}\n";
Nick Lewycky565706b2006-11-22 23:49:16 +0000892 }
893 }
Nick Lewycky565706b2006-11-22 23:49:16 +0000894#endif
895 };
Nick Lewycky05450ae2006-08-28 22:44:55 +0000896
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000897 class VRPSolver;
898
899 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
900 /// in the InequalityGraph.
901 class VISIBILITY_HIDDEN ValueRanges {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000902 ValueNumbering &VN;
903 TargetData *TD;
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000904
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000905 class VISIBILITY_HIDDEN ScopedRange {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000906 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
907 RangeListType;
908 RangeListType RangeList;
909
910 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
911 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
912 return *LHS.first < *RHS.first;
913 }
914
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000915 public:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000916#ifndef NDEBUG
917 virtual ~ScopedRange() {}
918 virtual void dump() const {
919 dump(*cerr.stream());
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000920 }
921
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000922 void dump(std::ostream &os) const {
923 os << "{";
924 for (const_iterator I = begin(), E = end(); I != E; ++I) {
925 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
926 }
927 os << "}";
928 }
929#endif
930
931 typedef RangeListType::iterator iterator;
932 typedef RangeListType::const_iterator const_iterator;
933
934 iterator begin() { return RangeList.begin(); }
935 iterator end() { return RangeList.end(); }
936 const_iterator begin() const { return RangeList.begin(); }
937 const_iterator end() const { return RangeList.end(); }
938
939 iterator find(DomTreeDFS::Node *Subtree) {
940 static ConstantRange empty(1, false);
941 iterator E = end();
942 iterator I = std::lower_bound(begin(), E,
943 std::make_pair(Subtree, empty), swo);
944
945 while (I != E && !I->first->dominates(Subtree)) ++I;
946 return I;
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000947 }
Bill Wendling851879c2007-06-04 23:52:59 +0000948
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000949 const_iterator find(DomTreeDFS::Node *Subtree) const {
950 static const ConstantRange empty(1, false);
951 const_iterator E = end();
952 const_iterator I = std::lower_bound(begin(), E,
953 std::make_pair(Subtree, empty), swo);
954
955 while (I != E && !I->first->dominates(Subtree)) ++I;
956 return I;
Bill Wendling851879c2007-06-04 23:52:59 +0000957 }
958
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000959 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
960 assert(!CR.isEmptySet() && "Empty ConstantRange.");
Nick Lewycky7956dae2007-08-04 18:45:32 +0000961 assert(!CR.isSingleElement() && "Refusing to store single element.");
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000962
963 static ConstantRange empty(1, false);
964 iterator E = end();
965 iterator I =
966 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
967
968 if (I != end() && I->first == Subtree) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +0000969 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000970 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
971 "Invalid union of ranges.");
972 I->second = CR2;
973 } else
974 RangeList.insert(I, std::make_pair(Subtree, CR));
Bill Wendling851879c2007-06-04 23:52:59 +0000975 }
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000976 };
977
978 std::vector<ScopedRange> Ranges;
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000979
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000980 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000981 if (CR.isFullSet()) return;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000982 if (Ranges.size() < n) Ranges.resize(n);
983 Ranges[n-1].update(CR, Subtree);
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000984 }
985
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000986 /// create - Creates a ConstantRange that matches the given LatticeVal
987 /// relation with a given integer.
988 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
989 assert(!CR.isEmptySet() && "Can't deal with empty set.");
990
991 if (LV == NE)
992 return makeConstantRange(ICmpInst::ICMP_NE, CR);
993
994 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
995 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
996 bool hasEQ = LV & EQ_BIT;
997
998 ConstantRange Range(CR.getBitWidth());
999
1000 if (LV_s == SGT_BIT) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001001 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001002 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1003 } else if (LV_s == SLT_BIT) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001004 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001005 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1006 }
1007
1008 if (LV_u == UGT_BIT) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001009 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001010 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1011 } else if (LV_u == ULT_BIT) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001012 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001013 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1014 }
1015
1016 return Range;
1017 }
1018
1019 /// makeConstantRange - Creates a ConstantRange representing the set of all
1020 /// value that match the ICmpInst::Predicate with any of the values in CR.
1021 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1022 const ConstantRange &CR) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001023 uint32_t W = CR.getBitWidth();
1024 switch (ICmpOpcode) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001025 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001026 case ICmpInst::ICMP_EQ:
1027 return ConstantRange(CR.getLower(), CR.getUpper());
1028 case ICmpInst::ICMP_NE:
1029 if (CR.isSingleElement())
1030 return ConstantRange(CR.getUpper(), CR.getLower());
1031 return ConstantRange(W);
1032 case ICmpInst::ICMP_ULT:
1033 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1034 case ICmpInst::ICMP_SLT:
1035 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1036 case ICmpInst::ICMP_ULE: {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001037 APInt UMax(CR.getUnsignedMax());
Zhou Shengc125c002007-04-26 16:42:07 +00001038 if (UMax.isMaxValue())
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001039 return ConstantRange(W);
1040 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1041 }
1042 case ICmpInst::ICMP_SLE: {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001043 APInt SMax(CR.getSignedMax());
Zhou Shengc125c002007-04-26 16:42:07 +00001044 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001045 return ConstantRange(W);
1046 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1047 }
1048 case ICmpInst::ICMP_UGT:
Zhou Sheng223d65b2007-04-19 05:35:00 +00001049 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001050 case ICmpInst::ICMP_SGT:
1051 return ConstantRange(CR.getSignedMin() + 1,
Zhou Sheng223d65b2007-04-19 05:35:00 +00001052 APInt::getSignedMinValue(W));
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001053 case ICmpInst::ICMP_UGE: {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001054 APInt UMin(CR.getUnsignedMin());
Zhou Shengc125c002007-04-26 16:42:07 +00001055 if (UMin.isMinValue())
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001056 return ConstantRange(W);
Zhou Sheng223d65b2007-04-19 05:35:00 +00001057 return ConstantRange(UMin, APInt::getNullValue(W));
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001058 }
1059 case ICmpInst::ICMP_SGE: {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001060 APInt SMin(CR.getSignedMin());
Zhou Shengc125c002007-04-26 16:42:07 +00001061 if (SMin.isMinSignedValue())
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001062 return ConstantRange(W);
Zhou Sheng223d65b2007-04-19 05:35:00 +00001063 return ConstantRange(SMin, APInt::getSignedMinValue(W));
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001064 }
1065 }
1066 }
1067
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001068#ifndef NDEBUG
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001069 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1070 return V == VN.canonicalize(V, Subtree);
1071 }
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001072#endif
1073
1074 public:
1075
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001076 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001077
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001078#ifndef NDEBUG
1079 virtual ~ValueRanges() {}
1080
1081 virtual void dump() const {
1082 dump(*cerr.stream());
1083 }
1084
1085 void dump(std::ostream &os) const {
1086 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1087 os << (i+1) << " = ";
1088 Ranges[i].dump(os);
1089 os << "\n";
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001090 }
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001091 }
1092#endif
1093
1094 /// range - looks up the ConstantRange associated with a value number.
1095 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1096 assert(VN.value(n)); // performs range checks
1097
1098 if (n <= Ranges.size()) {
1099 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1100 if (I != Ranges[n-1].end()) return I->second;
1101 }
1102
1103 Value *V = VN.value(n);
1104 ConstantRange CR = range(V);
1105 return CR;
1106 }
1107
1108 /// range - determine a range from a Value without performing any lookups.
1109 ConstantRange range(Value *V) const {
1110 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1111 return ConstantRange(C->getValue());
1112 else if (isa<ConstantPointerNull>(V))
1113 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1114 else
Dan Gohmanb5660dc2008-02-20 16:44:09 +00001115 return ConstantRange(typeToWidth(V->getType()));
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001116 }
1117
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00001118 // typeToWidth - returns the number of bits necessary to store a value of
1119 // this type, or zero if unknown.
1120 uint32_t typeToWidth(const Type *Ty) const {
1121 if (TD)
1122 return TD->getTypeSizeInBits(Ty);
Duncan Sands514ab342007-11-01 20:53:16 +00001123 else
1124 return Ty->getPrimitiveSizeInBits();
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001125 }
1126
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001127 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1128 LatticeVal LV) {
Nick Lewycky4c708752007-03-16 02:37:39 +00001129 switch (LV) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001130 default: assert(!"Impossible lattice value!");
1131 case NE:
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001132 return CR1.maximalIntersectWith(CR2).isEmptySet();
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001133 case ULT:
1134 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1135 case ULE:
1136 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1137 case UGT:
1138 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1139 case UGE:
1140 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1141 case SLT:
1142 return CR1.getSignedMax().slt(CR2.getSignedMin());
1143 case SLE:
1144 return CR1.getSignedMax().sle(CR2.getSignedMin());
1145 case SGT:
1146 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1147 case SGE:
1148 return CR1.getSignedMin().sge(CR2.getSignedMax());
1149 case LT:
1150 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1151 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1152 case LE:
1153 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1154 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1155 case GT:
1156 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1157 CR1.getSignedMin().sgt(CR2.getSignedMax());
1158 case GE:
1159 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1160 CR1.getSignedMin().sge(CR2.getSignedMax());
1161 case SLTUGT:
1162 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1163 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1164 case SLEUGE:
1165 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1166 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1167 case SGTULT:
1168 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1169 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1170 case SGEULE:
1171 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1172 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1173 }
1174 }
1175
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001176 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1177 LatticeVal LV) {
1178 ConstantRange CR1 = range(n1, Subtree);
1179 ConstantRange CR2 = range(n2, Subtree);
1180
1181 // True iff all values in CR1 are LV to all values in CR2.
1182 return isRelatedBy(CR1, CR2, LV);
1183 }
1184
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001185 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001186 VRPSolver *VRP);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001187 void markBlock(VRPSolver *VRP);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001188
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001189 void mergeInto(Value **I, unsigned n, unsigned New,
Nick Lewycky984504b2007-06-24 04:36:20 +00001190 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001191 ConstantRange CR_New = range(New, Subtree);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001192 ConstantRange Merged = CR_New;
1193
1194 for (; n != 0; ++I, --n) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001195 unsigned i = VN.valueNumber(*I, Subtree);
1196 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001197 if (CR_Kill.isFullSet()) continue;
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001198 Merged = Merged.maximalIntersectWith(CR_Kill);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001199 }
1200
1201 if (Merged.isFullSet() || Merged == CR_New) return;
1202
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001203 applyRange(New, Merged, Subtree, VRP);
1204 }
1205
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001206 void applyRange(unsigned n, const ConstantRange &CR,
Nick Lewycky984504b2007-06-24 04:36:20 +00001207 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001208 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001209 if (Merged.isEmptySet()) {
1210 markBlock(VRP);
1211 return;
1212 }
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001213
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001214 if (const APInt *I = Merged.getSingleElement()) {
1215 Value *V = VN.value(n); // XXX: redesign worklist.
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001216 const Type *Ty = V->getType();
1217 if (Ty->isInteger()) {
1218 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1219 return;
1220 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1221 assert(*I == 0 && "Pointer is null but not zero?");
1222 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001223 ICmpInst::ICMP_EQ, VRP);
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001224 return;
1225 }
1226 }
1227
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001228 update(n, Merged, Subtree);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001229 }
1230
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001231 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky984504b2007-06-24 04:36:20 +00001232 VRPSolver *VRP) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001233 ConstantRange CR1 = range(n1, Subtree);
1234 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckya995d922007-04-07 04:49:12 +00001235
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001236 uint32_t W = CR1.getBitWidth();
Nick Lewyckya995d922007-04-07 04:49:12 +00001237
1238 if (const APInt *I = CR1.getSingleElement()) {
1239 if (CR2.isFullSet()) {
1240 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001241 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001242 } else if (*I == CR2.getLower()) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001243 APInt NewLower(CR2.getLower() + 1),
1244 NewUpper(CR2.getUpper());
Nick Lewyckya995d922007-04-07 04:49:12 +00001245 if (NewLower == NewUpper)
1246 NewLower = NewUpper = APInt::getMinValue(W);
1247
1248 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001249 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001250 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001251 APInt NewLower(CR2.getLower()),
1252 NewUpper(CR2.getUpper() - 1);
Nick Lewyckya995d922007-04-07 04:49:12 +00001253 if (NewLower == NewUpper)
1254 NewLower = NewUpper = APInt::getMinValue(W);
1255
1256 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001257 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001258 }
1259 }
1260
1261 if (const APInt *I = CR2.getSingleElement()) {
1262 if (CR1.isFullSet()) {
1263 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001264 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001265 } else if (*I == CR1.getLower()) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001266 APInt NewLower(CR1.getLower() + 1),
1267 NewUpper(CR1.getUpper());
Nick Lewyckya995d922007-04-07 04:49:12 +00001268 if (NewLower == NewUpper)
1269 NewLower = NewUpper = APInt::getMinValue(W);
1270
1271 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001272 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001273 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001274 APInt NewLower(CR1.getLower()),
1275 NewUpper(CR1.getUpper() - 1);
Nick Lewyckya995d922007-04-07 04:49:12 +00001276 if (NewLower == NewUpper)
1277 NewLower = NewUpper = APInt::getMinValue(W);
1278
1279 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001280 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001281 }
1282 }
1283 }
1284
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001285 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky984504b2007-06-24 04:36:20 +00001286 LatticeVal LV, VRPSolver *VRP) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001287 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001288
Nick Lewyckya995d922007-04-07 04:49:12 +00001289 if (LV == NE) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001290 addNotEquals(n1, n2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001291 return;
1292 }
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001293
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001294 ConstantRange CR1 = range(n1, Subtree);
1295 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001296
1297 if (!CR1.isSingleElement()) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001298 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001299 if (NewCR1 != CR1)
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001300 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001301 }
1302
1303 if (!CR2.isSingleElement()) {
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001304 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1305 create(reversePredicate(LV), CR1));
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001306 if (NewCR2 != CR2)
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001307 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001308 }
1309 }
1310 };
1311
Nick Lewycky419c6f52007-01-11 02:32:38 +00001312 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1313 /// another discovered to be unreachable. This is used to cull the graph when
1314 /// analyzing instructions, and to mark blocks with the "unreachable"
1315 /// terminator instruction after the function has executed.
1316 class VISIBILITY_HIDDEN UnreachableBlocks {
1317 private:
1318 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky565706b2006-11-22 23:49:16 +00001319
Nick Lewycky419c6f52007-01-11 02:32:38 +00001320 public:
1321 /// mark - mark a block as dead
1322 void mark(BasicBlock *BB) {
1323 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1324 std::vector<BasicBlock *>::iterator I =
1325 std::lower_bound(DeadBlocks.begin(), E, BB);
1326
1327 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky565706b2006-11-22 23:49:16 +00001328 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001329
1330 /// isDead - returns whether a block is known to be dead already
1331 bool isDead(BasicBlock *BB) {
1332 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1333 std::vector<BasicBlock *>::iterator I =
1334 std::lower_bound(DeadBlocks.begin(), E, BB);
1335
1336 return I != E && *I == BB;
Nick Lewycky565706b2006-11-22 23:49:16 +00001337 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001338
Nick Lewycky419c6f52007-01-11 02:32:38 +00001339 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1340 bool kill() {
1341 bool modified = false;
1342 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1343 E = DeadBlocks.end(); I != E; ++I) {
1344 BasicBlock *BB = *I;
Nick Lewycky565706b2006-11-22 23:49:16 +00001345
Nick Lewycky419c6f52007-01-11 02:32:38 +00001346 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky565706b2006-11-22 23:49:16 +00001347
Nick Lewycky419c6f52007-01-11 02:32:38 +00001348 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1349 SI != SE; ++SI) {
1350 BasicBlock *Succ = *SI;
1351 Succ->removePredecessor(BB);
Nick Lewyckye63bf952006-10-25 23:48:24 +00001352 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001353
Nick Lewycky419c6f52007-01-11 02:32:38 +00001354 TerminatorInst *TI = BB->getTerminator();
1355 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1356 TI->eraseFromParent();
1357 new UnreachableInst(BB);
1358 ++NumBlocks;
1359 modified = true;
Nick Lewycky565706b2006-11-22 23:49:16 +00001360 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001361 DeadBlocks.clear();
1362 return modified;
Nick Lewyckye63bf952006-10-25 23:48:24 +00001363 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001364 };
Nick Lewycky565706b2006-11-22 23:49:16 +00001365
1366 /// VRPSolver keeps track of how changes to one variable affect other
1367 /// variables, and forwards changes along to the InequalityGraph. It
1368 /// also maintains the correct choice for "canonical" in the IG.
1369 /// @brief VRPSolver calculates inferences from a new relationship.
1370 class VISIBILITY_HIDDEN VRPSolver {
1371 private:
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001372 friend class ValueRanges;
1373
Nick Lewycky419c6f52007-01-11 02:32:38 +00001374 struct Operation {
1375 Value *LHS, *RHS;
1376 ICmpInst::Predicate Op;
1377
Nick Lewycky984504b2007-06-24 04:36:20 +00001378 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky0be7f472007-01-13 02:05:28 +00001379 Instruction *ContextInst;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001380 };
1381 std::deque<Operation> WorkList;
Nick Lewycky565706b2006-11-22 23:49:16 +00001382
Nick Lewycky29a05b62007-07-05 03:15:00 +00001383 ValueNumbering &VN;
Nick Lewycky565706b2006-11-22 23:49:16 +00001384 InequalityGraph &IG;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001385 UnreachableBlocks &UB;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001386 ValueRanges &VR;
Nick Lewycky984504b2007-06-24 04:36:20 +00001387 DomTreeDFS *DTDFS;
1388 DomTreeDFS::Node *Top;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001389 BasicBlock *TopBB;
1390 Instruction *TopInst;
1391 bool &modified;
Nick Lewycky565706b2006-11-22 23:49:16 +00001392
1393 typedef InequalityGraph::Node Node;
1394
Nick Lewycky419c6f52007-01-11 02:32:38 +00001395 // below - true if the Instruction is dominated by the current context
1396 // block or instruction
1397 bool below(Instruction *I) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001398 BasicBlock *BB = I->getParent();
1399 if (TopInst && TopInst->getParent() == BB) {
1400 if (isa<TerminatorInst>(TopInst)) return false;
1401 if (isa<TerminatorInst>(I)) return true;
1402 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1403 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1404
1405 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1406 Iter != E; ++Iter) {
1407 if (&*Iter == TopInst) return true;
1408 else if (&*Iter == I) return false;
1409 }
1410 assert(!"Instructions not found in parent BasicBlock?");
1411 } else {
Nick Lewyckydea25262007-06-24 04:40:16 +00001412 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
Nick Lewycky984504b2007-06-24 04:36:20 +00001413 if (!Node) return false;
1414 return Top->dominates(Node);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001415 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001416 return false; // Not reached
Nick Lewycky565706b2006-11-22 23:49:16 +00001417 }
1418
Nick Lewycky984504b2007-06-24 04:36:20 +00001419 // 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
Nick Lewycky419c6f52007-01-11 02:32:38 +00001429 bool makeEqual(Value *V1, Value *V2) {
1430 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky984504b2007-06-24 04:36:20 +00001431 DOUT << "context is ";
1432 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1433 else DOUT << "BB: " << TopBB->getName()
1434 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewyckye63bf952006-10-25 23:48:24 +00001435
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00001436 assert(V1->getType() == V2->getType() &&
1437 "Can't make two values with different types equal.");
1438
Nick Lewycky419c6f52007-01-11 02:32:38 +00001439 if (V1 == V2) return true;
Nick Lewyckye63bf952006-10-25 23:48:24 +00001440
Nick Lewycky419c6f52007-01-11 02:32:38 +00001441 if (isa<Constant>(V1) && isa<Constant>(V2))
1442 return false;
1443
Nick Lewycky29a05b62007-07-05 03:15:00 +00001444 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001445
1446 if (n1 && n2) {
1447 if (n1 == n2) return true;
1448 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1449 }
1450
Nick Lewycky29a05b62007-07-05 03:15:00 +00001451 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1452 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00001453
Nick Lewycky29a05b62007-07-05 03:15:00 +00001454 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00001455
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.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001466
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001467 Node::iterator end = IG.node(n2)->end();
Nick Lewyckydd402582007-01-15 14:30:07 +00001468
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.
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001472 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1473 I != E; ++I) {
Nick Lewyckydd402582007-01-15 14:30:07 +00001474 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);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001478 Node::iterator NI = IG.node(n2)->find(I->To, Top);
Nick Lewyckydd402582007-01-15 14:30:07 +00001479 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);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001487 }
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;
Reid Spencer7af9a132007-01-17 02:23:37 +00001493 SetVector<unsigned>::iterator DontRemove = Remove.end();
1494 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky419c6f52007-01-11 02:32:38 +00001495 E = Remove.end(); I != E; ++I) {
1496 unsigned n = *I;
Nick Lewycky29a05b62007-07-05 03:15:00 +00001497 Value *V = VN.value(n);
1498 if (VN.compare(V, V1)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001499 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);
Nick Lewycky565706b2006-11-22 23:49:16 +00001508 }
1509 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00001510
Nick Lewycky419c6f52007-01-11 02:32:38 +00001511 // We'd like to allow makeEqual on two values to perform a simple
Nick Lewycky70ef6292008-05-26 22:49:36 +00001512 // substitution without creating nodes in the IG whenever possible.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001513 //
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.
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001517 bool mergeIGNode = false;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001518 unsigned i = 0;
1519 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001520 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001521
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!
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001573 mergeIGNode = true;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001574 }
1575
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001576 if (!isa<Constant>(V1)) {
1577 if (Remove.empty()) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001578 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001579 } else {
1580 std::vector<Value*> RemoveVals;
1581 RemoveVals.reserve(Remove.size());
Nick Lewycky419c6f52007-01-11 02:32:38 +00001582
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001583 for (SetVector<unsigned>::iterator I = Remove.begin(),
1584 E = Remove.end(); I != E; ++I) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001585 Value *V = VN.value(*I);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001586 if (!V->use_empty())
1587 RemoveVals.push_back(V);
1588 }
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001589 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1590 VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001591 }
1592 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001593
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001594 if (mergeIGNode) {
1595 // Create N1.
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001596 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
Nick Lewycky6918a912008-05-27 00:59:05 +00001597 IG.node(n1); // Ensure that IG.Nodes won't get resized
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001598
1599 // Migrate relationships from removed nodes to N1.
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001600 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1601 I != E; ++I) {
1602 unsigned n = *I;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001603 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1604 NI != NE; ++NI) {
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001605 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);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001614 IG.node(n1)->update(NI->To, NI->LV, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001615 }
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001616 }
1617 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001618
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001619 // Point V2 (and all items in Remove) to N1.
1620 if (!n2)
Nick Lewycky29a05b62007-07-05 03:15:00 +00001621 VN.addEquality(n1, V2, Top);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001622 else {
1623 for (SetVector<unsigned>::iterator I = Remove.begin(),
1624 E = Remove.end(); I != E; ++I) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001625 VN.addEquality(n1, VN.value(*I), Top);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001626 }
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) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001633 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001634
1635 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001636 if (aboveOrBelow(I2))
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001637 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())) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001644 if (aboveOrBelow(I))
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001645 opsToDef(I);
1646 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001647 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001648 }
1649 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001650
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001651 // 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();
Nick Lewycky419c6f52007-01-11 02:32:38 +00001654 UI != UE;) {
1655 Use &TheUse = UI.getUse();
1656 ++UI;
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001657 Value *V = TheUse.getUser();
1658 if (!V->use_empty()) {
1659 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001660 if (aboveOrBelow(Inst))
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001661 opsToDef(Inst);
1662 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001663 }
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:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001682 return UGT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001683 case ICmpInst::ICMP_UGE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001684 return UGE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001685 case ICmpInst::ICMP_ULT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001686 return ULT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001687 case ICmpInst::ICMP_ULE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001688 return ULE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001689 case ICmpInst::ICMP_SGT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001690 return SGT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001691 case ICmpInst::ICMP_SGE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001692 return SGE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001693 case ICmpInst::ICMP_SLT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001694 return SLT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001695 case ICmpInst::ICMP_SLE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001696 return SLE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001697 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001698 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00001699
Nick Lewycky565706b2006-11-22 23:49:16 +00001700 public:
Nick Lewycky29a05b62007-07-05 03:15:00 +00001701 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1702 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1703 BasicBlock *TopBB)
1704 : VN(VN),
1705 IG(IG),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001706 UB(UB),
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001707 VR(VR),
Nick Lewycky984504b2007-06-24 04:36:20 +00001708 DTDFS(DTDFS),
1709 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001710 TopBB(TopBB),
1711 TopInst(NULL),
Nick Lewycky984504b2007-06-24 04:36:20 +00001712 modified(modified)
1713 {
1714 assert(Top && "VRPSolver created for unreachable basic block.");
1715 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00001716
Nick Lewycky29a05b62007-07-05 03:15:00 +00001717 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1718 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1719 Instruction *TopInst)
1720 : VN(VN),
1721 IG(IG),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001722 UB(UB),
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001723 VR(VR),
Nick Lewycky984504b2007-06-24 04:36:20 +00001724 DTDFS(DTDFS),
1725 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1726 TopBB(TopInst->getParent()),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001727 TopInst(TopInst),
1728 modified(modified)
1729 {
Nick Lewycky984504b2007-06-24 04:36:20 +00001730 assert(Top && "VRPSolver created for unreachable basic block.");
1731 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00001732 }
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) ==
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001738 ConstantInt::getTrue();
Nick Lewycky419c6f52007-01-11 02:32:38 +00001739
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001740 unsigned n1 = VN.valueNumber(V1, Top);
1741 unsigned n2 = VN.valueNumber(V2, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001742
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001743 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 }
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001765 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001766 return false;
Nick Lewycky565706b2006-11-22 23:49:16 +00001767 }
1768
Nick Lewycky419c6f52007-01-11 02:32:38 +00001769 /// 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;
Nick Lewycky984504b2007-06-24 04:36:20 +00001774 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky419c6f52007-01-11 02:32:38 +00001775 DOUT << "\n";
1776
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00001777 assert(V1->getType() == V2->getType() &&
1778 "Can't relate two values with different types.");
1779
Nick Lewycky419c6f52007-01-11 02:32:38 +00001780 WorkList.push_back(Operation());
1781 Operation &O = WorkList.back();
Nick Lewycky0be7f472007-01-13 02:05:28 +00001782 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1783 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky565706b2006-11-22 23:49:16 +00001784 }
1785
Nick Lewycky419c6f52007-01-11 02:32:38 +00001786 /// 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;
Nick Lewycky29a05b62007-07-05 03:15:00 +00001790 Value *Canonical = VN.canonicalize(I, Top);
Nick Lewycky565706b2006-11-22 23:49:16 +00001791
Nick Lewycky419c6f52007-01-11 02:32:38 +00001792 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1793 const Type *Ty = BO->getType();
1794 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky565706b2006-11-22 23:49:16 +00001795
Nick Lewycky29a05b62007-07-05 03:15:00 +00001796 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1797 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky565706b2006-11-22 23:49:16 +00001798
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001799 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky565706b2006-11-22 23:49:16 +00001800
Nick Lewycky419c6f52007-01-11 02:32:38 +00001801 switch (BO->getOpcode()) {
1802 case Instruction::And: {
Nick Lewycky4c708752007-03-16 02:37:39 +00001803 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001804 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001805 if (Canonical == CI) {
1806 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1807 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky565706b2006-11-22 23:49:16 +00001808 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001809 } break;
1810 case Instruction::Or: {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001811 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky419c6f52007-01-11 02:32:38 +00001812 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: {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001819 // "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.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001823 Value *LHS = Op0;
1824 Value *RHS = Op1;
1825 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1826
Nick Lewyckyc2a7d092007-01-12 00:02:12 +00001827 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1828 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spenceraf3e9462007-03-03 00:48:31 +00001829 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewyckyc2a7d092007-01-12 00:02:12 +00001830 ICmpInst::ICMP_EQ, NewContext);
1831 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001832 }
1833 if (Canonical == LHS) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001834 if (isa<ConstantInt>(Canonical))
Nick Lewycky419c6f52007-01-11 02:32:38 +00001835 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)) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001846 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky419c6f52007-01-11 02:32:38 +00001847 // etc.
1848
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001849 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001850 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1851 NewContext);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001852 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001853 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
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001859 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky419c6f52007-01-11 02:32:38 +00001860 // %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)) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001866 if (Canonical == VN.canonicalize(True, Top) ||
Nick Lewycky419c6f52007-01-11 02:32:38 +00001867 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001868 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001869 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky29a05b62007-07-05 03:15:00 +00001870 else if (Canonical == VN.canonicalize(False, Top) ||
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001871 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001872 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001873 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky565706b2006-11-22 23:49:16 +00001874 }
Nick Lewycky27e4da92007-03-22 02:02:51 +00001875 } 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) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001878 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewycky27e4da92007-03-22 02:02:51 +00001879 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 }
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001889 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1890 const Type *SrcTy = CI->getSrcTy();
1891
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001892 unsigned ci = VN.getOrInsertVN(CI, Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001893 uint32_t W = VR.typeToWidth(SrcTy);
1894 if (!W) return;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001895 ConstantRange CR = VR.range(ci, Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001896
1897 if (CR.isFullSet()) return;
1898
1899 switch (CI->getOpcode()) {
1900 default: break;
1901 case Instruction::ZExt:
1902 case Instruction::SExt:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001903 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001904 CR.truncate(W), Top, this);
1905 break;
1906 case Instruction::BitCast:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001907 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001908 CR, Top, this);
1909 break;
1910 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001911 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001912 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001913
Nick Lewycky419c6f52007-01-11 02:32:38 +00001914 /// opsToDef - A new relationship was discovered involving one of this
1915 /// instruction's operands. Find any new relationship involving the
Nick Lewycky27e4da92007-03-22 02:02:51 +00001916 /// definition, or another operand.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001917 void opsToDef(Instruction *I) {
1918 Instruction *NewContext = below(I) ? I : TopInst;
1919
1920 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001921 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1922 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001923
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001924 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1925 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001926 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1927 ICmpInst::ICMP_EQ, NewContext);
1928 return;
1929 }
1930
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001931 // "%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();
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001937 const Type *Ty = BO->getType();
1938 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1939
1940 Constant *Zero = Constant::getNullValue(Ty);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001941 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001942
1943 switch (Opcode) {
1944 default: break;
Nick Lewycky27e4da92007-03-22 02:02:51 +00001945 case Instruction::LShr:
1946 case Instruction::AShr:
1947 case Instruction::Shl:
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001948 case Instruction::Sub:
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001949 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
Nick Lewycky27e4da92007-03-22 02:02:51 +00001959 case Instruction::Xor:
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001960 case Instruction::Add:
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001961 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 }
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001968 break;
1969 case Instruction::And:
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001970 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 }
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001977 // fall-through
1978 case Instruction::Mul:
1979 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001980 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1981 return;
1982 }
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001983 break;
Nick Lewycky565706b2006-11-22 23:49:16 +00001984 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001985
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001986 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewycky27e4da92007-03-22 02:02:51 +00001987 // "%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
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001989 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky565706b2006-11-22 23:49:16 +00001990
Nick Lewycky27e4da92007-03-22 02:02:51 +00001991 Value *Known = Op0, *Unknown = Op1,
Nick Lewycky29a05b62007-07-05 03:15:00 +00001992 *TheBO = VN.canonicalize(BO, Top);
Nick Lewycky27e4da92007-03-22 02:02:51 +00001993 if (Known != TheBO) std::swap(Known, Unknown);
1994 if (Known == TheBO) {
Nick Lewycky4c708752007-03-16 02:37:39 +00001995 switch (Opcode) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001996 default: break;
Nick Lewycky27e4da92007-03-22 02:02:51 +00001997 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 Lewyckye29578a2007-09-20 00:48:36 +00002003 if (Unknown == Op0) break;
Nick Lewycky27e4da92007-03-22 02:02:51 +00002004 // otherwise, fall-through.
Nick Lewycky419c6f52007-01-11 02:32:38 +00002005 case Instruction::Xor:
Nick Lewycky419c6f52007-01-11 02:32:38 +00002006 case Instruction::Add:
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00002007 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002008 break;
2009 case Instruction::UDiv:
2010 case Instruction::SDiv:
Nick Lewycky27e4da92007-03-22 02:02:51 +00002011 if (Unknown == Op1) break;
2012 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewyckyc2a7d092007-01-12 00:02:12 +00002013 Constant *One = ConstantInt::get(Ty, 1);
2014 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2015 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002016 break;
Nick Lewycky565706b2006-11-22 23:49:16 +00002017 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002018 }
Nick Lewycky565706b2006-11-22 23:49:16 +00002019
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002020 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky565706b2006-11-22 23:49:16 +00002021
Nick Lewycky419c6f52007-01-11 02:32:38 +00002022 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002023 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002024 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky419c6f52007-01-11 02:32:38 +00002025 // etc.
2026
Nick Lewycky29a05b62007-07-05 03:15:00 +00002027 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2028 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002029
2030 ICmpInst::Predicate Pred = IC->getPredicate();
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002031 if (isRelatedBy(Op0, Op1, Pred))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002032 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002033 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002034 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002035
Nick Lewycky419c6f52007-01-11 02:32:38 +00002036 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewycky27e4da92007-03-22 02:02:51 +00002037 if (I->getType()->isFPOrFPVector()) return;
2038
Nick Lewycky4c708752007-03-16 02:37:39 +00002039 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky419c6f52007-01-11 02:32:38 +00002040 // %x EQ true then %a EQ %b
2041 // %x EQ false then %a EQ %c
2042 // %b EQ %c then %a EQ %b
2043
Nick Lewycky29a05b62007-07-05 03:15:00 +00002044 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002045 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002046 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002047 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002048 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002049 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2050 VN.canonicalize(SI->getFalseValue(), Top)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002051 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2052 }
Nick Lewycky28c5b152007-01-12 01:23:53 +00002053 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002054 const Type *DestTy = CI->getDestTy();
2055 if (DestTy->isFPOrFPVector()) return;
Nick Lewycky28c5b152007-01-12 01:23:53 +00002056
Nick Lewycky29a05b62007-07-05 03:15:00 +00002057 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002058 Instruction::CastOps Opcode = CI->getOpcode();
2059
2060 if (Constant *C = dyn_cast<Constant>(Op)) {
2061 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewycky28c5b152007-01-12 01:23:53 +00002062 ICmpInst::ICMP_EQ, NewContext);
2063 }
2064
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002065 uint32_t W = VR.typeToWidth(DestTy);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002066 unsigned ci = VN.getOrInsertVN(CI, Top);
2067 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002068
2069 if (!CR.isFullSet()) {
2070 switch (Opcode) {
2071 default: break;
2072 case Instruction::ZExt:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002073 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002074 break;
2075 case Instruction::SExt:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002076 VR.applyRange(ci, CR.signExtend(W), Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002077 break;
2078 case Instruction::Trunc: {
2079 ConstantRange Result = CR.truncate(W);
2080 if (!Result.isFullSet())
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002081 VR.applyRange(ci, Result, Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002082 } break;
2083 case Instruction::BitCast:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002084 VR.applyRange(ci, CR, Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002085 break;
2086 // TODO: other casts?
2087 }
2088 }
Nick Lewycky27e4da92007-03-22 02:02:51 +00002089 } 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) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002092 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewycky27e4da92007-03-22 02:02:51 +00002093 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 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002103 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002104 }
2105
2106 /// solve - process the work queue
Nick Lewycky419c6f52007-01-11 02:32:38 +00002107 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();
Nick Lewycky0be7f472007-01-13 02:05:28 +00002113 TopInst = O.ContextInst;
2114 TopBB = O.ContextBB;
Nick Lewycky984504b2007-06-24 04:36:20 +00002115 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky0be7f472007-01-13 02:05:28 +00002116
Nick Lewycky29a05b62007-07-05 03:15:00 +00002117 O.LHS = VN.canonicalize(O.LHS, Top);
2118 O.RHS = VN.canonicalize(O.RHS, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002119
Nick Lewycky29a05b62007-07-05 03:15:00 +00002120 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2121 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00002122
2123 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky0be7f472007-01-13 02:05:28 +00002124 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2125 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002126 DOUT << "\n";
2127
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002128 DEBUG(VN.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002129 DEBUG(IG.dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002130 DEBUG(VR.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002131
Nick Lewycky45351752007-02-04 23:43:05 +00002132 // 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
Nick Lewycky29a05b62007-07-05 03:15:00 +00002145 if (VN.compare(O.LHS, O.RHS)) {
Nick Lewycky45351752007-02-04 23:43:05 +00002146 std::swap(O.LHS, O.RHS);
2147 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002148 }
2149
2150 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002151 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky419c6f52007-01-11 02:32:38 +00002152 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))) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002158 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky419c6f52007-01-11 02:32:38 +00002159 UB.mark(TopBB);
2160 } else {
2161 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky45351752007-02-04 23:43:05 +00002162 UB.mark(TopBB);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002163 WorkList.pop_front();
2164 continue;
2165 }
2166
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002167 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2168 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002169
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002170 if (n1 == n2) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002171 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
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002179 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2180 IG.isRelatedBy(n1, n2, Top, LV)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002181 WorkList.pop_front();
2182 continue;
2183 }
2184
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002185 VR.addInequality(n1, n2, Top, LV, this);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002186 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002187 LV == NE)
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002188 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky45351752007-02-04 23:43:05 +00002189
Nick Lewyckydd402582007-01-15 14:30:07 +00002190 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002191 if (aboveOrBelow(I1))
Nick Lewyckydd402582007-01-15 14:30:07 +00002192 defToOps(I1);
2193 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002194 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())) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002200 if (aboveOrBelow(I))
Nick Lewyckydd402582007-01-15 14:30:07 +00002201 opsToDef(I);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002202 }
2203 }
2204 }
Nick Lewyckydd402582007-01-15 14:30:07 +00002205 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002206 if (aboveOrBelow(I2))
Nick Lewyckydd402582007-01-15 14:30:07 +00002207 defToOps(I2);
2208 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002209 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())) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002215 if (aboveOrBelow(I))
Nick Lewyckydd402582007-01-15 14:30:07 +00002216 opsToDef(I);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002217 }
2218 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002219 }
2220 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002221 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002222 WorkList.pop_front();
Nick Lewyckye63bf952006-10-25 23:48:24 +00002223 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002224 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002225 };
2226
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00002227 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002228 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00002229 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002230 }
2231
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002232 void ValueRanges::markBlock(VRPSolver *VRP) {
2233 VRP->UB.mark(VRP->TopBB);
2234 }
2235
Nick Lewycky05450ae2006-08-28 22:44:55 +00002236 /// 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.
Nick Lewycky565706b2006-11-22 23:49:16 +00002239 /// @brief Root of the predicate simplifier optimization.
2240 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky984504b2007-06-24 04:36:20 +00002241 DomTreeDFS *DTDFS;
Nick Lewycky565706b2006-11-22 23:49:16 +00002242 bool modified;
Nick Lewycky29a05b62007-07-05 03:15:00 +00002243 ValueNumbering *VN;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002244 InequalityGraph *IG;
2245 UnreachableBlocks UB;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002246 ValueRanges *VR;
Nick Lewycky565706b2006-11-22 23:49:16 +00002247
Nick Lewycky984504b2007-06-24 04:36:20 +00002248 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky565706b2006-11-22 23:49:16 +00002249
Nick Lewycky05450ae2006-08-28 22:44:55 +00002250 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +00002251 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +00002252 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2253
Nick Lewycky05450ae2006-08-28 22:44:55 +00002254 bool runOnFunction(Function &F);
Nick Lewycky565706b2006-11-22 23:49:16 +00002255
2256 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2257 AU.addRequiredID(BreakCriticalEdgesID);
Owen Andersonab0e4d32007-04-25 04:18:54 +00002258 AU.addRequired<DominatorTree>();
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00002259 AU.addRequired<TargetData>();
2260 AU.addPreserved<TargetData>();
Nick Lewycky565706b2006-11-22 23:49:16 +00002261 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002262
2263 private:
Nick Lewycky5380e942007-07-16 02:58:37 +00002264 /// Forwards - Adds new properties to VRPSolver and uses them to
Nick Lewycky078ff412006-10-12 02:02:44 +00002265 /// 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
Nick Lewycky5380e942007-07-16 02:58:37 +00002268 /// basic block.
Nick Lewycky565706b2006-11-22 23:49:16 +00002269 /// @brief Performs abstract execution of the program.
2270 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky078ff412006-10-12 02:02:44 +00002271 friend class InstVisitor<Forwards>;
2272 PredicateSimplifier *PS;
Nick Lewycky984504b2007-06-24 04:36:20 +00002273 DomTreeDFS::Node *DTNode;
Nick Lewycky565706b2006-11-22 23:49:16 +00002274
Nick Lewycky078ff412006-10-12 02:02:44 +00002275 public:
Nick Lewycky29a05b62007-07-05 03:15:00 +00002276 ValueNumbering &VN;
Nick Lewycky565706b2006-11-22 23:49:16 +00002277 InequalityGraph &IG;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002278 UnreachableBlocks &UB;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002279 ValueRanges &VR;
Nick Lewycky078ff412006-10-12 02:02:44 +00002280
Nick Lewycky984504b2007-06-24 04:36:20 +00002281 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Nick Lewycky29a05b62007-07-05 03:15:00 +00002282 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2283 VR(*PS->VR) {}
Nick Lewycky078ff412006-10-12 02:02:44 +00002284
2285 void visitTerminatorInst(TerminatorInst &TI);
2286 void visitBranchInst(BranchInst &BI);
2287 void visitSwitchInst(SwitchInst &SI);
2288
Nick Lewycky802fe272006-10-22 19:53:27 +00002289 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky078ff412006-10-12 02:02:44 +00002290 void visitLoadInst(LoadInst &LI);
2291 void visitStoreInst(StoreInst &SI);
Nick Lewycky565706b2006-11-22 23:49:16 +00002292
Nick Lewycky45351752007-02-04 23:43:05 +00002293 void visitSExtInst(SExtInst &SI);
2294 void visitZExtInst(ZExtInst &ZI);
2295
Nick Lewycky078ff412006-10-12 02:02:44 +00002296 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002297 void visitICmpInst(ICmpInst &IC);
Nick Lewycky078ff412006-10-12 02:02:44 +00002298 };
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002299
Nick Lewycky05450ae2006-08-28 22:44:55 +00002300 // Used by terminator instructions to proceed from the current basic
2301 // block to the next. Verifies that "current" dominates "next",
2302 // then calls visitBasicBlock.
Nick Lewycky984504b2007-06-24 04:36:20 +00002303 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2304 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Andersonab0e4d32007-04-25 04:18:54 +00002305 E = Current->end(); I != E; ++I) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002306 WorkList.push_back(*I);
Nick Lewycky565706b2006-11-22 23:49:16 +00002307 }
2308 }
2309
Nick Lewycky984504b2007-06-24 04:36:20 +00002310 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002311 WorkList.push_back(Next);
Nick Lewycky565706b2006-11-22 23:49:16 +00002312 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002313
2314 // Visits each instruction in the basic block.
Nick Lewycky984504b2007-06-24 04:36:20 +00002315 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002316 BasicBlock *BB = Node->getBlock();
Nick Lewyckydd402582007-01-15 14:30:07 +00002317 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky984504b2007-06-24 04:36:20 +00002318 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling832171c2006-12-07 20:04:42 +00002319 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002320 visitInstruction(I++, Node);
Nick Lewycky565706b2006-11-22 23:49:16 +00002321 }
2322 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002323
Nick Lewycky5380e942007-07-16 02:58:37 +00002324 // Tries to simplify each Instruction and add new properties.
Nick Lewycky984504b2007-06-24 04:36:20 +00002325 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling832171c2006-12-07 20:04:42 +00002326 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002327 DEBUG(VN->dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002328 DEBUG(IG->dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002329 DEBUG(VR->dump());
Nick Lewycky05450ae2006-08-28 22:44:55 +00002330
Nick Lewycky419c6f52007-01-11 02:32:38 +00002331 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky565706b2006-11-22 23:49:16 +00002332 if (isInstructionTriviallyDead(I)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002333 ++NumSimple;
2334 modified = true;
Nick Lewycky29a05b62007-07-05 03:15:00 +00002335 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2336 if (VN->value(n) == I) IG->remove(n);
2337 VN->remove(I);
Nick Lewycky565706b2006-11-22 23:49:16 +00002338 I->eraseFromParent();
2339 return;
2340 }
2341
Nick Lewycky0be7f472007-01-13 02:05:28 +00002342#ifndef NDEBUG
Nick Lewycky565706b2006-11-22 23:49:16 +00002343 // Try to replace the whole instruction.
Nick Lewycky29a05b62007-07-05 03:15:00 +00002344 Value *V = VN->canonicalize(I, DT);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002345 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky565706b2006-11-22 23:49:16 +00002346 if (V != I) {
2347 modified = true;
2348 ++NumInstruction;
Bill Wendling832171c2006-12-07 20:04:42 +00002349 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky29a05b62007-07-05 03:15:00 +00002350 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2351 if (VN->value(n) == I) IG->remove(n);
2352 VN->remove(I);
Nick Lewycky565706b2006-11-22 23:49:16 +00002353 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);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002361 Value *V = VN->canonicalize(Oper, DT);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002362 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky565706b2006-11-22 23:49:16 +00002363 if (V != Oper) {
2364 modified = true;
2365 ++NumVarsReplaced;
Bill Wendling832171c2006-12-07 20:04:42 +00002366 DOUT << "Resolving " << *I;
Nick Lewycky565706b2006-11-22 23:49:16 +00002367 I->setOperand(i, V);
Bill Wendling832171c2006-12-07 20:04:42 +00002368 DOUT << " into " << *I;
Nick Lewycky565706b2006-11-22 23:49:16 +00002369 }
2370 }
Nick Lewycky0be7f472007-01-13 02:05:28 +00002371#endif
Nick Lewycky565706b2006-11-22 23:49:16 +00002372
Nick Lewycky4c708752007-03-16 02:37:39 +00002373 std::string name = I->getParent()->getName();
2374 DOUT << "push (%" << name << ")\n";
Owen Andersonab0e4d32007-04-25 04:18:54 +00002375 Forwards visit(this, DT);
Nick Lewycky565706b2006-11-22 23:49:16 +00002376 visit.visit(*I);
Nick Lewycky4c708752007-03-16 02:37:39 +00002377 DOUT << "pop (%" << name << ")\n";
Nick Lewycky565706b2006-11-22 23:49:16 +00002378 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002379 };
2380
Nick Lewycky565706b2006-11-22 23:49:16 +00002381 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002382 DominatorTree *DT = &getAnalysis<DominatorTree>();
2383 DTDFS = new DomTreeDFS(DT);
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00002384 TargetData *TD = &getAnalysis<TargetData>();
2385
Bill Wendling832171c2006-12-07 20:04:42 +00002386 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002387
Nick Lewycky565706b2006-11-22 23:49:16 +00002388 modified = false;
Nick Lewycky984504b2007-06-24 04:36:20 +00002389 DomTreeDFS::Node *Root = DTDFS->getRootNode();
Nick Lewycky29a05b62007-07-05 03:15:00 +00002390 VN = new ValueNumbering(DTDFS);
2391 IG = new InequalityGraph(*VN, Root);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002392 VR = new ValueRanges(*VN, TD);
Nick Lewycky984504b2007-06-24 04:36:20 +00002393 WorkList.push_back(Root);
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002394
Nick Lewycky565706b2006-11-22 23:49:16 +00002395 do {
Nick Lewycky984504b2007-06-24 04:36:20 +00002396 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky565706b2006-11-22 23:49:16 +00002397 WorkList.pop_back();
Owen Andersonab0e4d32007-04-25 04:18:54 +00002398 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002399 } while (!WorkList.empty());
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002400
Nick Lewycky984504b2007-06-24 04:36:20 +00002401 delete DTDFS;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002402 delete VR;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002403 delete IG;
2404
2405 modified |= UB.kill();
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002406
Nick Lewycky565706b2006-11-22 23:49:16 +00002407 return modified;
Nick Lewyckya3a68bd2006-09-02 19:40:38 +00002408 }
2409
Nick Lewycky565706b2006-11-22 23:49:16 +00002410 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002411 PS->proceedToSuccessors(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002412 }
2413
2414 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky565706b2006-11-22 23:49:16 +00002415 if (BI.isUnconditional()) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002416 PS->proceedToSuccessors(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002417 return;
2418 }
2419
2420 Value *Condition = BI.getCondition();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002421 BasicBlock *TrueDest = BI.getSuccessor(0);
2422 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky565706b2006-11-22 23:49:16 +00002423
Nick Lewycky419c6f52007-01-11 02:32:38 +00002424 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002425 PS->proceedToSuccessors(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002426 return;
2427 }
2428
Nick Lewycky984504b2007-06-24 04:36:20 +00002429 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Andersonab0e4d32007-04-25 04:18:54 +00002430 I != E; ++I) {
2431 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002432 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky984504b2007-06-24 04:36:20 +00002433 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky565706b2006-11-22 23:49:16 +00002434
2435 if (Dest == TrueDest) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002436 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky29a05b62007-07-05 03:15:00 +00002437 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002438 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002439 VRP.solve();
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002440 DEBUG(VN.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002441 DEBUG(IG.dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002442 DEBUG(VR.dump());
Nick Lewycky565706b2006-11-22 23:49:16 +00002443 } else if (Dest == FalseDest) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002444 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky29a05b62007-07-05 03:15:00 +00002445 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002446 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002447 VRP.solve();
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002448 DEBUG(VN.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002449 DEBUG(IG.dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002450 DEBUG(VR.dump());
Nick Lewycky565706b2006-11-22 23:49:16 +00002451 }
2452
Nick Lewycky419c6f52007-01-11 02:32:38 +00002453 PS->proceedToSuccessor(*I);
Nick Lewycky05450ae2006-08-28 22:44:55 +00002454 }
2455 }
2456
Nick Lewycky565706b2006-11-22 23:49:16 +00002457 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2458 Value *Condition = SI.getCondition();
Nick Lewycky05450ae2006-08-28 22:44:55 +00002459
Nick Lewycky565706b2006-11-22 23:49:16 +00002460 // Set the EQProperty in each of the cases BBs, and the NEProperties
2461 // in the default BB.
Owen Andersonab0e4d32007-04-25 04:18:54 +00002462
Nick Lewycky984504b2007-06-24 04:36:20 +00002463 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Andersonab0e4d32007-04-25 04:18:54 +00002464 I != E; ++I) {
2465 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002466 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky984504b2007-06-24 04:36:20 +00002467 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewycky05450ae2006-08-28 22:44:55 +00002468
Nick Lewycky29a05b62007-07-05 03:15:00 +00002469 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky565706b2006-11-22 23:49:16 +00002470 if (BB == SI.getDefaultDest()) {
2471 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2472 if (SI.getSuccessor(i) != BB)
Nick Lewycky419c6f52007-01-11 02:32:38 +00002473 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2474 VRP.solve();
Nick Lewycky565706b2006-11-22 23:49:16 +00002475 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002476 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2477 VRP.solve();
Nick Lewycky565706b2006-11-22 23:49:16 +00002478 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002479 PS->proceedToSuccessor(*I);
Nick Lewyckya73a6542006-10-03 15:19:11 +00002480 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002481 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002482
Nick Lewycky565706b2006-11-22 23:49:16 +00002483 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002484 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002485 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky565706b2006-11-22 23:49:16 +00002486 VRP.solve();
2487 }
Nick Lewycky802fe272006-10-22 19:53:27 +00002488
Nick Lewycky565706b2006-11-22 23:49:16 +00002489 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;
Nick Lewycky05450ae2006-08-28 22:44:55 +00002493
Nick Lewycky29a05b62007-07-05 03:15:00 +00002494 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002495 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky565706b2006-11-22 23:49:16 +00002496 VRP.solve();
2497 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002498
Nick Lewycky565706b2006-11-22 23:49:16 +00002499 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2500 Value *Ptr = SI.getPointerOperand();
2501 if (isa<Constant>(Ptr)) return;
Nick Lewycky05450ae2006-08-28 22:44:55 +00002502
Nick Lewycky29a05b62007-07-05 03:15:00 +00002503 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002504 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky565706b2006-11-22 23:49:16 +00002505 VRP.solve();
2506 }
2507
Nick Lewycky45351752007-02-04 23:43:05 +00002508 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002509 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Reid Spenceraf3e9462007-03-03 00:48:31 +00002510 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2511 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng223d65b2007-04-19 05:35:00 +00002512 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2513 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Reid Spenceraf3e9462007-03-03 00:48:31 +00002514 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2515 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky45351752007-02-04 23:43:05 +00002516 VRP.solve();
2517 }
2518
2519 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002520 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Reid Spenceraf3e9462007-03-03 00:48:31 +00002521 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2522 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng223d65b2007-04-19 05:35:00 +00002523 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Reid Spenceraf3e9462007-03-03 00:48:31 +00002524 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky45351752007-02-04 23:43:05 +00002525 VRP.solve();
2526 }
2527
Nick Lewycky565706b2006-11-22 23:49:16 +00002528 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2529 Instruction::BinaryOps ops = BO.getOpcode();
2530
2531 switch (ops) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002532 default: break;
Nick Lewycky45351752007-02-04 23:43:05 +00002533 case Instruction::URem:
2534 case Instruction::SRem:
2535 case Instruction::UDiv:
2536 case Instruction::SDiv: {
2537 Value *Divisor = BO.getOperand(1);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002538 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky45351752007-02-04 23:43:05 +00002539 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2540 ICmpInst::ICMP_NE);
2541 VRP.solve();
2542 break;
2543 }
Nick Lewycky4c708752007-03-16 02:37:39 +00002544 }
2545
2546 switch (ops) {
2547 default: break;
2548 case Instruction::Shl: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002549 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002550 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2551 VRP.solve();
2552 } break;
2553 case Instruction::AShr: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002554 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002555 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2556 VRP.solve();
2557 } break;
2558 case Instruction::LShr:
2559 case Instruction::UDiv: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002560 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002561 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2562 VRP.solve();
2563 } break;
2564 case Instruction::URem: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002565 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002566 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2567 VRP.solve();
2568 } break;
2569 case Instruction::And: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002570 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002571 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: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002576 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002577 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
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002589 // XXX: once we do full PHI handling, modifying the instruction in the
2590 // Forwards visitor will cause missed optimizations.
2591
Nick Lewycky4c708752007-03-16 02:37:39 +00002592 ICmpInst::Predicate Pred = IC.getPredicate();
2593
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002594 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()) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002602 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002603 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
Nick Lewycky4c708752007-03-16 02:37:39 +00002613 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2614 ConstantInt *NextVal = 0;
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002615 switch (Pred) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002616 default: break;
2617 case ICmpInst::ICMP_SLT:
2618 case ICmpInst::ICMP_ULT:
2619 if (Op1->getValue() != 0)
Zhou Sheng223d65b2007-04-19 05:35:00 +00002620 NextVal = ConstantInt::get(Op1->getValue()-1);
Nick Lewycky4c708752007-03-16 02:37:39 +00002621 break;
2622 case ICmpInst::ICMP_SGT:
2623 case ICmpInst::ICMP_UGT:
2624 if (!Op1->getValue().isAllOnesValue())
Zhou Sheng223d65b2007-04-19 05:35:00 +00002625 NextVal = ConstantInt::get(Op1->getValue()+1);
Nick Lewycky4c708752007-03-16 02:37:39 +00002626 break;
2627
2628 }
2629 if (NextVal) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002630 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4c708752007-03-16 02:37:39 +00002631 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);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002637
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
Nick Lewycky4c708752007-03-16 02:37:39 +00002643 IC.eraseFromParent();
2644 ++NumSnuggle;
2645 PS->modified = true;
Nick Lewycky4c708752007-03-16 02:37:39 +00002646 }
2647 }
2648 }
Nick Lewycky3947a762006-08-30 02:46:48 +00002649 }
Nick Lewycky565706b2006-11-22 23:49:16 +00002650}
2651
Dan Gohman844731a2008-05-13 00:00:25 +00002652char PredicateSimplifier::ID = 0;
2653static RegisterPass<PredicateSimplifier>
2654X("predsimplify", "Predicate Simplifier");
2655
Nick Lewycky565706b2006-11-22 23:49:16 +00002656FunctionPass *llvm::createPredicateSimplifierPass() {
2657 return new PredicateSimplifier();
Nick Lewycky05450ae2006-08-28 22:44:55 +00002658}