blob: a0f686e204e57b355387a704bd12d90327ef2ea6 [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 Lewycky15245952007-02-04 23:43:05 +000055// %P = icmp ne int* %ptr, null
Nick Lewycky56639802007-01-29 02:56:54 +000056// %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) {
Nick Lewycky15245952007-02-04 23:43:05 +0000143 case GT: case GE: case LT: case LE: case NE:
144 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:
148 return true;
149 default:
150 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000151 }
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();
Reid Spencerc34dedf2007-03-03 00:48:31 +0000380 return LHS.first->getValue().ult(RHS.first->getValue());
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 &&
Reid Spencerc34dedf2007-03-03 00:48:31 +0000410 iULT->first->getValue().isNegative() ==
411 iUGT->first->getValue().isNegative()) { // signs match
Nick Lewycky56639802007-01-29 02:56:54 +0000412 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;
Reid Spencerc34dedf2007-03-03 00:48:31 +0000418 } else if (iULT->first->getValue().isNegative()) {
419 assert(iUGT->first->getValue().isPositive() &&
420 "Bad sign comparison.");
Nick Lewycky56639802007-01-29 02:56:54 +0000421 iSGT = iUGT;
422 iSLT = iULT;
423 } else {
Reid Spencerc34dedf2007-03-03 00:48:31 +0000424 assert(iULT->first->getValue().isPositive() >= 0 &&
425 iUGT->first->getValue().isNegative() &&"Bad sign comparison.");
Nick Lewycky56639802007-01-29 02:56:54 +0000426 iSGT = iULT;
427 iSLT = iUGT;
Nick Lewycky15245952007-02-04 23:43:05 +0000428 }
Nick Lewycky56639802007-01-29 02:56:54 +0000429
430 if (iSGT != end &&
Reid Spencerc34dedf2007-03-03 00:48:31 +0000431 iSGT->first->getValue().slt(CI->getValue()))
432 iSGT = end;
Nick Lewycky56639802007-01-29 02:56:54 +0000433 if (iSLT != end &&
Reid Spencerc34dedf2007-03-03 00:48:31 +0000434 iSLT->first->getValue().sgt(CI->getValue()))
435 iSLT = end;
Nick Lewycky56639802007-01-29 02:56:54 +0000436
437 if (begin != end) {
Reid Spencerc34dedf2007-03-03 00:48:31 +0000438 if (begin->first->getValue().slt(CI->getValue()))
Nick Lewycky56639802007-01-29 02:56:54 +0000439 if (iSLT == end ||
Reid Spencerc34dedf2007-03-03 00:48:31 +0000440 begin->first->getValue().sgt(iSLT->first->getValue()))
Nick Lewycky56639802007-01-29 02:56:54 +0000441 iSLT = begin;
Nick Lewycky15245952007-02-04 23:43:05 +0000442 }
Nick Lewycky56639802007-01-29 02:56:54 +0000443 if (last != end) {
Reid Spencerc34dedf2007-03-03 00:48:31 +0000444 if (last->first->getValue().sgt(CI->getValue()))
Nick Lewycky56639802007-01-29 02:56:54 +0000445 if (iSGT == end ||
Reid Spencerc34dedf2007-03-03 00:48:31 +0000446 last->first->getValue().slt(iSGT->first->getValue()))
Nick Lewycky56639802007-01-29 02:56:54 +0000447 iSGT = last;
Nick Lewycky15245952007-02-04 23:43:05 +0000448 }
Nick Lewycky56639802007-01-29 02:56:54 +0000449 }
450
451 if (iULT != end) addInequality(iULT->second, index, TreeRoot, ULT);
452 if (iUGT != end) addInequality(iUGT->second, index, TreeRoot, UGT);
453 if (iSLT != end) addInequality(iSLT->second, index, TreeRoot, SLT);
454 if (iSGT != end) addInequality(iSGT->second, index, TreeRoot, SGT);
455
456 Ints.insert(iUGT, pair);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000457 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000458
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000459 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000460 /// node - returns the node object at a given index retrieved from getNode.
461 /// Index zero is reserved and may not be passed in here. The pointer
462 /// returned is valid until the next call to newNode or getOrInsertNode.
463 Node *node(unsigned index) {
464 assert(index != 0 && "Zero index is reserved for not found.");
465 assert(index <= Nodes.size() && "Index out of range.");
466 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000467 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000468
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000469 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000470 /// node exists.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000471 unsigned getNode(Value *V, ETNode *Subtree) {
472 NodeMapType::iterator E = NodeMap.end();
473 NodeMapEdge Edge(V, 0, Subtree);
474 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
475 while (I != E && I->V == V) {
476 if (Subtree->DominatedBy(I->Subtree))
477 return I->index;
478 ++I;
479 }
480 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000481 }
482
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000483 /// getOrInsertNode - always returns a valid node index, creating a node
484 /// to match the Value if needed.
485 unsigned getOrInsertNode(Value *V, ETNode *Subtree) {
486 if (unsigned n = getNode(V, Subtree))
487 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000488 else
489 return newNode(V);
490 }
491
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000492 /// newNode - creates a new node for a given Value and returns the index.
493 unsigned newNode(Value *V) {
494 Nodes.push_back(Node(V));
495
496 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
497 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
498 "Attempt to create a duplicate Node.");
499 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
500 MapEntry), MapEntry);
501
Nick Lewycky56639802007-01-29 02:56:54 +0000502 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
503 initializeInt(CI, MapEntry.index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000504
505 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000506 }
507
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000508 /// If the Value is in the graph, return the canonical form. Otherwise,
509 /// return the original Value.
510 Value *canonicalize(Value *V, ETNode *Subtree) {
511 if (isa<Constant>(V)) return V;
512
513 if (unsigned n = getNode(V, Subtree))
514 return node(n)->getValue();
515 else
516 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000517 }
518
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000519 /// isRelatedBy - true iff n1 op n2
520 bool isRelatedBy(unsigned n1, unsigned n2, ETNode *Subtree, LatticeVal LV) {
521 if (n1 == n2) return LV & EQ_BIT;
522
523 Node *N1 = node(n1);
524 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
525 if (I != E) return (I->LV & LV) == I->LV;
526
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000527 return false;
528 }
529
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000530 // The add* methods assume that your input is logically valid and may
531 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000532
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000533 void addEquality(unsigned n, Value *V, ETNode *Subtree) {
534 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
535 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000536
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000537 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
538 // we may already have "%z -> node #2 (%x)" somewhere above us in the
539 // graph. We need to find those edges and add "%z -> node #1 (%y)"
540 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000541
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000542 std::vector<Value *> ToRepoint;
543 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000544
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000545 if (unsigned Conflict = getNode(V, Subtree)) {
Nick Lewycky56639802007-01-29 02:56:54 +0000546 // XXX: NodeMap.size() exceeds 68,000 entries compiling kimwitu++!
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000547 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
548 I != E; ++I) {
549 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
550 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000551 }
552 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000553
554 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
555 VE = ToRepoint.end(); VI != VE; ++VI) {
556 Value *V = *VI;
557
558 // XXX: review this code. This may be doing too many insertions.
559 NodeMapEdge Edge(V, n, Subtree);
560 NodeMapType::iterator E = NodeMap.end();
561 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
562 if (I == E || I->V != V || I->Subtree != Subtree) {
563 // New Value
564 NodeMap.insert(I, Edge);
565 } else if (I != E && I->V == V && I->Subtree == Subtree) {
566 // Update best choice
567 I->index = n;
568 }
569
570#ifndef NDEBUG
571 Node *N = node(n);
572 if (isa<Constant>(V)) {
573 if (isa<Constant>(N->getValue())) {
574 assert(V == N->getValue() && "Constant equals different constant?");
575 }
576 }
577#endif
578 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000579 }
580
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000581 /// addInequality - Sets n1 op n2.
582 /// It is also an error to call this on an inequality that is already true.
583 void addInequality(unsigned n1, unsigned n2, ETNode *Subtree,
584 LatticeVal LV1) {
585 assert(n1 != n2 && "A node can't be inequal to itself.");
586
587 if (LV1 != NE)
588 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
589 "Contradictory inequality.");
590
591 Node *N1 = node(n1);
592 Node *N2 = node(n2);
593
594 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
595 // add %a < %n2 too. This keeps the graph fully connected.
596 if (LV1 != NE) {
597 // Someone with a head for this sort of logic, please review this.
Nick Lewycky56639802007-01-29 02:56:54 +0000598 // Given that %x SLTUGT %y and %a SLE %x, what is the relationship
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000599 // between %a and %y? I believe the below code is correct, but I don't
600 // think it's the most efficient solution.
601
602 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
603 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
604 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
605 if (I->LV != NE && I->To != n2) {
606 ETNode *Local_Subtree = NULL;
607 if (Subtree->DominatedBy(I->Subtree))
608 Local_Subtree = Subtree;
609 else if (I->Subtree->DominatedBy(Subtree))
610 Local_Subtree = I->Subtree;
611
612 if (Local_Subtree) {
613 unsigned new_relationship = 0;
614 LatticeVal ILV = reversePredicate(I->LV);
615 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
616 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
617
618 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
619 new_relationship |= ILV_s;
620
621 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
622 new_relationship |= ILV_u;
623
624 if (new_relationship) {
625 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
626 new_relationship |= (SLT_BIT|SGT_BIT);
627 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
628 new_relationship |= (ULT_BIT|UGT_BIT);
629 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
630 new_relationship |= EQ_BIT;
631
632 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
633
634 node(I->To)->update(n2, NewLV, Local_Subtree);
635 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
636 }
637 }
638 }
639 }
640
641 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
642 if (I->LV != NE && I->To != n1) {
643 ETNode *Local_Subtree = NULL;
644 if (Subtree->DominatedBy(I->Subtree))
645 Local_Subtree = Subtree;
646 else if (I->Subtree->DominatedBy(Subtree))
647 Local_Subtree = I->Subtree;
648
649 if (Local_Subtree) {
650 unsigned new_relationship = 0;
651 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
652 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
653
654 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
655 new_relationship |= ILV_s;
656
657 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
658 new_relationship |= ILV_u;
659
660 if (new_relationship) {
661 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
662 new_relationship |= (SLT_BIT|SGT_BIT);
663 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
664 new_relationship |= (ULT_BIT|UGT_BIT);
665 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
666 new_relationship |= EQ_BIT;
667
668 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
669
670 N1->update(I->To, NewLV, Local_Subtree);
671 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
672 }
673 }
674 }
675 }
676 }
677
678 N1->update(n2, LV1, Subtree);
679 N2->update(n1, reversePredicate(LV1), Subtree);
680 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000681
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000682 /// Removes a Value from the graph, but does not delete any nodes. As this
683 /// method does not delete Nodes, V may not be the canonical choice for
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000684 /// a node with any relationships. It is invalid to call newNode on a Value
685 /// that has been removed.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000686 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000687 for (unsigned i = 0; i < NodeMap.size();) {
688 NodeMapType::iterator I = NodeMap.begin()+i;
689 assert((node(I->index)->getValue() != V || node(I->index)->begin() ==
690 node(I->index)->end()) && "Tried to delete in-use node.");
691 if (I->V == V) {
692#ifndef NDEBUG
693 if (node(I->index)->getValue() == V)
694 node(I->index)->Canonical = NULL;
695#endif
696 NodeMap.erase(I);
697 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000698 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000699 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000700
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000701#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000702 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000703 virtual void dump() {
704 dump(*cerr.stream());
705 }
706
707 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000708 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000709 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000710 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000711 Node *N = node(I->index);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000712 os << *I->V << " == " << I->index
713 << "(" << I->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000714 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000715 os << I->index << ". ";
716 if (!N->getValue()) os << "(deleted node)\n";
717 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000718 }
719 }
720 }
721#endif
722 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000723
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000724 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
725 /// another discovered to be unreachable. This is used to cull the graph when
726 /// analyzing instructions, and to mark blocks with the "unreachable"
727 /// terminator instruction after the function has executed.
728 class VISIBILITY_HIDDEN UnreachableBlocks {
729 private:
730 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000731
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000732 public:
733 /// mark - mark a block as dead
734 void mark(BasicBlock *BB) {
735 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
736 std::vector<BasicBlock *>::iterator I =
737 std::lower_bound(DeadBlocks.begin(), E, BB);
738
739 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000740 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000741
742 /// isDead - returns whether a block is known to be dead already
743 bool isDead(BasicBlock *BB) {
744 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
745 std::vector<BasicBlock *>::iterator I =
746 std::lower_bound(DeadBlocks.begin(), E, BB);
747
748 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000749 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000750
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000751 /// kill - replace the dead blocks' terminator with an UnreachableInst.
752 bool kill() {
753 bool modified = false;
754 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
755 E = DeadBlocks.end(); I != E; ++I) {
756 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000757
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000758 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000759
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000760 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
761 SI != SE; ++SI) {
762 BasicBlock *Succ = *SI;
763 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +0000764 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000765
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000766 TerminatorInst *TI = BB->getTerminator();
767 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
768 TI->eraseFromParent();
769 new UnreachableInst(BB);
770 ++NumBlocks;
771 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000772 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000773 DeadBlocks.clear();
774 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000775 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000776 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000777
778 /// VRPSolver keeps track of how changes to one variable affect other
779 /// variables, and forwards changes along to the InequalityGraph. It
780 /// also maintains the correct choice for "canonical" in the IG.
781 /// @brief VRPSolver calculates inferences from a new relationship.
782 class VISIBILITY_HIDDEN VRPSolver {
783 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000784 struct Operation {
785 Value *LHS, *RHS;
786 ICmpInst::Predicate Op;
787
Nick Lewycky42944462007-01-13 02:05:28 +0000788 BasicBlock *ContextBB;
789 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000790 };
791 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000792
793 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000794 UnreachableBlocks &UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000795 ETForest *Forest;
796 ETNode *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000797 BasicBlock *TopBB;
798 Instruction *TopInst;
799 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000800
801 typedef InequalityGraph::Node Node;
802
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000803 /// IdomI - Determines whether one Instruction dominates another.
804 bool IdomI(Instruction *I1, Instruction *I2) const {
805 BasicBlock *BB1 = I1->getParent(),
806 *BB2 = I2->getParent();
807 if (BB1 == BB2) {
808 if (isa<TerminatorInst>(I1)) return false;
809 if (isa<TerminatorInst>(I2)) return true;
810 if (isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
811 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
812
813 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
814 I != E; ++I) {
815 if (&*I == I1) return true;
816 if (&*I == I2) return false;
817 }
818 assert(!"Instructions not found in parent BasicBlock?");
819 } else {
820 return Forest->properlyDominates(BB1, BB2);
821 }
822 return false;
823 }
824
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000825 /// Returns true if V1 is a better canonical value than V2.
826 bool compare(Value *V1, Value *V2) const {
827 if (isa<Constant>(V1))
828 return !isa<Constant>(V2);
829 else if (isa<Constant>(V2))
830 return false;
831 else if (isa<Argument>(V1))
832 return !isa<Argument>(V2);
833 else if (isa<Argument>(V2))
834 return false;
835
836 Instruction *I1 = dyn_cast<Instruction>(V1);
837 Instruction *I2 = dyn_cast<Instruction>(V2);
838
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000839 if (!I1 || !I2)
840 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000841
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000842 return IdomI(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000843 }
844
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000845 // below - true if the Instruction is dominated by the current context
846 // block or instruction
847 bool below(Instruction *I) {
848 if (TopInst)
849 return IdomI(TopInst, I);
850 else {
851 ETNode *Node = Forest->getNodeForBlock(I->getParent());
Nick Lewycky56639802007-01-29 02:56:54 +0000852 return Node->DominatedBy(Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000853 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000854 }
855
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000856 bool makeEqual(Value *V1, Value *V2) {
857 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +0000858
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000859 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000860
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000861 if (isa<Constant>(V1) && isa<Constant>(V2))
862 return false;
863
864 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
865
866 if (n1 && n2) {
867 if (n1 == n2) return true;
868 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
869 }
870
871 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
872 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
873
Nick Lewycky15245952007-02-04 23:43:05 +0000874 assert(!compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000875
876 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
877
878 SetVector<unsigned> Remove;
879 if (n2) Remove.insert(n2);
880
881 if (n1 && n2) {
882 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
883 // We can't just merge %x and %y because the relationship with %z would
884 // be EQ and that's invalid. What we're doing is looking for any nodes
885 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000886
887 Node *N1 = IG.node(n1);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000888 Node *N2 = IG.node(n2);
889 Node::iterator end = N2->end();
890
891 // Find the intersection between N1 and N2 which is dominated by
892 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
893 // Remove.
894 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
895 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
896
897 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
898 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
899 Node::iterator NI = N2->find(I->To, Top);
900 if (NI != end) {
901 LatticeVal NILV = reversePredicate(NI->LV);
902 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
903 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
904
905 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
906 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
907 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000908 }
909 }
910
911 // See if one of the nodes about to be removed is actually a better
912 // canonical choice than n1.
913 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +0000914 SetVector<unsigned>::iterator DontRemove = Remove.end();
915 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000916 E = Remove.end(); I != E; ++I) {
917 unsigned n = *I;
918 Value *V = IG.node(n)->getValue();
919 if (compare(V, V1)) {
920 V1 = V;
921 n1 = n;
922 DontRemove = I;
923 }
924 }
925 if (DontRemove != Remove.end()) {
926 unsigned n = *DontRemove;
927 Remove.remove(n);
928 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000929 }
930 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000931
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000932 // We'd like to allow makeEqual on two values to perform a simple
933 // substitution without every creating nodes in the IG whenever possible.
934 //
935 // The first iteration through this loop operates on V2 before going
936 // through the Remove list and operating on those too. If all of the
937 // iterations performed simple replacements then we exit early.
938 bool exitEarly = true;
939 unsigned i = 0;
940 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
941 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
942
943 // Try to replace the whole instruction. If we can, we're done.
944 Instruction *I2 = dyn_cast<Instruction>(R);
945 if (I2 && below(I2)) {
946 std::vector<Instruction *> ToNotify;
947 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
948 UI != UE;) {
949 Use &TheUse = UI.getUse();
950 ++UI;
951 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
952 ToNotify.push_back(I);
953 }
954
955 DOUT << "Simply removing " << *I2
956 << ", replacing with " << *V1 << "\n";
957 I2->replaceAllUsesWith(V1);
958 // leave it dead; it'll get erased later.
959 ++NumInstruction;
960 modified = true;
961
962 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
963 IE = ToNotify.end(); II != IE; ++II) {
964 opsToDef(*II);
965 }
966
967 continue;
968 }
969
970 // Otherwise, replace all dominated uses.
971 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
972 UI != UE;) {
973 Use &TheUse = UI.getUse();
974 ++UI;
975 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
976 if (below(I)) {
977 TheUse.set(V1);
978 modified = true;
979 ++NumVarsReplaced;
980 opsToDef(I);
981 }
982 }
983 }
984
985 // If that killed the instruction, stop here.
986 if (I2 && isInstructionTriviallyDead(I2)) {
987 DOUT << "Killed all uses of " << *I2
988 << ", replacing with " << *V1 << "\n";
989 continue;
990 }
991
992 // If we make it to here, then we will need to create a node for N1.
993 // Otherwise, we can skip out early!
994 exitEarly = false;
995 }
996
997 if (exitEarly) return true;
998
999 // Create N1.
1000 // XXX: this should call newNode, but instead the node might be created
1001 // in isRelatedBy. That's also a fixme.
Nick Lewycky56639802007-01-29 02:56:54 +00001002 if (!n1) {
1003 n1 = IG.getOrInsertNode(V1, Top);
1004
1005 if (isa<ConstantInt>(V1))
1006 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1007 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001008
1009 // Migrate relationships from removed nodes to N1.
1010 Node *N1 = IG.node(n1);
Reid Spencera8a15472007-01-17 02:23:37 +00001011 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001012 I != E; ++I) {
1013 unsigned n = *I;
1014 Node *N = IG.node(n);
1015 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
Nick Lewycky56639802007-01-29 02:56:54 +00001016 if (NI->Subtree->DominatedBy(Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001017 if (NI->To == n1) {
1018 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1019 continue;
1020 }
1021 if (Remove.count(NI->To))
1022 continue;
1023
1024 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1025 N1->update(NI->To, NI->LV, Top);
1026 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001027 }
1028 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001029
1030 // Point V2 (and all items in Remove) to N1.
1031 if (!n2)
1032 IG.addEquality(n1, V2, Top);
1033 else {
Reid Spencera8a15472007-01-17 02:23:37 +00001034 for (SetVector<unsigned>::iterator I = Remove.begin(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001035 E = Remove.end(); I != E; ++I) {
1036 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
1037 }
1038 }
1039
1040 // If !Remove.empty() then V2 = Remove[0]->getValue().
1041 // Even when Remove is empty, we still want to process V2.
1042 i = 0;
1043 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1044 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1045
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001046 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1047 if (below(I2) ||
1048 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1049 defToOps(I2);
1050 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001051 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1052 UI != UE;) {
1053 Use &TheUse = UI.getUse();
1054 ++UI;
1055 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001056 if (below(I) ||
1057 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1058 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001059 }
1060 }
1061 }
1062
1063 return true;
1064 }
1065
1066 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1067 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1068 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1069 switch (Pred) {
1070 case ICmpInst::ICMP_EQ:
1071 assert(!"No matching lattice value.");
1072 return static_cast<LatticeVal>(EQ_BIT);
1073 default:
1074 assert(!"Invalid 'icmp' predicate.");
1075 case ICmpInst::ICMP_NE:
1076 return NE;
1077 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001078 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001079 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001080 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001081 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001082 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001083 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001084 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001085 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001086 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001087 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001088 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001089 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001090 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001091 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001092 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001093 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001094 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001095
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001096 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001097 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1098 bool &modified, BasicBlock *TopBB)
1099 : IG(IG),
1100 UB(UB),
1101 Forest(Forest),
1102 Top(Forest->getNodeForBlock(TopBB)),
1103 TopBB(TopBB),
1104 TopInst(NULL),
1105 modified(modified) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +00001106
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001107 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1108 bool &modified, Instruction *TopInst)
1109 : IG(IG),
1110 UB(UB),
1111 Forest(Forest),
1112 TopInst(TopInst),
1113 modified(modified)
1114 {
1115 TopBB = TopInst->getParent();
1116 Top = Forest->getNodeForBlock(TopBB);
1117 }
1118
1119 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1120 if (Constant *C1 = dyn_cast<Constant>(V1))
1121 if (Constant *C2 = dyn_cast<Constant>(V2))
1122 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001123 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001124
1125 // XXX: this is lousy. If we're passed a Constant, then we might miss
1126 // some relationships if it isn't in the IG because the relationships
1127 // added by initializeConstant are missing.
1128 if (isa<Constant>(V1)) IG.getOrInsertNode(V1, Top);
1129 if (isa<Constant>(V2)) IG.getOrInsertNode(V2, Top);
1130
1131 if (unsigned n1 = IG.getNode(V1, Top))
1132 if (unsigned n2 = IG.getNode(V2, Top)) {
1133 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1134 Pred == ICmpInst::ICMP_ULE ||
1135 Pred == ICmpInst::ICMP_UGE ||
1136 Pred == ICmpInst::ICMP_SLE ||
1137 Pred == ICmpInst::ICMP_SGE;
1138 if (Pred == ICmpInst::ICMP_EQ) return false;
1139 return IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred));
1140 }
1141
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001142 return false;
1143 }
1144
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001145 /// add - adds a new property to the work queue
1146 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1147 Instruction *I = NULL) {
1148 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1149 if (I) DOUT << " context: " << *I;
1150 else DOUT << " default context";
1151 DOUT << "\n";
1152
1153 WorkList.push_back(Operation());
1154 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001155 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1156 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001157 }
1158
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001159 /// defToOps - Given an instruction definition that we've learned something
1160 /// new about, find any new relationships between its operands.
1161 void defToOps(Instruction *I) {
1162 Instruction *NewContext = below(I) ? I : TopInst;
1163 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001164
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1166 const Type *Ty = BO->getType();
1167 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001168
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001169 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1170 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001171
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001172 // TODO: "and bool true, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001173
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001174 switch (BO->getOpcode()) {
1175 case Instruction::And: {
1176 // "and int %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1177 // "and bool %a, %b" EQ true then %a EQ true and %b EQ true
Zhou Sheng75b871f2007-01-11 12:24:14 +00001178 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001179 if (Canonical == CI) {
1180 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1181 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001182 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001183 } break;
1184 case Instruction::Or: {
1185 // "or int %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1186 // "or bool %a, %b" EQ false then %a EQ false and %b EQ false
1187 Constant *Zero = Constant::getNullValue(Ty);
1188 if (Canonical == Zero) {
1189 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1190 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1191 }
1192 } break;
1193 case Instruction::Xor: {
1194 // "xor bool true, %a" EQ true then %a EQ false
1195 // "xor bool true, %a" EQ false then %a EQ true
1196 // "xor bool false, %a" EQ true then %a EQ true
1197 // "xor bool false, %a" EQ false then %a EQ false
1198 // "xor int %c, %a" EQ %c then %a EQ 0
1199 // "xor int %c, %a" NE %c then %a NE 0
1200 // 1. Repeat all of the above, with order of operands reversed.
1201 Value *LHS = Op0;
1202 Value *RHS = Op1;
1203 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1204
Nick Lewycky4a74a752007-01-12 00:02:12 +00001205 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1206 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001207 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001208 ICmpInst::ICMP_EQ, NewContext);
1209 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001210 }
1211 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001212 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001213 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1214 NewContext);
1215 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1216 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1217 NewContext);
1218 }
1219 } break;
1220 default:
1221 break;
1222 }
1223 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1224 // "icmp ult int %a, int %y" EQ true then %a u< y
1225 // etc.
1226
Zhou Sheng75b871f2007-01-11 12:24:14 +00001227 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001228 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1229 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001230 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001231 add(IC->getOperand(0), IC->getOperand(1),
1232 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1233 }
1234 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1235 if (I->getType()->isFPOrFPVector()) return;
1236
1237 // Given: "%a = select bool %x, int %b, int %c"
1238 // %a EQ %b and %b NE %c then %x EQ true
1239 // %a EQ %c and %b NE %c then %x EQ false
1240
1241 Value *True = SI->getTrueValue();
1242 Value *False = SI->getFalseValue();
1243 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1244 if (Canonical == IG.canonicalize(True, Top) ||
1245 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001246 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001247 ICmpInst::ICMP_EQ, NewContext);
1248 else if (Canonical == IG.canonicalize(False, Top) ||
1249 isRelatedBy(I, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001250 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001251 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001252 }
1253 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001254 // TODO: CastInst "%a = cast ... %b" where %a is EQ or NE a constant.
1255 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001256
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001257 /// opsToDef - A new relationship was discovered involving one of this
1258 /// instruction's operands. Find any new relationship involving the
1259 /// definition.
1260 void opsToDef(Instruction *I) {
1261 Instruction *NewContext = below(I) ? I : TopInst;
1262
1263 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1264 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1265 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1266
Zhou Sheng75b871f2007-01-11 12:24:14 +00001267 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1268 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001269 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1270 ICmpInst::ICMP_EQ, NewContext);
1271 return;
1272 }
1273
1274 // "%y = and bool true, %x" then %x EQ %y.
1275 // "%y = or bool false, %x" then %x EQ %y.
1276 if (BO->getOpcode() == Instruction::Or) {
1277 Constant *Zero = Constant::getNullValue(BO->getType());
1278 if (Op0 == Zero) {
1279 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1280 return;
1281 } else if (Op1 == Zero) {
1282 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1283 return;
1284 }
1285 } else if (BO->getOpcode() == Instruction::And) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001286 Constant *AllOnes = ConstantInt::getAllOnesValue(BO->getType());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001287 if (Op0 == AllOnes) {
1288 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1289 return;
1290 } else if (Op1 == AllOnes) {
1291 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1292 return;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001293 }
1294 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001295
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001296 // "%x = add int %y, %z" and %x EQ %y then %z EQ 0
1297 // "%x = mul int %y, %z" and %x EQ %y then %z EQ 1
1298 // 1. Repeat all of the above, with order of operands reversed.
1299 // "%x = udiv int %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001300
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001301 Value *Known = Op0, *Unknown = Op1;
1302 if (Known != BO) std::swap(Known, Unknown);
1303 if (Known == BO) {
1304 const Type *Ty = BO->getType();
1305 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001306
1307 switch (BO->getOpcode()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001308 default: break;
1309 case Instruction::Xor:
1310 case Instruction::Or:
1311 case Instruction::Add:
1312 case Instruction::Sub:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001313 add(Unknown, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1314 NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001315 break;
1316 case Instruction::UDiv:
1317 case Instruction::SDiv:
1318 if (Unknown == Op0) break; // otherwise, fallthrough
1319 case Instruction::And:
1320 case Instruction::Mul:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001321 if (isa<ConstantInt>(Unknown)) {
1322 Constant *One = ConstantInt::get(Ty, 1);
1323 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1324 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001325 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001326 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001327 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001328
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001329 // TODO: "%a = add int %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001330
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001331 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1332 // "%a = icmp ult %b, %c" and %b u< %c then %a EQ true
1333 // "%a = icmp ult %b, %c" and %b u>= %c then %a EQ false
1334 // etc.
1335
1336 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1337 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1338
1339 ICmpInst::Predicate Pred = IC->getPredicate();
1340 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001341 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001342 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001343 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001344 }
1345
Nick Lewycky4a74a752007-01-12 00:02:12 +00001346 // TODO: "bool %x s<u> %y" implies %x = true and %y = false.
1347
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001348 // TODO: make the predicate more strict, if possible.
1349
1350 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1351 // Given: "%a = select bool %x, int %b, int %c"
1352 // %x EQ true then %a EQ %b
1353 // %x EQ false then %a EQ %c
1354 // %b EQ %c then %a EQ %b
1355
1356 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001357 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001358 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001359 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001360 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1361 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1362 IG.canonicalize(SI->getFalseValue(), Top)) {
1363 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1364 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001365 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1366 if (CI->getDestTy()->isFPOrFPVector()) return;
1367
1368 if (Constant *C = dyn_cast<Constant>(
1369 IG.canonicalize(CI->getOperand(0), Top))) {
1370 add(CI, ConstantExpr::getCast(CI->getOpcode(), C, CI->getDestTy()),
1371 ICmpInst::ICMP_EQ, NewContext);
1372 }
1373
1374 // TODO: "%a = cast ... %b" where %b is NE/LT/GT a constant.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001375 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001376 }
1377
1378 /// solve - process the work queue
1379 /// Return false if a logical contradiction occurs.
1380 void solve() {
1381 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
1382 while (!WorkList.empty()) {
1383 //DOUT << "WorkList size: " << WorkList.size() << "\n";
1384
1385 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00001386 TopInst = O.ContextInst;
1387 TopBB = O.ContextBB;
1388 Top = Forest->getNodeForBlock(TopBB);
1389
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001390 O.LHS = IG.canonicalize(O.LHS, Top);
1391 O.RHS = IG.canonicalize(O.RHS, Top);
1392
1393 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
1394 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
1395
1396 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00001397 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
1398 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001399 DOUT << "\n";
1400
1401 DEBUG(IG.dump());
1402
Nick Lewycky15245952007-02-04 23:43:05 +00001403 // If they're both Constant, skip it. Check for contradiction and mark
1404 // the BB as unreachable if so.
1405 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
1406 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
1407 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
1408 ConstantInt::getFalse())
1409 UB.mark(TopBB);
1410
1411 WorkList.pop_front();
1412 continue;
1413 }
1414 }
1415
1416 if (compare(O.RHS, O.LHS)) {
1417 std::swap(O.LHS, O.RHS);
1418 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001419 }
1420
1421 if (O.Op == ICmpInst::ICMP_EQ) {
1422 if (!makeEqual(O.LHS, O.RHS))
1423 UB.mark(TopBB);
1424 } else {
1425 LatticeVal LV = cmpInstToLattice(O.Op);
1426
1427 if ((LV & EQ_BIT) &&
1428 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
1429 if (!makeEqual(O.LHS, O.RHS))
1430 UB.mark(TopBB);
1431 } else {
1432 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00001433 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001434 WorkList.pop_front();
1435 continue;
1436 }
1437
1438 unsigned n1 = IG.getOrInsertNode(O.LHS, Top);
1439 unsigned n2 = IG.getOrInsertNode(O.RHS, Top);
1440
1441 if (n1 == n2) {
1442 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
1443 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
1444 UB.mark(TopBB);
1445
1446 WorkList.pop_front();
1447 continue;
1448 }
1449
1450 if (IG.isRelatedBy(n1, n2, Top, LV)) {
1451 WorkList.pop_front();
1452 continue;
1453 }
1454
Nick Lewycky15245952007-02-04 23:43:05 +00001455 // Generalize %x u> -10 to %x > -10.
1456 if (ConstantInt *CI = dyn_cast<ConstantInt>(O.RHS)) {
1457 // xform doesn't apply to i1
1458 if (CI->getType()->getBitWidth() > 1) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001459 if (LV == SLT && CI->getValue().isNegative()) {
Nick Lewycky15245952007-02-04 23:43:05 +00001460 // i8 %x s< -5 implies %x < -5 and %x u> 127
1461
1462 const IntegerType *Ty = CI->getType();
1463 LV = LT;
Reid Spencerc34dedf2007-03-03 00:48:31 +00001464 add(O.LHS, ConstantInt::get(Ty->getMask().lshr(1)),
Nick Lewycky15245952007-02-04 23:43:05 +00001465 ICmpInst::ICMP_UGT);
Reid Spencerc34dedf2007-03-03 00:48:31 +00001466 } else if (LV == SGT && CI->getValue().isPositive()) {
Nick Lewycky15245952007-02-04 23:43:05 +00001467 // i8 %x s> 5 implies %x > 5 and %x u< 128
1468
1469 const IntegerType *Ty = CI->getType();
1470 LV = LT;
Reid Spencerc34dedf2007-03-03 00:48:31 +00001471 add(O.LHS, ConstantInt::get(
1472 APInt::getSignedMinValue(Ty->getBitWidth())),
Nick Lewycky15245952007-02-04 23:43:05 +00001473 ICmpInst::ICMP_ULT);
Reid Spencerc34dedf2007-03-03 00:48:31 +00001474 } else if (CI->getValue().isPositive()) {
Nick Lewycky15245952007-02-04 23:43:05 +00001475 if (LV == ULT || LV == SLT) LV = LT;
1476 if (LV == UGT || LV == SGT) LV = GT;
1477 }
1478 }
1479 }
1480
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001481 IG.addInequality(n1, n2, Top, LV);
1482
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001483 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
1484 if (below(I1) ||
1485 Top->DominatedBy(Forest->getNodeForBlock(I1->getParent())))
1486 defToOps(I1);
1487 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001488 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
1489 for (Value::use_iterator UI = O.LHS->use_begin(),
1490 UE = O.LHS->use_end(); UI != UE;) {
1491 Use &TheUse = UI.getUse();
1492 ++UI;
1493 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001494 if (below(I) ||
1495 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1496 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001497 }
1498 }
1499 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001500 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
1501 if (below(I2) ||
1502 Top->DominatedBy(Forest->getNodeForBlock(I2->getParent())))
1503 defToOps(I2);
1504 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001505 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
1506 for (Value::use_iterator UI = O.RHS->use_begin(),
1507 UE = O.RHS->use_end(); UI != UE;) {
1508 Use &TheUse = UI.getUse();
1509 ++UI;
1510 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001511 if (below(I) ||
1512 Top->DominatedBy(Forest->getNodeForBlock(I->getParent())))
1513
1514 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001515 }
1516 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001517 }
1518 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001519 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001520 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00001521 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001522 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001523 };
1524
1525 /// PredicateSimplifier - This class is a simplifier that replaces
1526 /// one equivalent variable with another. It also tracks what
1527 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001528 /// @brief Root of the predicate simplifier optimization.
1529 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1530 DominatorTree *DT;
1531 ETForest *Forest;
1532 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001533 InequalityGraph *IG;
1534 UnreachableBlocks UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001535
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001536 std::vector<DominatorTree::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001537
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001538 public:
1539 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001540
1541 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1542 AU.addRequiredID(BreakCriticalEdgesID);
1543 AU.addRequired<DominatorTree>();
1544 AU.addRequired<ETForest>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001545 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001546
1547 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001548 /// Forwards - Adds new properties into PropertySet and uses them to
1549 /// simplify instructions. Because new properties sometimes apply to
1550 /// a transition from one BasicBlock to another, this will use the
1551 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1552 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001553 /// @brief Performs abstract execution of the program.
1554 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001555 friend class InstVisitor<Forwards>;
1556 PredicateSimplifier *PS;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001557 DominatorTree::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001558
Nick Lewycky77e030b2006-10-12 02:02:44 +00001559 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001560 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001561 UnreachableBlocks &UB;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001562
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001563 Forwards(PredicateSimplifier *PS, DominatorTree::Node *DTNode)
1564 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001565
1566 void visitTerminatorInst(TerminatorInst &TI);
1567 void visitBranchInst(BranchInst &BI);
1568 void visitSwitchInst(SwitchInst &SI);
1569
Nick Lewyckyf3450082006-10-22 19:53:27 +00001570 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001571 void visitLoadInst(LoadInst &LI);
1572 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001573
Nick Lewycky15245952007-02-04 23:43:05 +00001574 void visitSExtInst(SExtInst &SI);
1575 void visitZExtInst(ZExtInst &ZI);
1576
Nick Lewycky77e030b2006-10-12 02:02:44 +00001577 void visitBinaryOperator(BinaryOperator &BO);
1578 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001579
1580 // Used by terminator instructions to proceed from the current basic
1581 // block to the next. Verifies that "current" dominates "next",
1582 // then calls visitBasicBlock.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001583 void proceedToSuccessors(DominatorTree::Node *Current) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001584 for (DominatorTree::Node::iterator I = Current->begin(),
1585 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001586 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001587 }
1588 }
1589
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001590 void proceedToSuccessor(DominatorTree::Node *Next) {
1591 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001592 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001593
1594 // Visits each instruction in the basic block.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001595 void visitBasicBlock(DominatorTree::Node *Node) {
1596 BasicBlock *BB = Node->getBlock();
1597 ETNode *ET = Forest->getNodeForBlock(BB);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001598 DOUT << "Entering Basic Block: " << BB->getName()
1599 << " (" << ET->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00001600 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001601 visitInstruction(I++, Node, ET);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001602 }
1603 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001604
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001605 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001606 // the PropertySet.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001607 void visitInstruction(Instruction *I, DominatorTree::Node *DT, ETNode *ET) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001608 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001609 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001610
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001611 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001612 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001613 ++NumSimple;
1614 modified = true;
1615 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001616 I->eraseFromParent();
1617 return;
1618 }
1619
Nick Lewycky42944462007-01-13 02:05:28 +00001620#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001621 // Try to replace the whole instruction.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001622 Value *V = IG->canonicalize(I, ET);
1623 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001624 if (V != I) {
1625 modified = true;
1626 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00001627 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001628 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001629 I->replaceAllUsesWith(V);
1630 I->eraseFromParent();
1631 return;
1632 }
1633
1634 // Try to substitute operands.
1635 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1636 Value *Oper = I->getOperand(i);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001637 Value *V = IG->canonicalize(Oper, ET);
1638 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001639 if (V != Oper) {
1640 modified = true;
1641 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00001642 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001643 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00001644 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001645 }
1646 }
Nick Lewycky42944462007-01-13 02:05:28 +00001647#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001648
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001649 DOUT << "push (%" << I->getParent()->getName() << ")\n";
1650 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001651 visit.visit(*I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001652 DOUT << "pop (%" << I->getParent()->getName() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001653 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001654 };
1655
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001656 bool PredicateSimplifier::runOnFunction(Function &F) {
1657 DT = &getAnalysis<DominatorTree>();
1658 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001659
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001660 Forest->updateDFSNumbers(); // XXX: should only act when numbers are out of date
1661
Bill Wendling22e978a2006-12-07 20:04:42 +00001662 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001663
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001664 modified = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001665 BasicBlock *RootBlock = &F.getEntryBlock();
1666 IG = new InequalityGraph(Forest->getNodeForBlock(RootBlock));
1667 WorkList.push_back(DT->getRootNode());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001668
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001669 do {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001670 DominatorTree::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001671 WorkList.pop_back();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001672 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001673 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001674
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001675 delete IG;
1676
1677 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001678
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001679 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00001680 }
1681
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001682 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001683 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001684 }
1685
1686 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001687 if (BI.isUnconditional()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001688 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001689 return;
1690 }
1691
1692 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001693 BasicBlock *TrueDest = BI.getSuccessor(0);
1694 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001695
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001696 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
1697 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001698 return;
1699 }
1700
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001701 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001702 I != E; ++I) {
1703 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001704 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001705 << "(" << PS->Forest->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001706
1707 if (Dest == TrueDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001708 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
1709 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001710 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001711 VRP.solve();
1712 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001713 } else if (Dest == FalseDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001714 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
1715 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001716 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001717 VRP.solve();
1718 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001719 }
1720
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001721 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001722 }
1723 }
1724
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001725 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
1726 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001727
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001728 // Set the EQProperty in each of the cases BBs, and the NEProperties
1729 // in the default BB.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001730
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001731 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001732 I != E; ++I) {
1733 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001734 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001735 << "(" << PS->Forest->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001736
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001737 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001738 if (BB == SI.getDefaultDest()) {
1739 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
1740 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001741 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
1742 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001743 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001744 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
1745 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001746 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001747 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00001748 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001749 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001750
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001751 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001752 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &AI);
1753 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001754 VRP.solve();
1755 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00001756
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001757 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
1758 Value *Ptr = LI.getPointerOperand();
1759 // avoid "load uint* null" -> null NE null.
1760 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001761
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001762 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &LI);
1763 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001764 VRP.solve();
1765 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001766
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001767 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
1768 Value *Ptr = SI.getPointerOperand();
1769 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001770
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001771 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &SI);
1772 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001773 VRP.solve();
1774 }
1775
Nick Lewycky15245952007-02-04 23:43:05 +00001776 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
1777 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00001778 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
1779 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
1780 APInt Min(APInt::getSignedMinValue(SrcBitWidth));
1781 APInt Max(APInt::getSignedMaxValue(SrcBitWidth));
1782 Min.sext(DstBitWidth);
1783 Max.sext(DstBitWidth);
1784 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
1785 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00001786 VRP.solve();
1787 }
1788
1789 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
1790 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00001791 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
1792 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
1793 APInt Max(APInt::getMaxValue(SrcBitWidth));
1794 Max.zext(DstBitWidth);
1795 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00001796 VRP.solve();
1797 }
1798
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001799 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
1800 Instruction::BinaryOps ops = BO.getOpcode();
1801
1802 switch (ops) {
Nick Lewycky15245952007-02-04 23:43:05 +00001803 case Instruction::URem:
1804 case Instruction::SRem:
1805 case Instruction::UDiv:
1806 case Instruction::SDiv: {
1807 Value *Divisor = BO.getOperand(1);
1808 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &BO);
1809 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
1810 ICmpInst::ICMP_NE);
1811 VRP.solve();
1812 break;
1813 }
1814 default:
1815 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001816 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001817 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001818
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001819 RegisterPass<PredicateSimplifier> X("predsimplify",
1820 "Predicate Simplifier");
1821}
1822
1823FunctionPass *llvm::createPredicateSimplifierPass() {
1824 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001825}