blob: ac8ceb260cc65bd6eb174b3c95d36ac417bd0f1d [file] [log] [blame]
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nick Lewycky and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00008//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-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 Lewycky09b7e4d2006-11-22 23:49:16 +000023//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000024//
Nick Lewycky4f73de22007-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 Lewycky09b7e4d2006-11-22 23:49:16 +000028// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000029//
Nick Lewycky09b7e4d2006-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 Lewyckyd9bd0bc2007-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 Lewycky09b7e4d2006-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 Lewycky2fc338f2007-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 Lewycky09b7e4d2006-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 Lewyckyd9bd0bc2007-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 Lewycky09b7e4d2006-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 Lewycky56639802007-01-29 02:56:54 +000062// branch it can't infer anything from the "and" instruction.
Nick Lewycky09b7e4d2006-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 Lewycky4f73de22007-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
73// %b = [0, 254]. Because we store these by Value*, you should always
74// canonicalize through the InequalityGraph first.
75//
76// It never stores an empty range, because that means that the code is
77// unreachable. It never stores a single-element range since that's an equality
78// relationship and better stored in the InequalityGraph.
79//
80//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000081
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000082#define DEBUG_TYPE "predsimplify"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000085#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000086#include "llvm/Instructions.h"
87#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000088#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000089#include "llvm/ADT/SetOperations.h"
Reid Spencer3f4e6e82007-02-04 00:40:42 +000090#include "llvm/ADT/SetVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000091#include "llvm/ADT/Statistic.h"
92#include "llvm/ADT/STLExtras.h"
93#include "llvm/Analysis/Dominators.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000094#include "llvm/Analysis/ET-Forest.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000095#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000100#include "llvm/Transforms/Utils/Local.h"
101#include <algorithm>
102#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000103#include <sstream>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000104using namespace llvm;
105
Chris Lattner0e5255b2006-12-19 21:49:03 +0000106STATISTIC(NumVarsReplaced, "Number of argument substitutions");
107STATISTIC(NumInstruction , "Number of instructions removed");
108STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000109STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4f73de22007-03-16 02:37:39 +0000110STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000111
Chris Lattner0e5255b2006-12-19 21:49:03 +0000112namespace {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000113 // SLT SGT ULT UGT EQ
114 // 0 1 0 1 0 -- GT 10
115 // 0 1 0 1 1 -- GE 11
116 // 0 1 1 0 0 -- SGTULT 12
117 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000118 // 0 1 1 1 0 -- SGT 14
119 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000120 // 1 0 0 1 0 -- SLTUGT 18
121 // 1 0 0 1 1 -- SLEUGE 19
122 // 1 0 1 0 0 -- LT 20
123 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000124 // 1 0 1 1 0 -- SLT 22
125 // 1 0 1 1 1 -- SLE 23
126 // 1 1 0 1 0 -- UGT 26
127 // 1 1 0 1 1 -- UGE 27
128 // 1 1 1 0 0 -- ULT 28
129 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000130 // 1 1 1 1 0 -- NE 30
131 enum LatticeBits {
132 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
133 };
134 enum LatticeVal {
135 GT = SGT_BIT | UGT_BIT,
136 GE = GT | EQ_BIT,
137 LT = SLT_BIT | ULT_BIT,
138 LE = LT | EQ_BIT,
139 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
140 SGTULT = SGT_BIT | ULT_BIT,
141 SGEULE = SGTULT | EQ_BIT,
142 SLTUGT = SLT_BIT | UGT_BIT,
143 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000144 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
145 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
146 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
147 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
148 SLE = SLT | EQ_BIT,
149 SGE = SGT | EQ_BIT,
150 ULE = ULT | EQ_BIT,
151 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000152 };
153
154 static bool validPredicate(LatticeVal LV) {
155 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000156 case GT: case GE: case LT: case LE: case NE:
157 case SGTULT: case SGT: case SGEULE:
158 case SLTUGT: case SLT: case SLEUGE:
159 case ULT: case UGT:
160 case SLE: case SGE: case ULE: case UGE:
161 return true;
162 default:
163 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000164 }
165 }
166
167 /// reversePredicate - reverse the direction of the inequality
168 static LatticeVal reversePredicate(LatticeVal LV) {
169 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4f73de22007-03-16 02:37:39 +0000170
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000171 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
172 reverse |= (SLT_BIT|SGT_BIT);
173
174 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
175 reverse |= (ULT_BIT|UGT_BIT);
176
177 LatticeVal Rev = static_cast<LatticeVal>(reverse);
178 assert(validPredicate(Rev) && "Failed reversing predicate.");
179 return Rev;
180 }
181
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000182 /// This is a StrictWeakOrdering predicate that sorts ETNodes by how many
Nick Lewycky4f73de22007-03-16 02:37:39 +0000183 /// descendants they have. With this, you can iterate through a list sorted
184 /// by this operation and the first matching entry is the most specific
185 /// match for your basic block. The order provided is stable; ETNodes with
186 /// the same number of children are sorted by pointer address.
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000187 struct VISIBILITY_HIDDEN OrderByDominance {
188 bool operator()(const ETNode *LHS, const ETNode *RHS) const {
189 unsigned LHS_spread = LHS->getDFSNumOut() - LHS->getDFSNumIn();
190 unsigned RHS_spread = RHS->getDFSNumOut() - RHS->getDFSNumIn();
191 if (LHS_spread != RHS_spread) return LHS_spread < RHS_spread;
192 else return LHS < RHS;
193 }
194 };
195
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000196 /// The InequalityGraph stores the relationships between values.
197 /// Each Value in the graph is assigned to a Node. Nodes are pointer
198 /// comparable for equality. The caller is expected to maintain the logical
199 /// consistency of the system.
200 ///
201 /// The InequalityGraph class may invalidate Node*s after any mutator call.
202 /// @brief The InequalityGraph stores the relationships between values.
203 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000204 ETNode *TreeRoot;
205
206 InequalityGraph(); // DO NOT IMPLEMENT
207 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000208 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000209 explicit InequalityGraph(ETNode *TreeRoot) : TreeRoot(TreeRoot) {}
210
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000211 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000212
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000213 /// An Edge is contained inside a Node making one end of the edge implicit
214 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000215 /// value specifying the relationship and an ETNode specifying the root
216 /// in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000217 class VISIBILITY_HIDDEN Edge {
218 public:
219 Edge(unsigned T, LatticeVal V, ETNode *ST)
220 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000221
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000222 unsigned To;
223 LatticeVal LV;
224 ETNode *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000225
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000226 bool operator<(const Edge &edge) const {
227 if (To != edge.To) return To < edge.To;
228 else return OrderByDominance()(Subtree, edge.Subtree);
229 }
230 bool operator<(unsigned to) const {
231 return To < to;
232 }
233 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000234
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000235 /// A single node in the InequalityGraph. This stores the canonical Value
236 /// for the node, as well as the relationships with the neighbours.
237 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000238 /// @brief A single node in the InequalityGraph.
239 class VISIBILITY_HIDDEN Node {
240 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000241
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000242 typedef SmallVector<Edge, 4> RelationsType;
243 RelationsType Relations;
244
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000245 Value *Canonical;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000246
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000247 // TODO: can this idea improve performance?
248 //friend class std::vector<Node>;
249 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
250
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000251 public:
252 typedef RelationsType::iterator iterator;
253 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000254
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000255 Node(Value *V) : Canonical(V) {}
256
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000257 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000258#ifndef NDEBUG
259 public:
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000260 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000261 virtual void dump() const {
262 dump(*cerr.stream());
263 }
264 private:
265 void dump(std::ostream &os) const {
266 os << *getValue() << ":\n";
267 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
268 static const std::string names[32] =
269 { "000000", "000001", "000002", "000003", "000004", "000005",
270 "000006", "000007", "000008", "000009", " >", " >=",
271 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
272 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
273 "000024", "000025", " u>", " u>=", " u<", " u<=",
274 " !=", "000031" };
275 os << " " << names[NI->LV] << " " << NI->To
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000276 << " (" << NI->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000277 }
278 }
279#endif
280
281 public:
282 iterator begin() { return Relations.begin(); }
283 iterator end() { return Relations.end(); }
284 const_iterator begin() const { return Relations.begin(); }
285 const_iterator end() const { return Relations.end(); }
286
287 iterator find(unsigned n, ETNode *Subtree) {
288 iterator E = end();
289 for (iterator I = std::lower_bound(begin(), E, n);
290 I != E && I->To == n; ++I) {
291 if (Subtree->DominatedBy(I->Subtree))
292 return I;
293 }
294 return E;
295 }
296
297 const_iterator find(unsigned n, ETNode *Subtree) const {
298 const_iterator E = end();
299 for (const_iterator I = std::lower_bound(begin(), E, n);
300 I != E && I->To == n; ++I) {
301 if (Subtree->DominatedBy(I->Subtree))
302 return I;
303 }
304 return E;
305 }
306
307 Value *getValue() const
308 {
309 return Canonical;
310 }
311
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000312 /// Updates the lattice value for a given node. Create a new entry if
313 /// one doesn't exist, otherwise it merges the values. The new lattice
314 /// value must not be inconsistent with any previously existing value.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000315 void update(unsigned n, LatticeVal R, ETNode *Subtree) {
316 assert(validPredicate(R) && "Invalid predicate.");
317 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000318 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000319 Edge edge(n, R, Subtree);
320 iterator Insert = std::lower_bound(begin(), end(), edge);
321 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000322 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000323 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
324 assert(validPredicate(LV) && "Invalid union of lattice values.");
325 if (LV != I->LV) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000326 if (Subtree != I->Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000327 assert(Subtree->DominatedBy(I->Subtree) &&
328 "Find returned subtree that doesn't apply.");
329
330 Edge edge(n, R, Subtree);
331 iterator Insert = std::lower_bound(begin(), end(), edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000332 Relations.insert(Insert, edge); // invalidates I
333 I = find(n, Subtree);
334 }
335
336 // Also, we have to tighten any edge that Subtree dominates.
337 for (iterator B = begin(); I->To == n; --I) {
338 if (I->Subtree->DominatedBy(Subtree)) {
339 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
340 assert(validPredicate(LV) && "Invalid union of lattice values.");
341 I->LV = LV;
342 }
343 if (I == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000344 }
345 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000346 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000347 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000348 };
349
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000350 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000351 struct VISIBILITY_HIDDEN NodeMapEdge {
352 Value *V;
353 unsigned index;
354 ETNode *Subtree;
355
356 NodeMapEdge(Value *V, unsigned index, ETNode *Subtree)
357 : V(V), index(index), Subtree(Subtree) {}
358
359 bool operator==(const NodeMapEdge &RHS) const {
360 return V == RHS.V &&
361 Subtree == RHS.Subtree;
362 }
363
364 bool operator<(const NodeMapEdge &RHS) const {
365 if (V != RHS.V) return V < RHS.V;
366 return OrderByDominance()(Subtree, RHS.Subtree);
367 }
368
369 bool operator<(Value *RHS) const {
370 return V < RHS;
371 }
372 };
373
374 typedef std::vector<NodeMapEdge> NodeMapType;
375 NodeMapType NodeMap;
376
377 std::vector<Node> Nodes;
378
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000379 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000380 /// node - returns the node object at a given index retrieved from getNode.
381 /// Index zero is reserved and may not be passed in here. The pointer
382 /// returned is valid until the next call to newNode or getOrInsertNode.
383 Node *node(unsigned index) {
384 assert(index != 0 && "Zero index is reserved for not found.");
385 assert(index <= Nodes.size() && "Index out of range.");
386 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000387 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000388
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000389 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000390 /// node exists.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000391 unsigned getNode(Value *V, ETNode *Subtree) {
392 NodeMapType::iterator E = NodeMap.end();
393 NodeMapEdge Edge(V, 0, Subtree);
394 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
395 while (I != E && I->V == V) {
396 if (Subtree->DominatedBy(I->Subtree))
397 return I->index;
398 ++I;
399 }
400 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000401 }
402
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000403 /// getOrInsertNode - always returns a valid node index, creating a node
404 /// to match the Value if needed.
405 unsigned getOrInsertNode(Value *V, ETNode *Subtree) {
406 if (unsigned n = getNode(V, Subtree))
407 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000408 else
409 return newNode(V);
410 }
411
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000412 /// newNode - creates a new node for a given Value and returns the index.
413 unsigned newNode(Value *V) {
414 Nodes.push_back(Node(V));
415
416 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
417 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
418 "Attempt to create a duplicate Node.");
419 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
420 MapEntry), MapEntry);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000421 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000422 }
423
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000424 /// If the Value is in the graph, return the canonical form. Otherwise,
425 /// return the original Value.
426 Value *canonicalize(Value *V, ETNode *Subtree) {
427 if (isa<Constant>(V)) return V;
428
429 if (unsigned n = getNode(V, Subtree))
430 return node(n)->getValue();
431 else
432 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000433 }
434
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000435 /// isRelatedBy - true iff n1 op n2
436 bool isRelatedBy(unsigned n1, unsigned n2, ETNode *Subtree, LatticeVal LV) {
437 if (n1 == n2) return LV & EQ_BIT;
438
439 Node *N1 = node(n1);
440 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
441 if (I != E) return (I->LV & LV) == I->LV;
442
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000443 return false;
444 }
445
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000446 // The add* methods assume that your input is logically valid and may
447 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000448
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000449 void addEquality(unsigned n, Value *V, ETNode *Subtree) {
450 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
451 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000452
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000453 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
454 // we may already have "%z -> node #2 (%x)" somewhere above us in the
455 // graph. We need to find those edges and add "%z -> node #1 (%y)"
456 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000457
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000458 std::vector<Value *> ToRepoint;
459 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000460
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000461 if (unsigned Conflict = getNode(V, Subtree)) {
Nick Lewycky56639802007-01-29 02:56:54 +0000462 // XXX: NodeMap.size() exceeds 68,000 entries compiling kimwitu++!
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000463 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
464 I != E; ++I) {
465 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
466 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000467 }
468 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000469
470 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
471 VE = ToRepoint.end(); VI != VE; ++VI) {
472 Value *V = *VI;
473
474 // XXX: review this code. This may be doing too many insertions.
475 NodeMapEdge Edge(V, n, Subtree);
476 NodeMapType::iterator E = NodeMap.end();
477 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
478 if (I == E || I->V != V || I->Subtree != Subtree) {
479 // New Value
480 NodeMap.insert(I, Edge);
481 } else if (I != E && I->V == V && I->Subtree == Subtree) {
482 // Update best choice
483 I->index = n;
484 }
485
486#ifndef NDEBUG
487 Node *N = node(n);
488 if (isa<Constant>(V)) {
489 if (isa<Constant>(N->getValue())) {
490 assert(V == N->getValue() && "Constant equals different constant?");
491 }
492 }
493#endif
494 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000495 }
496
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000497 /// addInequality - Sets n1 op n2.
498 /// It is also an error to call this on an inequality that is already true.
499 void addInequality(unsigned n1, unsigned n2, ETNode *Subtree,
500 LatticeVal LV1) {
501 assert(n1 != n2 && "A node can't be inequal to itself.");
502
503 if (LV1 != NE)
504 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
505 "Contradictory inequality.");
506
507 Node *N1 = node(n1);
508 Node *N2 = node(n2);
509
510 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
511 // add %a < %n2 too. This keeps the graph fully connected.
512 if (LV1 != NE) {
513 // Someone with a head for this sort of logic, please review this.
Nick Lewycky56639802007-01-29 02:56:54 +0000514 // Given that %x SLTUGT %y and %a SLE %x, what is the relationship
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000515 // between %a and %y? I believe the below code is correct, but I don't
516 // think it's the most efficient solution.
517
518 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
519 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
520 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
521 if (I->LV != NE && I->To != n2) {
522 ETNode *Local_Subtree = NULL;
523 if (Subtree->DominatedBy(I->Subtree))
524 Local_Subtree = Subtree;
525 else if (I->Subtree->DominatedBy(Subtree))
526 Local_Subtree = I->Subtree;
527
528 if (Local_Subtree) {
529 unsigned new_relationship = 0;
530 LatticeVal ILV = reversePredicate(I->LV);
531 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
532 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
533
534 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
535 new_relationship |= ILV_s;
536
537 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
538 new_relationship |= ILV_u;
539
540 if (new_relationship) {
541 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
542 new_relationship |= (SLT_BIT|SGT_BIT);
543 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
544 new_relationship |= (ULT_BIT|UGT_BIT);
545 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
546 new_relationship |= EQ_BIT;
547
548 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
549
550 node(I->To)->update(n2, NewLV, Local_Subtree);
551 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
552 }
553 }
554 }
555 }
556
557 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
558 if (I->LV != NE && I->To != n1) {
559 ETNode *Local_Subtree = NULL;
560 if (Subtree->DominatedBy(I->Subtree))
561 Local_Subtree = Subtree;
562 else if (I->Subtree->DominatedBy(Subtree))
563 Local_Subtree = I->Subtree;
564
565 if (Local_Subtree) {
566 unsigned new_relationship = 0;
567 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
568 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
569
570 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
571 new_relationship |= ILV_s;
572
573 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
574 new_relationship |= ILV_u;
575
576 if (new_relationship) {
577 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
578 new_relationship |= (SLT_BIT|SGT_BIT);
579 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
580 new_relationship |= (ULT_BIT|UGT_BIT);
581 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
582 new_relationship |= EQ_BIT;
583
584 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
585
586 N1->update(I->To, NewLV, Local_Subtree);
587 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
588 }
589 }
590 }
591 }
592 }
593
594 N1->update(n2, LV1, Subtree);
595 N2->update(n1, reversePredicate(LV1), Subtree);
596 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000597
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000598 /// remove - Removes a Value from the graph. If the value is the canonical
599 /// choice for a Node, destroys the Node from the graph deleting all edges
600 /// to and from it. This method does not renumber the nodes.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000601 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000602 for (unsigned i = 0; i < NodeMap.size();) {
603 NodeMapType::iterator I = NodeMap.begin()+i;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000604 if (I->V == V) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000605 Node *N = node(I->index);
606 if (node(I->index)->getValue() == V) {
607 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI){
608 Node::iterator Iter = node(NI->To)->find(I->index, TreeRoot);
609 do {
610 node(NI->To)->Relations.erase(Iter);
611 Iter = node(NI->To)->find(I->index, TreeRoot);
612 } while (Iter != node(NI->To)->end());
613 }
614 N->Canonical = NULL;
615 }
616 N->Relations.clear();
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000617 NodeMap.erase(I);
618 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000619 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000620 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000621
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000622#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000623 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000624 virtual void dump() {
625 dump(*cerr.stream());
626 }
627
628 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000629 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000630 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000631 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000632 Node *N = node(I->index);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000633 os << *I->V << " == " << I->index
634 << "(" << I->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000635 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000636 os << I->index << ". ";
637 if (!N->getValue()) os << "(deleted node)\n";
638 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000639 }
640 }
641 }
642#endif
643 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000644
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000645 class VRPSolver;
646
647 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
648 /// in the InequalityGraph.
649 class VISIBILITY_HIDDEN ValueRanges {
650
651 /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
652 /// the scope of a rooted subtree in the dominator tree.
653 class VISIBILITY_HIDDEN ScopedRange {
654 public:
655 ScopedRange(Value *V, ConstantRange CR, ETNode *ST)
656 : V(V), CR(CR), Subtree(ST) {}
657
658 Value *V;
659 ConstantRange CR;
660 ETNode *Subtree;
661
662 bool operator<(const ScopedRange &range) const {
663 if (V != range.V) return V < range.V;
664 else return OrderByDominance()(Subtree, range.Subtree);
665 }
666
667 bool operator<(const Value *value) const {
668 return V < value;
669 }
670 };
671
672 std::vector<ScopedRange> Ranges;
673 typedef std::vector<ScopedRange>::iterator iterator;
674
675 // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
676 // intrusive domtree-scoped container is in order?
677
678 iterator begin() { return Ranges.begin(); }
679 iterator end() { return Ranges.end(); }
680
681 iterator find(Value *V, ETNode *Subtree) {
682 iterator E = end();
683 for (iterator I = std::lower_bound(begin(), E, V);
684 I != E && I->V == V; ++I) {
685 if (Subtree->DominatedBy(I->Subtree))
686 return I;
687 }
688 return E;
689 }
690
691 void update(Value *V, ConstantRange CR, ETNode *Subtree) {
692 assert(!CR.isEmptySet() && "Empty ConstantRange!");
693 if (CR.isFullSet()) return;
694
695 iterator I = find(V, Subtree);
696 if (I == end()) {
697 ScopedRange range(V, CR, Subtree);
698 iterator Insert = std::lower_bound(begin(), end(), range);
699 Ranges.insert(Insert, range);
700 } else {
701 CR = CR.intersectWith(I->CR);
702 assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
703
704 if (CR != I->CR) {
705 if (Subtree != I->Subtree) {
706 assert(Subtree->DominatedBy(I->Subtree) &&
707 "Find returned subtree that doesn't apply.");
708
709 ScopedRange range(V, CR, Subtree);
710 iterator Insert = std::lower_bound(begin(), end(), range);
711 Ranges.insert(Insert, range); // invalidates I
712 I = find(V, Subtree);
713 }
714
715 // Also, we have to tighten any edge that Subtree dominates.
716 for (iterator B = begin(); I->V == V; --I) {
717 if (I->Subtree->DominatedBy(Subtree)) {
718 CR = CR.intersectWith(I->CR);
719 assert(!CR.isEmptySet() &&
720 "Empty intersection of ConstantRanges!");
721 I->CR = CR;
722 }
723 if (I == B) break;
724 }
725 }
726 }
727 }
728
729 /// range - Creates a ConstantRange representing the set of all values
730 /// that match the ICmpInst::Predicate with any of the values in CR.
731 ConstantRange range(ICmpInst::Predicate ICmpOpcode,
732 const ConstantRange &CR) {
733 uint32_t W = CR.getBitWidth();
734 switch (ICmpOpcode) {
735 default: assert(!"Invalid ICmp opcode to range()");
736 case ICmpInst::ICMP_EQ:
737 return ConstantRange(CR.getLower(), CR.getUpper());
738 case ICmpInst::ICMP_NE:
739 if (CR.isSingleElement())
740 return ConstantRange(CR.getUpper(), CR.getLower());
741 return ConstantRange(W);
742 case ICmpInst::ICMP_ULT:
743 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
744 case ICmpInst::ICMP_SLT:
745 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
746 case ICmpInst::ICMP_ULE: {
747 APInt UMax = CR.getUnsignedMax();
748 if (UMax == APInt::getMaxValue(W))
749 return ConstantRange(W);
750 return ConstantRange(APInt::getMinValue(W), UMax + 1);
751 }
752 case ICmpInst::ICMP_SLE: {
753 APInt SMax = CR.getSignedMax();
754 if (SMax == APInt::getSignedMaxValue(W) ||
755 SMax + 1 == APInt::getSignedMaxValue(W))
756 return ConstantRange(W);
757 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
758 }
759 case ICmpInst::ICMP_UGT:
760 return ConstantRange(CR.getUnsignedMin() + 1,
761 APInt::getMaxValue(W) + 1);
762 case ICmpInst::ICMP_SGT:
763 return ConstantRange(CR.getSignedMin() + 1,
764 APInt::getSignedMaxValue(W) + 1);
765 case ICmpInst::ICMP_UGE: {
766 APInt UMin = CR.getUnsignedMin();
767 if (UMin == APInt::getMinValue(W))
768 return ConstantRange(W);
769 return ConstantRange(UMin, APInt::getMaxValue(W) + 1);
770 }
771 case ICmpInst::ICMP_SGE: {
772 APInt SMin = CR.getSignedMin();
773 if (SMin == APInt::getSignedMinValue(W))
774 return ConstantRange(W);
775 return ConstantRange(SMin, APInt::getSignedMaxValue(W) + 1);
776 }
777 }
778 }
779
780 /// create - Creates a ConstantRange that matches the given LatticeVal
781 /// relation with a given integer.
782 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
783 assert(!CR.isEmptySet() && "Can't deal with empty set.");
784
785 if (LV == NE)
786 return range(ICmpInst::ICMP_NE, CR);
787
788 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
789 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
790 bool hasEQ = LV & EQ_BIT;
791
792 ConstantRange Range(CR.getBitWidth());
793
794 if (LV_s == SGT_BIT) {
795 Range = Range.intersectWith(range(
796 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
797 } else if (LV_s == SLT_BIT) {
798 Range = Range.intersectWith(range(
799 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
800 }
801
802 if (LV_u == UGT_BIT) {
803 Range = Range.intersectWith(range(
804 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
805 } else if (LV_u == ULT_BIT) {
806 Range = Range.intersectWith(range(
807 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
808 }
809
810 return Range;
811 }
812
813 ConstantRange rangeFromValue(Value *V, ETNode *Subtree, uint32_t W) {
814 ConstantInt *C = dyn_cast<ConstantInt>(V);
815 if (C) {
816 return ConstantRange(C->getValue());
817 } else {
818 iterator I = find(V, Subtree);
819 if (I != end())
820 return I->CR;
821 }
822 return ConstantRange(W);
823 }
824
825 static uint32_t widthOfValue(Value *V) {
826 const Type *Ty = V->getType();
827 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
828 return ITy->getBitWidth();
829
830 // XXX: I'd like to transform T* into the appropriate integer by
831 // bit length, however that data may not be available.
832
833 return 0;
834 }
835
Nick Lewycky17d20fd2007-03-18 01:09:32 +0000836#ifndef NDEBUG
837 bool isCanonical(Value *V, ETNode *Subtree, VRPSolver *VRP);
838#endif
839
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000840 public:
841
842 bool isRelatedBy(Value *V1, Value *V2, ETNode *Subtree, LatticeVal LV) {
843 uint32_t W = widthOfValue(V1);
844 if (!W) return false;
845
846 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
847 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
848
849 // True iff all values in CR1 are LV to all values in CR2.
Nick Lewycky4f73de22007-03-16 02:37:39 +0000850 switch (LV) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000851 default: assert(!"Impossible lattice value!");
852 case NE:
853 return CR1.intersectWith(CR2).isEmptySet();
854 case ULT:
855 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
856 case ULE:
857 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
858 case UGT:
859 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
860 case UGE:
861 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
862 case SLT:
863 return CR1.getSignedMax().slt(CR2.getSignedMin());
864 case SLE:
865 return CR1.getSignedMax().sle(CR2.getSignedMin());
866 case SGT:
867 return CR1.getSignedMin().sgt(CR2.getSignedMax());
868 case SGE:
869 return CR1.getSignedMin().sge(CR2.getSignedMax());
870 case LT:
871 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
872 CR1.getSignedMax().slt(CR2.getUnsignedMin());
873 case LE:
874 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
875 CR1.getSignedMax().sle(CR2.getUnsignedMin());
876 case GT:
877 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
878 CR1.getSignedMin().sgt(CR2.getSignedMax());
879 case GE:
880 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
881 CR1.getSignedMin().sge(CR2.getSignedMax());
882 case SLTUGT:
883 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
884 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
885 case SLEUGE:
886 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
887 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
888 case SGTULT:
889 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
890 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
891 case SGEULE:
892 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
893 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
894 }
895 }
896
897 void addToWorklist(Value *V, const APInt *I, ICmpInst::Predicate Pred,
898 VRPSolver *VRP);
899
Nick Lewycky17d20fd2007-03-18 01:09:32 +0000900 void mergeInto(Value **I, unsigned n, Value *New, ETNode *Subtree,
901 VRPSolver *VRP) {
902 assert(isCanonical(New, Subtree, VRP) && "Best choice not canonical?");
903
904 uint32_t W = widthOfValue(New);
905 if (!W) return;
906
907 ConstantRange CR_New = rangeFromValue(New, Subtree, W);
908 ConstantRange Merged = CR_New;
909
910 for (; n != 0; ++I, --n) {
911 ConstantRange CR_Kill = rangeFromValue(*I, Subtree, W);
912 if (CR_Kill.isFullSet()) continue;
913 Merged = Merged.intersectWith(CR_Kill);
914 }
915
916 if (Merged.isFullSet() || Merged == CR_New) return;
917
918 if (Merged.isSingleElement())
919 addToWorklist(New, Merged.getSingleElement(),
920 ICmpInst::ICMP_EQ, VRP);
921 else
922 update(New, Merged, Subtree);
923 }
924
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000925 void addInequality(Value *V1, Value *V2, ETNode *Subtree, LatticeVal LV,
926 VRPSolver *VRP) {
927 assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
928
Nick Lewycky17d20fd2007-03-18 01:09:32 +0000929 assert(isCanonical(V1, Subtree, VRP) && "Value not canonical.");
930 assert(isCanonical(V2, Subtree, VRP) && "Value not canonical.");
931
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000932 if (LV == NE) return; // we can't represent those.
933 // XXX: except in the case where isSingleElement and equal to either
934 // Lower or Upper. That's probably not profitable. (Type::Int1Ty?)
935
936 uint32_t W = widthOfValue(V1);
937 if (!W) return;
938
939 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
940 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
941
942 if (!CR1.isSingleElement()) {
943 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
944 if (NewCR1 != CR1) {
945 if (NewCR1.isSingleElement())
946 addToWorklist(V1, NewCR1.getSingleElement(),
947 ICmpInst::ICMP_EQ, VRP);
948 else
949 update(V1, NewCR1, Subtree);
950 }
951 }
952
953 if (!CR2.isSingleElement()) {
954 ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
955 CR1));
956 if (NewCR2 != CR2) {
957 if (NewCR2.isSingleElement())
958 addToWorklist(V2, NewCR2.getSingleElement(),
959 ICmpInst::ICMP_EQ, VRP);
960 else
961 update(V2, NewCR2, Subtree);
962 }
963 }
964 }
965 };
966
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000967 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
968 /// another discovered to be unreachable. This is used to cull the graph when
969 /// analyzing instructions, and to mark blocks with the "unreachable"
970 /// terminator instruction after the function has executed.
971 class VISIBILITY_HIDDEN UnreachableBlocks {
972 private:
973 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000974
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000975 public:
976 /// mark - mark a block as dead
977 void mark(BasicBlock *BB) {
978 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
979 std::vector<BasicBlock *>::iterator I =
980 std::lower_bound(DeadBlocks.begin(), E, BB);
981
982 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000983 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000984
985 /// isDead - returns whether a block is known to be dead already
986 bool isDead(BasicBlock *BB) {
987 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
988 std::vector<BasicBlock *>::iterator I =
989 std::lower_bound(DeadBlocks.begin(), E, BB);
990
991 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000992 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000993
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000994 /// kill - replace the dead blocks' terminator with an UnreachableInst.
995 bool kill() {
996 bool modified = false;
997 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
998 E = DeadBlocks.end(); I != E; ++I) {
999 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001000
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001001 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001002
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001003 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1004 SI != SE; ++SI) {
1005 BasicBlock *Succ = *SI;
1006 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +00001007 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001008
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001009 TerminatorInst *TI = BB->getTerminator();
1010 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1011 TI->eraseFromParent();
1012 new UnreachableInst(BB);
1013 ++NumBlocks;
1014 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001015 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001016 DeadBlocks.clear();
1017 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001018 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001019 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001020
1021 /// VRPSolver keeps track of how changes to one variable affect other
1022 /// variables, and forwards changes along to the InequalityGraph. It
1023 /// also maintains the correct choice for "canonical" in the IG.
1024 /// @brief VRPSolver calculates inferences from a new relationship.
1025 class VISIBILITY_HIDDEN VRPSolver {
1026 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001027 friend class ValueRanges;
1028
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001029 struct Operation {
1030 Value *LHS, *RHS;
1031 ICmpInst::Predicate Op;
1032
Nick Lewycky42944462007-01-13 02:05:28 +00001033 BasicBlock *ContextBB;
1034 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001035 };
1036 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001037
1038 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001039 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001040 ValueRanges &VR;
1041
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001042 ETForest *Forest;
1043 ETNode *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001044 BasicBlock *TopBB;
1045 Instruction *TopInst;
1046 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001047
1048 typedef InequalityGraph::Node Node;
1049
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001050 /// IdomI - Determines whether one Instruction dominates another.
1051 bool IdomI(Instruction *I1, Instruction *I2) const {
1052 BasicBlock *BB1 = I1->getParent(),
1053 *BB2 = I2->getParent();
1054 if (BB1 == BB2) {
1055 if (isa<TerminatorInst>(I1)) return false;
1056 if (isa<TerminatorInst>(I2)) return true;
1057 if (isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
1058 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
1059
1060 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
1061 I != E; ++I) {
1062 if (&*I == I1) return true;
1063 if (&*I == I2) return false;
1064 }
1065 assert(!"Instructions not found in parent BasicBlock?");
1066 } else {
1067 return Forest->properlyDominates(BB1, BB2);
1068 }
1069 return false;
1070 }
1071
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001072 /// Returns true if V1 is a better canonical value than V2.
1073 bool compare(Value *V1, Value *V2) const {
1074 if (isa<Constant>(V1))
1075 return !isa<Constant>(V2);
1076 else if (isa<Constant>(V2))
1077 return false;
1078 else if (isa<Argument>(V1))
1079 return !isa<Argument>(V2);
1080 else if (isa<Argument>(V2))
1081 return false;
1082
1083 Instruction *I1 = dyn_cast<Instruction>(V1);
1084 Instruction *I2 = dyn_cast<Instruction>(V2);
1085
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001086 if (!I1 || !I2)
1087 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001088
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001089 return IdomI(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001090 }
1091
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001092 // below - true if the Instruction is dominated by the current context
1093 // block or instruction
1094 bool below(Instruction *I) {
1095 if (TopInst)
1096 return IdomI(TopInst, I);
1097 else {
1098 ETNode *Node = Forest->getNodeForBlock(I->getParent());
Nick Lewycky56639802007-01-29 02:56:54 +00001099 return Node->DominatedBy(Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001100 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001101 }
1102
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001103 bool makeEqual(Value *V1, Value *V2) {
1104 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001105
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001106 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001107
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001108 if (isa<Constant>(V1) && isa<Constant>(V2))
1109 return false;
1110
1111 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
1112
1113 if (n1 && n2) {
1114 if (n1 == n2) return true;
1115 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1116 }
1117
1118 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
1119 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
1120
Nick Lewycky15245952007-02-04 23:43:05 +00001121 assert(!compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001122
1123 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1124
1125 SetVector<unsigned> Remove;
1126 if (n2) Remove.insert(n2);
1127
1128 if (n1 && n2) {
1129 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1130 // We can't just merge %x and %y because the relationship with %z would
1131 // be EQ and that's invalid. What we're doing is looking for any nodes
1132 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001133
1134 Node *N1 = IG.node(n1);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001135 Node *N2 = IG.node(n2);
1136 Node::iterator end = N2->end();
1137
1138 // Find the intersection between N1 and N2 which is dominated by
1139 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1140 // Remove.
1141 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
1142 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1143
1144 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1145 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1146 Node::iterator NI = N2->find(I->To, Top);
1147 if (NI != end) {
1148 LatticeVal NILV = reversePredicate(NI->LV);
1149 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1150 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1151
1152 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1153 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1154 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001155 }
1156 }
1157
1158 // See if one of the nodes about to be removed is actually a better
1159 // canonical choice than n1.
1160 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001161 SetVector<unsigned>::iterator DontRemove = Remove.end();
1162 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001163 E = Remove.end(); I != E; ++I) {
1164 unsigned n = *I;
1165 Value *V = IG.node(n)->getValue();
1166 if (compare(V, V1)) {
1167 V1 = V;
1168 n1 = n;
1169 DontRemove = I;
1170 }
1171 }
1172 if (DontRemove != Remove.end()) {
1173 unsigned n = *DontRemove;
1174 Remove.remove(n);
1175 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001176 }
1177 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001178
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001179 // We'd like to allow makeEqual on two values to perform a simple
1180 // substitution without every creating nodes in the IG whenever possible.
1181 //
1182 // The first iteration through this loop operates on V2 before going
1183 // through the Remove list and operating on those too. If all of the
1184 // iterations performed simple replacements then we exit early.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001185 bool mergeIGNode = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001186 unsigned i = 0;
1187 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1188 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1189
1190 // Try to replace the whole instruction. If we can, we're done.
1191 Instruction *I2 = dyn_cast<Instruction>(R);
1192 if (I2 && below(I2)) {
1193 std::vector<Instruction *> ToNotify;
1194 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1195 UI != UE;) {
1196 Use &TheUse = UI.getUse();
1197 ++UI;
1198 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1199 ToNotify.push_back(I);
1200 }
1201
1202 DOUT << "Simply removing " << *I2
1203 << ", replacing with " << *V1 << "\n";
1204 I2->replaceAllUsesWith(V1);
1205 // leave it dead; it'll get erased later.
1206 ++NumInstruction;
1207 modified = true;
1208
1209 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1210 IE = ToNotify.end(); II != IE; ++II) {
1211 opsToDef(*II);
1212 }
1213
1214 continue;
1215 }
1216
1217 // Otherwise, replace all dominated uses.
1218 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1219 UI != UE;) {
1220 Use &TheUse = UI.getUse();
1221 ++UI;
1222 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1223 if (below(I)) {
1224 TheUse.set(V1);
1225 modified = true;
1226 ++NumVarsReplaced;
1227 opsToDef(I);
1228 }
1229 }
1230 }
1231
1232 // If that killed the instruction, stop here.
1233 if (I2 && isInstructionTriviallyDead(I2)) {
1234 DOUT << "Killed all uses of " << *I2
1235 << ", replacing with " << *V1 << "\n";
1236 continue;
1237 }
1238
1239 // If we make it to here, then we will need to create a node for N1.
1240 // Otherwise, we can skip out early!
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001241 mergeIGNode = true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001242 }
1243
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001244 if (!isa<Constant>(V1)) {
1245 if (Remove.empty()) {
1246 VR.mergeInto(&V2, 1, V1, Top, this);
1247 } else {
1248 std::vector<Value*> RemoveVals;
1249 RemoveVals.reserve(Remove.size());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001250
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001251 for (SetVector<unsigned>::iterator I = Remove.begin(),
1252 E = Remove.end(); I != E; ++I) {
1253 Value *V = IG.node(*I)->getValue();
1254 if (!V->use_empty())
1255 RemoveVals.push_back(V);
1256 }
1257 VR.mergeInto(&RemoveVals[0], RemoveVals.size(), V1, Top, this);
1258 }
1259 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001260
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001261 if (mergeIGNode) {
1262 // Create N1.
1263 if (!n1) n1 = IG.newNode(V1);
1264
1265 // Migrate relationships from removed nodes to N1.
1266 Node *N1 = IG.node(n1);
1267 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1268 I != E; ++I) {
1269 unsigned n = *I;
1270 Node *N = IG.node(n);
1271 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
1272 if (NI->Subtree->DominatedBy(Top)) {
1273 if (NI->To == n1) {
1274 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1275 continue;
1276 }
1277 if (Remove.count(NI->To))
1278 continue;
1279
1280 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1281 N1->update(NI->To, NI->LV, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001282 }
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001283 }
1284 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001285
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001286 // Point V2 (and all items in Remove) to N1.
1287 if (!n2)
1288 IG.addEquality(n1, V2, Top);
1289 else {
1290 for (SetVector<unsigned>::iterator I = Remove.begin(),
1291 E = Remove.end(); I != E; ++I) {
1292 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
1293 }
1294 }
1295
1296 // If !Remove.empty() then V2 = Remove[0]->getValue().
1297 // Even when Remove is empty, we still want to process V2.
1298 i = 0;
1299 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1300 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1301
1302 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1303 if (below(I2) ||
1304 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1305 defToOps(I2);
1306 }
1307 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1308 UI != UE;) {
1309 Use &TheUse = UI.getUse();
1310 ++UI;
1311 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1312 if (below(I) ||
1313 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1314 opsToDef(I);
1315 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001316 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001317 }
1318 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001319
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001320 // re-opsToDef all dominated users of V1.
1321 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1322 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001323 UI != UE;) {
1324 Use &TheUse = UI.getUse();
1325 ++UI;
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001326 Value *V = TheUse.getUser();
1327 if (!V->use_empty()) {
1328 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
1329 if (below(Inst) ||
1330 Top->DominatedBy(Forest->getNodeForBlock(Inst->getParent())))
1331 opsToDef(Inst);
1332 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001333 }
1334 }
1335 }
1336
1337 return true;
1338 }
1339
1340 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1341 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1342 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1343 switch (Pred) {
1344 case ICmpInst::ICMP_EQ:
1345 assert(!"No matching lattice value.");
1346 return static_cast<LatticeVal>(EQ_BIT);
1347 default:
1348 assert(!"Invalid 'icmp' predicate.");
1349 case ICmpInst::ICMP_NE:
1350 return NE;
1351 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001352 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001353 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001354 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001355 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001356 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001357 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001358 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001359 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001360 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001361 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001362 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001363 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001364 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001365 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001366 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001367 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001368 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001369
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001370 public:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001371 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
1372 ETForest *Forest, bool &modified, BasicBlock *TopBB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001373 : IG(IG),
1374 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001375 VR(VR),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001376 Forest(Forest),
1377 Top(Forest->getNodeForBlock(TopBB)),
1378 TopBB(TopBB),
1379 TopInst(NULL),
1380 modified(modified) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +00001381
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001382 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
1383 ETForest *Forest, bool &modified, Instruction *TopInst)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001384 : IG(IG),
1385 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001386 VR(VR),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001387 Forest(Forest),
1388 TopInst(TopInst),
1389 modified(modified)
1390 {
1391 TopBB = TopInst->getParent();
1392 Top = Forest->getNodeForBlock(TopBB);
1393 }
1394
1395 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1396 if (Constant *C1 = dyn_cast<Constant>(V1))
1397 if (Constant *C2 = dyn_cast<Constant>(V2))
1398 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001399 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001400
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001401 if (unsigned n1 = IG.getNode(V1, Top))
1402 if (unsigned n2 = IG.getNode(V2, Top)) {
1403 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1404 Pred == ICmpInst::ICMP_ULE ||
1405 Pred == ICmpInst::ICMP_UGE ||
1406 Pred == ICmpInst::ICMP_SLE ||
1407 Pred == ICmpInst::ICMP_SGE;
1408 if (Pred == ICmpInst::ICMP_EQ) return false;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001409 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001410 }
1411
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001412 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1413 return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001414 }
1415
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001416 /// add - adds a new property to the work queue
1417 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1418 Instruction *I = NULL) {
1419 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1420 if (I) DOUT << " context: " << *I;
1421 else DOUT << " default context";
1422 DOUT << "\n";
1423
1424 WorkList.push_back(Operation());
1425 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001426 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1427 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001428 }
1429
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001430 /// defToOps - Given an instruction definition that we've learned something
1431 /// new about, find any new relationships between its operands.
1432 void defToOps(Instruction *I) {
1433 Instruction *NewContext = below(I) ? I : TopInst;
1434 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001435
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1437 const Type *Ty = BO->getType();
1438 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001439
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001440 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1441 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001442
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001443 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001444
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001445 switch (BO->getOpcode()) {
1446 case Instruction::And: {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001447 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001448 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001449 if (Canonical == CI) {
1450 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1451 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001452 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001453 } break;
1454 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001455 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001456 Constant *Zero = Constant::getNullValue(Ty);
1457 if (Canonical == Zero) {
1458 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1459 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1460 }
1461 } break;
1462 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001463 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1464 // "xor i32 %c, %a" EQ %c then %a EQ 0
1465 // "xor i32 %c, %a" NE %c then %a NE 0
1466 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001467 Value *LHS = Op0;
1468 Value *RHS = Op1;
1469 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1470
Nick Lewycky4a74a752007-01-12 00:02:12 +00001471 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1472 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001473 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001474 ICmpInst::ICMP_EQ, NewContext);
1475 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001476 }
1477 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001478 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001479 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1480 NewContext);
1481 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1482 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1483 NewContext);
1484 }
1485 } break;
1486 default:
1487 break;
1488 }
1489 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001490 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001491 // etc.
1492
Zhou Sheng75b871f2007-01-11 12:24:14 +00001493 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001494 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1495 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001496 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001497 add(IC->getOperand(0), IC->getOperand(1),
1498 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1499 }
1500 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1501 if (I->getType()->isFPOrFPVector()) return;
1502
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001503 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001504 // %a EQ %b and %b NE %c then %x EQ true
1505 // %a EQ %c and %b NE %c then %x EQ false
1506
1507 Value *True = SI->getTrueValue();
1508 Value *False = SI->getFalseValue();
1509 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1510 if (Canonical == IG.canonicalize(True, Top) ||
1511 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001512 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001513 ICmpInst::ICMP_EQ, NewContext);
1514 else if (Canonical == IG.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001515 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001516 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001517 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001518 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001519 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1520 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1521 OE = GEPI->idx_end(); OI != OE; ++OI) {
1522 ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
1523 if (!Op || !Op->isZero()) return;
1524 }
1525 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1526 // jumping the type plane as needed.
1527 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1528 ICmpInst::ICMP_NE)) {
1529 Value *Ptr = GEPI->getPointerOperand();
1530 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1531 NewContext);
1532 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001533 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001534 // TODO: CastInst "%a = cast ... %b" where %a is EQ or NE a constant.
1535 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001536
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001537 /// opsToDef - A new relationship was discovered involving one of this
1538 /// instruction's operands. Find any new relationship involving the
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001539 /// definition, or another operand.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001540 void opsToDef(Instruction *I) {
1541 Instruction *NewContext = below(I) ? I : TopInst;
1542
1543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1544 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1545 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1546
Zhou Sheng75b871f2007-01-11 12:24:14 +00001547 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1548 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001549 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1550 ICmpInst::ICMP_EQ, NewContext);
1551 return;
1552 }
1553
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001554 // "%y = and i1 true, %x" then %x EQ %y
1555 // "%y = or i1 false, %x" then %x EQ %y
1556 // "%x = add i32 %y, 0" then %x EQ %y
1557 // "%x = mul i32 %y, 0" then %x EQ 0
1558
1559 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001560 const Type *Ty = BO->getType();
1561 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1562
1563 Constant *Zero = Constant::getNullValue(Ty);
1564 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001565
1566 switch (Opcode) {
1567 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001568 case Instruction::LShr:
1569 case Instruction::AShr:
1570 case Instruction::Shl:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001571 case Instruction::Sub:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001572 if (Op1 == Zero) {
1573 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1574 return;
1575 }
1576 break;
1577 case Instruction::Or:
1578 if (Op0 == AllOnes || Op1 == AllOnes) {
1579 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1580 return;
1581 } // fall-through
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001582 case Instruction::Xor:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001583 case Instruction::Add:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001584 if (Op0 == Zero) {
1585 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1586 return;
1587 } else if (Op1 == Zero) {
1588 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1589 return;
1590 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001591 break;
1592 case Instruction::And:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001593 if (Op0 == AllOnes) {
1594 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1595 return;
1596 } else if (Op1 == AllOnes) {
1597 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1598 return;
1599 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001600 // fall-through
1601 case Instruction::Mul:
1602 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001603 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1604 return;
1605 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001606 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001607 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001608
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001609 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001610 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1611 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001612 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001613
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001614 Value *Known = Op0, *Unknown = Op1,
1615 *TheBO = IG.canonicalize(BO, Top);
1616 if (Known != TheBO) std::swap(Known, Unknown);
1617 if (Known == TheBO) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001618 switch (Opcode) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001619 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001620 case Instruction::LShr:
1621 case Instruction::AShr:
1622 case Instruction::Shl:
1623 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1624 // otherwise, fall-through.
1625 case Instruction::Sub:
1626 if (Unknown == Op1) break;
1627 // otherwise, fall-through.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001628 case Instruction::Xor:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001629 case Instruction::Add:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001630 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001631 break;
1632 case Instruction::UDiv:
1633 case Instruction::SDiv:
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001634 if (Unknown == Op1) break;
1635 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewycky4a74a752007-01-12 00:02:12 +00001636 Constant *One = ConstantInt::get(Ty, 1);
1637 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1638 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001639 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001640 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001641 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001642
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001643 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001644
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001645 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001646 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001647 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001648 // etc.
1649
1650 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1651 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1652
1653 ICmpInst::Predicate Pred = IC->getPredicate();
1654 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001655 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001656 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001657 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001658 }
1659
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001660 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001661 if (I->getType()->isFPOrFPVector()) return;
1662
Nick Lewycky4f73de22007-03-16 02:37:39 +00001663 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001664 // %x EQ true then %a EQ %b
1665 // %x EQ false then %a EQ %c
1666 // %b EQ %c then %a EQ %b
1667
1668 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001669 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001670 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001671 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001672 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1673 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1674 IG.canonicalize(SI->getFalseValue(), Top)) {
1675 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1676 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001677 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001678 const Type *Ty = CI->getDestTy();
1679 if (Ty->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001680
1681 if (Constant *C = dyn_cast<Constant>(
1682 IG.canonicalize(CI->getOperand(0), Top))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001683 add(CI, ConstantExpr::getCast(CI->getOpcode(), C, Ty),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001684 ICmpInst::ICMP_EQ, NewContext);
1685 }
1686
1687 // TODO: "%a = cast ... %b" where %b is NE/LT/GT a constant.
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001688 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1689 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1690 OE = GEPI->idx_end(); OI != OE; ++OI) {
1691 ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
1692 if (!Op || !Op->isZero()) return;
1693 }
1694 // TODO: The GEPI indices are all zero. Copy from operand to definition,
1695 // jumping the type plane as needed.
1696 Value *Ptr = GEPI->getPointerOperand();
1697 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
1698 ICmpInst::ICMP_NE)) {
1699 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
1700 NewContext);
1701 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001702 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001703 }
1704
1705 /// solve - process the work queue
1706 /// Return false if a logical contradiction occurs.
1707 void solve() {
1708 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
1709 while (!WorkList.empty()) {
1710 //DOUT << "WorkList size: " << WorkList.size() << "\n";
1711
1712 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00001713 TopInst = O.ContextInst;
1714 TopBB = O.ContextBB;
1715 Top = Forest->getNodeForBlock(TopBB);
1716
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001717 O.LHS = IG.canonicalize(O.LHS, Top);
1718 O.RHS = IG.canonicalize(O.RHS, Top);
1719
1720 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
1721 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
1722
1723 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00001724 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
1725 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001726 DOUT << "\n";
1727
1728 DEBUG(IG.dump());
1729
Nick Lewycky15245952007-02-04 23:43:05 +00001730 // If they're both Constant, skip it. Check for contradiction and mark
1731 // the BB as unreachable if so.
1732 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
1733 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
1734 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
1735 ConstantInt::getFalse())
1736 UB.mark(TopBB);
1737
1738 WorkList.pop_front();
1739 continue;
1740 }
1741 }
1742
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001743 if (compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00001744 std::swap(O.LHS, O.RHS);
1745 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001746 }
1747
1748 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001749 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001750 UB.mark(TopBB);
1751 } else {
1752 LatticeVal LV = cmpInstToLattice(O.Op);
1753
1754 if ((LV & EQ_BIT) &&
1755 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001756 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001757 UB.mark(TopBB);
1758 } else {
1759 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00001760 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001761 WorkList.pop_front();
1762 continue;
1763 }
1764
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001765 unsigned n1 = IG.getNode(O.LHS, Top);
1766 unsigned n2 = IG.getNode(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001767
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001768 if (n1 && n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001769 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
1770 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
1771 UB.mark(TopBB);
1772
1773 WorkList.pop_front();
1774 continue;
1775 }
1776
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001777 if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
1778 (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001779 WorkList.pop_front();
1780 continue;
1781 }
1782
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001783 VR.addInequality(O.LHS, O.RHS, Top, LV, this);
1784 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
1785 LV == NE) {
1786 if (!n1) n1 = IG.newNode(O.LHS);
1787 if (!n2) n2 = IG.newNode(O.RHS);
1788 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00001789 }
1790
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001791 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
1792 if (below(I1) ||
1793 Top->DominatedBy(Forest->getNodeForBlock(I1->getParent())))
1794 defToOps(I1);
1795 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001796 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
1797 for (Value::use_iterator UI = O.LHS->use_begin(),
1798 UE = O.LHS->use_end(); UI != UE;) {
1799 Use &TheUse = UI.getUse();
1800 ++UI;
1801 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001802 if (below(I) ||
1803 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1804 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001805 }
1806 }
1807 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001808 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
1809 if (below(I2) ||
1810 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1811 defToOps(I2);
1812 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001813 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
1814 for (Value::use_iterator UI = O.RHS->use_begin(),
1815 UE = O.RHS->use_end(); UI != UE;) {
1816 Use &TheUse = UI.getUse();
1817 ++UI;
1818 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001819 if (below(I) ||
1820 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1821
1822 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001823 }
1824 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001825 }
1826 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001827 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001828 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00001829 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001830 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001831 };
1832
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001833 void ValueRanges::addToWorklist(Value *V, const APInt *I,
1834 ICmpInst::Predicate Pred, VRPSolver *VRP) {
1835 VRP->add(V, ConstantInt::get(*I), Pred, VRP->TopInst);
1836 }
1837
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001838#ifndef NDEBUG
1839 bool ValueRanges::isCanonical(Value *V, ETNode *Subtree, VRPSolver *VRP) {
1840 return V == VRP->IG.canonicalize(V, Subtree);
1841 }
1842#endif
1843
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001844 /// PredicateSimplifier - This class is a simplifier that replaces
1845 /// one equivalent variable with another. It also tracks what
1846 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001847 /// @brief Root of the predicate simplifier optimization.
1848 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1849 DominatorTree *DT;
1850 ETForest *Forest;
1851 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001852 InequalityGraph *IG;
1853 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001854 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001855
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001856 std::vector<DominatorTree::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001857
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001858 public:
1859 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001860
1861 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1862 AU.addRequiredID(BreakCriticalEdgesID);
1863 AU.addRequired<DominatorTree>();
1864 AU.addRequired<ETForest>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001865 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001866
1867 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001868 /// Forwards - Adds new properties into PropertySet and uses them to
1869 /// simplify instructions. Because new properties sometimes apply to
1870 /// a transition from one BasicBlock to another, this will use the
1871 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1872 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001873 /// @brief Performs abstract execution of the program.
1874 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001875 friend class InstVisitor<Forwards>;
1876 PredicateSimplifier *PS;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001877 DominatorTree::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001878
Nick Lewycky77e030b2006-10-12 02:02:44 +00001879 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001880 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001881 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001882 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001883
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001884 Forwards(PredicateSimplifier *PS, DominatorTree::Node *DTNode)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001885 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB), VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001886
1887 void visitTerminatorInst(TerminatorInst &TI);
1888 void visitBranchInst(BranchInst &BI);
1889 void visitSwitchInst(SwitchInst &SI);
1890
Nick Lewyckyf3450082006-10-22 19:53:27 +00001891 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001892 void visitLoadInst(LoadInst &LI);
1893 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001894
Nick Lewycky15245952007-02-04 23:43:05 +00001895 void visitSExtInst(SExtInst &SI);
1896 void visitZExtInst(ZExtInst &ZI);
1897
Nick Lewycky77e030b2006-10-12 02:02:44 +00001898 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00001899 void visitICmpInst(ICmpInst &IC);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001900 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001901
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001902 // Used by terminator instructions to proceed from the current basic
1903 // block to the next. Verifies that "current" dominates "next",
1904 // then calls visitBasicBlock.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001905 void proceedToSuccessors(DominatorTree::Node *Current) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001906 for (DominatorTree::Node::iterator I = Current->begin(),
1907 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001908 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001909 }
1910 }
1911
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001912 void proceedToSuccessor(DominatorTree::Node *Next) {
1913 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001914 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001915
1916 // Visits each instruction in the basic block.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001917 void visitBasicBlock(DominatorTree::Node *Node) {
1918 BasicBlock *BB = Node->getBlock();
1919 ETNode *ET = Forest->getNodeForBlock(BB);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001920 DOUT << "Entering Basic Block: " << BB->getName()
1921 << " (" << ET->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00001922 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001923 visitInstruction(I++, Node, ET);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001924 }
1925 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001926
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001927 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001928 // the PropertySet.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001929 void visitInstruction(Instruction *I, DominatorTree::Node *DT, ETNode *ET) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001930 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001931 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001932
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001933 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001934 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001935 ++NumSimple;
1936 modified = true;
1937 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001938 I->eraseFromParent();
1939 return;
1940 }
1941
Nick Lewycky42944462007-01-13 02:05:28 +00001942#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001943 // Try to replace the whole instruction.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001944 Value *V = IG->canonicalize(I, ET);
1945 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001946 if (V != I) {
1947 modified = true;
1948 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00001949 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001950 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001951 I->replaceAllUsesWith(V);
1952 I->eraseFromParent();
1953 return;
1954 }
1955
1956 // Try to substitute operands.
1957 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1958 Value *Oper = I->getOperand(i);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001959 Value *V = IG->canonicalize(Oper, ET);
1960 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001961 if (V != Oper) {
1962 modified = true;
1963 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00001964 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001965 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00001966 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001967 }
1968 }
Nick Lewycky42944462007-01-13 02:05:28 +00001969#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001970
Nick Lewycky4f73de22007-03-16 02:37:39 +00001971 std::string name = I->getParent()->getName();
1972 DOUT << "push (%" << name << ")\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001973 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001974 visit.visit(*I);
Nick Lewycky4f73de22007-03-16 02:37:39 +00001975 DOUT << "pop (%" << name << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001976 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001977 };
1978
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001979 bool PredicateSimplifier::runOnFunction(Function &F) {
1980 DT = &getAnalysis<DominatorTree>();
1981 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001982
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001983 Forest->updateDFSNumbers(); // XXX: should only act when numbers are out of date
1984
Bill Wendling22e978a2006-12-07 20:04:42 +00001985 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001986
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001987 modified = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001988 BasicBlock *RootBlock = &F.getEntryBlock();
1989 IG = new InequalityGraph(Forest->getNodeForBlock(RootBlock));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001990 VR = new ValueRanges();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001991 WorkList.push_back(DT->getRootNode());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001992
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001993 do {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001994 DominatorTree::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001995 WorkList.pop_back();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001996 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001997 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001998
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001999 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002000 delete IG;
2001
2002 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002003
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002004 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00002005 }
2006
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002007 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002008 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002009 }
2010
2011 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002012 if (BI.isUnconditional()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002013 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002014 return;
2015 }
2016
2017 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002018 BasicBlock *TrueDest = BI.getSuccessor(0);
2019 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002020
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002021 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2022 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002023 return;
2024 }
2025
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002026 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002027 I != E; ++I) {
2028 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002029 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002030 << "(" << PS->Forest->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002031
2032 if (Dest == TrueDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002033 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002034 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002035 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002036 VRP.solve();
2037 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002038 } else if (Dest == FalseDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002039 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002040 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002041 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002042 VRP.solve();
2043 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002044 }
2045
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002046 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002047 }
2048 }
2049
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002050 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2051 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002052
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002053 // Set the EQProperty in each of the cases BBs, and the NEProperties
2054 // in the default BB.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002055
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002056 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002057 I != E; ++I) {
2058 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002059 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002060 << "(" << PS->Forest->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002061
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002062 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002063 if (BB == SI.getDefaultDest()) {
2064 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2065 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002066 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2067 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002068 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002069 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2070 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002071 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002072 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00002073 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002074 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002075
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002076 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002077 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002078 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002079 VRP.solve();
2080 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00002081
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002082 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2083 Value *Ptr = LI.getPointerOperand();
2084 // avoid "load uint* null" -> null NE null.
2085 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002086
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002087 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002088 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002089 VRP.solve();
2090 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002091
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002092 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2093 Value *Ptr = SI.getPointerOperand();
2094 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002095
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002096 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002097 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002098 VRP.solve();
2099 }
2100
Nick Lewycky15245952007-02-04 23:43:05 +00002101 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002102 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002103 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2104 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2105 APInt Min(APInt::getSignedMinValue(SrcBitWidth));
2106 APInt Max(APInt::getSignedMaxValue(SrcBitWidth));
2107 Min.sext(DstBitWidth);
2108 Max.sext(DstBitWidth);
2109 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2110 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002111 VRP.solve();
2112 }
2113
2114 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002115 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002116 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2117 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2118 APInt Max(APInt::getMaxValue(SrcBitWidth));
2119 Max.zext(DstBitWidth);
2120 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002121 VRP.solve();
2122 }
2123
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002124 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2125 Instruction::BinaryOps ops = BO.getOpcode();
2126
2127 switch (ops) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002128 default: break;
Nick Lewycky15245952007-02-04 23:43:05 +00002129 case Instruction::URem:
2130 case Instruction::SRem:
2131 case Instruction::UDiv:
2132 case Instruction::SDiv: {
2133 Value *Divisor = BO.getOperand(1);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002134 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00002135 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2136 ICmpInst::ICMP_NE);
2137 VRP.solve();
2138 break;
2139 }
Nick Lewycky4f73de22007-03-16 02:37:39 +00002140 }
2141
2142 switch (ops) {
2143 default: break;
2144 case Instruction::Shl: {
2145 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
2146 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2147 VRP.solve();
2148 } break;
2149 case Instruction::AShr: {
2150 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
2151 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2152 VRP.solve();
2153 } break;
2154 case Instruction::LShr:
2155 case Instruction::UDiv: {
2156 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
2157 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2158 VRP.solve();
2159 } break;
2160 case Instruction::URem: {
2161 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
2162 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2163 VRP.solve();
2164 } break;
2165 case Instruction::And: {
2166 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
2167 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2168 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2169 VRP.solve();
2170 } break;
2171 case Instruction::Or: {
2172 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
2173 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2174 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2175 VRP.solve();
2176 } break;
2177 }
2178 }
2179
2180 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2181 // If possible, squeeze the ICmp predicate into something simpler.
2182 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2183 // the predicate to eq.
2184
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002185 // XXX: once we do full PHI handling, modifying the instruction in the
2186 // Forwards visitor will cause missed optimizations.
2187
Nick Lewycky4f73de22007-03-16 02:37:39 +00002188 ICmpInst::Predicate Pred = IC.getPredicate();
2189
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002190 switch (Pred) {
2191 default: break;
2192 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2193 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2194 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2195 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2196 }
2197 if (Pred != IC.getPredicate()) {
2198 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &IC);
2199 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2200 ICmpInst::ICMP_NE)) {
2201 ++NumSnuggle;
2202 PS->modified = true;
2203 IC.setPredicate(Pred);
2204 }
2205 }
2206
2207 Pred = IC.getPredicate();
2208
Nick Lewycky4f73de22007-03-16 02:37:39 +00002209 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2210 ConstantInt *NextVal = 0;
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002211 switch (Pred) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002212 default: break;
2213 case ICmpInst::ICMP_SLT:
2214 case ICmpInst::ICMP_ULT:
2215 if (Op1->getValue() != 0)
Anton Korobeynikov22f436d2007-03-17 14:48:06 +00002216 NextVal = cast<ConstantInt>(ConstantExpr::getSub(
2217 Op1, ConstantInt::get(Op1->getType(), 1)));
Nick Lewycky4f73de22007-03-16 02:37:39 +00002218 break;
2219 case ICmpInst::ICMP_SGT:
2220 case ICmpInst::ICMP_UGT:
2221 if (!Op1->getValue().isAllOnesValue())
2222 NextVal = cast<ConstantInt>(ConstantExpr::getAdd(
2223 Op1, ConstantInt::get(Op1->getType(), 1)));
2224 break;
2225
2226 }
2227 if (NextVal) {
2228 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &IC);
2229 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2230 ICmpInst::getInversePredicate(Pred))) {
2231 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2232 NextVal, "", &IC);
2233 NewIC->takeName(&IC);
2234 IC.replaceAllUsesWith(NewIC);
2235 IG.remove(&IC); // XXX: prove this isn't necessary
2236 IC.eraseFromParent();
2237 ++NumSnuggle;
2238 PS->modified = true;
Nick Lewycky4f73de22007-03-16 02:37:39 +00002239 }
2240 }
2241 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00002242 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002243
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002244 RegisterPass<PredicateSimplifier> X("predsimplify",
2245 "Predicate Simplifier");
2246}
2247
2248FunctionPass *llvm::createPredicateSimplifierPass() {
2249 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002250}