blob: 836720115a0c16904d1819d0e24e4eca33c382e5 [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 Lewycky09b7e4d2006-11-22 23:49:16 +000025// This pass focusses on four properties; equals, not equals, less-than
26// and less-than-or-equals-to. The greater-than forms are also held just
27// to allow walking from a lesser node to a greater one. These properties
28// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
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 Lewyckyb2e8ae12006-08-28 22:44:55 +000070
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000071#define DEBUG_TYPE "predsimplify"
72#include "llvm/Transforms/Scalar.h"
73#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000074#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000075#include "llvm/Instructions.h"
76#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000077#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000078#include "llvm/ADT/SetOperations.h"
Reid Spencer3f4e6e82007-02-04 00:40:42 +000079#include "llvm/ADT/SetVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000080#include "llvm/ADT/Statistic.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/Analysis/Dominators.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000083#include "llvm/Analysis/ET-Forest.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000084#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000085#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000086#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000087#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000088#include "llvm/Support/InstVisitor.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000089#include "llvm/Transforms/Utils/Local.h"
90#include <algorithm>
91#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000092#include <sstream>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000093using namespace llvm;
94
Chris Lattner0e5255b2006-12-19 21:49:03 +000095STATISTIC(NumVarsReplaced, "Number of argument substitutions");
96STATISTIC(NumInstruction , "Number of instructions removed");
97STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +000098STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000099
Chris Lattner0e5255b2006-12-19 21:49:03 +0000100namespace {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000101 // SLT SGT ULT UGT EQ
102 // 0 1 0 1 0 -- GT 10
103 // 0 1 0 1 1 -- GE 11
104 // 0 1 1 0 0 -- SGTULT 12
105 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000106 // 0 1 1 1 0 -- SGT 14
107 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000108 // 1 0 0 1 0 -- SLTUGT 18
109 // 1 0 0 1 1 -- SLEUGE 19
110 // 1 0 1 0 0 -- LT 20
111 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000112 // 1 0 1 1 0 -- SLT 22
113 // 1 0 1 1 1 -- SLE 23
114 // 1 1 0 1 0 -- UGT 26
115 // 1 1 0 1 1 -- UGE 27
116 // 1 1 1 0 0 -- ULT 28
117 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000118 // 1 1 1 1 0 -- NE 30
119 enum LatticeBits {
120 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
121 };
122 enum LatticeVal {
123 GT = SGT_BIT | UGT_BIT,
124 GE = GT | EQ_BIT,
125 LT = SLT_BIT | ULT_BIT,
126 LE = LT | EQ_BIT,
127 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
128 SGTULT = SGT_BIT | ULT_BIT,
129 SGEULE = SGTULT | EQ_BIT,
130 SLTUGT = SLT_BIT | UGT_BIT,
131 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000132 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
133 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
134 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
135 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
136 SLE = SLT | EQ_BIT,
137 SGE = SGT | EQ_BIT,
138 ULE = ULT | EQ_BIT,
139 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000140 };
141
142 static bool validPredicate(LatticeVal LV) {
143 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000144 case GT: case GE: case LT: case LE: case NE:
145 case SGTULT: case SGT: case SGEULE:
146 case SLTUGT: case SLT: case SLEUGE:
147 case ULT: case UGT:
148 case SLE: case SGE: case ULE: case UGE:
149 return true;
150 default:
151 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000152 }
153 }
154
155 /// reversePredicate - reverse the direction of the inequality
156 static LatticeVal reversePredicate(LatticeVal LV) {
157 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
158 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
159 reverse |= (SLT_BIT|SGT_BIT);
160
161 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
162 reverse |= (ULT_BIT|UGT_BIT);
163
164 LatticeVal Rev = static_cast<LatticeVal>(reverse);
165 assert(validPredicate(Rev) && "Failed reversing predicate.");
166 return Rev;
167 }
168
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000169 /// This is a StrictWeakOrdering predicate that sorts ETNodes by how many
170 /// children they have. With this, you can iterate through a list sorted by
171 /// this operation and the first matching entry is the most specific match
172 /// for your basic block. The order provided is total; ETNodes with the
173 /// same number of children are sorted by pointer address.
174 struct VISIBILITY_HIDDEN OrderByDominance {
175 bool operator()(const ETNode *LHS, const ETNode *RHS) const {
176 unsigned LHS_spread = LHS->getDFSNumOut() - LHS->getDFSNumIn();
177 unsigned RHS_spread = RHS->getDFSNumOut() - RHS->getDFSNumIn();
178 if (LHS_spread != RHS_spread) return LHS_spread < RHS_spread;
179 else return LHS < RHS;
180 }
181 };
182
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000183 /// The InequalityGraph stores the relationships between values.
184 /// Each Value in the graph is assigned to a Node. Nodes are pointer
185 /// comparable for equality. The caller is expected to maintain the logical
186 /// consistency of the system.
187 ///
188 /// The InequalityGraph class may invalidate Node*s after any mutator call.
189 /// @brief The InequalityGraph stores the relationships between values.
190 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000191 ETNode *TreeRoot;
192
193 InequalityGraph(); // DO NOT IMPLEMENT
194 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000195 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000196 explicit InequalityGraph(ETNode *TreeRoot) : TreeRoot(TreeRoot) {}
197
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000198 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000199
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000200 /// An Edge is contained inside a Node making one end of the edge implicit
201 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000202 /// value specifying the relationship and an ETNode specifying the root
203 /// in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000204 class VISIBILITY_HIDDEN Edge {
205 public:
206 Edge(unsigned T, LatticeVal V, ETNode *ST)
207 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000208
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000209 unsigned To;
210 LatticeVal LV;
211 ETNode *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000212
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000213 bool operator<(const Edge &edge) const {
214 if (To != edge.To) return To < edge.To;
215 else return OrderByDominance()(Subtree, edge.Subtree);
216 }
217 bool operator<(unsigned to) const {
218 return To < to;
219 }
220 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000221
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000222 /// A single node in the InequalityGraph. This stores the canonical Value
223 /// for the node, as well as the relationships with the neighbours.
224 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000225 /// @brief A single node in the InequalityGraph.
226 class VISIBILITY_HIDDEN Node {
227 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000228
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000229 typedef SmallVector<Edge, 4> RelationsType;
230 RelationsType Relations;
231
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000232 Value *Canonical;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000233
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000234 // TODO: can this idea improve performance?
235 //friend class std::vector<Node>;
236 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
237
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000238 public:
239 typedef RelationsType::iterator iterator;
240 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000241
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000242 Node(Value *V) : Canonical(V) {}
243
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000244 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000245#ifndef NDEBUG
246 public:
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000247 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000248 virtual void dump() const {
249 dump(*cerr.stream());
250 }
251 private:
252 void dump(std::ostream &os) const {
253 os << *getValue() << ":\n";
254 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
255 static const std::string names[32] =
256 { "000000", "000001", "000002", "000003", "000004", "000005",
257 "000006", "000007", "000008", "000009", " >", " >=",
258 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
259 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
260 "000024", "000025", " u>", " u>=", " u<", " u<=",
261 " !=", "000031" };
262 os << " " << names[NI->LV] << " " << NI->To
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000263 << " (" << NI->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000264 }
265 }
266#endif
267
268 public:
269 iterator begin() { return Relations.begin(); }
270 iterator end() { return Relations.end(); }
271 const_iterator begin() const { return Relations.begin(); }
272 const_iterator end() const { return Relations.end(); }
273
274 iterator find(unsigned n, ETNode *Subtree) {
275 iterator E = end();
276 for (iterator I = std::lower_bound(begin(), E, n);
277 I != E && I->To == n; ++I) {
278 if (Subtree->DominatedBy(I->Subtree))
279 return I;
280 }
281 return E;
282 }
283
284 const_iterator find(unsigned n, ETNode *Subtree) const {
285 const_iterator E = end();
286 for (const_iterator I = std::lower_bound(begin(), E, n);
287 I != E && I->To == n; ++I) {
288 if (Subtree->DominatedBy(I->Subtree))
289 return I;
290 }
291 return E;
292 }
293
294 Value *getValue() const
295 {
296 return Canonical;
297 }
298
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000299 /// Updates the lattice value for a given node. Create a new entry if
300 /// one doesn't exist, otherwise it merges the values. The new lattice
301 /// value must not be inconsistent with any previously existing value.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000302 void update(unsigned n, LatticeVal R, ETNode *Subtree) {
303 assert(validPredicate(R) && "Invalid predicate.");
304 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000305 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000306 Edge edge(n, R, Subtree);
307 iterator Insert = std::lower_bound(begin(), end(), edge);
308 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000309 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000310 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
311 assert(validPredicate(LV) && "Invalid union of lattice values.");
312 if (LV != I->LV) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000313 if (Subtree != I->Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000314 assert(Subtree->DominatedBy(I->Subtree) &&
315 "Find returned subtree that doesn't apply.");
316
317 Edge edge(n, R, Subtree);
318 iterator Insert = std::lower_bound(begin(), end(), edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000319 Relations.insert(Insert, edge); // invalidates I
320 I = find(n, Subtree);
321 }
322
323 // Also, we have to tighten any edge that Subtree dominates.
324 for (iterator B = begin(); I->To == n; --I) {
325 if (I->Subtree->DominatedBy(Subtree)) {
326 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
327 assert(validPredicate(LV) && "Invalid union of lattice values.");
328 I->LV = LV;
329 }
330 if (I == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000331 }
332 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000333 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000334 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000335 };
336
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000337 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000338 struct VISIBILITY_HIDDEN NodeMapEdge {
339 Value *V;
340 unsigned index;
341 ETNode *Subtree;
342
343 NodeMapEdge(Value *V, unsigned index, ETNode *Subtree)
344 : V(V), index(index), Subtree(Subtree) {}
345
346 bool operator==(const NodeMapEdge &RHS) const {
347 return V == RHS.V &&
348 Subtree == RHS.Subtree;
349 }
350
351 bool operator<(const NodeMapEdge &RHS) const {
352 if (V != RHS.V) return V < RHS.V;
353 return OrderByDominance()(Subtree, RHS.Subtree);
354 }
355
356 bool operator<(Value *RHS) const {
357 return V < RHS;
358 }
359 };
360
361 typedef std::vector<NodeMapEdge> NodeMapType;
362 NodeMapType NodeMap;
363
364 std::vector<Node> Nodes;
365
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000366 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000367 /// node - returns the node object at a given index retrieved from getNode.
368 /// Index zero is reserved and may not be passed in here. The pointer
369 /// returned is valid until the next call to newNode or getOrInsertNode.
370 Node *node(unsigned index) {
371 assert(index != 0 && "Zero index is reserved for not found.");
372 assert(index <= Nodes.size() && "Index out of range.");
373 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000374 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000375
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000376 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000377 /// node exists.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000378 unsigned getNode(Value *V, ETNode *Subtree) {
379 NodeMapType::iterator E = NodeMap.end();
380 NodeMapEdge Edge(V, 0, Subtree);
381 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
382 while (I != E && I->V == V) {
383 if (Subtree->DominatedBy(I->Subtree))
384 return I->index;
385 ++I;
386 }
387 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000388 }
389
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000390 /// getOrInsertNode - always returns a valid node index, creating a node
391 /// to match the Value if needed.
392 unsigned getOrInsertNode(Value *V, ETNode *Subtree) {
393 if (unsigned n = getNode(V, Subtree))
394 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000395 else
396 return newNode(V);
397 }
398
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000399 /// newNode - creates a new node for a given Value and returns the index.
400 unsigned newNode(Value *V) {
401 Nodes.push_back(Node(V));
402
403 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
404 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
405 "Attempt to create a duplicate Node.");
406 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
407 MapEntry), MapEntry);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000408 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000409 }
410
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000411 /// If the Value is in the graph, return the canonical form. Otherwise,
412 /// return the original Value.
413 Value *canonicalize(Value *V, ETNode *Subtree) {
414 if (isa<Constant>(V)) return V;
415
416 if (unsigned n = getNode(V, Subtree))
417 return node(n)->getValue();
418 else
419 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000420 }
421
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000422 /// isRelatedBy - true iff n1 op n2
423 bool isRelatedBy(unsigned n1, unsigned n2, ETNode *Subtree, LatticeVal LV) {
424 if (n1 == n2) return LV & EQ_BIT;
425
426 Node *N1 = node(n1);
427 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
428 if (I != E) return (I->LV & LV) == I->LV;
429
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000430 return false;
431 }
432
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000433 // The add* methods assume that your input is logically valid and may
434 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000435
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000436 void addEquality(unsigned n, Value *V, ETNode *Subtree) {
437 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
438 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000439
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000440 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
441 // we may already have "%z -> node #2 (%x)" somewhere above us in the
442 // graph. We need to find those edges and add "%z -> node #1 (%y)"
443 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000444
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000445 std::vector<Value *> ToRepoint;
446 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000447
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000448 if (unsigned Conflict = getNode(V, Subtree)) {
Nick Lewycky56639802007-01-29 02:56:54 +0000449 // XXX: NodeMap.size() exceeds 68,000 entries compiling kimwitu++!
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000450 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
451 I != E; ++I) {
452 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
453 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000454 }
455 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000456
457 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
458 VE = ToRepoint.end(); VI != VE; ++VI) {
459 Value *V = *VI;
460
461 // XXX: review this code. This may be doing too many insertions.
462 NodeMapEdge Edge(V, n, Subtree);
463 NodeMapType::iterator E = NodeMap.end();
464 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
465 if (I == E || I->V != V || I->Subtree != Subtree) {
466 // New Value
467 NodeMap.insert(I, Edge);
468 } else if (I != E && I->V == V && I->Subtree == Subtree) {
469 // Update best choice
470 I->index = n;
471 }
472
473#ifndef NDEBUG
474 Node *N = node(n);
475 if (isa<Constant>(V)) {
476 if (isa<Constant>(N->getValue())) {
477 assert(V == N->getValue() && "Constant equals different constant?");
478 }
479 }
480#endif
481 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000482 }
483
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000484 /// addInequality - Sets n1 op n2.
485 /// It is also an error to call this on an inequality that is already true.
486 void addInequality(unsigned n1, unsigned n2, ETNode *Subtree,
487 LatticeVal LV1) {
488 assert(n1 != n2 && "A node can't be inequal to itself.");
489
490 if (LV1 != NE)
491 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
492 "Contradictory inequality.");
493
494 Node *N1 = node(n1);
495 Node *N2 = node(n2);
496
497 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
498 // add %a < %n2 too. This keeps the graph fully connected.
499 if (LV1 != NE) {
500 // Someone with a head for this sort of logic, please review this.
Nick Lewycky56639802007-01-29 02:56:54 +0000501 // Given that %x SLTUGT %y and %a SLE %x, what is the relationship
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000502 // between %a and %y? I believe the below code is correct, but I don't
503 // think it's the most efficient solution.
504
505 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
506 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
507 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
508 if (I->LV != NE && I->To != n2) {
509 ETNode *Local_Subtree = NULL;
510 if (Subtree->DominatedBy(I->Subtree))
511 Local_Subtree = Subtree;
512 else if (I->Subtree->DominatedBy(Subtree))
513 Local_Subtree = I->Subtree;
514
515 if (Local_Subtree) {
516 unsigned new_relationship = 0;
517 LatticeVal ILV = reversePredicate(I->LV);
518 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
519 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
520
521 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
522 new_relationship |= ILV_s;
523
524 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
525 new_relationship |= ILV_u;
526
527 if (new_relationship) {
528 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
529 new_relationship |= (SLT_BIT|SGT_BIT);
530 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
531 new_relationship |= (ULT_BIT|UGT_BIT);
532 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
533 new_relationship |= EQ_BIT;
534
535 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
536
537 node(I->To)->update(n2, NewLV, Local_Subtree);
538 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
539 }
540 }
541 }
542 }
543
544 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
545 if (I->LV != NE && I->To != n1) {
546 ETNode *Local_Subtree = NULL;
547 if (Subtree->DominatedBy(I->Subtree))
548 Local_Subtree = Subtree;
549 else if (I->Subtree->DominatedBy(Subtree))
550 Local_Subtree = I->Subtree;
551
552 if (Local_Subtree) {
553 unsigned new_relationship = 0;
554 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
555 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
556
557 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
558 new_relationship |= ILV_s;
559
560 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
561 new_relationship |= ILV_u;
562
563 if (new_relationship) {
564 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
565 new_relationship |= (SLT_BIT|SGT_BIT);
566 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
567 new_relationship |= (ULT_BIT|UGT_BIT);
568 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
569 new_relationship |= EQ_BIT;
570
571 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
572
573 N1->update(I->To, NewLV, Local_Subtree);
574 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
575 }
576 }
577 }
578 }
579 }
580
581 N1->update(n2, LV1, Subtree);
582 N2->update(n1, reversePredicate(LV1), Subtree);
583 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000584
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000585 /// remove - Removes a Value from the graph. If the value is the canonical
586 /// choice for a Node, destroys the Node from the graph deleting all edges
587 /// to and from it. This method does not renumber the nodes.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000588 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000589 for (unsigned i = 0; i < NodeMap.size();) {
590 NodeMapType::iterator I = NodeMap.begin()+i;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000591 if (I->V == V) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000592 Node *N = node(I->index);
593 if (node(I->index)->getValue() == V) {
594 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI){
595 Node::iterator Iter = node(NI->To)->find(I->index, TreeRoot);
596 do {
597 node(NI->To)->Relations.erase(Iter);
598 Iter = node(NI->To)->find(I->index, TreeRoot);
599 } while (Iter != node(NI->To)->end());
600 }
601 N->Canonical = NULL;
602 }
603 N->Relations.clear();
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000604 NodeMap.erase(I);
605 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000606 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000607 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000608
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000609#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000610 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000611 virtual void dump() {
612 dump(*cerr.stream());
613 }
614
615 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000616 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000617 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000618 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000619 Node *N = node(I->index);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000620 os << *I->V << " == " << I->index
621 << "(" << I->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000622 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000623 os << I->index << ". ";
624 if (!N->getValue()) os << "(deleted node)\n";
625 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000626 }
627 }
628 }
629#endif
630 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000631
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000632 class VRPSolver;
633
634 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
635 /// in the InequalityGraph.
636 class VISIBILITY_HIDDEN ValueRanges {
637
638 /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
639 /// the scope of a rooted subtree in the dominator tree.
640 class VISIBILITY_HIDDEN ScopedRange {
641 public:
642 ScopedRange(Value *V, ConstantRange CR, ETNode *ST)
643 : V(V), CR(CR), Subtree(ST) {}
644
645 Value *V;
646 ConstantRange CR;
647 ETNode *Subtree;
648
649 bool operator<(const ScopedRange &range) const {
650 if (V != range.V) return V < range.V;
651 else return OrderByDominance()(Subtree, range.Subtree);
652 }
653
654 bool operator<(const Value *value) const {
655 return V < value;
656 }
657 };
658
659 std::vector<ScopedRange> Ranges;
660 typedef std::vector<ScopedRange>::iterator iterator;
661
662 // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
663 // intrusive domtree-scoped container is in order?
664
665 iterator begin() { return Ranges.begin(); }
666 iterator end() { return Ranges.end(); }
667
668 iterator find(Value *V, ETNode *Subtree) {
669 iterator E = end();
670 for (iterator I = std::lower_bound(begin(), E, V);
671 I != E && I->V == V; ++I) {
672 if (Subtree->DominatedBy(I->Subtree))
673 return I;
674 }
675 return E;
676 }
677
678 void update(Value *V, ConstantRange CR, ETNode *Subtree) {
679 assert(!CR.isEmptySet() && "Empty ConstantRange!");
680 if (CR.isFullSet()) return;
681
682 iterator I = find(V, Subtree);
683 if (I == end()) {
684 ScopedRange range(V, CR, Subtree);
685 iterator Insert = std::lower_bound(begin(), end(), range);
686 Ranges.insert(Insert, range);
687 } else {
688 CR = CR.intersectWith(I->CR);
689 assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
690
691 if (CR != I->CR) {
692 if (Subtree != I->Subtree) {
693 assert(Subtree->DominatedBy(I->Subtree) &&
694 "Find returned subtree that doesn't apply.");
695
696 ScopedRange range(V, CR, Subtree);
697 iterator Insert = std::lower_bound(begin(), end(), range);
698 Ranges.insert(Insert, range); // invalidates I
699 I = find(V, Subtree);
700 }
701
702 // Also, we have to tighten any edge that Subtree dominates.
703 for (iterator B = begin(); I->V == V; --I) {
704 if (I->Subtree->DominatedBy(Subtree)) {
705 CR = CR.intersectWith(I->CR);
706 assert(!CR.isEmptySet() &&
707 "Empty intersection of ConstantRanges!");
708 I->CR = CR;
709 }
710 if (I == B) break;
711 }
712 }
713 }
714 }
715
716 /// range - Creates a ConstantRange representing the set of all values
717 /// that match the ICmpInst::Predicate with any of the values in CR.
718 ConstantRange range(ICmpInst::Predicate ICmpOpcode,
719 const ConstantRange &CR) {
720 uint32_t W = CR.getBitWidth();
721 switch (ICmpOpcode) {
722 default: assert(!"Invalid ICmp opcode to range()");
723 case ICmpInst::ICMP_EQ:
724 return ConstantRange(CR.getLower(), CR.getUpper());
725 case ICmpInst::ICMP_NE:
726 if (CR.isSingleElement())
727 return ConstantRange(CR.getUpper(), CR.getLower());
728 return ConstantRange(W);
729 case ICmpInst::ICMP_ULT:
730 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
731 case ICmpInst::ICMP_SLT:
732 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
733 case ICmpInst::ICMP_ULE: {
734 APInt UMax = CR.getUnsignedMax();
735 if (UMax == APInt::getMaxValue(W))
736 return ConstantRange(W);
737 return ConstantRange(APInt::getMinValue(W), UMax + 1);
738 }
739 case ICmpInst::ICMP_SLE: {
740 APInt SMax = CR.getSignedMax();
741 if (SMax == APInt::getSignedMaxValue(W) ||
742 SMax + 1 == APInt::getSignedMaxValue(W))
743 return ConstantRange(W);
744 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
745 }
746 case ICmpInst::ICMP_UGT:
747 return ConstantRange(CR.getUnsignedMin() + 1,
748 APInt::getMaxValue(W) + 1);
749 case ICmpInst::ICMP_SGT:
750 return ConstantRange(CR.getSignedMin() + 1,
751 APInt::getSignedMaxValue(W) + 1);
752 case ICmpInst::ICMP_UGE: {
753 APInt UMin = CR.getUnsignedMin();
754 if (UMin == APInt::getMinValue(W))
755 return ConstantRange(W);
756 return ConstantRange(UMin, APInt::getMaxValue(W) + 1);
757 }
758 case ICmpInst::ICMP_SGE: {
759 APInt SMin = CR.getSignedMin();
760 if (SMin == APInt::getSignedMinValue(W))
761 return ConstantRange(W);
762 return ConstantRange(SMin, APInt::getSignedMaxValue(W) + 1);
763 }
764 }
765 }
766
767 /// create - Creates a ConstantRange that matches the given LatticeVal
768 /// relation with a given integer.
769 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
770 assert(!CR.isEmptySet() && "Can't deal with empty set.");
771
772 if (LV == NE)
773 return range(ICmpInst::ICMP_NE, CR);
774
775 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
776 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
777 bool hasEQ = LV & EQ_BIT;
778
779 ConstantRange Range(CR.getBitWidth());
780
781 if (LV_s == SGT_BIT) {
782 Range = Range.intersectWith(range(
783 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
784 } else if (LV_s == SLT_BIT) {
785 Range = Range.intersectWith(range(
786 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
787 }
788
789 if (LV_u == UGT_BIT) {
790 Range = Range.intersectWith(range(
791 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
792 } else if (LV_u == ULT_BIT) {
793 Range = Range.intersectWith(range(
794 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
795 }
796
797 return Range;
798 }
799
800 ConstantRange rangeFromValue(Value *V, ETNode *Subtree, uint32_t W) {
801 ConstantInt *C = dyn_cast<ConstantInt>(V);
802 if (C) {
803 return ConstantRange(C->getValue());
804 } else {
805 iterator I = find(V, Subtree);
806 if (I != end())
807 return I->CR;
808 }
809 return ConstantRange(W);
810 }
811
812 static uint32_t widthOfValue(Value *V) {
813 const Type *Ty = V->getType();
814 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
815 return ITy->getBitWidth();
816
817 // XXX: I'd like to transform T* into the appropriate integer by
818 // bit length, however that data may not be available.
819
820 return 0;
821 }
822
823 public:
824
825 bool isRelatedBy(Value *V1, Value *V2, ETNode *Subtree, LatticeVal LV) {
826 uint32_t W = widthOfValue(V1);
827 if (!W) return false;
828
829 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
830 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
831
832 // True iff all values in CR1 are LV to all values in CR2.
833 switch(LV) {
834 default: assert(!"Impossible lattice value!");
835 case NE:
836 return CR1.intersectWith(CR2).isEmptySet();
837 case ULT:
838 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
839 case ULE:
840 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
841 case UGT:
842 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
843 case UGE:
844 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
845 case SLT:
846 return CR1.getSignedMax().slt(CR2.getSignedMin());
847 case SLE:
848 return CR1.getSignedMax().sle(CR2.getSignedMin());
849 case SGT:
850 return CR1.getSignedMin().sgt(CR2.getSignedMax());
851 case SGE:
852 return CR1.getSignedMin().sge(CR2.getSignedMax());
853 case LT:
854 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
855 CR1.getSignedMax().slt(CR2.getUnsignedMin());
856 case LE:
857 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
858 CR1.getSignedMax().sle(CR2.getUnsignedMin());
859 case GT:
860 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
861 CR1.getSignedMin().sgt(CR2.getSignedMax());
862 case GE:
863 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
864 CR1.getSignedMin().sge(CR2.getSignedMax());
865 case SLTUGT:
866 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
867 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
868 case SLEUGE:
869 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
870 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
871 case SGTULT:
872 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
873 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
874 case SGEULE:
875 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
876 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
877 }
878 }
879
880 void addToWorklist(Value *V, const APInt *I, ICmpInst::Predicate Pred,
881 VRPSolver *VRP);
882
883 void addInequality(Value *V1, Value *V2, ETNode *Subtree, LatticeVal LV,
884 VRPSolver *VRP) {
885 assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
886
887 if (LV == NE) return; // we can't represent those.
888 // XXX: except in the case where isSingleElement and equal to either
889 // Lower or Upper. That's probably not profitable. (Type::Int1Ty?)
890
891 uint32_t W = widthOfValue(V1);
892 if (!W) return;
893
894 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
895 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
896
897 if (!CR1.isSingleElement()) {
898 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
899 if (NewCR1 != CR1) {
900 if (NewCR1.isSingleElement())
901 addToWorklist(V1, NewCR1.getSingleElement(),
902 ICmpInst::ICMP_EQ, VRP);
903 else
904 update(V1, NewCR1, Subtree);
905 }
906 }
907
908 if (!CR2.isSingleElement()) {
909 ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
910 CR1));
911 if (NewCR2 != CR2) {
912 if (NewCR2.isSingleElement())
913 addToWorklist(V2, NewCR2.getSingleElement(),
914 ICmpInst::ICMP_EQ, VRP);
915 else
916 update(V2, NewCR2, Subtree);
917 }
918 }
919 }
920 };
921
922
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000923 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
924 /// another discovered to be unreachable. This is used to cull the graph when
925 /// analyzing instructions, and to mark blocks with the "unreachable"
926 /// terminator instruction after the function has executed.
927 class VISIBILITY_HIDDEN UnreachableBlocks {
928 private:
929 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000930
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000931 public:
932 /// mark - mark a block as dead
933 void mark(BasicBlock *BB) {
934 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
935 std::vector<BasicBlock *>::iterator I =
936 std::lower_bound(DeadBlocks.begin(), E, BB);
937
938 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000939 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000940
941 /// isDead - returns whether a block is known to be dead already
942 bool isDead(BasicBlock *BB) {
943 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
944 std::vector<BasicBlock *>::iterator I =
945 std::lower_bound(DeadBlocks.begin(), E, BB);
946
947 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000948 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000949
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000950 /// kill - replace the dead blocks' terminator with an UnreachableInst.
951 bool kill() {
952 bool modified = false;
953 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
954 E = DeadBlocks.end(); I != E; ++I) {
955 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000956
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000957 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000958
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000959 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
960 SI != SE; ++SI) {
961 BasicBlock *Succ = *SI;
962 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +0000963 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000964
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000965 TerminatorInst *TI = BB->getTerminator();
966 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
967 TI->eraseFromParent();
968 new UnreachableInst(BB);
969 ++NumBlocks;
970 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000971 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000972 DeadBlocks.clear();
973 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000974 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000975 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000976
977 /// VRPSolver keeps track of how changes to one variable affect other
978 /// variables, and forwards changes along to the InequalityGraph. It
979 /// also maintains the correct choice for "canonical" in the IG.
980 /// @brief VRPSolver calculates inferences from a new relationship.
981 class VISIBILITY_HIDDEN VRPSolver {
982 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000983 friend class ValueRanges;
984
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000985 struct Operation {
986 Value *LHS, *RHS;
987 ICmpInst::Predicate Op;
988
Nick Lewycky42944462007-01-13 02:05:28 +0000989 BasicBlock *ContextBB;
990 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000991 };
992 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000993
994 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000995 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000996 ValueRanges &VR;
997
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000998 ETForest *Forest;
999 ETNode *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001000 BasicBlock *TopBB;
1001 Instruction *TopInst;
1002 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001003
1004 typedef InequalityGraph::Node Node;
1005
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001006 /// IdomI - Determines whether one Instruction dominates another.
1007 bool IdomI(Instruction *I1, Instruction *I2) const {
1008 BasicBlock *BB1 = I1->getParent(),
1009 *BB2 = I2->getParent();
1010 if (BB1 == BB2) {
1011 if (isa<TerminatorInst>(I1)) return false;
1012 if (isa<TerminatorInst>(I2)) return true;
1013 if (isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
1014 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
1015
1016 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
1017 I != E; ++I) {
1018 if (&*I == I1) return true;
1019 if (&*I == I2) return false;
1020 }
1021 assert(!"Instructions not found in parent BasicBlock?");
1022 } else {
1023 return Forest->properlyDominates(BB1, BB2);
1024 }
1025 return false;
1026 }
1027
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001028 /// Returns true if V1 is a better canonical value than V2.
1029 bool compare(Value *V1, Value *V2) const {
1030 if (isa<Constant>(V1))
1031 return !isa<Constant>(V2);
1032 else if (isa<Constant>(V2))
1033 return false;
1034 else if (isa<Argument>(V1))
1035 return !isa<Argument>(V2);
1036 else if (isa<Argument>(V2))
1037 return false;
1038
1039 Instruction *I1 = dyn_cast<Instruction>(V1);
1040 Instruction *I2 = dyn_cast<Instruction>(V2);
1041
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001042 if (!I1 || !I2)
1043 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001044
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001045 return IdomI(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001046 }
1047
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001048 // below - true if the Instruction is dominated by the current context
1049 // block or instruction
1050 bool below(Instruction *I) {
1051 if (TopInst)
1052 return IdomI(TopInst, I);
1053 else {
1054 ETNode *Node = Forest->getNodeForBlock(I->getParent());
Nick Lewycky56639802007-01-29 02:56:54 +00001055 return Node->DominatedBy(Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001056 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001057 }
1058
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001059 bool makeEqual(Value *V1, Value *V2) {
1060 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001061
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001062 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001063
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001064 if (isa<Constant>(V1) && isa<Constant>(V2))
1065 return false;
1066
1067 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
1068
1069 if (n1 && n2) {
1070 if (n1 == n2) return true;
1071 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1072 }
1073
1074 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
1075 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
1076
Nick Lewycky15245952007-02-04 23:43:05 +00001077 assert(!compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001078
1079 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1080
1081 SetVector<unsigned> Remove;
1082 if (n2) Remove.insert(n2);
1083
1084 if (n1 && n2) {
1085 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1086 // We can't just merge %x and %y because the relationship with %z would
1087 // be EQ and that's invalid. What we're doing is looking for any nodes
1088 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001089
1090 Node *N1 = IG.node(n1);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001091 Node *N2 = IG.node(n2);
1092 Node::iterator end = N2->end();
1093
1094 // Find the intersection between N1 and N2 which is dominated by
1095 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1096 // Remove.
1097 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
1098 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1099
1100 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1101 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1102 Node::iterator NI = N2->find(I->To, Top);
1103 if (NI != end) {
1104 LatticeVal NILV = reversePredicate(NI->LV);
1105 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1106 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1107
1108 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1109 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1110 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001111 }
1112 }
1113
1114 // See if one of the nodes about to be removed is actually a better
1115 // canonical choice than n1.
1116 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001117 SetVector<unsigned>::iterator DontRemove = Remove.end();
1118 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001119 E = Remove.end(); I != E; ++I) {
1120 unsigned n = *I;
1121 Value *V = IG.node(n)->getValue();
1122 if (compare(V, V1)) {
1123 V1 = V;
1124 n1 = n;
1125 DontRemove = I;
1126 }
1127 }
1128 if (DontRemove != Remove.end()) {
1129 unsigned n = *DontRemove;
1130 Remove.remove(n);
1131 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001132 }
1133 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001134
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001135 // We'd like to allow makeEqual on two values to perform a simple
1136 // substitution without every creating nodes in the IG whenever possible.
1137 //
1138 // The first iteration through this loop operates on V2 before going
1139 // through the Remove list and operating on those too. If all of the
1140 // iterations performed simple replacements then we exit early.
1141 bool exitEarly = true;
1142 unsigned i = 0;
1143 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1144 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1145
1146 // Try to replace the whole instruction. If we can, we're done.
1147 Instruction *I2 = dyn_cast<Instruction>(R);
1148 if (I2 && below(I2)) {
1149 std::vector<Instruction *> ToNotify;
1150 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1151 UI != UE;) {
1152 Use &TheUse = UI.getUse();
1153 ++UI;
1154 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1155 ToNotify.push_back(I);
1156 }
1157
1158 DOUT << "Simply removing " << *I2
1159 << ", replacing with " << *V1 << "\n";
1160 I2->replaceAllUsesWith(V1);
1161 // leave it dead; it'll get erased later.
1162 ++NumInstruction;
1163 modified = true;
1164
1165 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1166 IE = ToNotify.end(); II != IE; ++II) {
1167 opsToDef(*II);
1168 }
1169
1170 continue;
1171 }
1172
1173 // Otherwise, replace all dominated uses.
1174 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1175 UI != UE;) {
1176 Use &TheUse = UI.getUse();
1177 ++UI;
1178 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1179 if (below(I)) {
1180 TheUse.set(V1);
1181 modified = true;
1182 ++NumVarsReplaced;
1183 opsToDef(I);
1184 }
1185 }
1186 }
1187
1188 // If that killed the instruction, stop here.
1189 if (I2 && isInstructionTriviallyDead(I2)) {
1190 DOUT << "Killed all uses of " << *I2
1191 << ", replacing with " << *V1 << "\n";
1192 continue;
1193 }
1194
1195 // If we make it to here, then we will need to create a node for N1.
1196 // Otherwise, we can skip out early!
1197 exitEarly = false;
1198 }
1199
1200 if (exitEarly) return true;
1201
1202 // Create N1.
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001203 if (!n1) n1 = IG.newNode(V1);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001204
1205 // Migrate relationships from removed nodes to N1.
1206 Node *N1 = IG.node(n1);
Reid Spencera8a15472007-01-17 02:23:37 +00001207 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001208 I != E; ++I) {
1209 unsigned n = *I;
1210 Node *N = IG.node(n);
1211 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
Nick Lewycky56639802007-01-29 02:56:54 +00001212 if (NI->Subtree->DominatedBy(Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001213 if (NI->To == n1) {
1214 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1215 continue;
1216 }
1217 if (Remove.count(NI->To))
1218 continue;
1219
1220 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1221 N1->update(NI->To, NI->LV, Top);
1222 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001223 }
1224 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001225
1226 // Point V2 (and all items in Remove) to N1.
1227 if (!n2)
1228 IG.addEquality(n1, V2, Top);
1229 else {
Reid Spencera8a15472007-01-17 02:23:37 +00001230 for (SetVector<unsigned>::iterator I = Remove.begin(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001231 E = Remove.end(); I != E; ++I) {
1232 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
1233 }
1234 }
1235
1236 // If !Remove.empty() then V2 = Remove[0]->getValue().
1237 // Even when Remove is empty, we still want to process V2.
1238 i = 0;
1239 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1240 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1241
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001242 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1243 if (below(I2) ||
1244 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1245 defToOps(I2);
1246 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001247 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1248 UI != UE;) {
1249 Use &TheUse = UI.getUse();
1250 ++UI;
1251 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001252 if (below(I) ||
1253 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1254 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001255 }
1256 }
1257 }
1258
1259 return true;
1260 }
1261
1262 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1263 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1264 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1265 switch (Pred) {
1266 case ICmpInst::ICMP_EQ:
1267 assert(!"No matching lattice value.");
1268 return static_cast<LatticeVal>(EQ_BIT);
1269 default:
1270 assert(!"Invalid 'icmp' predicate.");
1271 case ICmpInst::ICMP_NE:
1272 return NE;
1273 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001274 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001275 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001276 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001277 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001278 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001279 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001280 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001281 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001282 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001283 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001284 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001285 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001286 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001287 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001288 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001289 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001290 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001291
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001292 public:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001293 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
1294 ETForest *Forest, bool &modified, BasicBlock *TopBB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001295 : IG(IG),
1296 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001297 VR(VR),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001298 Forest(Forest),
1299 Top(Forest->getNodeForBlock(TopBB)),
1300 TopBB(TopBB),
1301 TopInst(NULL),
1302 modified(modified) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +00001303
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001304 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
1305 ETForest *Forest, bool &modified, Instruction *TopInst)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001306 : IG(IG),
1307 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001308 VR(VR),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001309 Forest(Forest),
1310 TopInst(TopInst),
1311 modified(modified)
1312 {
1313 TopBB = TopInst->getParent();
1314 Top = Forest->getNodeForBlock(TopBB);
1315 }
1316
1317 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1318 if (Constant *C1 = dyn_cast<Constant>(V1))
1319 if (Constant *C2 = dyn_cast<Constant>(V2))
1320 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001321 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001322
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001323 if (unsigned n1 = IG.getNode(V1, Top))
1324 if (unsigned n2 = IG.getNode(V2, Top)) {
1325 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1326 Pred == ICmpInst::ICMP_ULE ||
1327 Pred == ICmpInst::ICMP_UGE ||
1328 Pred == ICmpInst::ICMP_SLE ||
1329 Pred == ICmpInst::ICMP_SGE;
1330 if (Pred == ICmpInst::ICMP_EQ) return false;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001331 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001332 }
1333
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001334 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1335 return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001336 }
1337
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001338 /// add - adds a new property to the work queue
1339 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1340 Instruction *I = NULL) {
1341 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1342 if (I) DOUT << " context: " << *I;
1343 else DOUT << " default context";
1344 DOUT << "\n";
1345
1346 WorkList.push_back(Operation());
1347 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001348 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1349 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001350 }
1351
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001352 /// defToOps - Given an instruction definition that we've learned something
1353 /// new about, find any new relationships between its operands.
1354 void defToOps(Instruction *I) {
1355 Instruction *NewContext = below(I) ? I : TopInst;
1356 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001357
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1359 const Type *Ty = BO->getType();
1360 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001361
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001362 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1363 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001364
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001365 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001366
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001367 switch (BO->getOpcode()) {
1368 case Instruction::And: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001369 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001370 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001371 if (Canonical == CI) {
1372 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1373 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001374 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001375 } break;
1376 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001377 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001378 Constant *Zero = Constant::getNullValue(Ty);
1379 if (Canonical == Zero) {
1380 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1381 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1382 }
1383 } break;
1384 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001385 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1386 // "xor i32 %c, %a" EQ %c then %a EQ 0
1387 // "xor i32 %c, %a" NE %c then %a NE 0
1388 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001389 Value *LHS = Op0;
1390 Value *RHS = Op1;
1391 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1392
Nick Lewycky4a74a752007-01-12 00:02:12 +00001393 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1394 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001395 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001396 ICmpInst::ICMP_EQ, NewContext);
1397 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001398 }
1399 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001400 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001401 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1402 NewContext);
1403 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1404 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1405 NewContext);
1406 }
1407 } break;
1408 default:
1409 break;
1410 }
1411 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001412 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001413 // etc.
1414
Zhou Sheng75b871f2007-01-11 12:24:14 +00001415 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001416 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1417 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001418 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001419 add(IC->getOperand(0), IC->getOperand(1),
1420 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1421 }
1422 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1423 if (I->getType()->isFPOrFPVector()) return;
1424
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001425 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001426 // %a EQ %b and %b NE %c then %x EQ true
1427 // %a EQ %c and %b NE %c then %x EQ false
1428
1429 Value *True = SI->getTrueValue();
1430 Value *False = SI->getFalseValue();
1431 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1432 if (Canonical == IG.canonicalize(True, Top) ||
1433 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001434 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001435 ICmpInst::ICMP_EQ, NewContext);
1436 else if (Canonical == IG.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001437 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001438 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001439 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001440 }
1441 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001442 // TODO: CastInst "%a = cast ... %b" where %a is EQ or NE a constant.
1443 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001444
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001445 /// opsToDef - A new relationship was discovered involving one of this
1446 /// instruction's operands. Find any new relationship involving the
1447 /// definition.
1448 void opsToDef(Instruction *I) {
1449 Instruction *NewContext = below(I) ? I : TopInst;
1450
1451 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1452 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1453 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1454
Zhou Sheng75b871f2007-01-11 12:24:14 +00001455 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1456 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001457 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1458 ICmpInst::ICMP_EQ, NewContext);
1459 return;
1460 }
1461
1462 // "%y = and bool true, %x" then %x EQ %y.
1463 // "%y = or bool false, %x" then %x EQ %y.
1464 if (BO->getOpcode() == Instruction::Or) {
1465 Constant *Zero = Constant::getNullValue(BO->getType());
1466 if (Op0 == Zero) {
1467 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1468 return;
1469 } else if (Op1 == Zero) {
1470 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1471 return;
1472 }
1473 } else if (BO->getOpcode() == Instruction::And) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001474 Constant *AllOnes = ConstantInt::getAllOnesValue(BO->getType());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001475 if (Op0 == AllOnes) {
1476 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1477 return;
1478 } else if (Op1 == AllOnes) {
1479 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1480 return;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001481 }
1482 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001483
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001484 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
1485 // "%x = mul i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001486 // 1. Repeat all of the above, with order of operands reversed.
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001487 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001488
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001489 Value *Known = Op0, *Unknown = Op1;
1490 if (Known != BO) std::swap(Known, Unknown);
1491 if (Known == BO) {
1492 const Type *Ty = BO->getType();
1493 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001494
1495 switch (BO->getOpcode()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001496 default: break;
1497 case Instruction::Xor:
1498 case Instruction::Or:
1499 case Instruction::Add:
1500 case Instruction::Sub:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001501 add(Unknown, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1502 NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001503 break;
1504 case Instruction::UDiv:
1505 case Instruction::SDiv:
1506 if (Unknown == Op0) break; // otherwise, fallthrough
1507 case Instruction::And:
1508 case Instruction::Mul:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001509 if (isa<ConstantInt>(Unknown)) {
1510 Constant *One = ConstantInt::get(Ty, 1);
1511 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1512 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001513 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001514 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001515 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001516
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001517 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001518
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001519 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001520 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
1521 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001522 // etc.
1523
1524 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1525 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1526
1527 ICmpInst::Predicate Pred = IC->getPredicate();
1528 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001529 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001530 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001531 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001532 }
1533
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001534 // TODO: "i1 %x s<u> %y" implies %x = true and %y = false.
Nick Lewycky4a74a752007-01-12 00:02:12 +00001535
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001536 // TODO: make the predicate more strict, if possible.
1537
1538 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1539 // Given: "%a = select bool %x, int %b, int %c"
1540 // %x EQ true then %a EQ %b
1541 // %x EQ false then %a EQ %c
1542 // %b EQ %c then %a EQ %b
1543
1544 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001545 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001546 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001547 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001548 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1549 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1550 IG.canonicalize(SI->getFalseValue(), Top)) {
1551 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1552 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001553 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001554 const Type *Ty = CI->getDestTy();
1555 if (Ty->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001556
1557 if (Constant *C = dyn_cast<Constant>(
1558 IG.canonicalize(CI->getOperand(0), Top))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001559 add(CI, ConstantExpr::getCast(CI->getOpcode(), C, Ty),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001560 ICmpInst::ICMP_EQ, NewContext);
1561 }
1562
1563 // TODO: "%a = cast ... %b" where %b is NE/LT/GT a constant.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001564 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001565 }
1566
1567 /// solve - process the work queue
1568 /// Return false if a logical contradiction occurs.
1569 void solve() {
1570 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
1571 while (!WorkList.empty()) {
1572 //DOUT << "WorkList size: " << WorkList.size() << "\n";
1573
1574 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00001575 TopInst = O.ContextInst;
1576 TopBB = O.ContextBB;
1577 Top = Forest->getNodeForBlock(TopBB);
1578
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001579 O.LHS = IG.canonicalize(O.LHS, Top);
1580 O.RHS = IG.canonicalize(O.RHS, Top);
1581
1582 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
1583 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
1584
1585 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00001586 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
1587 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001588 DOUT << "\n";
1589
1590 DEBUG(IG.dump());
1591
Nick Lewycky15245952007-02-04 23:43:05 +00001592 // If they're both Constant, skip it. Check for contradiction and mark
1593 // the BB as unreachable if so.
1594 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
1595 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
1596 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
1597 ConstantInt::getFalse())
1598 UB.mark(TopBB);
1599
1600 WorkList.pop_front();
1601 continue;
1602 }
1603 }
1604
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001605 if (compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00001606 std::swap(O.LHS, O.RHS);
1607 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001608 }
1609
1610 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001611 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001612 UB.mark(TopBB);
1613 } else {
1614 LatticeVal LV = cmpInstToLattice(O.Op);
1615
1616 if ((LV & EQ_BIT) &&
1617 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001618 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001619 UB.mark(TopBB);
1620 } else {
1621 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00001622 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001623 WorkList.pop_front();
1624 continue;
1625 }
1626
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001627 unsigned n1 = IG.getNode(O.LHS, Top);
1628 unsigned n2 = IG.getNode(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001629
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001630 if (n1 && n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001631 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
1632 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
1633 UB.mark(TopBB);
1634
1635 WorkList.pop_front();
1636 continue;
1637 }
1638
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001639 if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
1640 (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001641 WorkList.pop_front();
1642 continue;
1643 }
1644
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001645 VR.addInequality(O.LHS, O.RHS, Top, LV, this);
1646 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
1647 LV == NE) {
1648 if (!n1) n1 = IG.newNode(O.LHS);
1649 if (!n2) n2 = IG.newNode(O.RHS);
1650 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00001651 }
1652
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001653 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
1654 if (below(I1) ||
1655 Top->DominatedBy(Forest->getNodeForBlock(I1->getParent())))
1656 defToOps(I1);
1657 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001658 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
1659 for (Value::use_iterator UI = O.LHS->use_begin(),
1660 UE = O.LHS->use_end(); UI != UE;) {
1661 Use &TheUse = UI.getUse();
1662 ++UI;
1663 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001664 if (below(I) ||
1665 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1666 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001667 }
1668 }
1669 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001670 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
1671 if (below(I2) ||
1672 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1673 defToOps(I2);
1674 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001675 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
1676 for (Value::use_iterator UI = O.RHS->use_begin(),
1677 UE = O.RHS->use_end(); UI != UE;) {
1678 Use &TheUse = UI.getUse();
1679 ++UI;
1680 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001681 if (below(I) ||
1682 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1683
1684 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001685 }
1686 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001687 }
1688 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001689 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001690 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00001691 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001692 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001693 };
1694
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001695 void ValueRanges::addToWorklist(Value *V, const APInt *I,
1696 ICmpInst::Predicate Pred, VRPSolver *VRP) {
1697 VRP->add(V, ConstantInt::get(*I), Pred, VRP->TopInst);
1698 }
1699
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001700 /// PredicateSimplifier - This class is a simplifier that replaces
1701 /// one equivalent variable with another. It also tracks what
1702 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001703 /// @brief Root of the predicate simplifier optimization.
1704 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1705 DominatorTree *DT;
1706 ETForest *Forest;
1707 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001708 InequalityGraph *IG;
1709 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001710 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001711
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001712 std::vector<DominatorTree::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001713
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001714 public:
1715 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001716
1717 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1718 AU.addRequiredID(BreakCriticalEdgesID);
1719 AU.addRequired<DominatorTree>();
1720 AU.addRequired<ETForest>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001721 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001722
1723 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001724 /// Forwards - Adds new properties into PropertySet and uses them to
1725 /// simplify instructions. Because new properties sometimes apply to
1726 /// a transition from one BasicBlock to another, this will use the
1727 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1728 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001729 /// @brief Performs abstract execution of the program.
1730 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001731 friend class InstVisitor<Forwards>;
1732 PredicateSimplifier *PS;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001733 DominatorTree::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001734
Nick Lewycky77e030b2006-10-12 02:02:44 +00001735 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001736 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001737 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001738 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001739
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001740 Forwards(PredicateSimplifier *PS, DominatorTree::Node *DTNode)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001741 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB), VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001742
1743 void visitTerminatorInst(TerminatorInst &TI);
1744 void visitBranchInst(BranchInst &BI);
1745 void visitSwitchInst(SwitchInst &SI);
1746
Nick Lewyckyf3450082006-10-22 19:53:27 +00001747 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001748 void visitLoadInst(LoadInst &LI);
1749 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001750
Nick Lewycky15245952007-02-04 23:43:05 +00001751 void visitSExtInst(SExtInst &SI);
1752 void visitZExtInst(ZExtInst &ZI);
1753
Nick Lewycky77e030b2006-10-12 02:02:44 +00001754 void visitBinaryOperator(BinaryOperator &BO);
1755 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001756
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001757 // Used by terminator instructions to proceed from the current basic
1758 // block to the next. Verifies that "current" dominates "next",
1759 // then calls visitBasicBlock.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001760 void proceedToSuccessors(DominatorTree::Node *Current) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001761 for (DominatorTree::Node::iterator I = Current->begin(),
1762 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001763 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001764 }
1765 }
1766
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001767 void proceedToSuccessor(DominatorTree::Node *Next) {
1768 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001769 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001770
1771 // Visits each instruction in the basic block.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001772 void visitBasicBlock(DominatorTree::Node *Node) {
1773 BasicBlock *BB = Node->getBlock();
1774 ETNode *ET = Forest->getNodeForBlock(BB);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001775 DOUT << "Entering Basic Block: " << BB->getName()
1776 << " (" << ET->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00001777 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001778 visitInstruction(I++, Node, ET);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001779 }
1780 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001781
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001782 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001783 // the PropertySet.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001784 void visitInstruction(Instruction *I, DominatorTree::Node *DT, ETNode *ET) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001785 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001786 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001787
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001788 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001789 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001790 ++NumSimple;
1791 modified = true;
1792 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001793 I->eraseFromParent();
1794 return;
1795 }
1796
Nick Lewycky42944462007-01-13 02:05:28 +00001797#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001798 // Try to replace the whole instruction.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001799 Value *V = IG->canonicalize(I, ET);
1800 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001801 if (V != I) {
1802 modified = true;
1803 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00001804 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001805 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001806 I->replaceAllUsesWith(V);
1807 I->eraseFromParent();
1808 return;
1809 }
1810
1811 // Try to substitute operands.
1812 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1813 Value *Oper = I->getOperand(i);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001814 Value *V = IG->canonicalize(Oper, ET);
1815 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001816 if (V != Oper) {
1817 modified = true;
1818 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00001819 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001820 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00001821 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001822 }
1823 }
Nick Lewycky42944462007-01-13 02:05:28 +00001824#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001825
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001826 DOUT << "push (%" << I->getParent()->getName() << ")\n";
1827 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001828 visit.visit(*I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001829 DOUT << "pop (%" << I->getParent()->getName() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001830 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001831 };
1832
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001833 bool PredicateSimplifier::runOnFunction(Function &F) {
1834 DT = &getAnalysis<DominatorTree>();
1835 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001836
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001837 Forest->updateDFSNumbers(); // XXX: should only act when numbers are out of date
1838
Bill Wendling22e978a2006-12-07 20:04:42 +00001839 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001840
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001841 modified = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001842 BasicBlock *RootBlock = &F.getEntryBlock();
1843 IG = new InequalityGraph(Forest->getNodeForBlock(RootBlock));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001844 VR = new ValueRanges();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001845 WorkList.push_back(DT->getRootNode());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001846
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001847 do {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001848 DominatorTree::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001849 WorkList.pop_back();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001850 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001851 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001852
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001853 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001854 delete IG;
1855
1856 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001857
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001858 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00001859 }
1860
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001861 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001862 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001863 }
1864
1865 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001866 if (BI.isUnconditional()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001867 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001868 return;
1869 }
1870
1871 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001872 BasicBlock *TrueDest = BI.getSuccessor(0);
1873 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001874
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001875 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
1876 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001877 return;
1878 }
1879
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001880 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001881 I != E; ++I) {
1882 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001883 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001884 << "(" << PS->Forest->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001885
1886 if (Dest == TrueDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001887 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001888 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001889 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001890 VRP.solve();
1891 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001892 } else if (Dest == FalseDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001893 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001894 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001895 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001896 VRP.solve();
1897 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001898 }
1899
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001900 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001901 }
1902 }
1903
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001904 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
1905 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001906
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001907 // Set the EQProperty in each of the cases BBs, and the NEProperties
1908 // in the default BB.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001909
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001910 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001911 I != E; ++I) {
1912 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001913 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001914 << "(" << PS->Forest->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001915
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001916 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001917 if (BB == SI.getDefaultDest()) {
1918 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
1919 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001920 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
1921 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001922 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001923 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
1924 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001925 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001926 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00001927 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001928 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001929
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001930 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001931 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001932 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001933 VRP.solve();
1934 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00001935
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001936 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
1937 Value *Ptr = LI.getPointerOperand();
1938 // avoid "load uint* null" -> null NE null.
1939 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001940
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001941 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001942 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001943 VRP.solve();
1944 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001945
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001946 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
1947 Value *Ptr = SI.getPointerOperand();
1948 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001949
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001950 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001951 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001952 VRP.solve();
1953 }
1954
Nick Lewycky15245952007-02-04 23:43:05 +00001955 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001956 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00001957 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
1958 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
1959 APInt Min(APInt::getSignedMinValue(SrcBitWidth));
1960 APInt Max(APInt::getSignedMaxValue(SrcBitWidth));
1961 Min.sext(DstBitWidth);
1962 Max.sext(DstBitWidth);
1963 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
1964 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00001965 VRP.solve();
1966 }
1967
1968 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001969 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00001970 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
1971 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
1972 APInt Max(APInt::getMaxValue(SrcBitWidth));
1973 Max.zext(DstBitWidth);
1974 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00001975 VRP.solve();
1976 }
1977
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001978 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
1979 Instruction::BinaryOps ops = BO.getOpcode();
1980
1981 switch (ops) {
Nick Lewycky15245952007-02-04 23:43:05 +00001982 case Instruction::URem:
1983 case Instruction::SRem:
1984 case Instruction::UDiv:
1985 case Instruction::SDiv: {
1986 Value *Divisor = BO.getOperand(1);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001987 VRPSolver VRP(IG, UB, VR, PS->Forest, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00001988 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
1989 ICmpInst::ICMP_NE);
1990 VRP.solve();
1991 break;
1992 }
1993 default:
1994 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001995 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001996 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001997
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001998 RegisterPass<PredicateSimplifier> X("predsimplify",
1999 "Predicate Simplifier");
2000}
2001
2002FunctionPass *llvm::createPredicateSimplifierPass() {
2003 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002004}