blob: 81a22309b1e8426d869f1ac2510262e8426ae5a3 [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
32// is how EQ relationships are stored; the map contains pointers to the
33// same node. The node contains a most canonical Value* form and the list of
34// known relationships.
35//
36// If two nodes are known to be inequal, then they will contain pointers to
37// each other with an "NE" relationship. If node getNode(%x) is less than
38// getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39// <%x, LT>. This allows us to tie nodes together into a graph like this:
40//
41// %a < %b < %c < %d
42//
43// with four nodes representing the properties. The InequalityGraph provides
44// queries (such as "isEqual") and mutators (such as "addEqual"). To implement
45// "isLess(%a, %c)", we start with getNode(%c) and walk downwards until
46// we reach %a or the leaf node. Note that the graph is directed and acyclic,
47// but may contain joins, meaning that this walk is not a linear time
48// algorithm.
49//
50// To create these properties, we wait until a branch or switch instruction
51// implies that a particular value is true (or false). The VRPSolver is
52// responsible for analyzing the variable and seeing what new inferences
53// can be made from each property. For example:
54//
55// %P = seteq int* %ptr, null
56// %a = or bool %P, %Q
57// br bool %a label %cond_true, label %cond_false
58//
59// For the true branch, the VRPSolver will start with %a EQ true and look at
60// the definition of %a and find that it can infer that %P and %Q are both
61// true. From %P being true, it can infer that %ptr NE null. For the false
62// branch it can't infer anything from the "or" instruction.
63//
64// Besides branches, we can also infer properties from instruction that may
65// have undefined behaviour in certain cases. For example, the dividend of
66// a division may never be zero. After the division instruction, we may assume
67// that the dividend is not equal to zero.
68//
69//===----------------------------------------------------------------------===//
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 Lewycky09b7e4d2006-11-22 23:49:16 +000077#include "llvm/ADT/SetOperations.h"
78#include "llvm/ADT/SmallVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000079#include "llvm/ADT/Statistic.h"
80#include "llvm/ADT/STLExtras.h"
81#include "llvm/Analysis/Dominators.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000082#include "llvm/Analysis/ET-Forest.h"
83#include "llvm/Assembly/Writer.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 Lewyckyb2e8ae12006-08-28 22:44:55 +000086#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000087#include "llvm/Support/InstVisitor.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000088#include "llvm/Transforms/Utils/Local.h"
89#include <algorithm>
90#include <deque>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000091#include <iostream>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000092#include <sstream>
93#include <map>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000094using namespace llvm;
95
96namespace {
Chris Lattner700b8732006-12-06 17:46:33 +000097 Statistic
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098 NumVarsReplaced("predsimplify", "Number of argument substitutions");
Chris Lattner700b8732006-12-06 17:46:33 +000099 Statistic
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000100 NumInstruction("predsimplify", "Number of instructions removed");
Chris Lattner700b8732006-12-06 17:46:33 +0000101 Statistic
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000102 NumSimple("predsimplify", "Number of simple replacements");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000103
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000104 /// The InequalityGraph stores the relationships between values.
105 /// Each Value in the graph is assigned to a Node. Nodes are pointer
106 /// comparable for equality. The caller is expected to maintain the logical
107 /// consistency of the system.
108 ///
109 /// The InequalityGraph class may invalidate Node*s after any mutator call.
110 /// @brief The InequalityGraph stores the relationships between values.
111 class VISIBILITY_HIDDEN InequalityGraph {
112 public:
113 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000114
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000115 // LT GT EQ
116 // 0 0 0 -- invalid (false)
117 // 0 0 1 -- invalid (EQ)
118 // 0 1 0 -- GT
119 // 0 1 1 -- GE
120 // 1 0 0 -- LT
121 // 1 0 1 -- LE
122 // 1 1 0 -- NE
123 // 1 1 1 -- invalid (true)
124 enum LatticeBits {
125 EQ_BIT = 1, GT_BIT = 2, LT_BIT = 4
126 };
127 enum LatticeVal {
128 GT = GT_BIT, GE = GT_BIT | EQ_BIT,
129 LT = LT_BIT, LE = LT_BIT | EQ_BIT,
130 NE = GT_BIT | LT_BIT
131 };
132
133 static bool validPredicate(LatticeVal LV) {
134 return LV > 1 && LV < 7;
135 }
136
137 private:
138 typedef std::map<Value *, Node *> NodeMapType;
139 NodeMapType Nodes;
140
141 const InequalityGraph *ConcreteIG;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000142
143 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000144 /// A single node in the InequalityGraph. This stores the canonical Value
145 /// for the node, as well as the relationships with the neighbours.
146 ///
147 /// Because the lists are intended to be used for traversal, it is invalid
148 /// for the node to list itself in LessEqual or GreaterEqual lists. The
149 /// fact that a node is equal to itself is implied, and may be checked
150 /// with pointer comparison.
151 /// @brief A single node in the InequalityGraph.
152 class VISIBILITY_HIDDEN Node {
153 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000154
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000155 Value *Canonical;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000156
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000157 typedef SmallVector<std::pair<Node *, LatticeVal>, 4> RelationsType;
158 RelationsType Relations;
159 public:
160 typedef RelationsType::iterator iterator;
161 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000162
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000163 private:
164 /// Updates the lattice value for a given node. Create a new entry if
165 /// one doesn't exist, otherwise it merges the values. The new lattice
166 /// value must not be inconsistent with any previously existing value.
167 void update(Node *N, LatticeVal R) {
168 iterator I = find(N);
169 if (I == end()) {
170 Relations.push_back(std::make_pair(N, R));
171 } else {
172 I->second = static_cast<LatticeVal>(I->second & R);
173 assert(validPredicate(I->second) &&
174 "Invalid union of lattice values.");
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000175 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000176 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000177
178 void assign(Node *N, LatticeVal R) {
179 iterator I = find(N);
180 if (I != end()) I->second = R;
181
182 Relations.push_back(std::make_pair(N, R));
183 }
184
185 public:
186 iterator begin() { return Relations.begin(); }
187 iterator end() { return Relations.end(); }
188 iterator find(Node *N) {
189 iterator I = begin();
190 for (iterator E = end(); I != E; ++I)
191 if (I->first == N) break;
192 return I;
193 }
194
195 const_iterator begin() const { return Relations.begin(); }
196 const_iterator end() const { return Relations.end(); }
197 const_iterator find(Node *N) const {
198 const_iterator I = begin();
199 for (const_iterator E = end(); I != E; ++I)
200 if (I->first == N) break;
201 return I;
202 }
203
204 unsigned findIndex(Node *N) {
205 unsigned i = 0;
206 iterator I = begin();
207 for (iterator E = end(); I != E; ++I, ++i)
208 if (I->first == N) return i;
209 return (unsigned)-1;
210 }
211
212 void erase(iterator i) { Relations.erase(i); }
213
214 Value *getValue() const { return Canonical; }
215 void setValue(Value *V) { Canonical = V; }
216
217 void addNotEqual(Node *N) { update(N, NE); }
218 void addLess(Node *N) { update(N, LT); }
219 void addLessEqual(Node *N) { update(N, LE); }
220 void addGreater(Node *N) { update(N, GT); }
221 void addGreaterEqual(Node *N) { update(N, GE); }
222 };
223
224 InequalityGraph() : ConcreteIG(NULL) {}
225
226 InequalityGraph(const InequalityGraph &_IG) {
227#if 0 // disable COW
228 if (_IG.ConcreteIG) ConcreteIG = _IG.ConcreteIG;
229 else ConcreteIG = &_IG;
230#else
231 ConcreteIG = &_IG;
232 materialize();
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000233#endif
Nick Lewycky9d17c822006-10-25 23:48:24 +0000234 }
235
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000236 ~InequalityGraph();
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000237
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000238 private:
239 void materialize();
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000240
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000241 public:
242 /// If the Value is in the graph, return the canonical form. Otherwise,
243 /// return the original Value.
244 Value *canonicalize(Value *V) const {
245 if (const Node *N = getNode(V))
246 return N->getValue();
247 else
248 return V;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000249 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000250
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000251 /// Returns the node currently representing Value V, or null if no such
252 /// node exists.
253 Node *getNode(Value *V) {
254 materialize();
255
256 NodeMapType::const_iterator I = Nodes.find(V);
257 return (I != Nodes.end()) ? I->second : 0;
258 }
259
260 const Node *getNode(Value *V) const {
261 if (ConcreteIG) return ConcreteIG->getNode(V);
262
263 NodeMapType::const_iterator I = Nodes.find(V);
264 return (I != Nodes.end()) ? I->second : 0;
265 }
266
267 Node *getOrInsertNode(Value *V) {
268 if (Node *N = getNode(V))
269 return N;
270 else
271 return newNode(V);
272 }
273
274 Node *newNode(Value *V) {
275 //DEBUG(std::cerr << "new node: " << *V << "\n");
276 materialize();
277 Node *&N = Nodes[V];
278 assert(N == 0 && "Node already exists for value.");
279 N = new Node();
280 N->setValue(V);
281 return N;
282 }
283
284 /// Returns true iff the nodes are provably inequal.
285 bool isNotEqual(const Node *N1, const Node *N2) const {
286 if (N1 == N2) return false;
287 for (Node::const_iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
288 if (I->first == N2)
289 return (I->second & EQ_BIT) == 0;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000290 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000291 return isLess(N1, N2) || isGreater(N1, N2);
292 }
293
294 /// Returns true iff N1 is provably less than N2.
295 bool isLess(const Node *N1, const Node *N2) const {
296 if (N1 == N2) return false;
297 for (Node::const_iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
298 if (I->first == N1)
299 return I->second == LT;
300 }
301 for (Node::const_iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
302 if ((I->second & (LT_BIT | GT_BIT)) == LT_BIT)
303 if (isLess(N1, I->first)) return true;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000304 }
305 return false;
306 }
307
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000308 /// Returns true iff N1 is provably less than or equal to N2.
309 bool isLessEqual(const Node *N1, const Node *N2) const {
310 if (N1 == N2) return true;
311 for (Node::const_iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
312 if (I->first == N1)
313 return (I->second & (LT_BIT | GT_BIT)) == LT_BIT;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000314 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000315 for (Node::const_iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
316 if ((I->second & (LT_BIT | GT_BIT)) == LT_BIT)
317 if (isLessEqual(N1, I->first)) return true;
318 }
319 return false;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000320 }
321
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000322 /// Returns true iff N1 is provably greater than N2.
323 bool isGreater(const Node *N1, const Node *N2) const {
324 return isLess(N2, N1);
325 }
Nick Lewycky8e559932006-09-02 19:40:38 +0000326
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000327 /// Returns true iff N1 is provably greater than or equal to N2.
328 bool isGreaterEqual(const Node *N1, const Node *N2) const {
329 return isLessEqual(N2, N1);
330 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000331
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000332 // The add* methods assume that your input is logically valid and may
333 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000334
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000335 void addEqual(Node *N, Value *V) {
336 materialize();
337 Nodes[V] = N;
338 }
339
340 void addNotEqual(Node *N1, Node *N2) {
341 assert(N1 != N2 && "A node can't be inequal to itself.");
342 materialize();
343 N1->addNotEqual(N2);
344 N2->addNotEqual(N1);
345 }
346
347 /// N1 is less than N2.
348 void addLess(Node *N1, Node *N2) {
349 assert(N1 != N2 && !isLess(N2, N1) && "Attempt to create < cycle.");
350 materialize();
351 N2->addLess(N1);
352 N1->addGreater(N2);
353 }
354
355 /// N1 is less than or equal to N2.
356 void addLessEqual(Node *N1, Node *N2) {
357 assert(N1 != N2 && "Nodes are equal. Use mergeNodes instead.");
358 assert(!isGreater(N1, N2) && "Impossible: Adding x <= y when x > y.");
359 materialize();
360 N2->addLessEqual(N1);
361 N1->addGreaterEqual(N2);
362 }
363
364 /// Find the transitive closure starting at a node walking down the edges
365 /// of type Val. Type Inserter must be an inserter that accepts Node *.
366 template <typename Inserter>
367 void transitiveClosure(Node *N, LatticeVal Val, Inserter insert) {
368 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
369 if (I->second == Val) {
370 *insert = I->first;
371 transitiveClosure(I->first, Val, insert);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000372 }
373 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000374 }
375
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000376 /// Kills off all the nodes in Kill by replicating their properties into
377 /// node N. The elements of Kill must be unique. After merging, N's new
378 /// canonical value is NewCanonical. Type C must be a container of Node *.
379 template <typename C>
380 void mergeNodes(Node *N, C &Kill, Value *NewCanonical);
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000381
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000382 /// Removes a Value from the graph, but does not delete any nodes. As this
383 /// method does not delete Nodes, V may not be the canonical choice for
384 /// any node.
385 void remove(Value *V) {
386 materialize();
Nick Lewycky8e559932006-09-02 19:40:38 +0000387
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000388 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E;) {
389 NodeMapType::iterator J = I++;
390 assert(J->second->getValue() != V && "Can't delete canonical choice.");
391 if (J->first == V) Nodes.erase(J);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000392 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000393 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000394
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000395#ifndef NDEBUG
396 void debug(std::ostream &os) const {
397 std::set<Node *> VisitedNodes;
398 for (NodeMapType::const_iterator I = Nodes.begin(), E = Nodes.end();
399 I != E; ++I) {
400 Node *N = I->second;
401 os << *I->first << " == " << *N->getValue() << "\n";
402 if (VisitedNodes.insert(N).second) {
403 os << *N->getValue() << ":\n";
404 for (Node::const_iterator NI = N->begin(), NE = N->end();
405 NI != NE; ++NI) {
406 static const std::string names[8] =
407 { "00", "01", " <", "<=", " >", ">=", "!=", "07" };
408 os << " " << names[NI->second] << " "
409 << *NI->first->getValue() << "\n";
410 }
411 }
412 }
413 }
414#endif
415 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000416
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000417 InequalityGraph::~InequalityGraph() {
418 if (ConcreteIG) return;
419
420 std::vector<Node *> Remove;
421 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end();
422 I != E; ++I) {
423 if (I->first == I->second->getValue())
424 Remove.push_back(I->second);
425 }
426 for (std::vector<Node *>::iterator I = Remove.begin(), E = Remove.end();
427 I != E; ++I) {
428 delete *I;
429 }
430 }
431
432 template <typename C>
433 void InequalityGraph::mergeNodes(Node *N, C &Kill, Value *NewCanonical) {
434 materialize();
435
436 // Merge the relationships from the members of Kill into N.
437 for (typename C::iterator KI = Kill.begin(), KE = Kill.end();
438 KI != KE; ++KI) {
439
Jeff Cohencc08c832006-12-02 02:22:01 +0000440 for (Node::iterator I = (*KI)->begin(), E = (*KI)->end(); I != E; ++I) {
441 if (I->first == N) continue;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000442
443 Node::iterator NI = N->find(I->first);
444 if (NI == N->end()) {
445 N->Relations.push_back(std::make_pair(I->first, I->second));
446 } else {
447 unsigned char LV = NI->second & I->second;
448 if (LV == EQ_BIT) {
449
Jeff Cohencc08c832006-12-02 02:22:01 +0000450 assert(std::find(Kill.begin(), Kill.end(), I->first) != Kill.end()
451 && "Lost EQ property.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000452 N->erase(NI);
453 } else {
454 NI->second = static_cast<LatticeVal>(LV);
455 assert(InequalityGraph::validPredicate(NI->second) &&
456 "Invalid union of lattice values.");
Nick Lewycky9d17c822006-10-25 23:48:24 +0000457 }
458 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000459
460 // All edges are reciprocal; every Node that Kill points to also
461 // contains a pointer to Kill. Replace those with pointers with N.
462 unsigned iter = I->first->findIndex(*KI);
463 assert(iter != (unsigned)-1 && "Edge not reciprocal.");
464 I->first->assign(N, (I->first->begin()+iter)->second);
465 I->first->erase(I->first->begin()+iter);
466 }
467
468 // Removing references from N to Kill.
Jeff Cohencc08c832006-12-02 02:22:01 +0000469 Node::iterator NI = N->find(*KI);
470 if (NI != N->end()) {
471 N->erase(NI); // breaks reciprocity until Kill is deleted.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000472 }
473 }
474
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000475 N->setValue(NewCanonical);
Nick Lewycky9d17c822006-10-25 23:48:24 +0000476
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000477 // Update value mapping to point to the merged node.
478 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end();
479 I != E; ++I) {
480 if (std::find(Kill.begin(), Kill.end(), I->second) != Kill.end())
481 I->second = N;
482 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000483
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000484 for (typename C::iterator KI = Kill.begin(), KE = Kill.end();
485 KI != KE; ++KI) {
486 delete *KI;
487 }
488 }
489
490 void InequalityGraph::materialize() {
491 if (!ConcreteIG) return;
492 const InequalityGraph *IG = ConcreteIG;
493 ConcreteIG = NULL;
494
495 for (NodeMapType::const_iterator I = IG->Nodes.begin(),
496 E = IG->Nodes.end(); I != E; ++I) {
497 if (I->first == I->second->getValue()) {
498 Node *N = newNode(I->first);
499 N->Relations.reserve(N->Relations.size());
500 }
501 }
502 for (NodeMapType::const_iterator I = IG->Nodes.begin(),
503 E = IG->Nodes.end(); I != E; ++I) {
504 if (I->first != I->second->getValue()) {
505 Nodes[I->first] = getNode(I->second->getValue());
506 } else {
507 Node *Old = I->second;
508 Node *N = getNode(I->first);
509 for (Node::const_iterator NI = Old->begin(), NE = Old->end();
510 NI != NE; ++NI) {
511 N->assign(getNode(NI->first->getValue()), NI->second);
512 }
513 }
514 }
515 }
516
517 /// VRPSolver keeps track of how changes to one variable affect other
518 /// variables, and forwards changes along to the InequalityGraph. It
519 /// also maintains the correct choice for "canonical" in the IG.
520 /// @brief VRPSolver calculates inferences from a new relationship.
521 class VISIBILITY_HIDDEN VRPSolver {
522 private:
523 std::deque<Instruction *> WorkList;
524
525 InequalityGraph &IG;
526 const InequalityGraph &cIG;
527 ETForest *Forest;
528 ETNode *Top;
529
530 typedef InequalityGraph::Node Node;
531
532 /// Returns true if V1 is a better canonical value than V2.
533 bool compare(Value *V1, Value *V2) const {
534 if (isa<Constant>(V1))
535 return !isa<Constant>(V2);
536 else if (isa<Constant>(V2))
537 return false;
538 else if (isa<Argument>(V1))
539 return !isa<Argument>(V2);
540 else if (isa<Argument>(V2))
541 return false;
542
543 Instruction *I1 = dyn_cast<Instruction>(V1);
544 Instruction *I2 = dyn_cast<Instruction>(V2);
545
546 if (!I1 || !I2) return false;
547
548 BasicBlock *BB1 = I1->getParent(),
549 *BB2 = I2->getParent();
550 if (BB1 == BB2) {
551 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
552 I != E; ++I) {
553 if (&*I == I1) return true;
554 if (&*I == I2) return false;
555 }
556 assert(!"Instructions not found in parent BasicBlock?");
557 } else {
558 return Forest->properlyDominates(BB1, BB2);
559 }
560 return false;
561 }
562
563 void addToWorklist(Instruction *I) {
564 //DEBUG(std::cerr << "addToWorklist: " << *I << "\n");
565
566 if (!isa<BinaryOperator>(I) && !isa<SelectInst>(I)) return;
567
568 const Type *Ty = I->getType();
569 if (Ty == Type::VoidTy || Ty->isFPOrFPVector()) return;
570
571 if (isInstructionTriviallyDead(I)) return;
572
573 WorkList.push_back(I);
574 }
575
576 void addRecursive(Value *V) {
577 //DEBUG(std::cerr << "addRecursive: " << *V << "\n");
Nick Lewycky9d17c822006-10-25 23:48:24 +0000578
579 Instruction *I = dyn_cast<Instruction>(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000580 if (I)
581 addToWorklist(I);
582 else if (!isa<Argument>(V))
583 return;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000584
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000585 //DEBUG(std::cerr << "addRecursive uses...\n");
586 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
587 UI != UE; ++UI) {
588 // Use must be either be dominated by Top, or dominate Top.
589 if (Instruction *Inst = dyn_cast<Instruction>(*UI)) {
590 ETNode *INode = Forest->getNodeForBlock(Inst->getParent());
591 if (INode->DominatedBy(Top) || Top->DominatedBy(INode))
592 addToWorklist(Inst);
593 }
594 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000595
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000596 if (I) {
597 //DEBUG(std::cerr << "addRecursive ops...\n");
598 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
599 OI != OE; ++OI) {
600 if (Instruction *Inst = dyn_cast<Instruction>(*OI))
601 addToWorklist(Inst);
602 }
603 }
604 //DEBUG(std::cerr << "exit addRecursive (" << *V << ").\n");
605 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000606
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000607 public:
608 VRPSolver(InequalityGraph &IG, ETForest *Forest, BasicBlock *TopBB)
609 : IG(IG), cIG(IG), Forest(Forest), Top(Forest->getNodeForBlock(TopBB)) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +0000610
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000611 bool isEqual(Value *V1, Value *V2) const {
612 if (V1 == V2) return true;
613 if (const Node *N1 = cIG.getNode(V1))
614 return N1 == cIG.getNode(V2);
615 return false;
616 }
617
618 bool isNotEqual(Value *V1, Value *V2) const {
619 if (V1 == V2) return false;
620 if (const Node *N1 = cIG.getNode(V1))
621 if (const Node *N2 = cIG.getNode(V2))
622 return cIG.isNotEqual(N1, N2);
623 return false;
624 }
625
626 bool isLess(Value *V1, Value *V2) const {
627 if (V1 == V2) return false;
628 if (const Node *N1 = cIG.getNode(V1))
629 if (const Node *N2 = cIG.getNode(V2))
630 return cIG.isLess(N1, N2);
631 return false;
632 }
633
634 bool isLessEqual(Value *V1, Value *V2) const {
635 if (V1 == V2) return true;
636 if (const Node *N1 = cIG.getNode(V1))
637 if (const Node *N2 = cIG.getNode(V2))
638 return cIG.isLessEqual(N1, N2);
639 return false;
640 }
641
642 bool isGreater(Value *V1, Value *V2) const {
643 if (V1 == V2) return false;
644 if (const Node *N1 = cIG.getNode(V1))
645 if (const Node *N2 = cIG.getNode(V2))
646 return cIG.isGreater(N1, N2);
647 return false;
648 }
649
650 bool isGreaterEqual(Value *V1, Value *V2) const {
651 if (V1 == V2) return true;
652 if (const Node *N1 = IG.getNode(V1))
653 if (const Node *N2 = IG.getNode(V2))
654 return cIG.isGreaterEqual(N1, N2);
655 return false;
656 }
657
658 // All of the add* functions return true if the InequalityGraph represents
659 // the property, and false if there is a logical contradiction. On false,
660 // you may no longer perform any queries on the InequalityGraph.
661
662 bool addEqual(Value *V1, Value *V2) {
663 //DEBUG(std::cerr << "addEqual(" << *V1 << ", "
664 // << *V2 << ")\n");
665 if (isEqual(V1, V2)) return true;
666
667 const Node *cN1 = cIG.getNode(V1), *cN2 = cIG.getNode(V2);
668
669 if (cN1 && cN2 && cIG.isNotEqual(cN1, cN2))
670 return false;
671
672 if (compare(V2, V1)) { std::swap(V1, V2); std::swap(cN1, cN2); }
673
674 if (cN1) {
675 if (ConstantBool *CB = dyn_cast<ConstantBool>(V1)) {
676 Node *N1 = IG.getNode(V1);
677
678 // When "addEqual" is performed and the new value is a ConstantBool,
679 // iterate through the NE set and fix them up to be EQ of the
680 // opposite bool.
681
682 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I)
683 if ((I->second & 1) == 0) {
684 assert(N1 != I->first && "Node related to itself?");
685 addEqual(I->first->getValue(),
686 ConstantBool::get(!CB->getValue()));
687 }
688 }
689 }
690
691 if (!cN2) {
692 if (Instruction *I2 = dyn_cast<Instruction>(V2)) {
693 ETNode *Node_I2 = Forest->getNodeForBlock(I2->getParent());
694 if (Top != Node_I2 && Node_I2->DominatedBy(Top)) {
695 Value *V = V1;
696 if (cN1 && compare(V1, cN1->getValue())) V = cN1->getValue();
697 //DEBUG(std::cerr << "Simply removing " << *I2
698 // << ", replacing with " << *V << "\n");
699 I2->replaceAllUsesWith(V);
700 // leave it dead; it'll get erased later.
701 ++NumSimple;
702 addRecursive(V1);
703 return true;
704 }
705 }
706 }
707
708 Node *N1 = IG.getNode(V1), *N2 = IG.getNode(V2);
709
710 if ( N1 && !N2) {
711 IG.addEqual(N1, V2);
712 if (compare(V1, N1->getValue())) N1->setValue(V1);
713 }
714 if (!N1 && N2) {
715 IG.addEqual(N2, V1);
716 if (compare(V1, N2->getValue())) N2->setValue(V1);
717 }
718 if ( N1 && N2) {
719 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
720 // We can't just merge %x and %y because the relationship with %z would
721 // be EQ and that's invalid; they need to be the same Node.
722 //
723 // What we're doing is looking for any chain of nodes reaching %z such
724 // that %x <= %z and %y >= %z, and vice versa. The cool part is that
725 // every node in between is also equal because of the squeeze principle.
726
727 std::vector<Node *> N1_GE, N2_LE, N1_LE, N2_GE;
728 IG.transitiveClosure(N1, InequalityGraph::GE, back_inserter(N1_GE));
729 std::sort(N1_GE.begin(), N1_GE.end());
730 N1_GE.erase(std::unique(N1_GE.begin(), N1_GE.end()), N1_GE.end());
731 IG.transitiveClosure(N2, InequalityGraph::LE, back_inserter(N2_LE));
732 std::sort(N1_LE.begin(), N1_LE.end());
733 N1_LE.erase(std::unique(N1_LE.begin(), N1_LE.end()), N1_LE.end());
734 IG.transitiveClosure(N1, InequalityGraph::LE, back_inserter(N1_LE));
735 std::sort(N2_GE.begin(), N2_GE.end());
736 N2_GE.erase(std::unique(N2_GE.begin(), N2_GE.end()), N2_GE.end());
737 std::unique(N2_GE.begin(), N2_GE.end());
738 IG.transitiveClosure(N2, InequalityGraph::GE, back_inserter(N2_GE));
739 std::sort(N2_LE.begin(), N2_LE.end());
740 N2_LE.erase(std::unique(N2_LE.begin(), N2_LE.end()), N2_LE.end());
741
742 std::vector<Node *> Set1, Set2;
743 std::set_intersection(N1_GE.begin(), N1_GE.end(),
744 N2_LE.begin(), N2_LE.end(),
745 back_inserter(Set1));
746 std::set_intersection(N1_LE.begin(), N1_LE.end(),
747 N2_GE.begin(), N2_GE.end(),
748 back_inserter(Set2));
749
750 std::vector<Node *> Equal;
751 std::set_union(Set1.begin(), Set1.end(), Set2.begin(), Set2.end(),
752 back_inserter(Equal));
753
754 Value *Best = N1->getValue();
755 if (compare(N2->getValue(), Best)) Best = N2->getValue();
756
757 for (std::vector<Node *>::iterator I = Equal.begin(), E = Equal.end();
758 I != E; ++I) {
759 Value *V = (*I)->getValue();
760 if (compare(V, Best)) Best = V;
761 }
762
763 Equal.push_back(N2);
764 IG.mergeNodes(N1, Equal, Best);
765 }
766 if (!N1 && !N2) IG.addEqual(IG.newNode(V1), V2);
767
768 addRecursive(V1);
769 addRecursive(V2);
770
771 return true;
772 }
773
774 bool addNotEqual(Value *V1, Value *V2) {
775 //DEBUG(std::cerr << "addNotEqual(" << *V1 << ", "
776 // << *V2 << ")\n");
777 if (isNotEqual(V1, V2)) return true;
778
779 // Never permit %x NE true/false.
780 if (ConstantBool *B1 = dyn_cast<ConstantBool>(V1)) {
781 return addEqual(ConstantBool::get(!B1->getValue()), V2);
782 } else if (ConstantBool *B2 = dyn_cast<ConstantBool>(V2)) {
783 return addEqual(V1, ConstantBool::get(!B2->getValue()));
784 }
785
786 Node *N1 = IG.getOrInsertNode(V1),
787 *N2 = IG.getOrInsertNode(V2);
788
789 if (N1 == N2) return false;
790
791 IG.addNotEqual(N1, N2);
792
793 addRecursive(V1);
794 addRecursive(V2);
795
796 return true;
797 }
798
799 /// Set V1 less than V2.
800 bool addLess(Value *V1, Value *V2) {
801 if (isLess(V1, V2)) return true;
802 if (isGreaterEqual(V1, V2)) return false;
803
804 Node *N1 = IG.getOrInsertNode(V1), *N2 = IG.getOrInsertNode(V2);
805
806 if (N1 == N2) return false;
807
808 IG.addLess(N1, N2);
809
810 addRecursive(V1);
811 addRecursive(V2);
812
813 return true;
814 }
815
816 /// Set V1 less than or equal to V2.
817 bool addLessEqual(Value *V1, Value *V2) {
818 if (isLessEqual(V1, V2)) return true;
819 if (V1 == V2) return true;
820
821 if (isLessEqual(V2, V1))
822 return addEqual(V1, V2);
823
824 if (isGreater(V1, V2)) return false;
825
826 Node *N1 = IG.getOrInsertNode(V1),
827 *N2 = IG.getOrInsertNode(V2);
828
829 if (N1 == N2) return true;
830
831 IG.addLessEqual(N1, N2);
832
833 addRecursive(V1);
834 addRecursive(V2);
835
836 return true;
837 }
838
839 void solve() {
840 DEBUG(std::cerr << "WorkList entry, size: " << WorkList.size() << "\n");
841 while (!WorkList.empty()) {
842 DEBUG(std::cerr << "WorkList size: " << WorkList.size() << "\n");
843
844 Instruction *I = WorkList.front();
845 WorkList.pop_front();
846
847 Value *Canonical = cIG.canonicalize(I);
848 const Type *Ty = I->getType();
849
850 //DEBUG(std::cerr << "solving: " << *I << "\n");
851 //DEBUG(IG.debug(std::cerr));
852
853 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
854 Value *Op0 = cIG.canonicalize(BO->getOperand(0)),
855 *Op1 = cIG.canonicalize(BO->getOperand(1));
856
857 ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(Op0),
858 *CI2 = dyn_cast<ConstantIntegral>(Op1);
859
860 if (CI1 && CI2)
861 addEqual(BO, ConstantExpr::get(BO->getOpcode(), CI1, CI2));
862
863 switch (BO->getOpcode()) {
Nick Lewycky9d17c822006-10-25 23:48:24 +0000864 case Instruction::SetEQ:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000865 // "seteq int %a, %b" EQ true then %a EQ %b
866 // "seteq int %a, %b" EQ false then %a NE %b
867 if (Canonical == ConstantBool::getTrue())
868 addEqual(Op0, Op1);
869 else if (Canonical == ConstantBool::getFalse())
870 addNotEqual(Op0, Op1);
871
872 // %a EQ %b then "seteq int %a, %b" EQ true
873 // %a NE %b then "seteq int %a, %b" EQ false
874 if (isEqual(Op0, Op1))
875 addEqual(BO, ConstantBool::getTrue());
876 else if (isNotEqual(Op0, Op1))
877 addEqual(BO, ConstantBool::getFalse());
878
Nick Lewycky9d17c822006-10-25 23:48:24 +0000879 break;
880 case Instruction::SetNE:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000881 // "setne int %a, %b" EQ true then %a NE %b
882 // "setne int %a, %b" EQ false then %a EQ %b
883 if (Canonical == ConstantBool::getTrue())
884 addNotEqual(Op0, Op1);
885 else if (Canonical == ConstantBool::getFalse())
886 addEqual(Op0, Op1);
887
888 // %a EQ %b then "setne int %a, %b" EQ false
889 // %a NE %b then "setne int %a, %b" EQ true
890 if (isEqual(Op0, Op1))
891 addEqual(BO, ConstantBool::getFalse());
892 else if (isNotEqual(Op0, Op1))
893 addEqual(BO, ConstantBool::getTrue());
894
895 break;
896 case Instruction::SetLT:
897 // "setlt int %a, %b" EQ true then %a LT %b
898 // "setlt int %a, %b" EQ false then %b LE %a
899 if (Canonical == ConstantBool::getTrue())
900 addLess(Op0, Op1);
901 else if (Canonical == ConstantBool::getFalse())
902 addLessEqual(Op1, Op0);
903
904 // %a LT %b then "setlt int %a, %b" EQ true
905 // %a GE %b then "setlt int %a, %b" EQ false
906 if (isLess(Op0, Op1))
907 addEqual(BO, ConstantBool::getTrue());
908 else if (isGreaterEqual(Op0, Op1))
909 addEqual(BO, ConstantBool::getFalse());
910
Nick Lewycky9d17c822006-10-25 23:48:24 +0000911 break;
912 case Instruction::SetLE:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000913 // "setle int %a, %b" EQ true then %a LE %b
914 // "setle int %a, %b" EQ false then %b LT %a
915 if (Canonical == ConstantBool::getTrue())
916 addLessEqual(Op0, Op1);
917 else if (Canonical == ConstantBool::getFalse())
918 addLess(Op1, Op0);
919
920 // %a LE %b then "setle int %a, %b" EQ true
921 // %a GT %b then "setle int %a, %b" EQ false
922 if (isLessEqual(Op0, Op1))
923 addEqual(BO, ConstantBool::getTrue());
924 else if (isGreater(Op0, Op1))
925 addEqual(BO, ConstantBool::getFalse());
926
927 break;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000928 case Instruction::SetGT:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000929 // "setgt int %a, %b" EQ true then %b LT %a
930 // "setgt int %a, %b" EQ false then %a LE %b
931 if (Canonical == ConstantBool::getTrue())
932 addLess(Op1, Op0);
933 else if (Canonical == ConstantBool::getFalse())
934 addLessEqual(Op0, Op1);
935
936 // %a GT %b then "setgt int %a, %b" EQ true
937 // %a LE %b then "setgt int %a, %b" EQ false
938 if (isGreater(Op0, Op1))
939 addEqual(BO, ConstantBool::getTrue());
940 else if (isLessEqual(Op0, Op1))
941 addEqual(BO, ConstantBool::getFalse());
942
Nick Lewycky9d17c822006-10-25 23:48:24 +0000943 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000944 case Instruction::SetGE:
945 // "setge int %a, %b" EQ true then %b LE %a
946 // "setge int %a, %b" EQ false then %a LT %b
947 if (Canonical == ConstantBool::getTrue())
948 addLessEqual(Op1, Op0);
949 else if (Canonical == ConstantBool::getFalse())
950 addLess(Op0, Op1);
951
952 // %a GE %b then "setge int %a, %b" EQ true
953 // %a LT %b then "setlt int %a, %b" EQ false
954 if (isGreaterEqual(Op0, Op1))
955 addEqual(BO, ConstantBool::getTrue());
956 else if (isLess(Op0, Op1))
957 addEqual(BO, ConstantBool::getFalse());
958
959 break;
960 case Instruction::And: {
961 // "and int %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
962 // "and bool %a, %b" EQ true then %a EQ true and %b EQ true
963 ConstantIntegral *CI = ConstantIntegral::getAllOnesValue(Ty);
964 if (Canonical == CI) {
965 addEqual(CI, Op0);
966 addEqual(CI, Op1);
967 }
968 } break;
969 case Instruction::Or: {
970 // "or int %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
971 // "or bool %a, %b" EQ false then %a EQ false and %b EQ false
972 Constant *Zero = Constant::getNullValue(Ty);
973 if (Canonical == Zero) {
974 addEqual(Zero, Op0);
975 addEqual(Zero, Op1);
976 }
977 } break;
978 case Instruction::Xor: {
979 // "xor bool true, %a" EQ true then %a EQ false
980 // "xor bool true, %a" EQ false then %a EQ true
981 // "xor bool false, %a" EQ true then %a EQ true
982 // "xor bool false, %a" EQ false then %a EQ false
983 // "xor int %c, %a" EQ %c then %a EQ 0
984 // "xor int %c, %a" NE %c then %a NE 0
985 // 1. Repeat all of the above, with order of operands reversed.
986 Value *LHS = Op0, *RHS = Op1;
987 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
988
989 if (ConstantBool *CB = dyn_cast<ConstantBool>(Canonical)) {
990 if (ConstantBool *A = dyn_cast<ConstantBool>(LHS))
991 addEqual(RHS, ConstantBool::get(A->getValue() ^
992 CB->getValue()));
993 }
994 if (Canonical == LHS) {
995 if (isa<ConstantIntegral>(Canonical))
996 addEqual(RHS, Constant::getNullValue(Ty));
997 } else if (isNotEqual(LHS, Canonical)) {
998 addNotEqual(RHS, Constant::getNullValue(Ty));
999 }
1000 } break;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001001 default:
Nick Lewycky9d17c822006-10-25 23:48:24 +00001002 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001003 }
1004
1005 // "%x = add int %y, %z" and %x EQ %y then %z EQ 0
1006 // "%x = mul int %y, %z" and %x EQ %y then %z EQ 1
1007 // 1. Repeat all of the above, with order of operands reversed.
1008 // "%x = fdiv float %y, %z" and %x EQ %y then %z EQ 1
1009 Value *Known = Op0, *Unknown = Op1;
1010 if (Known != BO) std::swap(Known, Unknown);
1011 if (Known == BO) {
1012 switch (BO->getOpcode()) {
1013 default: break;
1014 case Instruction::Xor:
1015 case Instruction::Or:
1016 case Instruction::Add:
1017 case Instruction::Sub:
1018 if (!Ty->isFloatingPoint())
1019 addEqual(Unknown, Constant::getNullValue(Ty));
1020 break;
1021 case Instruction::UDiv:
1022 case Instruction::SDiv:
1023 case Instruction::FDiv:
1024 if (Unknown == Op0) break; // otherwise, fallthrough
1025 case Instruction::And:
1026 case Instruction::Mul:
1027 Constant *One = NULL;
1028 if (isa<ConstantInt>(Unknown))
1029 One = ConstantInt::get(Ty, 1);
1030 else if (isa<ConstantFP>(Unknown))
1031 One = ConstantFP::get(Ty, 1);
1032 else if (isa<ConstantBool>(Unknown))
1033 One = ConstantBool::getTrue();
1034
1035 if (One) addEqual(Unknown, One);
1036 break;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001037 }
1038 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001039 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1040 // Given: "%a = select bool %x, int %b, int %c"
1041 // %a EQ %b then %x EQ true
1042 // %a EQ %c then %x EQ false
1043 if (isEqual(I, SI->getTrueValue()) ||
1044 isNotEqual(I, SI->getFalseValue()))
1045 addEqual(SI->getCondition(), ConstantBool::getTrue());
1046 else if (isEqual(I, SI->getFalseValue()) ||
1047 isNotEqual(I, SI->getTrueValue()))
1048 addEqual(SI->getCondition(), ConstantBool::getFalse());
1049
1050 // %x EQ true then %a EQ %b
1051 // %x EQ false then %a NE %b
1052 if (isEqual(SI->getCondition(), ConstantBool::getTrue()))
1053 addEqual(SI, SI->getTrueValue());
1054 else if (isEqual(SI->getCondition(), ConstantBool::getFalse()))
1055 addEqual(SI, SI->getFalseValue());
Nick Lewycky9d17c822006-10-25 23:48:24 +00001056 }
1057 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001058 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001059 };
1060
1061 /// PredicateSimplifier - This class is a simplifier that replaces
1062 /// one equivalent variable with another. It also tracks what
1063 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001064 /// @brief Root of the predicate simplifier optimization.
1065 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1066 DominatorTree *DT;
1067 ETForest *Forest;
1068 bool modified;
1069
1070 class State {
1071 public:
1072 BasicBlock *ToVisit;
1073 InequalityGraph *IG;
1074
1075 State(BasicBlock *BB, InequalityGraph *IG) : ToVisit(BB), IG(IG) {}
1076 };
1077
1078 std::vector<State> WorkList;
1079
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001080 public:
1081 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001082
1083 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1084 AU.addRequiredID(BreakCriticalEdgesID);
1085 AU.addRequired<DominatorTree>();
1086 AU.addRequired<ETForest>();
1087 AU.setPreservesCFG();
1088 AU.addPreservedID(BreakCriticalEdgesID);
1089 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001090
1091 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001092 /// Forwards - Adds new properties into PropertySet and uses them to
1093 /// simplify instructions. Because new properties sometimes apply to
1094 /// a transition from one BasicBlock to another, this will use the
1095 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1096 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001097 /// @brief Performs abstract execution of the program.
1098 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001099 friend class InstVisitor<Forwards>;
1100 PredicateSimplifier *PS;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001101
Nick Lewycky77e030b2006-10-12 02:02:44 +00001102 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001103 InequalityGraph &IG;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001104
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001105 Forwards(PredicateSimplifier *PS, InequalityGraph &IG)
1106 : PS(PS), IG(IG) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001107
1108 void visitTerminatorInst(TerminatorInst &TI);
1109 void visitBranchInst(BranchInst &BI);
1110 void visitSwitchInst(SwitchInst &SI);
1111
Nick Lewyckyf3450082006-10-22 19:53:27 +00001112 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001113 void visitLoadInst(LoadInst &LI);
1114 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001115
Nick Lewycky77e030b2006-10-12 02:02:44 +00001116 void visitBinaryOperator(BinaryOperator &BO);
1117 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001118
1119 // Used by terminator instructions to proceed from the current basic
1120 // block to the next. Verifies that "current" dominates "next",
1121 // then calls visitBasicBlock.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001122 void proceedToSuccessors(const InequalityGraph &IG, BasicBlock *BBCurrent) {
1123 DominatorTree::Node *Current = DT->getNode(BBCurrent);
1124 for (DominatorTree::Node::iterator I = Current->begin(),
1125 E = Current->end(); I != E; ++I) {
1126 //visitBasicBlock((*I)->getBlock(), IG);
1127 WorkList.push_back(State((*I)->getBlock(), new InequalityGraph(IG)));
1128 }
1129 }
1130
1131 void proceedToSuccessor(InequalityGraph *NextIG, BasicBlock *Next) {
1132 //visitBasicBlock(Next, NextIG);
1133 WorkList.push_back(State(Next, NextIG));
1134 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001135
1136 // Visits each instruction in the basic block.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001137 void visitBasicBlock(BasicBlock *BB, InequalityGraph &IG) {
1138 DEBUG(std::cerr << "Entering Basic Block: " << BB->getName() << "\n");
1139 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
1140 visitInstruction(I++, IG);
1141 }
1142 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001143
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001144 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001145 // the PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001146 void visitInstruction(Instruction *I, InequalityGraph &IG) {
1147 DEBUG(std::cerr << "Considering instruction " << *I << "\n");
1148 DEBUG(IG.debug(std::cerr));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001149
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001150 // Sometimes instructions are made dead due to earlier analysis.
1151 if (isInstructionTriviallyDead(I)) {
1152 I->eraseFromParent();
1153 return;
1154 }
1155
1156 // Try to replace the whole instruction.
1157 Value *V = IG.canonicalize(I);
1158 if (V != I) {
1159 modified = true;
1160 ++NumInstruction;
1161 DEBUG(std::cerr << "Removing " << *I << ", replacing with "
1162 << *V << "\n");
1163 IG.remove(I);
1164 I->replaceAllUsesWith(V);
1165 I->eraseFromParent();
1166 return;
1167 }
1168
1169 // Try to substitute operands.
1170 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1171 Value *Oper = I->getOperand(i);
1172 Value *V = IG.canonicalize(Oper);
1173 if (V != Oper) {
1174 modified = true;
1175 ++NumVarsReplaced;
1176 DEBUG(std::cerr << "Resolving " << *I);
1177 I->setOperand(i, V);
1178 DEBUG(std::cerr << " into " << *I);
1179 }
1180 }
1181
1182 //DEBUG(std::cerr << "push (%" << I->getParent()->getName() << ")\n");
1183 Forwards visit(this, IG);
1184 visit.visit(*I);
1185 //DEBUG(std::cerr << "pop (%" << I->getParent()->getName() << ")\n");
1186 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001187 };
1188
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001189 bool PredicateSimplifier::runOnFunction(Function &F) {
1190 DT = &getAnalysis<DominatorTree>();
1191 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001192
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001193 DEBUG(std::cerr << "Entering Function: " << F.getName() << "\n");
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001194
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001195 modified = false;
1196 WorkList.push_back(State(DT->getRoot(), new InequalityGraph()));
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001197
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001198 do {
1199 State S = WorkList.back();
1200 WorkList.pop_back();
1201 visitBasicBlock(S.ToVisit, *S.IG);
1202 delete S.IG;
1203 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001204
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001205 //DEBUG(F.viewCFG());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001206
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001207 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00001208 }
1209
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001210 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
1211 PS->proceedToSuccessors(IG, TI.getParent());
1212 }
1213
1214 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
1215 BasicBlock *BB = BI.getParent();
1216
1217 if (BI.isUnconditional()) {
1218 PS->proceedToSuccessors(IG, BB);
1219 return;
1220 }
1221
1222 Value *Condition = BI.getCondition();
1223 BasicBlock *TrueDest = BI.getSuccessor(0),
1224 *FalseDest = BI.getSuccessor(1);
1225
1226 if (isa<ConstantBool>(Condition) || TrueDest == FalseDest) {
1227 PS->proceedToSuccessors(IG, BB);
1228 return;
1229 }
1230
1231 DominatorTree::Node *Node = PS->DT->getNode(BB);
1232 for (DominatorTree::Node::iterator I = Node->begin(), E = Node->end();
1233 I != E; ++I) {
1234 BasicBlock *Dest = (*I)->getBlock();
1235 InequalityGraph *DestProperties = new InequalityGraph(IG);
1236 VRPSolver Solver(*DestProperties, PS->Forest, Dest);
1237
1238 if (Dest == TrueDest) {
1239 DEBUG(std::cerr << "(" << BB->getName() << ") true set:\n");
1240 if (!Solver.addEqual(ConstantBool::getTrue(), Condition)) continue;
1241 Solver.solve();
1242 DEBUG(DestProperties->debug(std::cerr));
1243 } else if (Dest == FalseDest) {
1244 DEBUG(std::cerr << "(" << BB->getName() << ") false set:\n");
1245 if (!Solver.addEqual(ConstantBool::getFalse(), Condition)) continue;
1246 Solver.solve();
1247 DEBUG(DestProperties->debug(std::cerr));
1248 }
1249
1250 PS->proceedToSuccessor(DestProperties, Dest);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001251 }
1252 }
1253
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001254 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
1255 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001256
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001257 // Set the EQProperty in each of the cases BBs, and the NEProperties
1258 // in the default BB.
1259 // InequalityGraph DefaultProperties(IG);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001260
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001261 DominatorTree::Node *Node = PS->DT->getNode(SI.getParent());
1262 for (DominatorTree::Node::iterator I = Node->begin(), E = Node->end();
1263 I != E; ++I) {
1264 BasicBlock *BB = (*I)->getBlock();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001265
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001266 InequalityGraph *BBProperties = new InequalityGraph(IG);
1267 VRPSolver Solver(*BBProperties, PS->Forest, BB);
1268 if (BB == SI.getDefaultDest()) {
1269 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
1270 if (SI.getSuccessor(i) != BB)
1271 if (!Solver.addNotEqual(Condition, SI.getCaseValue(i))) continue;
1272 Solver.solve();
1273 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
1274 if (!Solver.addEqual(Condition, CI)) continue;
1275 Solver.solve();
1276 }
1277 PS->proceedToSuccessor(BBProperties, BB);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00001278 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001279 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001280
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001281 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
1282 VRPSolver VRP(IG, PS->Forest, AI.getParent());
1283 VRP.addNotEqual(Constant::getNullValue(AI.getType()), &AI);
1284 VRP.solve();
1285 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00001286
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001287 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
1288 Value *Ptr = LI.getPointerOperand();
1289 // avoid "load uint* null" -> null NE null.
1290 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001291
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001292 VRPSolver VRP(IG, PS->Forest, LI.getParent());
1293 VRP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
1294 VRP.solve();
1295 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001296
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001297 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
1298 Value *Ptr = SI.getPointerOperand();
1299 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001300
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001301 VRPSolver VRP(IG, PS->Forest, SI.getParent());
1302 VRP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
1303 VRP.solve();
1304 }
1305
1306 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
1307 Instruction::BinaryOps ops = BO.getOpcode();
1308
1309 switch (ops) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001310 case Instruction::URem:
1311 case Instruction::SRem:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001312 case Instruction::FRem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001313 case Instruction::UDiv:
1314 case Instruction::SDiv:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001315 case Instruction::FDiv: {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001316 Value *Divisor = BO.getOperand(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001317 VRPSolver VRP(IG, PS->Forest, BO.getParent());
1318 VRP.addNotEqual(Constant::getNullValue(Divisor->getType()), Divisor);
1319 VRP.solve();
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001320 break;
1321 }
1322 default:
1323 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001324 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001325 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001326
1327
1328 RegisterPass<PredicateSimplifier> X("predsimplify",
1329 "Predicate Simplifier");
1330}
1331
1332FunctionPass *llvm::createPredicateSimplifierPass() {
1333 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001334}