blob: 715818c686156c2f690dbd2812c32ede15c3d84f [file] [log] [blame]
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier -----------===//
2//
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//
8//===------------------------------------------------------------------===//
9//
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//
23//===------------------------------------------------------------------===//
24//
25// This optimization works by substituting %q for %p when protected by a
Nick Lewycky5f8f9af2006-08-30 02:46:48 +000026// conditional that assures us of that fact. Properties are stored as
27// relationships between two values.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000028//
29//===------------------------------------------------------------------===//
30
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000031#define DEBUG_TYPE "predsimplify"
32#include "llvm/Transforms/Scalar.h"
33#include "llvm/Constants.h"
34#include "llvm/Instructions.h"
35#include "llvm/Pass.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/Analysis/Dominators.h"
39#include "llvm/Support/CFG.h"
40#include "llvm/Support/Debug.h"
41#include <iostream>
42using namespace llvm;
43
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000044typedef DominatorTree::Node DTNodeType;
45
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000046namespace {
47 Statistic<>
48 NumVarsReplaced("predsimplify", "Number of argument substitutions");
49 Statistic<>
Nick Lewycky5f8f9af2006-08-30 02:46:48 +000050 NumInstruction("predsimplify", "Number of instructions removed");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000051
Nick Lewyckycfff1c32006-09-20 17:04:01 +000052 class PropertySet;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000053
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000054 /// Similar to EquivalenceClasses, this stores the set of equivalent
Nick Lewyckycfff1c32006-09-20 17:04:01 +000055 /// types. Beyond EquivalenceClasses, it allows us to specify which
56 /// element will act as leader.
57 template<typename ElemTy>
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000058 class VISIBILITY_HIDDEN Synonyms {
59 std::map<ElemTy, unsigned> mapping;
60 std::vector<ElemTy> leaders;
Nick Lewyckycfff1c32006-09-20 17:04:01 +000061 PropertySet *PS;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000062
63 public:
64 typedef unsigned iterator;
65 typedef const unsigned const_iterator;
66
Nick Lewyckycfff1c32006-09-20 17:04:01 +000067 Synonyms(PropertySet *PS) : PS(PS) {}
68
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000069 // Inspection
70
71 bool empty() const {
72 return leaders.empty();
73 }
74
75 iterator findLeader(ElemTy e) {
76 typename std::map<ElemTy, unsigned>::iterator MI = mapping.find(e);
77 if (MI == mapping.end()) return 0;
78
79 return MI->second;
80 }
81
82 const_iterator findLeader(ElemTy e) const {
83 typename std::map<ElemTy, unsigned>::const_iterator MI =
84 mapping.find(e);
85 if (MI == mapping.end()) return 0;
86
87 return MI->second;
88 }
89
90 ElemTy &getLeader(iterator I) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +000091 assert(I && I <= leaders.size() && "Illegal leader to get.");
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000092 return leaders[I-1];
93 }
94
95 const ElemTy &getLeader(const_iterator I) const {
Nick Lewyckyb9c54832006-09-18 21:09:35 +000096 assert(I && I <= leaders.size() && "Illegal leaders to get.");
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000097 return leaders[I-1];
98 }
99
100#ifdef DEBUG
101 void debug(std::ostream &os) const {
102 for (unsigned i = 1, e = leaders.size()+1; i != e; ++i) {
Nick Lewycky12efffc2006-09-13 19:32:53 +0000103 os << i << ". " << *getLeader(i) << ": [";
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000104 for (std::map<Value *, unsigned>::const_iterator
105 I = mapping.begin(), E = mapping.end(); I != E; ++I) {
106 if ((*I).second == i && (*I).first != leaders[i-1]) {
107 os << *(*I).first << " ";
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000108 }
109 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000110 os << "]\n";
111 }
112 }
113#endif
114
115 // Mutators
116
117 /// Combine two sets referring to the same element, inserting the
118 /// elements as needed. Returns a valid iterator iff two already
119 /// existing disjoint synonym sets were combined. The iterator
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000120 /// points to the no longer existing element.
121 iterator unionSets(ElemTy E1, ElemTy E2);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000122
123 /// Returns an iterator pointing to the synonym set containing
124 /// element e. If none exists, a new one is created and returned.
125 iterator findOrInsert(ElemTy e) {
126 iterator I = findLeader(e);
127 if (I) return I;
128
129 leaders.push_back(e);
130 I = leaders.size();
131 mapping[e] = I;
132 return I;
133 }
134 };
135
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000136 /// Represents the set of equivalent Value*s and provides insertion
137 /// and fast lookup. Also stores the set of inequality relationships.
138 class PropertySet {
Nick Lewycky059c7922006-09-23 15:13:08 +0000139 /// Returns true if V1 is a better choice than V2.
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000140 bool compare(Value *V1, Value *V2) const {
141 if (isa<Constant>(V1)) {
142 if (!isa<Constant>(V2)) {
143 return true;
144 }
145 } else if (isa<Argument>(V1)) {
146 if (!isa<Constant>(V2) && !isa<Argument>(V2)) {
147 return true;
148 }
149 }
150 if (Instruction *I1 = dyn_cast<Instruction>(V1)) {
151 if (Instruction *I2 = dyn_cast<Instruction>(V2)) {
152 BasicBlock *BB1 = I1->getParent(),
153 *BB2 = I2->getParent();
154 if (BB1 == BB2) {
155 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
156 I != E; ++I) {
157 if (&*I == I1) return true;
158 if (&*I == I2) return false;
159 }
160 assert(0 && "Instructions not found in parent BasicBlock?");
161 } else
162 return DT->getNode(BB1)->properlyDominates(DT->getNode(BB2));
163 }
164 }
165 return false;
166 }
167
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000168 struct Property;
169 public:
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000170 /// Choose the canonical Value in a synonym set.
171 /// Leaves the more canonical choice in V1.
172 void order(Value *&V1, Value *&V2) const {
173 if (compare(V2, V1)) std::swap(V1, V2);
174 }
175
176 PropertySet(DominatorTree *DT) : union_find(this), DT(DT) {}
177
178 class Synonyms<Value *> union_find;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000179
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000180 typedef std::vector<Property>::iterator PropertyIterator;
181 typedef std::vector<Property>::const_iterator ConstPropertyIterator;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000182 typedef Synonyms<Value *>::iterator SynonymIterator;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000183
184 enum Ops {
185 EQ,
186 NE
187 };
188
189 Value *canonicalize(Value *V) const {
190 Value *C = lookup(V);
191 return C ? C : V;
192 }
193
194 Value *lookup(Value *V) const {
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000195 SynonymIterator SI = union_find.findLeader(V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000196 if (!SI) return NULL;
197 return union_find.getLeader(SI);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000198 }
199
200 bool empty() const {
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000201 return union_find.empty();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000202 }
203
204 void addEqual(Value *V1, Value *V2) {
Nick Lewycky8e559932006-09-02 19:40:38 +0000205 // If %x = 0. and %y = -0., seteq %x, %y is true, but
206 // copysign(%x) is not the same as copysign(%y).
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000207 if (V1->getType()->isFloatingPoint()) return;
Nick Lewycky8e559932006-09-02 19:40:38 +0000208
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000209 order(V1, V2);
210 if (isa<Constant>(V2)) return; // refuse to set false == true.
211
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000212 SynonymIterator deleted = union_find.unionSets(V1, V2);
213 if (deleted) {
214 SynonymIterator replacement = union_find.findLeader(V1);
215 // Move Properties
216 for (PropertyIterator I = Properties.begin(), E = Properties.end();
217 I != E; ++I) {
218 if (I->I1 == deleted) I->I1 = replacement;
219 else if (I->I1 > deleted) --I->I1;
220 if (I->I2 == deleted) I->I2 = replacement;
221 else if (I->I2 > deleted) --I->I2;
222 }
223 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000224 addImpliedProperties(EQ, V1, V2);
225 }
226
227 void addNotEqual(Value *V1, Value *V2) {
Nick Lewycky8e559932006-09-02 19:40:38 +0000228 // If %x = NAN then seteq %x, %x is false.
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000229 if (V1->getType()->isFloatingPoint()) return;
230
231 // For example, %x = setne int 0, 0 causes "0 != 0".
232 if (isa<Constant>(V1) && isa<Constant>(V2)) return;
Nick Lewycky8e559932006-09-02 19:40:38 +0000233
Nick Lewycky08674ab2006-08-31 00:39:16 +0000234 if (findProperty(NE, V1, V2) != Properties.end())
235 return; // found.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000236
237 // Add the property.
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000238 SynonymIterator I1 = union_find.findOrInsert(V1),
239 I2 = union_find.findOrInsert(V2);
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000240
241 // Technically this means that the block is unreachable.
242 if (I1 == I2) return;
243
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000244 Properties.push_back(Property(NE, I1, I2));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000245 addImpliedProperties(NE, V1, V2);
246 }
247
248 PropertyIterator findProperty(Ops Opcode, Value *V1, Value *V2) {
249 assert(Opcode != EQ && "Can't findProperty on EQ."
250 "Use the lookup method instead.");
251
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000252 SynonymIterator I1 = union_find.findLeader(V1),
253 I2 = union_find.findLeader(V2);
254 if (!I1 || !I2) return Properties.end();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000255
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000256 return
257 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000258 }
259
260 ConstPropertyIterator
261 findProperty(Ops Opcode, Value *V1, Value *V2) const {
262 assert(Opcode != EQ && "Can't findProperty on EQ."
263 "Use the lookup method instead.");
264
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000265 SynonymIterator I1 = union_find.findLeader(V1),
266 I2 = union_find.findLeader(V2);
267 if (!I1 || !I2) return Properties.end();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000268
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000269 return
270 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000271 }
272
273 private:
274 // Represents Head OP [Tail1, Tail2, ...]
275 // For example: %x != %a, %x != %b.
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000276 struct VISIBILITY_HIDDEN Property {
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000277 typedef SynonymIterator Iter;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000278
279 Property(Ops opcode, Iter i1, Iter i2)
280 : Opcode(opcode), I1(i1), I2(i2)
Nick Lewycky8e559932006-09-02 19:40:38 +0000281 { assert(opcode != EQ && "Equality belongs in the synonym set, "
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000282 "not a property."); }
283
284 bool operator==(const Property &P) const {
285 return (Opcode == P.Opcode) &&
286 ((I1 == P.I1 && I2 == P.I2) ||
287 (I1 == P.I2 && I2 == P.I1));
288 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000289
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000290 Ops Opcode;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000291 Iter I1, I2;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000292 };
293
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000294 void add(Ops Opcode, Value *V1, Value *V2, bool invert) {
295 switch (Opcode) {
296 case EQ:
297 if (invert) addNotEqual(V1, V2);
298 else addEqual(V1, V2);
299 break;
300 case NE:
301 if (invert) addEqual(V1, V2);
302 else addNotEqual(V1, V2);
303 break;
304 default:
305 assert(0 && "Unknown property opcode.");
306 }
307 }
308
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000309 // Finds the properties implied by an equivalence and adds them too.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000310 // Example: ("seteq %a, %b", true, EQ) --> (%a, %b, EQ)
311 // ("seteq %a, %b", false, EQ) --> (%a, %b, NE)
312 void addImpliedProperties(Ops Opcode, Value *V1, Value *V2) {
313 order(V1, V2);
314
315 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V2)) {
316 switch (BO->getOpcode()) {
317 case Instruction::SetEQ:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000318 if (ConstantBool *V1CB = dyn_cast<ConstantBool>(V1))
319 add(Opcode, BO->getOperand(0), BO->getOperand(1),!V1CB->getValue());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000320 break;
321 case Instruction::SetNE:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000322 if (ConstantBool *V1CB = dyn_cast<ConstantBool>(V1))
323 add(Opcode, BO->getOperand(0), BO->getOperand(1), V1CB->getValue());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000324 break;
325 case Instruction::SetLT:
326 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000327 if (V1 == ConstantBool::getTrue())
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000328 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
329 break;
330 case Instruction::SetLE:
331 case Instruction::SetGE:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000332 if (V1 == ConstantBool::getFalse())
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000333 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
334 break;
335 case Instruction::And:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000336 if (V1 == ConstantBool::getTrue()) {
337 add(Opcode, V1, BO->getOperand(0), false);
338 add(Opcode, V1, BO->getOperand(1), false);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000339 }
340 break;
341 case Instruction::Or:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000342 if (V1 == ConstantBool::getFalse()) {
343 add(Opcode, V1, BO->getOperand(0), false);
344 add(Opcode, V1, BO->getOperand(1), false);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000345 }
346 break;
347 case Instruction::Xor:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000348 if (V1 == ConstantBool::getTrue()) {
349 if (BO->getOperand(0) == V1)
350 add(Opcode, ConstantBool::getFalse(), BO->getOperand(1), false);
351 if (BO->getOperand(1) == V1)
352 add(Opcode, ConstantBool::getFalse(), BO->getOperand(0), false);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000353 }
Chris Lattner6ab03f62006-09-28 23:35:22 +0000354 if (V1 == ConstantBool::getFalse()) {
355 if (BO->getOperand(0) == ConstantBool::getTrue())
356 add(Opcode, ConstantBool::getTrue(), BO->getOperand(1), false);
357 if (BO->getOperand(1) == ConstantBool::getTrue())
358 add(Opcode, ConstantBool::getTrue(), BO->getOperand(0), false);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000359 }
360 break;
361 default:
362 break;
363 }
Nick Lewycky8e559932006-09-02 19:40:38 +0000364 } else if (SelectInst *SI = dyn_cast<SelectInst>(V2)) {
365 if (Opcode != EQ && Opcode != NE) return;
366
Chris Lattner6ab03f62006-09-28 23:35:22 +0000367 ConstantBool *True = ConstantBool::get(Opcode==EQ),
368 *False = ConstantBool::get(Opcode!=EQ);
Nick Lewycky8e559932006-09-02 19:40:38 +0000369
370 if (V1 == SI->getTrueValue())
371 addEqual(SI->getCondition(), True);
372 else if (V1 == SI->getFalseValue())
373 addEqual(SI->getCondition(), False);
374 else if (Opcode == EQ)
375 assert("Result of select not equal to either value.");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000376 }
377 }
378
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000379 DominatorTree *DT;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000380 public:
Nick Lewycky8e559932006-09-02 19:40:38 +0000381#ifdef DEBUG
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000382 void debug(std::ostream &os) const {
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000383 static const char *OpcodeTable[] = { "EQ", "NE" };
384
385 union_find.debug(os);
386 for (std::vector<Property>::const_iterator I = Properties.begin(),
387 E = Properties.end(); I != E; ++I) {
388 os << (*I).I1 << " " << OpcodeTable[(*I).Opcode] << " "
389 << (*I).I2 << "\n";
Nick Lewycky08674ab2006-08-31 00:39:16 +0000390 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000391 os << "\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000392 }
Nick Lewycky8e559932006-09-02 19:40:38 +0000393#endif
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000394
395 std::vector<Property> Properties;
396 };
397
398 /// PredicateSimplifier - This class is a simplifier that replaces
399 /// one equivalent variable with another. It also tracks what
400 /// can't be equal and will solve setcc instructions when possible.
401 class PredicateSimplifier : public FunctionPass {
402 public:
403 bool runOnFunction(Function &F);
404 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
405
406 private:
407 // Try to replace the Use of the instruction with something simpler.
408 Value *resolve(SetCondInst *SCI, const PropertySet &);
409 Value *resolve(BinaryOperator *BO, const PropertySet &);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000410 Value *resolve(SelectInst *SI, const PropertySet &);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000411 Value *resolve(Value *V, const PropertySet &);
412
413 // Used by terminator instructions to proceed from the current basic
414 // block to the next. Verifies that "current" dominates "next",
415 // then calls visitBasicBlock.
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000416 void proceedToSuccessor(TerminatorInst *TI, unsigned edge,
417 PropertySet &CurrentPS, PropertySet &NextPS);
418 void proceedToSuccessors(PropertySet &CurrentPS, BasicBlock *Current);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000419
420 // Visits each instruction in the basic block.
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000421 void visitBasicBlock(BasicBlock *Block, PropertySet &KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000422
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000423 // Tries to simplify each Instruction and add new properties to
424 // the PropertySet. Returns true if it erase the instruction.
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000425 void visitInstruction(Instruction *I, PropertySet &);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000426 // For each instruction, add the properties to KnownProperties.
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000427
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000428 void visit(TerminatorInst *TI, PropertySet &);
429 void visit(BranchInst *BI, PropertySet &);
430 void visit(SwitchInst *SI, PropertySet);
431 void visit(LoadInst *LI, PropertySet &);
432 void visit(StoreInst *SI, PropertySet &);
433 void visit(BinaryOperator *BO, PropertySet &);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000434
435 DominatorTree *DT;
436 bool modified;
437 };
438
439 RegisterPass<PredicateSimplifier> X("predsimplify",
440 "Predicate Simplifier");
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000441
442 template <typename ElemTy>
443 typename Synonyms<ElemTy>::iterator
444 Synonyms<ElemTy>::unionSets(ElemTy E1, ElemTy E2) {
445 PS->order(E1, E2);
446
447 iterator I1 = findLeader(E1),
448 I2 = findLeader(E2);
449
450 if (!I1 && !I2) { // neither entry is in yet
451 leaders.push_back(E1);
452 I1 = leaders.size();
453 mapping[E1] = I1;
454 mapping[E2] = I1;
455 return 0;
456 }
457
458 if (!I1 && I2) {
459 mapping[E1] = I2;
460 std::swap(getLeader(I2), E1);
461 return 0;
462 }
463
464 if (I1 && !I2) {
465 mapping[E2] = I1;
466 return 0;
467 }
468
469 if (I1 == I2) return 0;
470
471 // This is the case where we have two sets, [%a1, %a2, %a3] and
472 // [%p1, %p2, %p3] and someone says that %a2 == %p3. We need to
473 // combine the two synsets.
474
475 if (I1 > I2) --I1;
476
477 for (std::map<Value *, unsigned>::iterator I = mapping.begin(),
478 E = mapping.end(); I != E; ++I) {
479 if (I->second == I2) I->second = I1;
480 else if (I->second > I2) --I->second;
481 }
482
483 leaders.erase(leaders.begin() + I2 - 1);
484
485 return I2;
486 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000487}
488
489FunctionPass *llvm::createPredicateSimplifierPass() {
490 return new PredicateSimplifier();
491}
492
493bool PredicateSimplifier::runOnFunction(Function &F) {
494 DT = &getAnalysis<DominatorTree>();
495
496 modified = false;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000497 PropertySet KnownProperties(DT);
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000498 visitBasicBlock(DT->getRootNode()->getBlock(), KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000499 return modified;
500}
501
502void PredicateSimplifier::getAnalysisUsage(AnalysisUsage &AU) const {
503 AU.addRequired<DominatorTree>();
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000504 AU.setPreservesCFG();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000505}
506
507// resolve catches cases addProperty won't because it wasn't used as a
508// condition in the branch, and that visit won't, because the instruction
Nick Lewycky8e559932006-09-02 19:40:38 +0000509// was defined outside of the scope that the properties apply to.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000510Value *PredicateSimplifier::resolve(SetCondInst *SCI,
511 const PropertySet &KP) {
512 // Attempt to resolve the SetCondInst to a boolean.
513
Nick Lewycky8e559932006-09-02 19:40:38 +0000514 Value *SCI0 = resolve(SCI->getOperand(0), KP),
515 *SCI1 = resolve(SCI->getOperand(1), KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000516
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000517 PropertySet::ConstPropertyIterator NE =
518 KP.findProperty(PropertySet::NE, SCI0, SCI1);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000519
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000520 if (NE != KP.Properties.end()) {
521 switch (SCI->getOpcode()) {
Chris Lattner6ab03f62006-09-28 23:35:22 +0000522 case Instruction::SetEQ: return ConstantBool::getFalse();
523 case Instruction::SetNE: return ConstantBool::getTrue();
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000524 case Instruction::SetLE:
525 case Instruction::SetGE:
526 case Instruction::SetLT:
527 case Instruction::SetGT:
528 break;
529 default:
530 assert(0 && "Unknown opcode in SetCondInst.");
531 break;
Nick Lewyckye94f42a2006-09-11 17:23:34 +0000532 }
Nick Lewyckye94f42a2006-09-11 17:23:34 +0000533 }
Nick Lewyckyd74c55f2006-09-20 23:02:24 +0000534 return SCI;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000535}
536
537Value *PredicateSimplifier::resolve(BinaryOperator *BO,
538 const PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000539 Value *lhs = resolve(BO->getOperand(0), KP),
540 *rhs = resolve(BO->getOperand(1), KP);
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000541
Nick Lewycky059c7922006-09-23 15:13:08 +0000542 ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(lhs),
543 *CI2 = dyn_cast<ConstantIntegral>(rhs);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000544
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000545 if (CI1 && CI2) return ConstantExpr::get(BO->getOpcode(), CI1, CI2);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000546
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000547 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BO))
548 return resolve(SCI, KP);
549
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000550 return BO;
551}
552
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000553Value *PredicateSimplifier::resolve(SelectInst *SI, const PropertySet &KP) {
554 Value *Condition = resolve(SI->getCondition(), KP);
Chris Lattner6ab03f62006-09-28 23:35:22 +0000555 if (ConstantBool *CB = dyn_cast<ConstantBool>(Condition))
556 return resolve(CB->getValue() ? SI->getTrueValue() : SI->getFalseValue(),
557 KP);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000558 return SI;
559}
560
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000561Value *PredicateSimplifier::resolve(Value *V, const PropertySet &KP) {
562 if (isa<Constant>(V) || isa<BasicBlock>(V) || KP.empty()) return V;
563
564 V = KP.canonicalize(V);
565
566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
567 return resolve(BO, KP);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000568 else if (SelectInst *SI = dyn_cast<SelectInst>(V))
569 return resolve(SI, KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000570
571 return V;
572}
573
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000574void PredicateSimplifier::visitBasicBlock(BasicBlock *BB,
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000575 PropertySet &KnownProperties) {
Nick Lewycky3a4dc7b2006-09-13 18:55:37 +0000576 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000577 visitInstruction(I++, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000578 }
579}
580
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000581void PredicateSimplifier::visitInstruction(Instruction *I,
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000582 PropertySet &KnownProperties) {
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000583 // Try to replace the whole instruction.
Nick Lewycky8e559932006-09-02 19:40:38 +0000584 Value *V = resolve(I, KnownProperties);
Nick Lewycky8e559932006-09-02 19:40:38 +0000585 if (V != I) {
586 modified = true;
587 ++NumInstruction;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000588 DEBUG(std::cerr << "Removing " << *I);
Nick Lewycky8e559932006-09-02 19:40:38 +0000589 I->replaceAllUsesWith(V);
Nick Lewycky3a4dc7b2006-09-13 18:55:37 +0000590 I->eraseFromParent();
Nick Lewycky8e559932006-09-02 19:40:38 +0000591 return;
592 }
593
594 // Try to substitute operands.
595 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000596 Value *Oper = I->getOperand(i);
597 Value *V = resolve(Oper, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000598 if (V != Oper) {
599 modified = true;
600 ++NumVarsReplaced;
Nick Lewycky059c7922006-09-23 15:13:08 +0000601 DEBUG(std::cerr << "Resolving " << *I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000602 I->setOperand(i, V);
603 DEBUG(std::cerr << "into " << *I);
604 }
605 }
606
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000607 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000608 visit(TI, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000609 else if (LoadInst *LI = dyn_cast<LoadInst>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000610 visit(LI, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000611 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000612 visit(SI, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000613 else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000614 visit(BO, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000615}
616
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000617// The basic block on the target of the specified edge must be known
618// to be immediately dominated by the parent of the TerminatorInst.
619void PredicateSimplifier::proceedToSuccessor(TerminatorInst *TI,
620 unsigned edge,
621 PropertySet &CurrentPS,
622 PropertySet &NextPS) {
623 assert(edge < TI->getNumSuccessors() && "Invalid index for edge.");
624
625 BasicBlock *BB = TI->getParent(),
626 *BBNext = TI->getSuccessor(edge);
627
628 if (BBNext->getSinglePredecessor() == BB)
629 visitBasicBlock(BBNext, NextPS);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000630 else
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000631 visitBasicBlock(BBNext, CurrentPS);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000632}
633
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000634void PredicateSimplifier::proceedToSuccessors(PropertySet &KP,
635 BasicBlock *BBCurrent) {
636 DTNodeType *Current = DT->getNode(BBCurrent);
637 for (DTNodeType::iterator I = Current->begin(), E = Current->end();
638 I != E; ++I) {
639 PropertySet Copy(KP);
640 visitBasicBlock((*I)->getBlock(), Copy);
641 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000642}
643
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000644void PredicateSimplifier::visit(TerminatorInst *TI, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000645 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000646 visit(BI, KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000647 return;
648 }
649 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000650 visit(SI, KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000651 return;
652 }
653
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000654 proceedToSuccessors(KP, TI->getParent());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000655}
656
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000657void PredicateSimplifier::visit(BranchInst *BI, PropertySet &KP) {
658 BasicBlock *BB = BI->getParent();
659
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000660 if (BI->isUnconditional()) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000661 proceedToSuccessors(KP, BB);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000662 return;
663 }
664
665 Value *Condition = BI->getCondition();
666
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000667 BasicBlock *TrueDest = BI->getSuccessor(0),
668 *FalseDest = BI->getSuccessor(1);
669
Chris Lattner6ab03f62006-09-28 23:35:22 +0000670 if (Condition == ConstantBool::getTrue() || TrueDest == FalseDest) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000671 proceedToSuccessors(KP, BB);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000672 return;
Chris Lattner6ab03f62006-09-28 23:35:22 +0000673 } else if (Condition == ConstantBool::getFalse()) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000674 proceedToSuccessors(KP, BB);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000675 return;
676 }
677
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000678 DTNodeType *Node = DT->getNode(BB);
679 for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
680 if ((*I)->getBlock() == TrueDest) {
681 PropertySet TrueProperties(KP);
Chris Lattner6ab03f62006-09-28 23:35:22 +0000682 TrueProperties.addEqual(ConstantBool::getTrue(), Condition);
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000683 proceedToSuccessor(BI, 0, KP, TrueProperties);
684 continue;
685 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000686
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000687 if ((*I)->getBlock() == FalseDest) {
688 PropertySet FalseProperties(KP);
Chris Lattner6ab03f62006-09-28 23:35:22 +0000689 FalseProperties.addEqual(ConstantBool::getFalse(), Condition);
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000690 proceedToSuccessor(BI, 1, KP, FalseProperties);
691 continue;
692 }
693
694 visitBasicBlock((*I)->getBlock(), KP);
695 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000696}
697
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000698void PredicateSimplifier::visit(SwitchInst *SI, PropertySet KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000699 Value *Condition = SI->getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000700
701 // Set the EQProperty in each of the cases BBs,
702 // and the NEProperties in the default BB.
703 PropertySet DefaultProperties(KP);
704
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000705 DTNodeType *Node = DT->getNode(SI->getParent());
706 for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
707 BasicBlock *BB = (*I)->getBlock();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000708
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000709 PropertySet Copy(KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000710
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000711 if (BB == SI->getDefaultDest()) {
712 PropertySet NewProperties(KP);
713 for (unsigned i = 1, e = SI->getNumCases(); i < e; ++i)
714 NewProperties.addNotEqual(Condition, SI->getCaseValue(i));
715
716 proceedToSuccessor(SI, 0, Copy, NewProperties);
717 } else if (ConstantInt *CI = SI->findCaseDest(BB)) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000718 PropertySet NewProperties(KP);
719 NewProperties.addEqual(Condition, CI);
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000720 proceedToSuccessor(SI, SI->findCaseValue(CI), Copy, NewProperties);
721 } else
722 visitBasicBlock(BB, Copy);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000723 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000724}
725
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000726void PredicateSimplifier::visit(LoadInst *LI, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000727 Value *Ptr = LI->getPointerOperand();
728 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
729}
730
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000731void PredicateSimplifier::visit(StoreInst *SI, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000732 Value *Ptr = SI->getPointerOperand();
733 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
734}
735
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000736void PredicateSimplifier::visit(BinaryOperator *BO, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000737 Instruction::BinaryOps ops = BO->getOpcode();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000738
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000739 switch (ops) {
740 case Instruction::Div:
741 case Instruction::Rem: {
742 Value *Divisor = BO->getOperand(1);
743 KP.addNotEqual(Constant::getNullValue(Divisor->getType()), Divisor);
744 break;
745 }
746 default:
747 break;
748 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000749}