blob: 8defb871b763db1773ec029a23d94a2dbb7b1739 [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//
55// %P = seteq int* %ptr, null
56// %a = or bool %P, %Q
57// br bool %a label %cond_true, label %cond_false
58//
59// For the true branch, the VRPSolver will start with %a EQ true and look at
60// the definition of %a and find that it can infer that %P and %Q are both
61// true. From %P being true, it can infer that %ptr NE null. For the false
62// branch it can't infer anything from the "or" instruction.
63//
64// Besides branches, we can also infer properties from instruction that may
65// have undefined behaviour in certain cases. For example, the dividend of
66// a division may never be zero. After the division instruction, we may assume
67// that the dividend is not equal to zero.
68//
69//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000070
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000071#define DEBUG_TYPE "predsimplify"
72#include "llvm/Transforms/Scalar.h"
73#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000074#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000075#include "llvm/Instructions.h"
76#include "llvm/Pass.h"
Nick 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"
79#include "llvm/ADT/SmallVector.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
105 // 0 1 1 1 0 -- SGTUNE 14
106 // 0 1 1 1 1 -- SGEUANY 15
107 // 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
111 // 1 0 1 1 0 -- SLTUNE 22
112 // 1 0 1 1 1 -- SLEUANY 23
113 // 1 1 0 1 0 -- SNEUGT 26
114 // 1 1 0 1 1 -- SANYUGE 27
115 // 1 1 1 0 0 -- SNEULT 28
116 // 1 1 1 0 1 -- SANYULE 29
117 // 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,
131 SNEULT = SLT_BIT | SGT_BIT | ULT_BIT,
132 SNEUGT = SLT_BIT | SGT_BIT | UGT_BIT,
133 SLTUNE = SLT_BIT | ULT_BIT | UGT_BIT,
134 SGTUNE = SGT_BIT | ULT_BIT | UGT_BIT,
135 SLEUANY = SLT_BIT | ULT_BIT | UGT_BIT | EQ_BIT,
136 SGEUANY = SGT_BIT | ULT_BIT | UGT_BIT | EQ_BIT,
137 SANYULE = SLT_BIT | SGT_BIT | ULT_BIT | EQ_BIT,
138 SANYUGE = SLT_BIT | SGT_BIT | UGT_BIT | EQ_BIT
139 };
140
141 static bool validPredicate(LatticeVal LV) {
142 switch (LV) {
143 case GT: case GE: case LT: case LE: case NE:
144 case SGTULT: case SGTUNE: case SGEULE:
145 case SLTUGT: case SLTUNE: case SLEUGE:
146 case SNEULT: case SNEUGT:
147 case SLEUANY: case SGEUANY: case SANYULE: case SANYUGE:
148 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
266 << "(" << NI->Subtree << ")\n";
267 }
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) {
316 if (Subtree == I->Subtree)
317 I->LV = LV;
318 else {
319 assert(Subtree->DominatedBy(I->Subtree) &&
320 "Find returned subtree that doesn't apply.");
321
322 Edge edge(n, R, Subtree);
323 iterator Insert = std::lower_bound(begin(), end(), edge);
324 Relations.insert(Insert, edge);
325 }
326 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000327 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000328 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000329 };
330
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000331 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000332 struct VISIBILITY_HIDDEN NodeMapEdge {
333 Value *V;
334 unsigned index;
335 ETNode *Subtree;
336
337 NodeMapEdge(Value *V, unsigned index, ETNode *Subtree)
338 : V(V), index(index), Subtree(Subtree) {}
339
340 bool operator==(const NodeMapEdge &RHS) const {
341 return V == RHS.V &&
342 Subtree == RHS.Subtree;
343 }
344
345 bool operator<(const NodeMapEdge &RHS) const {
346 if (V != RHS.V) return V < RHS.V;
347 return OrderByDominance()(Subtree, RHS.Subtree);
348 }
349
350 bool operator<(Value *RHS) const {
351 return V < RHS;
352 }
353 };
354
355 typedef std::vector<NodeMapEdge> NodeMapType;
356 NodeMapType NodeMap;
357
358 std::vector<Node> Nodes;
359
Zhou Sheng75b871f2007-01-11 12:24:14 +0000360 std::vector<std::pair<ConstantInt *, unsigned> > Constants;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000361 void initializeConstant(Constant *C, unsigned index) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000362 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000363 if (!CI) return;
364
365 // XXX: instead of O(n) calls to addInequality, just find the 2, 3 or 4
366 // nodes that are nearest less than or greater than (signed or unsigned).
Zhou Sheng75b871f2007-01-11 12:24:14 +0000367 for (std::vector<std::pair<ConstantInt *, unsigned> >::iterator
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000368 I = Constants.begin(), E = Constants.end(); I != E; ++I) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000369 ConstantInt *Other = I->first;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000370 if (CI->getType() == Other->getType()) {
371 unsigned lv = 0;
372
373 if (CI->getZExtValue() < Other->getZExtValue())
374 lv |= ULT_BIT;
375 else
376 lv |= UGT_BIT;
377
378 if (CI->getSExtValue() < Other->getSExtValue())
379 lv |= SLT_BIT;
380 else
381 lv |= SGT_BIT;
382
383 LatticeVal LV = static_cast<LatticeVal>(lv);
384 assert(validPredicate(LV) && "Not a valid predicate.");
385 if (!isRelatedBy(index, I->second, TreeRoot, LV))
386 addInequality(index, I->second, TreeRoot, LV);
387 }
388 }
389 Constants.push_back(std::make_pair(CI, index));
390 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000391
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000392 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000393 /// node - returns the node object at a given index retrieved from getNode.
394 /// Index zero is reserved and may not be passed in here. The pointer
395 /// returned is valid until the next call to newNode or getOrInsertNode.
396 Node *node(unsigned index) {
397 assert(index != 0 && "Zero index is reserved for not found.");
398 assert(index <= Nodes.size() && "Index out of range.");
399 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000400 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000401
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000402 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000403 /// node exists.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000404 unsigned getNode(Value *V, ETNode *Subtree) {
405 NodeMapType::iterator E = NodeMap.end();
406 NodeMapEdge Edge(V, 0, Subtree);
407 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
408 while (I != E && I->V == V) {
409 if (Subtree->DominatedBy(I->Subtree))
410 return I->index;
411 ++I;
412 }
413 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000414 }
415
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000416 /// getOrInsertNode - always returns a valid node index, creating a node
417 /// to match the Value if needed.
418 unsigned getOrInsertNode(Value *V, ETNode *Subtree) {
419 if (unsigned n = getNode(V, Subtree))
420 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000421 else
422 return newNode(V);
423 }
424
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000425 /// newNode - creates a new node for a given Value and returns the index.
426 unsigned newNode(Value *V) {
427 Nodes.push_back(Node(V));
428
429 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
430 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
431 "Attempt to create a duplicate Node.");
432 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
433 MapEntry), MapEntry);
434
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000435 if (Constant *C = dyn_cast<Constant>(V))
436 initializeConstant(C, MapEntry.index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000437
438 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000439 }
440
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000441 /// If the Value is in the graph, return the canonical form. Otherwise,
442 /// return the original Value.
443 Value *canonicalize(Value *V, ETNode *Subtree) {
444 if (isa<Constant>(V)) return V;
445
446 if (unsigned n = getNode(V, Subtree))
447 return node(n)->getValue();
448 else
449 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000450 }
451
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000452 /// isRelatedBy - true iff n1 op n2
453 bool isRelatedBy(unsigned n1, unsigned n2, ETNode *Subtree, LatticeVal LV) {
454 if (n1 == n2) return LV & EQ_BIT;
455
456 Node *N1 = node(n1);
457 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
458 if (I != E) return (I->LV & LV) == I->LV;
459
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000460 return false;
461 }
462
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000463 // The add* methods assume that your input is logically valid and may
464 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000465
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000466 void addEquality(unsigned n, Value *V, ETNode *Subtree) {
467 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
468 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000469
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000470 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
471 // we may already have "%z -> node #2 (%x)" somewhere above us in the
472 // graph. We need to find those edges and add "%z -> node #1 (%y)"
473 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000474
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000475 std::vector<Value *> ToRepoint;
476 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000477
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000478 if (unsigned Conflict = getNode(V, Subtree)) {
479 // XXX: NodeMap.size() exceeds 68000 entries compiling kimwitu++!
480 // This adds 57 seconds to the otherwise 3 second build. Unacceptable.
481 //
482 // IDEA: could we iterate 1..Nodes.size() calling getNode? It's
483 // O(n log n) but kimwitu++ only has about 300 nodes.
484 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
485 I != E; ++I) {
486 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
487 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000488 }
489 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000490
491 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
492 VE = ToRepoint.end(); VI != VE; ++VI) {
493 Value *V = *VI;
494
495 // XXX: review this code. This may be doing too many insertions.
496 NodeMapEdge Edge(V, n, Subtree);
497 NodeMapType::iterator E = NodeMap.end();
498 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
499 if (I == E || I->V != V || I->Subtree != Subtree) {
500 // New Value
501 NodeMap.insert(I, Edge);
502 } else if (I != E && I->V == V && I->Subtree == Subtree) {
503 // Update best choice
504 I->index = n;
505 }
506
507#ifndef NDEBUG
508 Node *N = node(n);
509 if (isa<Constant>(V)) {
510 if (isa<Constant>(N->getValue())) {
511 assert(V == N->getValue() && "Constant equals different constant?");
512 }
513 }
514#endif
515 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000516 }
517
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000518 /// addInequality - Sets n1 op n2.
519 /// It is also an error to call this on an inequality that is already true.
520 void addInequality(unsigned n1, unsigned n2, ETNode *Subtree,
521 LatticeVal LV1) {
522 assert(n1 != n2 && "A node can't be inequal to itself.");
523
524 if (LV1 != NE)
525 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
526 "Contradictory inequality.");
527
528 Node *N1 = node(n1);
529 Node *N2 = node(n2);
530
531 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
532 // add %a < %n2 too. This keeps the graph fully connected.
533 if (LV1 != NE) {
534 // Someone with a head for this sort of logic, please review this.
535 // Given that %x SLTUGT %y and %a SLEUANY %x, what is the relationship
536 // between %a and %y? I believe the below code is correct, but I don't
537 // think it's the most efficient solution.
538
539 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
540 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
541 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
542 if (I->LV != NE && I->To != n2) {
543 ETNode *Local_Subtree = NULL;
544 if (Subtree->DominatedBy(I->Subtree))
545 Local_Subtree = Subtree;
546 else if (I->Subtree->DominatedBy(Subtree))
547 Local_Subtree = I->Subtree;
548
549 if (Local_Subtree) {
550 unsigned new_relationship = 0;
551 LatticeVal ILV = reversePredicate(I->LV);
552 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
553 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
554
555 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
556 new_relationship |= ILV_s;
557
558 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
559 new_relationship |= ILV_u;
560
561 if (new_relationship) {
562 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
563 new_relationship |= (SLT_BIT|SGT_BIT);
564 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
565 new_relationship |= (ULT_BIT|UGT_BIT);
566 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
567 new_relationship |= EQ_BIT;
568
569 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
570
571 node(I->To)->update(n2, NewLV, Local_Subtree);
572 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
573 }
574 }
575 }
576 }
577
578 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
579 if (I->LV != NE && I->To != n1) {
580 ETNode *Local_Subtree = NULL;
581 if (Subtree->DominatedBy(I->Subtree))
582 Local_Subtree = Subtree;
583 else if (I->Subtree->DominatedBy(Subtree))
584 Local_Subtree = I->Subtree;
585
586 if (Local_Subtree) {
587 unsigned new_relationship = 0;
588 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
589 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
590
591 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
592 new_relationship |= ILV_s;
593
594 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
595 new_relationship |= ILV_u;
596
597 if (new_relationship) {
598 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
599 new_relationship |= (SLT_BIT|SGT_BIT);
600 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
601 new_relationship |= (ULT_BIT|UGT_BIT);
602 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
603 new_relationship |= EQ_BIT;
604
605 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
606
607 N1->update(I->To, NewLV, Local_Subtree);
608 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
609 }
610 }
611 }
612 }
613 }
614
615 N1->update(n2, LV1, Subtree);
616 N2->update(n1, reversePredicate(LV1), Subtree);
617 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000618
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000619 /// Removes a Value from the graph, but does not delete any nodes. As this
620 /// method does not delete Nodes, V may not be the canonical choice for
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000621 /// a node with any relationships. It is invalid to call newNode on a Value
622 /// that has been removed.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000623 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000624 for (unsigned i = 0; i < NodeMap.size();) {
625 NodeMapType::iterator I = NodeMap.begin()+i;
626 assert((node(I->index)->getValue() != V || node(I->index)->begin() ==
627 node(I->index)->end()) && "Tried to delete in-use node.");
628 if (I->V == V) {
629#ifndef NDEBUG
630 if (node(I->index)->getValue() == V)
631 node(I->index)->Canonical = NULL;
632#endif
633 NodeMap.erase(I);
634 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000635 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000636 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000637
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000638#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000639 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000640 virtual void dump() {
641 dump(*cerr.stream());
642 }
643
644 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000645 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000646 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000647 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000648 Node *N = node(I->index);
649 os << *I->V << " == " << I->index << "(" << I->Subtree << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000650 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000651 os << I->index << ". ";
652 if (!N->getValue()) os << "(deleted node)\n";
653 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000654 }
655 }
656 }
657#endif
658 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000659
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000660 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
661 /// another discovered to be unreachable. This is used to cull the graph when
662 /// analyzing instructions, and to mark blocks with the "unreachable"
663 /// terminator instruction after the function has executed.
664 class VISIBILITY_HIDDEN UnreachableBlocks {
665 private:
666 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000667
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000668 public:
669 /// mark - mark a block as dead
670 void mark(BasicBlock *BB) {
671 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
672 std::vector<BasicBlock *>::iterator I =
673 std::lower_bound(DeadBlocks.begin(), E, BB);
674
675 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000676 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000677
678 /// isDead - returns whether a block is known to be dead already
679 bool isDead(BasicBlock *BB) {
680 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
681 std::vector<BasicBlock *>::iterator I =
682 std::lower_bound(DeadBlocks.begin(), E, BB);
683
684 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000685 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000686
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000687 /// kill - replace the dead blocks' terminator with an UnreachableInst.
688 bool kill() {
689 bool modified = false;
690 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
691 E = DeadBlocks.end(); I != E; ++I) {
692 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000693
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000694 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000695
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000696 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
697 SI != SE; ++SI) {
698 BasicBlock *Succ = *SI;
699 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +0000700 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000701
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000702 TerminatorInst *TI = BB->getTerminator();
703 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
704 TI->eraseFromParent();
705 new UnreachableInst(BB);
706 ++NumBlocks;
707 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000708 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000709 DeadBlocks.clear();
710 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000711 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000712 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000713
714 /// VRPSolver keeps track of how changes to one variable affect other
715 /// variables, and forwards changes along to the InequalityGraph. It
716 /// also maintains the correct choice for "canonical" in the IG.
717 /// @brief VRPSolver calculates inferences from a new relationship.
718 class VISIBILITY_HIDDEN VRPSolver {
719 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000720 struct Operation {
721 Value *LHS, *RHS;
722 ICmpInst::Predicate Op;
723
724 Instruction *Context;
725 };
726 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000727
728 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000729 UnreachableBlocks &UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000730 ETForest *Forest;
731 ETNode *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000732 BasicBlock *TopBB;
733 Instruction *TopInst;
734 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000735
736 typedef InequalityGraph::Node Node;
737
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000738 /// IdomI - Determines whether one Instruction dominates another.
739 bool IdomI(Instruction *I1, Instruction *I2) const {
740 BasicBlock *BB1 = I1->getParent(),
741 *BB2 = I2->getParent();
742 if (BB1 == BB2) {
743 if (isa<TerminatorInst>(I1)) return false;
744 if (isa<TerminatorInst>(I2)) return true;
745 if (isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
746 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
747
748 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
749 I != E; ++I) {
750 if (&*I == I1) return true;
751 if (&*I == I2) return false;
752 }
753 assert(!"Instructions not found in parent BasicBlock?");
754 } else {
755 return Forest->properlyDominates(BB1, BB2);
756 }
757 return false;
758 }
759
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000760 /// Returns true if V1 is a better canonical value than V2.
761 bool compare(Value *V1, Value *V2) const {
762 if (isa<Constant>(V1))
763 return !isa<Constant>(V2);
764 else if (isa<Constant>(V2))
765 return false;
766 else if (isa<Argument>(V1))
767 return !isa<Argument>(V2);
768 else if (isa<Argument>(V2))
769 return false;
770
771 Instruction *I1 = dyn_cast<Instruction>(V1);
772 Instruction *I2 = dyn_cast<Instruction>(V2);
773
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000774 if (!I1 || !I2)
775 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000776
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000777 return IdomI(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000778 }
779
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000780 // below - true if the Instruction is dominated by the current context
781 // block or instruction
782 bool below(Instruction *I) {
783 if (TopInst)
784 return IdomI(TopInst, I);
785 else {
786 ETNode *Node = Forest->getNodeForBlock(I->getParent());
787 return Node == Top || Node->DominatedBy(Top);
788 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000789 }
790
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000791 bool makeEqual(Value *V1, Value *V2) {
792 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +0000793
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000794 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000795
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000796 if (isa<Constant>(V1) && isa<Constant>(V2))
797 return false;
798
799 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
800
801 if (n1 && n2) {
802 if (n1 == n2) return true;
803 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
804 }
805
806 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
807 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
808
809 if (compare(V2, V1)) { std::swap(V1, V2); std::swap(n1, n2); }
810
811 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
812
813 SetVector<unsigned> Remove;
814 if (n2) Remove.insert(n2);
815
816 if (n1 && n2) {
817 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
818 // We can't just merge %x and %y because the relationship with %z would
819 // be EQ and that's invalid. What we're doing is looking for any nodes
820 // %z such that %x <= %z and %y >= %z, and vice versa.
821 //
822 // Also handle %a <= %b and %c <= %a when adding %b <= %c.
823
824 Node *N1 = IG.node(n1);
825 Node::iterator end = N1->end();
826 for (unsigned i = 0; i < Remove.size(); ++i) {
827 Node *N = IG.node(Remove[i]);
828 Value *V = N->getValue();
829 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
830 if (I->LV & EQ_BIT) {
831 if (Top == I->Subtree || Top->DominatedBy(I->Subtree)) {
832 Node::iterator NI = N1->find(I->To, Top);
833 if (NI != end) {
834 if (!(NI->LV & EQ_BIT)) return false;
835 if (isRelatedBy(V, IG.node(NI->To)->getValue(),
836 ICmpInst::ICMP_NE))
837 return false;
838 Remove.insert(NI->To);
839 }
840 }
841 }
842 }
843 }
844
845 // See if one of the nodes about to be removed is actually a better
846 // canonical choice than n1.
847 unsigned orig_n1 = n1;
848 std::vector<unsigned>::iterator DontRemove = Remove.end();
849 for (std::vector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
850 E = Remove.end(); I != E; ++I) {
851 unsigned n = *I;
852 Value *V = IG.node(n)->getValue();
853 if (compare(V, V1)) {
854 V1 = V;
855 n1 = n;
856 DontRemove = I;
857 }
858 }
859 if (DontRemove != Remove.end()) {
860 unsigned n = *DontRemove;
861 Remove.remove(n);
862 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000863 }
864 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000865
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000866 // We'd like to allow makeEqual on two values to perform a simple
867 // substitution without every creating nodes in the IG whenever possible.
868 //
869 // The first iteration through this loop operates on V2 before going
870 // through the Remove list and operating on those too. If all of the
871 // iterations performed simple replacements then we exit early.
872 bool exitEarly = true;
873 unsigned i = 0;
874 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
875 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
876
877 // Try to replace the whole instruction. If we can, we're done.
878 Instruction *I2 = dyn_cast<Instruction>(R);
879 if (I2 && below(I2)) {
880 std::vector<Instruction *> ToNotify;
881 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
882 UI != UE;) {
883 Use &TheUse = UI.getUse();
884 ++UI;
885 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
886 ToNotify.push_back(I);
887 }
888
889 DOUT << "Simply removing " << *I2
890 << ", replacing with " << *V1 << "\n";
891 I2->replaceAllUsesWith(V1);
892 // leave it dead; it'll get erased later.
893 ++NumInstruction;
894 modified = true;
895
896 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
897 IE = ToNotify.end(); II != IE; ++II) {
898 opsToDef(*II);
899 }
900
901 continue;
902 }
903
904 // Otherwise, replace all dominated uses.
905 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
906 UI != UE;) {
907 Use &TheUse = UI.getUse();
908 ++UI;
909 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
910 if (below(I)) {
911 TheUse.set(V1);
912 modified = true;
913 ++NumVarsReplaced;
914 opsToDef(I);
915 }
916 }
917 }
918
919 // If that killed the instruction, stop here.
920 if (I2 && isInstructionTriviallyDead(I2)) {
921 DOUT << "Killed all uses of " << *I2
922 << ", replacing with " << *V1 << "\n";
923 continue;
924 }
925
926 // If we make it to here, then we will need to create a node for N1.
927 // Otherwise, we can skip out early!
928 exitEarly = false;
929 }
930
931 if (exitEarly) return true;
932
933 // Create N1.
934 // XXX: this should call newNode, but instead the node might be created
935 // in isRelatedBy. That's also a fixme.
936 if (!n1) n1 = IG.getOrInsertNode(V1, Top);
937
938 // Migrate relationships from removed nodes to N1.
939 Node *N1 = IG.node(n1);
940 for (std::vector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
941 I != E; ++I) {
942 unsigned n = *I;
943 Node *N = IG.node(n);
944 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
945 if (Top == NI->Subtree || NI->Subtree->DominatedBy(Top)) {
946 if (NI->To == n1) {
947 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
948 continue;
949 }
950 if (Remove.count(NI->To))
951 continue;
952
953 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
954 N1->update(NI->To, NI->LV, Top);
955 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000956 }
957 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000958
959 // Point V2 (and all items in Remove) to N1.
960 if (!n2)
961 IG.addEquality(n1, V2, Top);
962 else {
963 for (std::vector<unsigned>::iterator I = Remove.begin(),
964 E = Remove.end(); I != E; ++I) {
965 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
966 }
967 }
968
969 // If !Remove.empty() then V2 = Remove[0]->getValue().
970 // Even when Remove is empty, we still want to process V2.
971 i = 0;
972 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
973 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
974
975 if (Instruction *I2 = dyn_cast<Instruction>(R)) defToOps(I2);
976 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
977 UI != UE;) {
978 Use &TheUse = UI.getUse();
979 ++UI;
980 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
981 opsToDef(I);
982 }
983 }
984 }
985
986 return true;
987 }
988
989 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
990 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
991 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
992 switch (Pred) {
993 case ICmpInst::ICMP_EQ:
994 assert(!"No matching lattice value.");
995 return static_cast<LatticeVal>(EQ_BIT);
996 default:
997 assert(!"Invalid 'icmp' predicate.");
998 case ICmpInst::ICMP_NE:
999 return NE;
1000 case ICmpInst::ICMP_UGT:
1001 return SNEUGT;
1002 case ICmpInst::ICMP_UGE:
1003 return SANYUGE;
1004 case ICmpInst::ICMP_ULT:
1005 return SNEULT;
1006 case ICmpInst::ICMP_ULE:
1007 return SANYULE;
1008 case ICmpInst::ICMP_SGT:
1009 return SGTUNE;
1010 case ICmpInst::ICMP_SGE:
1011 return SGEUANY;
1012 case ICmpInst::ICMP_SLT:
1013 return SLTUNE;
1014 case ICmpInst::ICMP_SLE:
1015 return SLEUANY;
1016 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001017 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001018
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001019 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001020 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1021 bool &modified, BasicBlock *TopBB)
1022 : IG(IG),
1023 UB(UB),
1024 Forest(Forest),
1025 Top(Forest->getNodeForBlock(TopBB)),
1026 TopBB(TopBB),
1027 TopInst(NULL),
1028 modified(modified) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +00001029
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001030 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1031 bool &modified, Instruction *TopInst)
1032 : IG(IG),
1033 UB(UB),
1034 Forest(Forest),
1035 TopInst(TopInst),
1036 modified(modified)
1037 {
1038 TopBB = TopInst->getParent();
1039 Top = Forest->getNodeForBlock(TopBB);
1040 }
1041
1042 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1043 if (Constant *C1 = dyn_cast<Constant>(V1))
1044 if (Constant *C2 = dyn_cast<Constant>(V2))
1045 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001046 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001047
1048 // XXX: this is lousy. If we're passed a Constant, then we might miss
1049 // some relationships if it isn't in the IG because the relationships
1050 // added by initializeConstant are missing.
1051 if (isa<Constant>(V1)) IG.getOrInsertNode(V1, Top);
1052 if (isa<Constant>(V2)) IG.getOrInsertNode(V2, Top);
1053
1054 if (unsigned n1 = IG.getNode(V1, Top))
1055 if (unsigned n2 = IG.getNode(V2, Top)) {
1056 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1057 Pred == ICmpInst::ICMP_ULE ||
1058 Pred == ICmpInst::ICMP_UGE ||
1059 Pred == ICmpInst::ICMP_SLE ||
1060 Pred == ICmpInst::ICMP_SGE;
1061 if (Pred == ICmpInst::ICMP_EQ) return false;
1062 return IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred));
1063 }
1064
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001065 return false;
1066 }
1067
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001068 /// add - adds a new property to the work queue
1069 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1070 Instruction *I = NULL) {
1071 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1072 if (I) DOUT << " context: " << *I;
1073 else DOUT << " default context";
1074 DOUT << "\n";
1075
1076 WorkList.push_back(Operation());
1077 Operation &O = WorkList.back();
1078 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.Context = I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001079 }
1080
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001081 /// defToOps - Given an instruction definition that we've learned something
1082 /// new about, find any new relationships between its operands.
1083 void defToOps(Instruction *I) {
1084 Instruction *NewContext = below(I) ? I : TopInst;
1085 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001086
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001087 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1088 const Type *Ty = BO->getType();
1089 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001090
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001091 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1092 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001093
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001094 // TODO: "and bool true, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001095
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001096 switch (BO->getOpcode()) {
1097 case Instruction::And: {
1098 // "and int %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1099 // "and bool %a, %b" EQ true then %a EQ true and %b EQ true
Zhou Sheng75b871f2007-01-11 12:24:14 +00001100 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001101 if (Canonical == CI) {
1102 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1103 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001104 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001105 } break;
1106 case Instruction::Or: {
1107 // "or int %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1108 // "or bool %a, %b" EQ false then %a EQ false and %b EQ false
1109 Constant *Zero = Constant::getNullValue(Ty);
1110 if (Canonical == Zero) {
1111 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1112 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1113 }
1114 } break;
1115 case Instruction::Xor: {
1116 // "xor bool true, %a" EQ true then %a EQ false
1117 // "xor bool true, %a" EQ false then %a EQ true
1118 // "xor bool false, %a" EQ true then %a EQ true
1119 // "xor bool false, %a" EQ false then %a EQ false
1120 // "xor int %c, %a" EQ %c then %a EQ 0
1121 // "xor int %c, %a" NE %c then %a NE 0
1122 // 1. Repeat all of the above, with order of operands reversed.
1123 Value *LHS = Op0;
1124 Value *RHS = Op1;
1125 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1126
Nick Lewycky4a74a752007-01-12 00:02:12 +00001127 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1128 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1129 add(RHS, ConstantInt::get(CI->getType(), CI->getZExtValue() ^
1130 Arg->getZExtValue()),
1131 ICmpInst::ICMP_EQ, NewContext);
1132 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001133 }
1134 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001135 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001136 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1137 NewContext);
1138 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1139 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1140 NewContext);
1141 }
1142 } break;
1143 default:
1144 break;
1145 }
1146 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1147 // "icmp ult int %a, int %y" EQ true then %a u< y
1148 // etc.
1149
Zhou Sheng75b871f2007-01-11 12:24:14 +00001150 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001151 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1152 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001153 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001154 add(IC->getOperand(0), IC->getOperand(1),
1155 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1156 }
1157 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1158 if (I->getType()->isFPOrFPVector()) return;
1159
1160 // Given: "%a = select bool %x, int %b, int %c"
1161 // %a EQ %b and %b NE %c then %x EQ true
1162 // %a EQ %c and %b NE %c then %x EQ false
1163
1164 Value *True = SI->getTrueValue();
1165 Value *False = SI->getFalseValue();
1166 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1167 if (Canonical == IG.canonicalize(True, Top) ||
1168 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001169 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001170 ICmpInst::ICMP_EQ, NewContext);
1171 else if (Canonical == IG.canonicalize(False, Top) ||
1172 isRelatedBy(I, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001173 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001174 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001175 }
1176 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001177 // TODO: CastInst "%a = cast ... %b" where %a is EQ or NE a constant.
1178 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001179
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001180 /// opsToDef - A new relationship was discovered involving one of this
1181 /// instruction's operands. Find any new relationship involving the
1182 /// definition.
1183 void opsToDef(Instruction *I) {
1184 Instruction *NewContext = below(I) ? I : TopInst;
1185
1186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1187 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1188 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1189
Zhou Sheng75b871f2007-01-11 12:24:14 +00001190 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1191 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001192 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1193 ICmpInst::ICMP_EQ, NewContext);
1194 return;
1195 }
1196
1197 // "%y = and bool true, %x" then %x EQ %y.
1198 // "%y = or bool false, %x" then %x EQ %y.
1199 if (BO->getOpcode() == Instruction::Or) {
1200 Constant *Zero = Constant::getNullValue(BO->getType());
1201 if (Op0 == Zero) {
1202 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1203 return;
1204 } else if (Op1 == Zero) {
1205 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1206 return;
1207 }
1208 } else if (BO->getOpcode() == Instruction::And) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001209 Constant *AllOnes = ConstantInt::getAllOnesValue(BO->getType());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001210 if (Op0 == AllOnes) {
1211 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1212 return;
1213 } else if (Op1 == AllOnes) {
1214 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1215 return;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001216 }
1217 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001218
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001219 // "%x = add int %y, %z" and %x EQ %y then %z EQ 0
1220 // "%x = mul int %y, %z" and %x EQ %y then %z EQ 1
1221 // 1. Repeat all of the above, with order of operands reversed.
1222 // "%x = udiv int %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001223
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001224 Value *Known = Op0, *Unknown = Op1;
1225 if (Known != BO) std::swap(Known, Unknown);
1226 if (Known == BO) {
1227 const Type *Ty = BO->getType();
1228 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001229
1230 switch (BO->getOpcode()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001231 default: break;
1232 case Instruction::Xor:
1233 case Instruction::Or:
1234 case Instruction::Add:
1235 case Instruction::Sub:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001236 add(Unknown, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1237 NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001238 break;
1239 case Instruction::UDiv:
1240 case Instruction::SDiv:
1241 if (Unknown == Op0) break; // otherwise, fallthrough
1242 case Instruction::And:
1243 case Instruction::Mul:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001244 if (isa<ConstantInt>(Unknown)) {
1245 Constant *One = ConstantInt::get(Ty, 1);
1246 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1247 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001248 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001249 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001250 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001251
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001252 // TODO: "%a = add int %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001253
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001254 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1255 // "%a = icmp ult %b, %c" and %b u< %c then %a EQ true
1256 // "%a = icmp ult %b, %c" and %b u>= %c then %a EQ false
1257 // etc.
1258
1259 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1260 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1261
1262 ICmpInst::Predicate Pred = IC->getPredicate();
1263 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001264 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001265 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001266 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001267 }
1268
Nick Lewycky4a74a752007-01-12 00:02:12 +00001269 // TODO: "bool %x s<u> %y" implies %x = true and %y = false.
1270
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001271 // TODO: make the predicate more strict, if possible.
1272
1273 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1274 // Given: "%a = select bool %x, int %b, int %c"
1275 // %x EQ true then %a EQ %b
1276 // %x EQ false then %a EQ %c
1277 // %b EQ %c then %a EQ %b
1278
1279 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001280 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001281 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001282 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001283 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1284 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1285 IG.canonicalize(SI->getFalseValue(), Top)) {
1286 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1287 }
1288 }
1289 // TODO: CastInst "%a = cast ... %b" where %b is EQ or NE a constant.
1290 }
1291
1292 /// solve - process the work queue
1293 /// Return false if a logical contradiction occurs.
1294 void solve() {
1295 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
1296 while (!WorkList.empty()) {
1297 //DOUT << "WorkList size: " << WorkList.size() << "\n";
1298
1299 Operation &O = WorkList.front();
1300 if (O.Context) {
1301 TopInst = O.Context;
1302 Top = Forest->getNodeForBlock(TopInst->getParent());
1303 }
1304 O.LHS = IG.canonicalize(O.LHS, Top);
1305 O.RHS = IG.canonicalize(O.RHS, Top);
1306
1307 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
1308 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
1309
1310 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
1311 if (O.Context) DOUT << " context: " << *O.Context;
1312 else DOUT << " default context";
1313 DOUT << "\n";
1314
1315 DEBUG(IG.dump());
1316
1317 // TODO: actually check the constants and add to UB.
1318 if (isa<Constant>(O.LHS) && isa<Constant>(O.RHS)) {
1319 WorkList.pop_front();
1320 continue;
1321 }
1322
1323 if (O.Op == ICmpInst::ICMP_EQ) {
1324 if (!makeEqual(O.LHS, O.RHS))
1325 UB.mark(TopBB);
1326 } else {
1327 LatticeVal LV = cmpInstToLattice(O.Op);
1328
1329 if ((LV & EQ_BIT) &&
1330 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
1331 if (!makeEqual(O.LHS, O.RHS))
1332 UB.mark(TopBB);
1333 } else {
1334 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
1335 DOUT << "inequality contradiction!\n";
1336 WorkList.pop_front();
1337 continue;
1338 }
1339
1340 unsigned n1 = IG.getOrInsertNode(O.LHS, Top);
1341 unsigned n2 = IG.getOrInsertNode(O.RHS, Top);
1342
1343 if (n1 == n2) {
1344 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
1345 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
1346 UB.mark(TopBB);
1347
1348 WorkList.pop_front();
1349 continue;
1350 }
1351
1352 if (IG.isRelatedBy(n1, n2, Top, LV)) {
1353 WorkList.pop_front();
1354 continue;
1355 }
1356
1357 IG.addInequality(n1, n2, Top, LV);
1358
1359 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) defToOps(I1);
1360 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
1361 for (Value::use_iterator UI = O.LHS->use_begin(),
1362 UE = O.LHS->use_end(); UI != UE;) {
1363 Use &TheUse = UI.getUse();
1364 ++UI;
1365 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1366 opsToDef(I);
1367 }
1368 }
1369 }
1370 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) defToOps(I2);
1371 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
1372 for (Value::use_iterator UI = O.RHS->use_begin(),
1373 UE = O.RHS->use_end(); UI != UE;) {
1374 Use &TheUse = UI.getUse();
1375 ++UI;
1376 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1377 opsToDef(I);
1378 }
1379 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001380 }
1381 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001382 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001383 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00001384 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001385 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001386 };
1387
1388 /// PredicateSimplifier - This class is a simplifier that replaces
1389 /// one equivalent variable with another. It also tracks what
1390 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001391 /// @brief Root of the predicate simplifier optimization.
1392 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1393 DominatorTree *DT;
1394 ETForest *Forest;
1395 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001396 InequalityGraph *IG;
1397 UnreachableBlocks UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001398
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001399 std::vector<DominatorTree::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001400
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001401 public:
1402 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001403
1404 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1405 AU.addRequiredID(BreakCriticalEdgesID);
1406 AU.addRequired<DominatorTree>();
1407 AU.addRequired<ETForest>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001408 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001409
1410 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001411 /// Forwards - Adds new properties into PropertySet and uses them to
1412 /// simplify instructions. Because new properties sometimes apply to
1413 /// a transition from one BasicBlock to another, this will use the
1414 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1415 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001416 /// @brief Performs abstract execution of the program.
1417 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001418 friend class InstVisitor<Forwards>;
1419 PredicateSimplifier *PS;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001420 DominatorTree::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001421
Nick Lewycky77e030b2006-10-12 02:02:44 +00001422 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001423 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001424 UnreachableBlocks &UB;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001425
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001426 Forwards(PredicateSimplifier *PS, DominatorTree::Node *DTNode)
1427 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001428
1429 void visitTerminatorInst(TerminatorInst &TI);
1430 void visitBranchInst(BranchInst &BI);
1431 void visitSwitchInst(SwitchInst &SI);
1432
Nick Lewyckyf3450082006-10-22 19:53:27 +00001433 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001434 void visitLoadInst(LoadInst &LI);
1435 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001436
Nick Lewycky77e030b2006-10-12 02:02:44 +00001437 void visitBinaryOperator(BinaryOperator &BO);
1438 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001439
1440 // Used by terminator instructions to proceed from the current basic
1441 // block to the next. Verifies that "current" dominates "next",
1442 // then calls visitBasicBlock.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001443 void proceedToSuccessors(DominatorTree::Node *Current) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001444 for (DominatorTree::Node::iterator I = Current->begin(),
1445 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001446 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001447 }
1448 }
1449
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001450 void proceedToSuccessor(DominatorTree::Node *Next) {
1451 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001452 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001453
1454 // Visits each instruction in the basic block.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001455 void visitBasicBlock(DominatorTree::Node *Node) {
1456 BasicBlock *BB = Node->getBlock();
1457 ETNode *ET = Forest->getNodeForBlock(BB);
1458 DOUT << "Entering Basic Block: " << BB->getName() << " (" << ET << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00001459 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001460 visitInstruction(I++, Node, ET);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001461 }
1462 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001463
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001464 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001465 // the PropertySet.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001466 void visitInstruction(Instruction *I, DominatorTree::Node *DT, ETNode *ET) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001467 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001468 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001469
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001470 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001471 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001472 ++NumSimple;
1473 modified = true;
1474 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001475 I->eraseFromParent();
1476 return;
1477 }
1478
1479 // Try to replace the whole instruction.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001480 Value *V = IG->canonicalize(I, ET);
1481 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001482 if (V != I) {
1483 modified = true;
1484 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00001485 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001486 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001487 I->replaceAllUsesWith(V);
1488 I->eraseFromParent();
1489 return;
1490 }
1491
1492 // Try to substitute operands.
1493 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1494 Value *Oper = I->getOperand(i);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001495 Value *V = IG->canonicalize(Oper, ET);
1496 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001497 if (V != Oper) {
1498 modified = true;
1499 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00001500 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001501 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00001502 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001503 }
1504 }
1505
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001506 DOUT << "push (%" << I->getParent()->getName() << ")\n";
1507 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001508 visit.visit(*I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001509 DOUT << "pop (%" << I->getParent()->getName() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001510 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001511 };
1512
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001513 bool PredicateSimplifier::runOnFunction(Function &F) {
1514 DT = &getAnalysis<DominatorTree>();
1515 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001516
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001517 Forest->updateDFSNumbers(); // XXX: should only act when numbers are out of date
1518
Bill Wendling22e978a2006-12-07 20:04:42 +00001519 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001520
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001521 modified = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001522 BasicBlock *RootBlock = &F.getEntryBlock();
1523 IG = new InequalityGraph(Forest->getNodeForBlock(RootBlock));
1524 WorkList.push_back(DT->getRootNode());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001525
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001526 do {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001527 DominatorTree::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001528 WorkList.pop_back();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001529 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001530 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001531
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001532 delete IG;
1533
1534 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001535
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001536 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00001537 }
1538
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001539 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001540 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001541 }
1542
1543 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001544 if (BI.isUnconditional()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001545 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001546 return;
1547 }
1548
1549 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001550 BasicBlock *TrueDest = BI.getSuccessor(0);
1551 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001552
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001553 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
1554 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001555 return;
1556 }
1557
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001558 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001559 I != E; ++I) {
1560 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001561 DOUT << "Branch thinking about %" << Dest->getName()
1562 << "(" << PS->Forest->getNodeForBlock(Dest) << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001563
1564 if (Dest == TrueDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001565 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
1566 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001567 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001568 VRP.solve();
1569 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001570 } else if (Dest == FalseDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001571 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
1572 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001573 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001574 VRP.solve();
1575 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001576 }
1577
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001578 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001579 }
1580 }
1581
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001582 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
1583 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001584
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001585 // Set the EQProperty in each of the cases BBs, and the NEProperties
1586 // in the default BB.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001587
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001588 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001589 I != E; ++I) {
1590 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001591 DOUT << "Switch thinking about BB %" << BB->getName()
1592 << "(" << PS->Forest->getNodeForBlock(BB) << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001593
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001594 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001595 if (BB == SI.getDefaultDest()) {
1596 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
1597 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001598 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
1599 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001600 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001601 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
1602 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001603 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001604 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00001605 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001606 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001607
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001608 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001609 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &AI);
1610 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001611 VRP.solve();
1612 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00001613
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001614 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
1615 Value *Ptr = LI.getPointerOperand();
1616 // avoid "load uint* null" -> null NE null.
1617 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001618
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001619 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &LI);
1620 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001621 VRP.solve();
1622 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001623
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001624 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
1625 Value *Ptr = SI.getPointerOperand();
1626 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001627
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001628 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &SI);
1629 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001630 VRP.solve();
1631 }
1632
1633 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
1634 Instruction::BinaryOps ops = BO.getOpcode();
1635
1636 switch (ops) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001637 case Instruction::URem:
1638 case Instruction::SRem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001639 case Instruction::UDiv:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001640 case Instruction::SDiv: {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001641 Value *Divisor = BO.getOperand(1);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001642 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &BO);
1643 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
1644 ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001645 VRP.solve();
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001646 break;
1647 }
1648 default:
1649 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001650 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001651 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001652
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001653 RegisterPass<PredicateSimplifier> X("predsimplify",
1654 "Predicate Simplifier");
1655}
1656
1657FunctionPass *llvm::createPredicateSimplifierPass() {
1658 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001659}