blob: a11d5bdfcdff9f3cb4610f3cb967e7daef2f37da [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
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 Lewycky56639802007-01-29 02:56:54 +000055// %P = setne int* %ptr, null
56// %a = and bool %P, %Q
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000057// 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
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 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 Lewycky09b7e4d2006-11-22 23:49:16 +000091#include <sstream>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000092using namespace llvm;
93
Chris Lattner0e5255b2006-12-19 21:49:03 +000094STATISTIC(NumVarsReplaced, "Number of argument substitutions");
95STATISTIC(NumInstruction , "Number of instructions removed");
96STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +000097STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098
Chris Lattner0e5255b2006-12-19 21:49:03 +000099namespace {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000100 // SLT SGT ULT UGT EQ
101 // 0 1 0 1 0 -- GT 10
102 // 0 1 0 1 1 -- GE 11
103 // 0 1 1 0 0 -- SGTULT 12
104 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000105 // 0 1 1 1 0 -- SGT 14
106 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000107 // 1 0 0 1 0 -- SLTUGT 18
108 // 1 0 0 1 1 -- SLEUGE 19
109 // 1 0 1 0 0 -- LT 20
110 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000111 // 1 0 1 1 0 -- SLT 22
112 // 1 0 1 1 1 -- SLE 23
113 // 1 1 0 1 0 -- UGT 26
114 // 1 1 0 1 1 -- UGE 27
115 // 1 1 1 0 0 -- ULT 28
116 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000117 // 1 1 1 1 0 -- NE 30
118 enum LatticeBits {
119 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
120 };
121 enum LatticeVal {
122 GT = SGT_BIT | UGT_BIT,
123 GE = GT | EQ_BIT,
124 LT = SLT_BIT | ULT_BIT,
125 LE = LT | EQ_BIT,
126 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
127 SGTULT = SGT_BIT | ULT_BIT,
128 SGEULE = SGTULT | EQ_BIT,
129 SLTUGT = SLT_BIT | UGT_BIT,
130 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000131 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
132 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
133 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
134 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
135 SLE = SLT | EQ_BIT,
136 SGE = SGT | EQ_BIT,
137 ULE = ULT | EQ_BIT,
138 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000139 };
140
141 static bool validPredicate(LatticeVal LV) {
142 switch (LV) {
143 case GT: case GE: case LT: case LE: case NE:
Nick Lewycky56639802007-01-29 02:56:54 +0000144 case SGTULT: case SGT: case SGEULE:
145 case SLTUGT: case SLT: case SLEUGE:
146 case ULT: case UGT:
147 case SLE: case SGE: case ULE: case UGE:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000148 return true;
149 default:
150 return false;
151 }
152 }
153
154 /// reversePredicate - reverse the direction of the inequality
155 static LatticeVal reversePredicate(LatticeVal LV) {
156 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
157 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
158 reverse |= (SLT_BIT|SGT_BIT);
159
160 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
161 reverse |= (ULT_BIT|UGT_BIT);
162
163 LatticeVal Rev = static_cast<LatticeVal>(reverse);
164 assert(validPredicate(Rev) && "Failed reversing predicate.");
165 return Rev;
166 }
167
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000168 /// The InequalityGraph stores the relationships between values.
169 /// Each Value in the graph is assigned to a Node. Nodes are pointer
170 /// comparable for equality. The caller is expected to maintain the logical
171 /// consistency of the system.
172 ///
173 /// The InequalityGraph class may invalidate Node*s after any mutator call.
174 /// @brief The InequalityGraph stores the relationships between values.
175 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000176 ETNode *TreeRoot;
177
178 InequalityGraph(); // DO NOT IMPLEMENT
179 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000180 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000181 explicit InequalityGraph(ETNode *TreeRoot) : TreeRoot(TreeRoot) {}
182
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000183 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000184
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000185 /// This is a StrictWeakOrdering predicate that sorts ETNodes by how many
186 /// children they have. With this, you can iterate through a list sorted by
187 /// this operation and the first matching entry is the most specific match
188 /// for your basic block. The order provided is total; ETNodes with the
189 /// same number of children are sorted by pointer address.
190 struct VISIBILITY_HIDDEN OrderByDominance {
191 bool operator()(const ETNode *LHS, const ETNode *RHS) const {
192 unsigned LHS_spread = LHS->getDFSNumOut() - LHS->getDFSNumIn();
193 unsigned RHS_spread = RHS->getDFSNumOut() - RHS->getDFSNumIn();
194 if (LHS_spread != RHS_spread) return LHS_spread < RHS_spread;
195 else return LHS < RHS;
196 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000197 };
198
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000199 /// An Edge is contained inside a Node making one end of the edge implicit
200 /// and contains a pointer to the other end. The edge contains a lattice
201 /// value specifying the relationship between the two nodes. Further, there
202 /// is an ETNode specifying which subtree of the dominator the edge applies.
203 class VISIBILITY_HIDDEN Edge {
204 public:
205 Edge(unsigned T, LatticeVal V, ETNode *ST)
206 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000207
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000208 unsigned To;
209 LatticeVal LV;
210 ETNode *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000211
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000212 bool operator<(const Edge &edge) const {
213 if (To != edge.To) return To < edge.To;
214 else return OrderByDominance()(Subtree, edge.Subtree);
215 }
216 bool operator<(unsigned to) const {
217 return To < to;
218 }
219 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000220
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000221 /// A single node in the InequalityGraph. This stores the canonical Value
222 /// for the node, as well as the relationships with the neighbours.
223 ///
224 /// Because the lists are intended to be used for traversal, it is invalid
225 /// for the node to list itself in LessEqual or GreaterEqual lists. The
226 /// fact that a node is equal to itself is implied, and may be checked
227 /// with pointer comparison.
228 /// @brief A single node in the InequalityGraph.
229 class VISIBILITY_HIDDEN Node {
230 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000231
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000232 typedef SmallVector<Edge, 4> RelationsType;
233 RelationsType Relations;
234
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000235 Value *Canonical;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000236
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000237 // TODO: can this idea improve performance?
238 //friend class std::vector<Node>;
239 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
240
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000241 public:
242 typedef RelationsType::iterator iterator;
243 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000244
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000245 Node(Value *V) : Canonical(V) {}
246
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000247 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000248#ifndef NDEBUG
249 public:
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000250 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000251 virtual void dump() const {
252 dump(*cerr.stream());
253 }
254 private:
255 void dump(std::ostream &os) const {
256 os << *getValue() << ":\n";
257 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
258 static const std::string names[32] =
259 { "000000", "000001", "000002", "000003", "000004", "000005",
260 "000006", "000007", "000008", "000009", " >", " >=",
261 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
262 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
263 "000024", "000025", " u>", " u>=", " u<", " u<=",
264 " !=", "000031" };
265 os << " " << names[NI->LV] << " " << NI->To
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000266 << " (" << NI->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000267 }
268 }
269#endif
270
271 public:
272 iterator begin() { return Relations.begin(); }
273 iterator end() { return Relations.end(); }
274 const_iterator begin() const { return Relations.begin(); }
275 const_iterator end() const { return Relations.end(); }
276
277 iterator find(unsigned n, ETNode *Subtree) {
278 iterator E = end();
279 for (iterator I = std::lower_bound(begin(), E, n);
280 I != E && I->To == n; ++I) {
281 if (Subtree->DominatedBy(I->Subtree))
282 return I;
283 }
284 return E;
285 }
286
287 const_iterator find(unsigned n, ETNode *Subtree) const {
288 const_iterator E = end();
289 for (const_iterator I = std::lower_bound(begin(), E, n);
290 I != E && I->To == n; ++I) {
291 if (Subtree->DominatedBy(I->Subtree))
292 return I;
293 }
294 return E;
295 }
296
297 Value *getValue() const
298 {
299 return Canonical;
300 }
301
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000302 /// Updates the lattice value for a given node. Create a new entry if
303 /// one doesn't exist, otherwise it merges the values. The new lattice
304 /// value must not be inconsistent with any previously existing value.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000305 void update(unsigned n, LatticeVal R, ETNode *Subtree) {
306 assert(validPredicate(R) && "Invalid predicate.");
307 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000308 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000309 Edge edge(n, R, Subtree);
310 iterator Insert = std::lower_bound(begin(), end(), edge);
311 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000312 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000313 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
314 assert(validPredicate(LV) && "Invalid union of lattice values.");
315 if (LV != I->LV) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000316 if (Subtree != I->Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000317 assert(Subtree->DominatedBy(I->Subtree) &&
318 "Find returned subtree that doesn't apply.");
319
320 Edge edge(n, R, Subtree);
321 iterator Insert = std::lower_bound(begin(), end(), edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000322 Relations.insert(Insert, edge); // invalidates I
323 I = find(n, Subtree);
324 }
325
326 // Also, we have to tighten any edge that Subtree dominates.
327 for (iterator B = begin(); I->To == n; --I) {
328 if (I->Subtree->DominatedBy(Subtree)) {
329 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
330 assert(validPredicate(LV) && "Invalid union of lattice values.");
331 I->LV = LV;
332 }
333 if (I == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000334 }
335 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000336 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000337 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000338 };
339
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000340 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000341 struct VISIBILITY_HIDDEN NodeMapEdge {
342 Value *V;
343 unsigned index;
344 ETNode *Subtree;
345
346 NodeMapEdge(Value *V, unsigned index, ETNode *Subtree)
347 : V(V), index(index), Subtree(Subtree) {}
348
349 bool operator==(const NodeMapEdge &RHS) const {
350 return V == RHS.V &&
351 Subtree == RHS.Subtree;
352 }
353
354 bool operator<(const NodeMapEdge &RHS) const {
355 if (V != RHS.V) return V < RHS.V;
356 return OrderByDominance()(Subtree, RHS.Subtree);
357 }
358
359 bool operator<(Value *RHS) const {
360 return V < RHS;
361 }
362 };
363
364 typedef std::vector<NodeMapEdge> NodeMapType;
365 NodeMapType NodeMap;
366
367 std::vector<Node> Nodes;
368
Nick Lewycky56639802007-01-29 02:56:54 +0000369 std::vector<std::pair<ConstantInt *, unsigned> > Ints;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000370
Nick Lewycky56639802007-01-29 02:56:54 +0000371 /// This is used to keep the ConstantInts list in unsigned ascending order.
372 /// If the bitwidths don't match, this sorts smaller values ahead.
373 struct SortByZExt {
374 bool operator()(const std::pair<ConstantInt *, unsigned> &LHS,
375 const std::pair<ConstantInt *, unsigned> &RHS) const {
376 if (LHS.first->getType()->getBitWidth() !=
377 RHS.first->getType()->getBitWidth())
378 return LHS.first->getType()->getBitWidth() <
379 RHS.first->getType()->getBitWidth();
380 return LHS.first->getZExtValue() < RHS.first->getZExtValue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000381 }
Nick Lewycky56639802007-01-29 02:56:54 +0000382 };
383
384 /// True when the bitwidth of LHS < bitwidth of RHS.
385 struct FindByIntegerWidth {
386 bool operator()(const std::pair<ConstantInt *, unsigned> &LHS,
387 const std::pair<ConstantInt *, unsigned> &RHS) const {
388 return LHS.first->getType()->getBitWidth() <
389 RHS.first->getType()->getBitWidth();
390 }
391 };
392
393 void initializeInt(ConstantInt *CI, unsigned index) {
394 std::vector<std::pair<ConstantInt *, unsigned> >::iterator begin, end,
395 last, iULT, iUGT, iSLT, iSGT;
396
397 std::pair<ConstantInt *, unsigned> pair = std::make_pair(CI, index);
398
399 begin = std::lower_bound(Ints.begin(), Ints.end(), pair,
400 FindByIntegerWidth());
401 end = std::upper_bound(begin, Ints.end(), pair, FindByIntegerWidth());
402
403 if (begin == end) last = end;
404 else last = end - 1;
405
406 iUGT = std::lower_bound(begin, end, pair, SortByZExt());
407 iULT = (iUGT == begin || begin == end) ? end : iUGT - 1;
408
409 if (iUGT != end && iULT != end &&
410 (iULT->first->getSExtValue() >> 63) ==
411 (iUGT->first->getSExtValue() >> 63)) { // signs match
412 iSGT = iUGT;
413 iSLT = iULT;
414 } else {
415 if (iULT == end || iUGT == end) {
416 if (iULT == end) iSLT = last; else iSLT = iULT;
417 if (iUGT == end) iSGT = begin; else iSGT = iUGT;
418 } else if (iULT->first->getSExtValue() < 0) {
419 assert(iUGT->first->getSExtValue() >= 0 && "Bad sign comparison.");
420 iSGT = iUGT;
421 iSLT = iULT;
422 } else {
423 assert(iULT->first->getSExtValue() >= 0 &&
424 iUGT->first->getSExtValue() < 0 && "Bad sign comparison.");
425 iSGT = iULT;
426 iSLT = iUGT;
427 }
428
429 if (iSGT != end &&
430 iSGT->first->getSExtValue() < CI->getSExtValue()) iSGT = end;
431 if (iSLT != end &&
432 iSLT->first->getSExtValue() > CI->getSExtValue()) iSLT = end;
433
434 if (begin != end) {
435 if (begin->first->getSExtValue() < CI->getSExtValue())
436 if (iSLT == end ||
437 begin->first->getSExtValue() > iSLT->first->getSExtValue())
438 iSLT = begin;
439 }
440 if (last != end) {
441 if (last->first->getSExtValue() > CI->getSExtValue())
442 if (iSGT == end ||
443 last->first->getSExtValue() < iSGT->first->getSExtValue())
444 iSGT = last;
445 }
446 }
447
448 if (iULT != end) addInequality(iULT->second, index, TreeRoot, ULT);
449 if (iUGT != end) addInequality(iUGT->second, index, TreeRoot, UGT);
450 if (iSLT != end) addInequality(iSLT->second, index, TreeRoot, SLT);
451 if (iSGT != end) addInequality(iSGT->second, index, TreeRoot, SGT);
452
453 Ints.insert(iUGT, pair);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000454 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000455
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000456 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000457 /// node - returns the node object at a given index retrieved from getNode.
458 /// Index zero is reserved and may not be passed in here. The pointer
459 /// returned is valid until the next call to newNode or getOrInsertNode.
460 Node *node(unsigned index) {
461 assert(index != 0 && "Zero index is reserved for not found.");
462 assert(index <= Nodes.size() && "Index out of range.");
463 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000464 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000465
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000466 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000467 /// node exists.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000468 unsigned getNode(Value *V, ETNode *Subtree) {
469 NodeMapType::iterator E = NodeMap.end();
470 NodeMapEdge Edge(V, 0, Subtree);
471 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
472 while (I != E && I->V == V) {
473 if (Subtree->DominatedBy(I->Subtree))
474 return I->index;
475 ++I;
476 }
477 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000478 }
479
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000480 /// getOrInsertNode - always returns a valid node index, creating a node
481 /// to match the Value if needed.
482 unsigned getOrInsertNode(Value *V, ETNode *Subtree) {
483 if (unsigned n = getNode(V, Subtree))
484 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000485 else
486 return newNode(V);
487 }
488
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000489 /// newNode - creates a new node for a given Value and returns the index.
490 unsigned newNode(Value *V) {
491 Nodes.push_back(Node(V));
492
493 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
494 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
495 "Attempt to create a duplicate Node.");
496 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
497 MapEntry), MapEntry);
498
Nick Lewycky56639802007-01-29 02:56:54 +0000499 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
500 initializeInt(CI, MapEntry.index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000501
502 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000503 }
504
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000505 /// If the Value is in the graph, return the canonical form. Otherwise,
506 /// return the original Value.
507 Value *canonicalize(Value *V, ETNode *Subtree) {
508 if (isa<Constant>(V)) return V;
509
510 if (unsigned n = getNode(V, Subtree))
511 return node(n)->getValue();
512 else
513 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000514 }
515
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000516 /// isRelatedBy - true iff n1 op n2
517 bool isRelatedBy(unsigned n1, unsigned n2, ETNode *Subtree, LatticeVal LV) {
518 if (n1 == n2) return LV & EQ_BIT;
519
520 Node *N1 = node(n1);
521 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
522 if (I != E) return (I->LV & LV) == I->LV;
523
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000524 return false;
525 }
526
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000527 // The add* methods assume that your input is logically valid and may
528 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000529
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000530 void addEquality(unsigned n, Value *V, ETNode *Subtree) {
531 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
532 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000533
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000534 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
535 // we may already have "%z -> node #2 (%x)" somewhere above us in the
536 // graph. We need to find those edges and add "%z -> node #1 (%y)"
537 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000538
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000539 std::vector<Value *> ToRepoint;
540 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000541
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000542 if (unsigned Conflict = getNode(V, Subtree)) {
Nick Lewycky56639802007-01-29 02:56:54 +0000543 // XXX: NodeMap.size() exceeds 68,000 entries compiling kimwitu++!
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000544 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
545 I != E; ++I) {
546 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
547 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000548 }
549 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000550
551 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
552 VE = ToRepoint.end(); VI != VE; ++VI) {
553 Value *V = *VI;
554
555 // XXX: review this code. This may be doing too many insertions.
556 NodeMapEdge Edge(V, n, Subtree);
557 NodeMapType::iterator E = NodeMap.end();
558 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
559 if (I == E || I->V != V || I->Subtree != Subtree) {
560 // New Value
561 NodeMap.insert(I, Edge);
562 } else if (I != E && I->V == V && I->Subtree == Subtree) {
563 // Update best choice
564 I->index = n;
565 }
566
567#ifndef NDEBUG
568 Node *N = node(n);
569 if (isa<Constant>(V)) {
570 if (isa<Constant>(N->getValue())) {
571 assert(V == N->getValue() && "Constant equals different constant?");
572 }
573 }
574#endif
575 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000576 }
577
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000578 /// addInequality - Sets n1 op n2.
579 /// It is also an error to call this on an inequality that is already true.
580 void addInequality(unsigned n1, unsigned n2, ETNode *Subtree,
581 LatticeVal LV1) {
582 assert(n1 != n2 && "A node can't be inequal to itself.");
583
584 if (LV1 != NE)
585 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
586 "Contradictory inequality.");
587
588 Node *N1 = node(n1);
589 Node *N2 = node(n2);
590
591 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
592 // add %a < %n2 too. This keeps the graph fully connected.
593 if (LV1 != NE) {
594 // Someone with a head for this sort of logic, please review this.
Nick Lewycky56639802007-01-29 02:56:54 +0000595 // Given that %x SLTUGT %y and %a SLE %x, what is the relationship
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000596 // between %a and %y? I believe the below code is correct, but I don't
597 // think it's the most efficient solution.
598
599 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
600 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
601 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
602 if (I->LV != NE && I->To != n2) {
603 ETNode *Local_Subtree = NULL;
604 if (Subtree->DominatedBy(I->Subtree))
605 Local_Subtree = Subtree;
606 else if (I->Subtree->DominatedBy(Subtree))
607 Local_Subtree = I->Subtree;
608
609 if (Local_Subtree) {
610 unsigned new_relationship = 0;
611 LatticeVal ILV = reversePredicate(I->LV);
612 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
613 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
614
615 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
616 new_relationship |= ILV_s;
617
618 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
619 new_relationship |= ILV_u;
620
621 if (new_relationship) {
622 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
623 new_relationship |= (SLT_BIT|SGT_BIT);
624 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
625 new_relationship |= (ULT_BIT|UGT_BIT);
626 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
627 new_relationship |= EQ_BIT;
628
629 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
630
631 node(I->To)->update(n2, NewLV, Local_Subtree);
632 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
633 }
634 }
635 }
636 }
637
638 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
639 if (I->LV != NE && I->To != n1) {
640 ETNode *Local_Subtree = NULL;
641 if (Subtree->DominatedBy(I->Subtree))
642 Local_Subtree = Subtree;
643 else if (I->Subtree->DominatedBy(Subtree))
644 Local_Subtree = I->Subtree;
645
646 if (Local_Subtree) {
647 unsigned new_relationship = 0;
648 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
649 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
650
651 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
652 new_relationship |= ILV_s;
653
654 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
655 new_relationship |= ILV_u;
656
657 if (new_relationship) {
658 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
659 new_relationship |= (SLT_BIT|SGT_BIT);
660 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
661 new_relationship |= (ULT_BIT|UGT_BIT);
662 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
663 new_relationship |= EQ_BIT;
664
665 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
666
667 N1->update(I->To, NewLV, Local_Subtree);
668 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
669 }
670 }
671 }
672 }
673 }
674
675 N1->update(n2, LV1, Subtree);
676 N2->update(n1, reversePredicate(LV1), Subtree);
677 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000678
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000679 /// Removes a Value from the graph, but does not delete any nodes. As this
680 /// method does not delete Nodes, V may not be the canonical choice for
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000681 /// a node with any relationships. It is invalid to call newNode on a Value
682 /// that has been removed.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000683 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000684 for (unsigned i = 0; i < NodeMap.size();) {
685 NodeMapType::iterator I = NodeMap.begin()+i;
686 assert((node(I->index)->getValue() != V || node(I->index)->begin() ==
687 node(I->index)->end()) && "Tried to delete in-use node.");
688 if (I->V == V) {
689#ifndef NDEBUG
690 if (node(I->index)->getValue() == V)
691 node(I->index)->Canonical = NULL;
692#endif
693 NodeMap.erase(I);
694 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000695 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000696 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000697
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000698#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000699 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000700 virtual void dump() {
701 dump(*cerr.stream());
702 }
703
704 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000705 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000706 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000707 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000708 Node *N = node(I->index);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000709 os << *I->V << " == " << I->index
710 << "(" << I->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000711 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000712 os << I->index << ". ";
713 if (!N->getValue()) os << "(deleted node)\n";
714 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000715 }
716 }
717 }
718#endif
719 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000720
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000721 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
722 /// another discovered to be unreachable. This is used to cull the graph when
723 /// analyzing instructions, and to mark blocks with the "unreachable"
724 /// terminator instruction after the function has executed.
725 class VISIBILITY_HIDDEN UnreachableBlocks {
726 private:
727 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000728
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000729 public:
730 /// mark - mark a block as dead
731 void mark(BasicBlock *BB) {
732 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
733 std::vector<BasicBlock *>::iterator I =
734 std::lower_bound(DeadBlocks.begin(), E, BB);
735
736 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000737 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000738
739 /// isDead - returns whether a block is known to be dead already
740 bool isDead(BasicBlock *BB) {
741 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
742 std::vector<BasicBlock *>::iterator I =
743 std::lower_bound(DeadBlocks.begin(), E, BB);
744
745 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000746 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000747
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000748 /// kill - replace the dead blocks' terminator with an UnreachableInst.
749 bool kill() {
750 bool modified = false;
751 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
752 E = DeadBlocks.end(); I != E; ++I) {
753 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000754
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000755 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000756
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000757 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
758 SI != SE; ++SI) {
759 BasicBlock *Succ = *SI;
760 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +0000761 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000762
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000763 TerminatorInst *TI = BB->getTerminator();
764 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
765 TI->eraseFromParent();
766 new UnreachableInst(BB);
767 ++NumBlocks;
768 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000769 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000770 DeadBlocks.clear();
771 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000772 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000773 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000774
775 /// VRPSolver keeps track of how changes to one variable affect other
776 /// variables, and forwards changes along to the InequalityGraph. It
777 /// also maintains the correct choice for "canonical" in the IG.
778 /// @brief VRPSolver calculates inferences from a new relationship.
779 class VISIBILITY_HIDDEN VRPSolver {
780 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000781 struct Operation {
782 Value *LHS, *RHS;
783 ICmpInst::Predicate Op;
784
Nick Lewycky42944462007-01-13 02:05:28 +0000785 BasicBlock *ContextBB;
786 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000787 };
788 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000789
790 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000791 UnreachableBlocks &UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000792 ETForest *Forest;
793 ETNode *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000794 BasicBlock *TopBB;
795 Instruction *TopInst;
796 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000797
798 typedef InequalityGraph::Node Node;
799
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000800 /// IdomI - Determines whether one Instruction dominates another.
801 bool IdomI(Instruction *I1, Instruction *I2) const {
802 BasicBlock *BB1 = I1->getParent(),
803 *BB2 = I2->getParent();
804 if (BB1 == BB2) {
805 if (isa<TerminatorInst>(I1)) return false;
806 if (isa<TerminatorInst>(I2)) return true;
807 if (isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
808 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
809
810 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
811 I != E; ++I) {
812 if (&*I == I1) return true;
813 if (&*I == I2) return false;
814 }
815 assert(!"Instructions not found in parent BasicBlock?");
816 } else {
817 return Forest->properlyDominates(BB1, BB2);
818 }
819 return false;
820 }
821
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000822 /// Returns true if V1 is a better canonical value than V2.
823 bool compare(Value *V1, Value *V2) const {
824 if (isa<Constant>(V1))
825 return !isa<Constant>(V2);
826 else if (isa<Constant>(V2))
827 return false;
828 else if (isa<Argument>(V1))
829 return !isa<Argument>(V2);
830 else if (isa<Argument>(V2))
831 return false;
832
833 Instruction *I1 = dyn_cast<Instruction>(V1);
834 Instruction *I2 = dyn_cast<Instruction>(V2);
835
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000836 if (!I1 || !I2)
837 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000838
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000839 return IdomI(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000840 }
841
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000842 // below - true if the Instruction is dominated by the current context
843 // block or instruction
844 bool below(Instruction *I) {
845 if (TopInst)
846 return IdomI(TopInst, I);
847 else {
848 ETNode *Node = Forest->getNodeForBlock(I->getParent());
Nick Lewycky56639802007-01-29 02:56:54 +0000849 return Node->DominatedBy(Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000850 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000851 }
852
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000853 bool makeEqual(Value *V1, Value *V2) {
854 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +0000855
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000856 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000857
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000858 if (isa<Constant>(V1) && isa<Constant>(V2))
859 return false;
860
861 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
862
863 if (n1 && n2) {
864 if (n1 == n2) return true;
865 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
866 }
867
868 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
869 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
870
871 if (compare(V2, V1)) { std::swap(V1, V2); std::swap(n1, n2); }
872
873 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
874
875 SetVector<unsigned> Remove;
876 if (n2) Remove.insert(n2);
877
878 if (n1 && n2) {
879 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
880 // We can't just merge %x and %y because the relationship with %z would
881 // be EQ and that's invalid. What we're doing is looking for any nodes
882 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000883
884 Node *N1 = IG.node(n1);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000885 Node *N2 = IG.node(n2);
886 Node::iterator end = N2->end();
887
888 // Find the intersection between N1 and N2 which is dominated by
889 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
890 // Remove.
891 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
892 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
893
894 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
895 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
896 Node::iterator NI = N2->find(I->To, Top);
897 if (NI != end) {
898 LatticeVal NILV = reversePredicate(NI->LV);
899 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
900 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
901
902 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
903 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
904 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000905 }
906 }
907
908 // See if one of the nodes about to be removed is actually a better
909 // canonical choice than n1.
910 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +0000911 SetVector<unsigned>::iterator DontRemove = Remove.end();
912 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000913 E = Remove.end(); I != E; ++I) {
914 unsigned n = *I;
915 Value *V = IG.node(n)->getValue();
916 if (compare(V, V1)) {
917 V1 = V;
918 n1 = n;
919 DontRemove = I;
920 }
921 }
922 if (DontRemove != Remove.end()) {
923 unsigned n = *DontRemove;
924 Remove.remove(n);
925 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000926 }
927 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000928
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000929 // We'd like to allow makeEqual on two values to perform a simple
930 // substitution without every creating nodes in the IG whenever possible.
931 //
932 // The first iteration through this loop operates on V2 before going
933 // through the Remove list and operating on those too. If all of the
934 // iterations performed simple replacements then we exit early.
935 bool exitEarly = true;
936 unsigned i = 0;
937 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
938 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
939
940 // Try to replace the whole instruction. If we can, we're done.
941 Instruction *I2 = dyn_cast<Instruction>(R);
942 if (I2 && below(I2)) {
943 std::vector<Instruction *> ToNotify;
944 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
945 UI != UE;) {
946 Use &TheUse = UI.getUse();
947 ++UI;
948 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
949 ToNotify.push_back(I);
950 }
951
952 DOUT << "Simply removing " << *I2
953 << ", replacing with " << *V1 << "\n";
954 I2->replaceAllUsesWith(V1);
955 // leave it dead; it'll get erased later.
956 ++NumInstruction;
957 modified = true;
958
959 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
960 IE = ToNotify.end(); II != IE; ++II) {
961 opsToDef(*II);
962 }
963
964 continue;
965 }
966
967 // Otherwise, replace all dominated uses.
968 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
969 UI != UE;) {
970 Use &TheUse = UI.getUse();
971 ++UI;
972 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
973 if (below(I)) {
974 TheUse.set(V1);
975 modified = true;
976 ++NumVarsReplaced;
977 opsToDef(I);
978 }
979 }
980 }
981
982 // If that killed the instruction, stop here.
983 if (I2 && isInstructionTriviallyDead(I2)) {
984 DOUT << "Killed all uses of " << *I2
985 << ", replacing with " << *V1 << "\n";
986 continue;
987 }
988
989 // If we make it to here, then we will need to create a node for N1.
990 // Otherwise, we can skip out early!
991 exitEarly = false;
992 }
993
994 if (exitEarly) return true;
995
996 // Create N1.
997 // XXX: this should call newNode, but instead the node might be created
998 // in isRelatedBy. That's also a fixme.
Nick Lewycky56639802007-01-29 02:56:54 +0000999 if (!n1) {
1000 n1 = IG.getOrInsertNode(V1, Top);
1001
1002 if (isa<ConstantInt>(V1))
1003 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1004 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001005
1006 // Migrate relationships from removed nodes to N1.
1007 Node *N1 = IG.node(n1);
Reid Spencera8a15472007-01-17 02:23:37 +00001008 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001009 I != E; ++I) {
1010 unsigned n = *I;
1011 Node *N = IG.node(n);
1012 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
Nick Lewycky56639802007-01-29 02:56:54 +00001013 if (NI->Subtree->DominatedBy(Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001014 if (NI->To == n1) {
1015 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1016 continue;
1017 }
1018 if (Remove.count(NI->To))
1019 continue;
1020
1021 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1022 N1->update(NI->To, NI->LV, Top);
1023 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001024 }
1025 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001026
1027 // Point V2 (and all items in Remove) to N1.
1028 if (!n2)
1029 IG.addEquality(n1, V2, Top);
1030 else {
Reid Spencera8a15472007-01-17 02:23:37 +00001031 for (SetVector<unsigned>::iterator I = Remove.begin(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001032 E = Remove.end(); I != E; ++I) {
1033 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
1034 }
1035 }
1036
1037 // If !Remove.empty() then V2 = Remove[0]->getValue().
1038 // Even when Remove is empty, we still want to process V2.
1039 i = 0;
1040 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1041 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1042
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001043 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1044 if (below(I2) ||
1045 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1046 defToOps(I2);
1047 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001048 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1049 UI != UE;) {
1050 Use &TheUse = UI.getUse();
1051 ++UI;
1052 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001053 if (below(I) ||
1054 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1055 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001056 }
1057 }
1058 }
1059
1060 return true;
1061 }
1062
1063 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1064 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1065 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1066 switch (Pred) {
1067 case ICmpInst::ICMP_EQ:
1068 assert(!"No matching lattice value.");
1069 return static_cast<LatticeVal>(EQ_BIT);
1070 default:
1071 assert(!"Invalid 'icmp' predicate.");
1072 case ICmpInst::ICMP_NE:
1073 return NE;
1074 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001075 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001076 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001077 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001078 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001079 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001080 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001081 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001082 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001083 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001084 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001085 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001086 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001087 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001088 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001089 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001090 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001091 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001092
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001093 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001094 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1095 bool &modified, BasicBlock *TopBB)
1096 : IG(IG),
1097 UB(UB),
1098 Forest(Forest),
1099 Top(Forest->getNodeForBlock(TopBB)),
1100 TopBB(TopBB),
1101 TopInst(NULL),
1102 modified(modified) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +00001103
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001104 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1105 bool &modified, Instruction *TopInst)
1106 : IG(IG),
1107 UB(UB),
1108 Forest(Forest),
1109 TopInst(TopInst),
1110 modified(modified)
1111 {
1112 TopBB = TopInst->getParent();
1113 Top = Forest->getNodeForBlock(TopBB);
1114 }
1115
1116 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1117 if (Constant *C1 = dyn_cast<Constant>(V1))
1118 if (Constant *C2 = dyn_cast<Constant>(V2))
1119 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001120 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001121
1122 // XXX: this is lousy. If we're passed a Constant, then we might miss
1123 // some relationships if it isn't in the IG because the relationships
1124 // added by initializeConstant are missing.
1125 if (isa<Constant>(V1)) IG.getOrInsertNode(V1, Top);
1126 if (isa<Constant>(V2)) IG.getOrInsertNode(V2, Top);
1127
1128 if (unsigned n1 = IG.getNode(V1, Top))
1129 if (unsigned n2 = IG.getNode(V2, Top)) {
1130 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1131 Pred == ICmpInst::ICMP_ULE ||
1132 Pred == ICmpInst::ICMP_UGE ||
1133 Pred == ICmpInst::ICMP_SLE ||
1134 Pred == ICmpInst::ICMP_SGE;
1135 if (Pred == ICmpInst::ICMP_EQ) return false;
1136 return IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred));
1137 }
1138
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001139 return false;
1140 }
1141
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001142 /// add - adds a new property to the work queue
1143 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1144 Instruction *I = NULL) {
1145 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1146 if (I) DOUT << " context: " << *I;
1147 else DOUT << " default context";
1148 DOUT << "\n";
1149
1150 WorkList.push_back(Operation());
1151 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001152 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1153 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001154 }
1155
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001156 /// defToOps - Given an instruction definition that we've learned something
1157 /// new about, find any new relationships between its operands.
1158 void defToOps(Instruction *I) {
1159 Instruction *NewContext = below(I) ? I : TopInst;
1160 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001161
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1163 const Type *Ty = BO->getType();
1164 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001165
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001166 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1167 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001168
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001169 // TODO: "and bool true, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001170
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001171 switch (BO->getOpcode()) {
1172 case Instruction::And: {
1173 // "and int %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1174 // "and bool %a, %b" EQ true then %a EQ true and %b EQ true
Zhou Sheng75b871f2007-01-11 12:24:14 +00001175 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001176 if (Canonical == CI) {
1177 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1178 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001179 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001180 } break;
1181 case Instruction::Or: {
1182 // "or int %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1183 // "or bool %a, %b" EQ false then %a EQ false and %b EQ false
1184 Constant *Zero = Constant::getNullValue(Ty);
1185 if (Canonical == Zero) {
1186 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1187 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1188 }
1189 } break;
1190 case Instruction::Xor: {
1191 // "xor bool true, %a" EQ true then %a EQ false
1192 // "xor bool true, %a" EQ false then %a EQ true
1193 // "xor bool false, %a" EQ true then %a EQ true
1194 // "xor bool false, %a" EQ false then %a EQ false
1195 // "xor int %c, %a" EQ %c then %a EQ 0
1196 // "xor int %c, %a" NE %c then %a NE 0
1197 // 1. Repeat all of the above, with order of operands reversed.
1198 Value *LHS = Op0;
1199 Value *RHS = Op1;
1200 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1201
Nick Lewycky4a74a752007-01-12 00:02:12 +00001202 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1203 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1204 add(RHS, ConstantInt::get(CI->getType(), CI->getZExtValue() ^
1205 Arg->getZExtValue()),
1206 ICmpInst::ICMP_EQ, NewContext);
1207 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001208 }
1209 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001210 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001211 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1212 NewContext);
1213 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1214 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1215 NewContext);
1216 }
1217 } break;
1218 default:
1219 break;
1220 }
1221 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1222 // "icmp ult int %a, int %y" EQ true then %a u< y
1223 // etc.
1224
Zhou Sheng75b871f2007-01-11 12:24:14 +00001225 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001226 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1227 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001228 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001229 add(IC->getOperand(0), IC->getOperand(1),
1230 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1231 }
1232 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1233 if (I->getType()->isFPOrFPVector()) return;
1234
1235 // Given: "%a = select bool %x, int %b, int %c"
1236 // %a EQ %b and %b NE %c then %x EQ true
1237 // %a EQ %c and %b NE %c then %x EQ false
1238
1239 Value *True = SI->getTrueValue();
1240 Value *False = SI->getFalseValue();
1241 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1242 if (Canonical == IG.canonicalize(True, Top) ||
1243 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001244 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001245 ICmpInst::ICMP_EQ, NewContext);
1246 else if (Canonical == IG.canonicalize(False, Top) ||
1247 isRelatedBy(I, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001248 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001249 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001250 }
1251 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001252 // TODO: CastInst "%a = cast ... %b" where %a is EQ or NE a constant.
1253 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001254
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001255 /// opsToDef - A new relationship was discovered involving one of this
1256 /// instruction's operands. Find any new relationship involving the
1257 /// definition.
1258 void opsToDef(Instruction *I) {
1259 Instruction *NewContext = below(I) ? I : TopInst;
1260
1261 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1262 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1263 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1264
Zhou Sheng75b871f2007-01-11 12:24:14 +00001265 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1266 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001267 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1268 ICmpInst::ICMP_EQ, NewContext);
1269 return;
1270 }
1271
1272 // "%y = and bool true, %x" then %x EQ %y.
1273 // "%y = or bool false, %x" then %x EQ %y.
1274 if (BO->getOpcode() == Instruction::Or) {
1275 Constant *Zero = Constant::getNullValue(BO->getType());
1276 if (Op0 == Zero) {
1277 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1278 return;
1279 } else if (Op1 == Zero) {
1280 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1281 return;
1282 }
1283 } else if (BO->getOpcode() == Instruction::And) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001284 Constant *AllOnes = ConstantInt::getAllOnesValue(BO->getType());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001285 if (Op0 == AllOnes) {
1286 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1287 return;
1288 } else if (Op1 == AllOnes) {
1289 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1290 return;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001291 }
1292 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001293
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001294 // "%x = add int %y, %z" and %x EQ %y then %z EQ 0
1295 // "%x = mul int %y, %z" and %x EQ %y then %z EQ 1
1296 // 1. Repeat all of the above, with order of operands reversed.
1297 // "%x = udiv int %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001298
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001299 Value *Known = Op0, *Unknown = Op1;
1300 if (Known != BO) std::swap(Known, Unknown);
1301 if (Known == BO) {
1302 const Type *Ty = BO->getType();
1303 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001304
1305 switch (BO->getOpcode()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001306 default: break;
1307 case Instruction::Xor:
1308 case Instruction::Or:
1309 case Instruction::Add:
1310 case Instruction::Sub:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001311 add(Unknown, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1312 NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001313 break;
1314 case Instruction::UDiv:
1315 case Instruction::SDiv:
1316 if (Unknown == Op0) break; // otherwise, fallthrough
1317 case Instruction::And:
1318 case Instruction::Mul:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001319 if (isa<ConstantInt>(Unknown)) {
1320 Constant *One = ConstantInt::get(Ty, 1);
1321 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1322 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001323 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001324 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001325 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001326
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001327 // TODO: "%a = add int %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001328
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001329 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1330 // "%a = icmp ult %b, %c" and %b u< %c then %a EQ true
1331 // "%a = icmp ult %b, %c" and %b u>= %c then %a EQ false
1332 // etc.
1333
1334 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1335 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1336
1337 ICmpInst::Predicate Pred = IC->getPredicate();
1338 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001339 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001340 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001341 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001342 }
1343
Nick Lewycky4a74a752007-01-12 00:02:12 +00001344 // TODO: "bool %x s<u> %y" implies %x = true and %y = false.
1345
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001346 // TODO: make the predicate more strict, if possible.
1347
1348 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1349 // Given: "%a = select bool %x, int %b, int %c"
1350 // %x EQ true then %a EQ %b
1351 // %x EQ false then %a EQ %c
1352 // %b EQ %c then %a EQ %b
1353
1354 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001355 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001356 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001357 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001358 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1359 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1360 IG.canonicalize(SI->getFalseValue(), Top)) {
1361 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1362 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001363 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1364 if (CI->getDestTy()->isFPOrFPVector()) return;
1365
1366 if (Constant *C = dyn_cast<Constant>(
1367 IG.canonicalize(CI->getOperand(0), Top))) {
1368 add(CI, ConstantExpr::getCast(CI->getOpcode(), C, CI->getDestTy()),
1369 ICmpInst::ICMP_EQ, NewContext);
1370 }
1371
1372 // TODO: "%a = cast ... %b" where %b is NE/LT/GT a constant.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001373 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001374 }
1375
1376 /// solve - process the work queue
1377 /// Return false if a logical contradiction occurs.
1378 void solve() {
1379 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
1380 while (!WorkList.empty()) {
1381 //DOUT << "WorkList size: " << WorkList.size() << "\n";
1382
1383 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00001384 TopInst = O.ContextInst;
1385 TopBB = O.ContextBB;
1386 Top = Forest->getNodeForBlock(TopBB);
1387
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001388 O.LHS = IG.canonicalize(O.LHS, Top);
1389 O.RHS = IG.canonicalize(O.RHS, Top);
1390
1391 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
1392 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
1393
1394 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00001395 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
1396 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001397 DOUT << "\n";
1398
1399 DEBUG(IG.dump());
1400
1401 // TODO: actually check the constants and add to UB.
1402 if (isa<Constant>(O.LHS) && isa<Constant>(O.RHS)) {
1403 WorkList.pop_front();
1404 continue;
1405 }
1406
1407 if (O.Op == ICmpInst::ICMP_EQ) {
1408 if (!makeEqual(O.LHS, O.RHS))
1409 UB.mark(TopBB);
1410 } else {
1411 LatticeVal LV = cmpInstToLattice(O.Op);
1412
1413 if ((LV & EQ_BIT) &&
1414 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
1415 if (!makeEqual(O.LHS, O.RHS))
1416 UB.mark(TopBB);
1417 } else {
1418 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
1419 DOUT << "inequality contradiction!\n";
1420 WorkList.pop_front();
1421 continue;
1422 }
1423
1424 unsigned n1 = IG.getOrInsertNode(O.LHS, Top);
1425 unsigned n2 = IG.getOrInsertNode(O.RHS, Top);
1426
1427 if (n1 == n2) {
1428 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
1429 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
1430 UB.mark(TopBB);
1431
1432 WorkList.pop_front();
1433 continue;
1434 }
1435
1436 if (IG.isRelatedBy(n1, n2, Top, LV)) {
1437 WorkList.pop_front();
1438 continue;
1439 }
1440
1441 IG.addInequality(n1, n2, Top, LV);
1442
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001443 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
1444 if (below(I1) ||
1445 Top->DominatedBy(Forest->getNodeForBlock(I1->getParent())))
1446 defToOps(I1);
1447 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001448 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
1449 for (Value::use_iterator UI = O.LHS->use_begin(),
1450 UE = O.LHS->use_end(); UI != UE;) {
1451 Use &TheUse = UI.getUse();
1452 ++UI;
1453 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001454 if (below(I) ||
1455 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1456 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001457 }
1458 }
1459 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001460 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
1461 if (below(I2) ||
1462 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1463 defToOps(I2);
1464 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001465 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
1466 for (Value::use_iterator UI = O.RHS->use_begin(),
1467 UE = O.RHS->use_end(); UI != UE;) {
1468 Use &TheUse = UI.getUse();
1469 ++UI;
1470 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001471 if (below(I) ||
1472 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1473
1474 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001475 }
1476 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001477 }
1478 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001479 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001480 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00001481 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001482 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001483 };
1484
1485 /// PredicateSimplifier - This class is a simplifier that replaces
1486 /// one equivalent variable with another. It also tracks what
1487 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001488 /// @brief Root of the predicate simplifier optimization.
1489 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1490 DominatorTree *DT;
1491 ETForest *Forest;
1492 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001493 InequalityGraph *IG;
1494 UnreachableBlocks UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001495
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001496 std::vector<DominatorTree::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001497
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001498 public:
1499 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001500
1501 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1502 AU.addRequiredID(BreakCriticalEdgesID);
1503 AU.addRequired<DominatorTree>();
1504 AU.addRequired<ETForest>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001505 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001506
1507 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001508 /// Forwards - Adds new properties into PropertySet and uses them to
1509 /// simplify instructions. Because new properties sometimes apply to
1510 /// a transition from one BasicBlock to another, this will use the
1511 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1512 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001513 /// @brief Performs abstract execution of the program.
1514 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001515 friend class InstVisitor<Forwards>;
1516 PredicateSimplifier *PS;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001517 DominatorTree::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001518
Nick Lewycky77e030b2006-10-12 02:02:44 +00001519 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001520 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001521 UnreachableBlocks &UB;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001522
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001523 Forwards(PredicateSimplifier *PS, DominatorTree::Node *DTNode)
1524 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001525
1526 void visitTerminatorInst(TerminatorInst &TI);
1527 void visitBranchInst(BranchInst &BI);
1528 void visitSwitchInst(SwitchInst &SI);
1529
Nick Lewyckyf3450082006-10-22 19:53:27 +00001530 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001531 void visitLoadInst(LoadInst &LI);
1532 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001533
Nick Lewycky77e030b2006-10-12 02:02:44 +00001534 void visitBinaryOperator(BinaryOperator &BO);
1535 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001536
1537 // Used by terminator instructions to proceed from the current basic
1538 // block to the next. Verifies that "current" dominates "next",
1539 // then calls visitBasicBlock.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001540 void proceedToSuccessors(DominatorTree::Node *Current) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001541 for (DominatorTree::Node::iterator I = Current->begin(),
1542 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001543 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001544 }
1545 }
1546
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001547 void proceedToSuccessor(DominatorTree::Node *Next) {
1548 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001549 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001550
1551 // Visits each instruction in the basic block.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001552 void visitBasicBlock(DominatorTree::Node *Node) {
1553 BasicBlock *BB = Node->getBlock();
1554 ETNode *ET = Forest->getNodeForBlock(BB);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001555 DOUT << "Entering Basic Block: " << BB->getName()
1556 << " (" << ET->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00001557 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001558 visitInstruction(I++, Node, ET);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001559 }
1560 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001561
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001562 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001563 // the PropertySet.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001564 void visitInstruction(Instruction *I, DominatorTree::Node *DT, ETNode *ET) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001565 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001566 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001567
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001568 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001569 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001570 ++NumSimple;
1571 modified = true;
1572 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001573 I->eraseFromParent();
1574 return;
1575 }
1576
Nick Lewycky42944462007-01-13 02:05:28 +00001577#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001578 // Try to replace the whole instruction.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001579 Value *V = IG->canonicalize(I, ET);
1580 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001581 if (V != I) {
1582 modified = true;
1583 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00001584 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001585 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001586 I->replaceAllUsesWith(V);
1587 I->eraseFromParent();
1588 return;
1589 }
1590
1591 // Try to substitute operands.
1592 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1593 Value *Oper = I->getOperand(i);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001594 Value *V = IG->canonicalize(Oper, ET);
1595 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001596 if (V != Oper) {
1597 modified = true;
1598 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00001599 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001600 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00001601 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001602 }
1603 }
Nick Lewycky42944462007-01-13 02:05:28 +00001604#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001605
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001606 DOUT << "push (%" << I->getParent()->getName() << ")\n";
1607 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001608 visit.visit(*I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001609 DOUT << "pop (%" << I->getParent()->getName() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001610 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001611 };
1612
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001613 bool PredicateSimplifier::runOnFunction(Function &F) {
1614 DT = &getAnalysis<DominatorTree>();
1615 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001616
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001617 Forest->updateDFSNumbers(); // XXX: should only act when numbers are out of date
1618
Bill Wendling22e978a2006-12-07 20:04:42 +00001619 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001620
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001621 modified = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001622 BasicBlock *RootBlock = &F.getEntryBlock();
1623 IG = new InequalityGraph(Forest->getNodeForBlock(RootBlock));
1624 WorkList.push_back(DT->getRootNode());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001625
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001626 do {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001627 DominatorTree::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001628 WorkList.pop_back();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001629 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001630 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001631
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001632 delete IG;
1633
1634 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001635
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001636 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00001637 }
1638
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001639 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001640 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001641 }
1642
1643 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001644 if (BI.isUnconditional()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001645 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001646 return;
1647 }
1648
1649 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001650 BasicBlock *TrueDest = BI.getSuccessor(0);
1651 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001652
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001653 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
1654 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001655 return;
1656 }
1657
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001658 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001659 I != E; ++I) {
1660 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001661 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001662 << "(" << PS->Forest->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001663
1664 if (Dest == TrueDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001665 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
1666 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001667 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001668 VRP.solve();
1669 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001670 } else if (Dest == FalseDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001671 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
1672 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001673 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001674 VRP.solve();
1675 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001676 }
1677
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001678 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001679 }
1680 }
1681
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001682 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
1683 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001684
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001685 // Set the EQProperty in each of the cases BBs, and the NEProperties
1686 // in the default BB.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001687
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001688 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001689 I != E; ++I) {
1690 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001691 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001692 << "(" << PS->Forest->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001693
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001694 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001695 if (BB == SI.getDefaultDest()) {
1696 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
1697 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001698 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
1699 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001700 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001701 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
1702 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001703 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001704 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00001705 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001706 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001707
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001708 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001709 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &AI);
1710 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001711 VRP.solve();
1712 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00001713
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001714 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
1715 Value *Ptr = LI.getPointerOperand();
1716 // avoid "load uint* null" -> null NE null.
1717 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001718
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001719 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &LI);
1720 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001721 VRP.solve();
1722 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001723
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001724 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
1725 Value *Ptr = SI.getPointerOperand();
1726 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001727
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001728 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &SI);
1729 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001730 VRP.solve();
1731 }
1732
1733 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
1734 Instruction::BinaryOps ops = BO.getOpcode();
1735
1736 switch (ops) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001737 case Instruction::URem:
1738 case Instruction::SRem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001739 case Instruction::UDiv:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001740 case Instruction::SDiv: {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001741 Value *Divisor = BO.getOperand(1);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001742 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &BO);
1743 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
1744 ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001745 VRP.solve();
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001746 break;
1747 }
1748 default:
1749 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001750 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001751 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001752
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001753 RegisterPass<PredicateSimplifier> X("predsimplify",
1754 "Predicate Simplifier");
1755}
1756
1757FunctionPass *llvm::createPredicateSimplifierPass() {
1758 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001759}