blob: 7fca951cca9d03c2e662b8f0d815de3059ff7367 [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
Nick Lewyckycfff1c32006-09-20 17:04:01 +000075 typename std::vector<ElemTy>::size_type countLeaders() const {
Nick Lewycky12efffc2006-09-13 19:32:53 +000076 return leaders.size();
77 }
78
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000079 iterator findLeader(ElemTy e) {
80 typename std::map<ElemTy, unsigned>::iterator MI = mapping.find(e);
81 if (MI == mapping.end()) return 0;
82
83 return MI->second;
84 }
85
86 const_iterator findLeader(ElemTy e) const {
87 typename std::map<ElemTy, unsigned>::const_iterator MI =
88 mapping.find(e);
89 if (MI == mapping.end()) return 0;
90
91 return MI->second;
92 }
93
94 ElemTy &getLeader(iterator I) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +000095 assert(I && I <= leaders.size() && "Illegal leader to get.");
Nick Lewycky9a22d7b2006-09-10 02:27:07 +000096 return leaders[I-1];
97 }
98
99 const ElemTy &getLeader(const_iterator I) const {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000100 assert(I && I <= leaders.size() && "Illegal leaders to get.");
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000101 return leaders[I-1];
102 }
103
104#ifdef DEBUG
105 void debug(std::ostream &os) const {
106 for (unsigned i = 1, e = leaders.size()+1; i != e; ++i) {
Nick Lewycky12efffc2006-09-13 19:32:53 +0000107 os << i << ". " << *getLeader(i) << ": [";
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000108 for (std::map<Value *, unsigned>::const_iterator
109 I = mapping.begin(), E = mapping.end(); I != E; ++I) {
110 if ((*I).second == i && (*I).first != leaders[i-1]) {
111 os << *(*I).first << " ";
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000112 }
113 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000114 os << "]\n";
115 }
116 }
117#endif
118
119 // Mutators
120
121 /// Combine two sets referring to the same element, inserting the
122 /// elements as needed. Returns a valid iterator iff two already
123 /// existing disjoint synonym sets were combined. The iterator
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000124 /// points to the no longer existing element.
125 iterator unionSets(ElemTy E1, ElemTy E2);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000126
127 /// Returns an iterator pointing to the synonym set containing
128 /// element e. If none exists, a new one is created and returned.
129 iterator findOrInsert(ElemTy e) {
130 iterator I = findLeader(e);
131 if (I) return I;
132
133 leaders.push_back(e);
134 I = leaders.size();
135 mapping[e] = I;
136 return I;
137 }
138 };
139
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000140 /// Represents the set of equivalent Value*s and provides insertion
141 /// and fast lookup. Also stores the set of inequality relationships.
142 class PropertySet {
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000143 /// Returns true if V1 is a better choice than V2. Note that it is
144 /// not a total ordering.
145 bool compare(Value *V1, Value *V2) const {
146 if (isa<Constant>(V1)) {
147 if (!isa<Constant>(V2)) {
148 return true;
149 }
150 } else if (isa<Argument>(V1)) {
151 if (!isa<Constant>(V2) && !isa<Argument>(V2)) {
152 return true;
153 }
154 }
155 if (Instruction *I1 = dyn_cast<Instruction>(V1)) {
156 if (Instruction *I2 = dyn_cast<Instruction>(V2)) {
157 BasicBlock *BB1 = I1->getParent(),
158 *BB2 = I2->getParent();
159 if (BB1 == BB2) {
160 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
161 I != E; ++I) {
162 if (&*I == I1) return true;
163 if (&*I == I2) return false;
164 }
165 assert(0 && "Instructions not found in parent BasicBlock?");
166 } else
167 return DT->getNode(BB1)->properlyDominates(DT->getNode(BB2));
168 }
169 }
170 return false;
171 }
172
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000173 struct Property;
174 public:
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000175 /// Choose the canonical Value in a synonym set.
176 /// Leaves the more canonical choice in V1.
177 void order(Value *&V1, Value *&V2) const {
178 if (compare(V2, V1)) std::swap(V1, V2);
179 }
180
181 PropertySet(DominatorTree *DT) : union_find(this), DT(DT) {}
182
183 class Synonyms<Value *> union_find;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000184
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000185 typedef std::vector<Property>::iterator PropertyIterator;
186 typedef std::vector<Property>::const_iterator ConstPropertyIterator;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000187 typedef Synonyms<Value *>::iterator SynonymIterator;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000188
189 enum Ops {
190 EQ,
191 NE
192 };
193
194 Value *canonicalize(Value *V) const {
195 Value *C = lookup(V);
196 return C ? C : V;
197 }
198
199 Value *lookup(Value *V) const {
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000200 SynonymIterator SI = union_find.findLeader(V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000201 if (!SI) return NULL;
202 return union_find.getLeader(SI);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000203 }
204
205 bool empty() const {
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000206 return union_find.empty();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000207 }
208
209 void addEqual(Value *V1, Value *V2) {
Nick Lewycky8e559932006-09-02 19:40:38 +0000210 // If %x = 0. and %y = -0., seteq %x, %y is true, but
211 // copysign(%x) is not the same as copysign(%y).
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000212 if (V1->getType()->isFloatingPoint()) return;
Nick Lewycky8e559932006-09-02 19:40:38 +0000213
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000214 order(V1, V2);
215 if (isa<Constant>(V2)) return; // refuse to set false == true.
216
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000217 SynonymIterator deleted = union_find.unionSets(V1, V2);
218 if (deleted) {
219 SynonymIterator replacement = union_find.findLeader(V1);
220 // Move Properties
221 for (PropertyIterator I = Properties.begin(), E = Properties.end();
222 I != E; ++I) {
223 if (I->I1 == deleted) I->I1 = replacement;
224 else if (I->I1 > deleted) --I->I1;
225 if (I->I2 == deleted) I->I2 = replacement;
226 else if (I->I2 > deleted) --I->I2;
227 }
228 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000229 addImpliedProperties(EQ, V1, V2);
230 }
231
232 void addNotEqual(Value *V1, Value *V2) {
Nick Lewycky8e559932006-09-02 19:40:38 +0000233 // If %x = NAN then seteq %x, %x is false.
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000234 if (V1->getType()->isFloatingPoint()) return;
235
236 // For example, %x = setne int 0, 0 causes "0 != 0".
237 if (isa<Constant>(V1) && isa<Constant>(V2)) return;
Nick Lewycky8e559932006-09-02 19:40:38 +0000238
Nick Lewycky08674ab2006-08-31 00:39:16 +0000239 if (findProperty(NE, V1, V2) != Properties.end())
240 return; // found.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000241
242 // Add the property.
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000243 SynonymIterator I1 = union_find.findOrInsert(V1),
244 I2 = union_find.findOrInsert(V2);
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000245
246 // Technically this means that the block is unreachable.
247 if (I1 == I2) return;
248
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000249 Properties.push_back(Property(NE, I1, I2));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000250 addImpliedProperties(NE, V1, V2);
251 }
252
253 PropertyIterator findProperty(Ops Opcode, Value *V1, Value *V2) {
254 assert(Opcode != EQ && "Can't findProperty on EQ."
255 "Use the lookup method instead.");
256
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000257 SynonymIterator I1 = union_find.findLeader(V1),
258 I2 = union_find.findLeader(V2);
259 if (!I1 || !I2) return Properties.end();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000260
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000261 return
262 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000263 }
264
265 ConstPropertyIterator
266 findProperty(Ops Opcode, Value *V1, Value *V2) const {
267 assert(Opcode != EQ && "Can't findProperty on EQ."
268 "Use the lookup method instead.");
269
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000270 SynonymIterator I1 = union_find.findLeader(V1),
271 I2 = union_find.findLeader(V2);
272 if (!I1 || !I2) return Properties.end();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000273
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000274 return
275 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000276 }
277
278 private:
279 // Represents Head OP [Tail1, Tail2, ...]
280 // For example: %x != %a, %x != %b.
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000281 struct VISIBILITY_HIDDEN Property {
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000282 typedef SynonymIterator Iter;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000283
284 Property(Ops opcode, Iter i1, Iter i2)
285 : Opcode(opcode), I1(i1), I2(i2)
Nick Lewycky8e559932006-09-02 19:40:38 +0000286 { assert(opcode != EQ && "Equality belongs in the synonym set, "
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000287 "not a property."); }
288
289 bool operator==(const Property &P) const {
290 return (Opcode == P.Opcode) &&
291 ((I1 == P.I1 && I2 == P.I2) ||
292 (I1 == P.I2 && I2 == P.I1));
293 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000294
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000295 Ops Opcode;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000296 Iter I1, I2;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000297 };
298
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000299 void add(Ops Opcode, Value *V1, Value *V2, bool invert) {
300 switch (Opcode) {
301 case EQ:
302 if (invert) addNotEqual(V1, V2);
303 else addEqual(V1, V2);
304 break;
305 case NE:
306 if (invert) addEqual(V1, V2);
307 else addNotEqual(V1, V2);
308 break;
309 default:
310 assert(0 && "Unknown property opcode.");
311 }
312 }
313
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000314 // Finds the properties implied by an equivalence and adds them too.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000315 // Example: ("seteq %a, %b", true, EQ) --> (%a, %b, EQ)
316 // ("seteq %a, %b", false, EQ) --> (%a, %b, NE)
317 void addImpliedProperties(Ops Opcode, Value *V1, Value *V2) {
318 order(V1, V2);
319
320 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V2)) {
321 switch (BO->getOpcode()) {
322 case Instruction::SetEQ:
323 if (V1 == ConstantBool::True)
324 add(Opcode, BO->getOperand(0), BO->getOperand(1), false);
325 if (V1 == ConstantBool::False)
326 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
327 break;
328 case Instruction::SetNE:
329 if (V1 == ConstantBool::True)
330 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
331 if (V1 == ConstantBool::False)
332 add(Opcode, BO->getOperand(0), BO->getOperand(1), false);
333 break;
334 case Instruction::SetLT:
335 case Instruction::SetGT:
336 if (V1 == ConstantBool::True)
337 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
338 break;
339 case Instruction::SetLE:
340 case Instruction::SetGE:
341 if (V1 == ConstantBool::False)
342 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
343 break;
344 case Instruction::And:
345 if (V1 == ConstantBool::True) {
346 add(Opcode, ConstantBool::True, BO->getOperand(0), false);
347 add(Opcode, ConstantBool::True, BO->getOperand(1), false);
348 }
349 break;
350 case Instruction::Or:
351 if (V1 == ConstantBool::False) {
352 add(Opcode, ConstantBool::False, BO->getOperand(0), false);
353 add(Opcode, ConstantBool::False, BO->getOperand(1), false);
354 }
355 break;
356 case Instruction::Xor:
357 if (V1 == ConstantBool::True) {
358 if (BO->getOperand(0) == ConstantBool::True)
359 add(Opcode, ConstantBool::False, BO->getOperand(1), false);
360 if (BO->getOperand(1) == ConstantBool::True)
361 add(Opcode, ConstantBool::False, BO->getOperand(0), false);
362 }
363 if (V1 == ConstantBool::False) {
364 if (BO->getOperand(0) == ConstantBool::True)
365 add(Opcode, ConstantBool::True, BO->getOperand(1), false);
366 if (BO->getOperand(1) == ConstantBool::True)
367 add(Opcode, ConstantBool::True, BO->getOperand(0), false);
368 }
369 break;
370 default:
371 break;
372 }
Nick Lewycky8e559932006-09-02 19:40:38 +0000373 } else if (SelectInst *SI = dyn_cast<SelectInst>(V2)) {
374 if (Opcode != EQ && Opcode != NE) return;
375
376 ConstantBool *True = (Opcode==EQ) ? ConstantBool::True
377 : ConstantBool::False,
378 *False = (Opcode==EQ) ? ConstantBool::False
379 : ConstantBool::True;
380
381 if (V1 == SI->getTrueValue())
382 addEqual(SI->getCondition(), True);
383 else if (V1 == SI->getFalseValue())
384 addEqual(SI->getCondition(), False);
385 else if (Opcode == EQ)
386 assert("Result of select not equal to either value.");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000387 }
388 }
389
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000390 DominatorTree *DT;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000391 public:
Nick Lewycky8e559932006-09-02 19:40:38 +0000392#ifdef DEBUG
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000393 void debug(std::ostream &os) const {
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000394 static const char *OpcodeTable[] = { "EQ", "NE" };
395
Nick Lewycky12efffc2006-09-13 19:32:53 +0000396 unsigned int size = union_find.countLeaders();
397
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000398 union_find.debug(os);
399 for (std::vector<Property>::const_iterator I = Properties.begin(),
400 E = Properties.end(); I != E; ++I) {
401 os << (*I).I1 << " " << OpcodeTable[(*I).Opcode] << " "
402 << (*I).I2 << "\n";
Nick Lewycky08674ab2006-08-31 00:39:16 +0000403 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000404 os << "\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000405 }
Nick Lewycky8e559932006-09-02 19:40:38 +0000406#endif
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000407
408 std::vector<Property> Properties;
409 };
410
411 /// PredicateSimplifier - This class is a simplifier that replaces
412 /// one equivalent variable with another. It also tracks what
413 /// can't be equal and will solve setcc instructions when possible.
414 class PredicateSimplifier : public FunctionPass {
415 public:
416 bool runOnFunction(Function &F);
417 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
418
419 private:
420 // Try to replace the Use of the instruction with something simpler.
421 Value *resolve(SetCondInst *SCI, const PropertySet &);
422 Value *resolve(BinaryOperator *BO, const PropertySet &);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000423 Value *resolve(SelectInst *SI, const PropertySet &);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000424 Value *resolve(Value *V, const PropertySet &);
425
426 // Used by terminator instructions to proceed from the current basic
427 // block to the next. Verifies that "current" dominates "next",
428 // then calls visitBasicBlock.
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000429 void proceedToSuccessor(TerminatorInst *TI, unsigned edge,
430 PropertySet &CurrentPS, PropertySet &NextPS);
431 void proceedToSuccessors(PropertySet &CurrentPS, BasicBlock *Current);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000432
433 // Visits each instruction in the basic block.
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000434 void visitBasicBlock(BasicBlock *Block, PropertySet &KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000435
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000436 // Tries to simplify each Instruction and add new properties to
437 // the PropertySet. Returns true if it erase the instruction.
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000438 void visitInstruction(Instruction *I, PropertySet &);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000439 // For each instruction, add the properties to KnownProperties.
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000440
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000441 void visit(TerminatorInst *TI, PropertySet &);
442 void visit(BranchInst *BI, PropertySet &);
443 void visit(SwitchInst *SI, PropertySet);
444 void visit(LoadInst *LI, PropertySet &);
445 void visit(StoreInst *SI, PropertySet &);
446 void visit(BinaryOperator *BO, PropertySet &);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000447
448 DominatorTree *DT;
449 bool modified;
450 };
451
452 RegisterPass<PredicateSimplifier> X("predsimplify",
453 "Predicate Simplifier");
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000454
455 template <typename ElemTy>
456 typename Synonyms<ElemTy>::iterator
457 Synonyms<ElemTy>::unionSets(ElemTy E1, ElemTy E2) {
458 PS->order(E1, E2);
459
460 iterator I1 = findLeader(E1),
461 I2 = findLeader(E2);
462
463 if (!I1 && !I2) { // neither entry is in yet
464 leaders.push_back(E1);
465 I1 = leaders.size();
466 mapping[E1] = I1;
467 mapping[E2] = I1;
468 return 0;
469 }
470
471 if (!I1 && I2) {
472 mapping[E1] = I2;
473 std::swap(getLeader(I2), E1);
474 return 0;
475 }
476
477 if (I1 && !I2) {
478 mapping[E2] = I1;
479 return 0;
480 }
481
482 if (I1 == I2) return 0;
483
484 // This is the case where we have two sets, [%a1, %a2, %a3] and
485 // [%p1, %p2, %p3] and someone says that %a2 == %p3. We need to
486 // combine the two synsets.
487
488 if (I1 > I2) --I1;
489
490 for (std::map<Value *, unsigned>::iterator I = mapping.begin(),
491 E = mapping.end(); I != E; ++I) {
492 if (I->second == I2) I->second = I1;
493 else if (I->second > I2) --I->second;
494 }
495
496 leaders.erase(leaders.begin() + I2 - 1);
497
498 return I2;
499 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000500}
501
502FunctionPass *llvm::createPredicateSimplifierPass() {
503 return new PredicateSimplifier();
504}
505
506bool PredicateSimplifier::runOnFunction(Function &F) {
507 DT = &getAnalysis<DominatorTree>();
508
509 modified = false;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000510 PropertySet KnownProperties(DT);
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000511 visitBasicBlock(DT->getRootNode()->getBlock(), KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000512 return modified;
513}
514
515void PredicateSimplifier::getAnalysisUsage(AnalysisUsage &AU) const {
516 AU.addRequired<DominatorTree>();
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000517 AU.setPreservesCFG();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000518}
519
520// resolve catches cases addProperty won't because it wasn't used as a
521// condition in the branch, and that visit won't, because the instruction
Nick Lewycky8e559932006-09-02 19:40:38 +0000522// was defined outside of the scope that the properties apply to.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000523Value *PredicateSimplifier::resolve(SetCondInst *SCI,
524 const PropertySet &KP) {
525 // Attempt to resolve the SetCondInst to a boolean.
526
Nick Lewycky8e559932006-09-02 19:40:38 +0000527 Value *SCI0 = resolve(SCI->getOperand(0), KP),
528 *SCI1 = resolve(SCI->getOperand(1), KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000529
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000530 PropertySet::ConstPropertyIterator NE =
531 KP.findProperty(PropertySet::NE, SCI0, SCI1);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000532
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000533 if (NE != KP.Properties.end()) {
534 switch (SCI->getOpcode()) {
535 case Instruction::SetEQ: return ConstantBool::False;
536 case Instruction::SetNE: return ConstantBool::True;
537 case Instruction::SetLE:
538 case Instruction::SetGE:
539 case Instruction::SetLT:
540 case Instruction::SetGT:
541 break;
542 default:
543 assert(0 && "Unknown opcode in SetCondInst.");
544 break;
Nick Lewyckye94f42a2006-09-11 17:23:34 +0000545 }
Nick Lewyckye94f42a2006-09-11 17:23:34 +0000546 }
Nick Lewyckyd74c55f2006-09-20 23:02:24 +0000547 return SCI;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000548}
549
550Value *PredicateSimplifier::resolve(BinaryOperator *BO,
551 const PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000552 Value *lhs = resolve(BO->getOperand(0), KP),
553 *rhs = resolve(BO->getOperand(1), KP);
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000554
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000555 ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(lhs);
556 ConstantIntegral *CI2 = dyn_cast<ConstantIntegral>(rhs);
557
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000558 if (CI1 && CI2) return ConstantExpr::get(BO->getOpcode(), CI1, CI2);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000559
Nick Lewyckyfde9c302006-09-21 01:05:35 +0000560 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BO))
561 return resolve(SCI, KP);
562
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000563 return BO;
564}
565
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000566Value *PredicateSimplifier::resolve(SelectInst *SI, const PropertySet &KP) {
567 Value *Condition = resolve(SI->getCondition(), KP);
568 if (Condition == ConstantBool::True)
569 return resolve(SI->getTrueValue(), KP);
570 else if (Condition == ConstantBool::False)
571 return resolve(SI->getFalseValue(), KP);
572 return SI;
573}
574
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000575Value *PredicateSimplifier::resolve(Value *V, const PropertySet &KP) {
576 if (isa<Constant>(V) || isa<BasicBlock>(V) || KP.empty()) return V;
577
578 V = KP.canonicalize(V);
579
580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
581 return resolve(BO, KP);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000582 else if (SelectInst *SI = dyn_cast<SelectInst>(V))
583 return resolve(SI, KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000584
585 return V;
586}
587
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000588void PredicateSimplifier::visitBasicBlock(BasicBlock *BB,
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000589 PropertySet &KnownProperties) {
Nick Lewycky3a4dc7b2006-09-13 18:55:37 +0000590 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000591 visitInstruction(I++, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000592 }
593}
594
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000595void PredicateSimplifier::visitInstruction(Instruction *I,
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000596 PropertySet &KnownProperties) {
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000597 // Try to replace the whole instruction.
Nick Lewycky8e559932006-09-02 19:40:38 +0000598 Value *V = resolve(I, KnownProperties);
Nick Lewycky8e559932006-09-02 19:40:38 +0000599 if (V != I) {
600 modified = true;
601 ++NumInstruction;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000602 DEBUG(std::cerr << "Removing " << *I);
Nick Lewycky8e559932006-09-02 19:40:38 +0000603 I->replaceAllUsesWith(V);
Nick Lewycky3a4dc7b2006-09-13 18:55:37 +0000604 I->eraseFromParent();
Nick Lewycky8e559932006-09-02 19:40:38 +0000605 return;
606 }
607
608 // Try to substitute operands.
609 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000610 Value *Oper = I->getOperand(i);
611 Value *V = resolve(Oper, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000612 if (V != Oper) {
613 modified = true;
614 ++NumVarsReplaced;
615 DEBUG(std::cerr << "resolving " << *I);
616 I->setOperand(i, V);
617 DEBUG(std::cerr << "into " << *I);
618 }
619 }
620
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000621 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000622 visit(TI, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000623 else if (LoadInst *LI = dyn_cast<LoadInst>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000624 visit(LI, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000625 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000626 visit(SI, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000627 else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000628 visit(BO, KnownProperties);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000629}
630
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000631// The basic block on the target of the specified edge must be known
632// to be immediately dominated by the parent of the TerminatorInst.
633void PredicateSimplifier::proceedToSuccessor(TerminatorInst *TI,
634 unsigned edge,
635 PropertySet &CurrentPS,
636 PropertySet &NextPS) {
637 assert(edge < TI->getNumSuccessors() && "Invalid index for edge.");
638
639 BasicBlock *BB = TI->getParent(),
640 *BBNext = TI->getSuccessor(edge);
641
642 if (BBNext->getSinglePredecessor() == BB)
643 visitBasicBlock(BBNext, NextPS);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000644 else
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000645 visitBasicBlock(BBNext, CurrentPS);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000646}
647
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000648void PredicateSimplifier::proceedToSuccessors(PropertySet &KP,
649 BasicBlock *BBCurrent) {
650 DTNodeType *Current = DT->getNode(BBCurrent);
651 for (DTNodeType::iterator I = Current->begin(), E = Current->end();
652 I != E; ++I) {
653 PropertySet Copy(KP);
654 visitBasicBlock((*I)->getBlock(), Copy);
655 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000656}
657
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000658void PredicateSimplifier::visit(TerminatorInst *TI, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000659 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000660 visit(BI, KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000661 return;
662 }
663 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000664 visit(SI, KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000665 return;
666 }
667
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000668 proceedToSuccessors(KP, TI->getParent());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000669}
670
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000671void PredicateSimplifier::visit(BranchInst *BI, PropertySet &KP) {
672 BasicBlock *BB = BI->getParent();
673
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000674 if (BI->isUnconditional()) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000675 proceedToSuccessors(KP, BB);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000676 return;
677 }
678
679 Value *Condition = BI->getCondition();
680
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000681 BasicBlock *TrueDest = BI->getSuccessor(0),
682 *FalseDest = BI->getSuccessor(1);
683
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000684 if (Condition == ConstantBool::True || TrueDest == FalseDest) {
685 proceedToSuccessors(KP, BB);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000686 return;
687 } else if (Condition == ConstantBool::False) {
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000688 proceedToSuccessors(KP, BB);
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000689 return;
690 }
691
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000692 DTNodeType *Node = DT->getNode(BB);
693 for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
694 if ((*I)->getBlock() == TrueDest) {
695 PropertySet TrueProperties(KP);
696 TrueProperties.addEqual(ConstantBool::True, Condition);
697 proceedToSuccessor(BI, 0, KP, TrueProperties);
698 continue;
699 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000700
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000701 if ((*I)->getBlock() == FalseDest) {
702 PropertySet FalseProperties(KP);
703 FalseProperties.addEqual(ConstantBool::False, Condition);
704 proceedToSuccessor(BI, 1, KP, FalseProperties);
705 continue;
706 }
707
708 visitBasicBlock((*I)->getBlock(), KP);
709 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000710}
711
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000712void PredicateSimplifier::visit(SwitchInst *SI, PropertySet KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000713 Value *Condition = SI->getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000714
715 // Set the EQProperty in each of the cases BBs,
716 // and the NEProperties in the default BB.
717 PropertySet DefaultProperties(KP);
718
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000719 DTNodeType *Node = DT->getNode(SI->getParent());
720 for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
721 BasicBlock *BB = (*I)->getBlock();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000722
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000723 PropertySet Copy(KP);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000724
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000725 if (BB == SI->getDefaultDest()) {
726 PropertySet NewProperties(KP);
727 for (unsigned i = 1, e = SI->getNumCases(); i < e; ++i)
728 NewProperties.addNotEqual(Condition, SI->getCaseValue(i));
729
730 proceedToSuccessor(SI, 0, Copy, NewProperties);
731 } else if (ConstantInt *CI = SI->findCaseDest(BB)) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000732 PropertySet NewProperties(KP);
733 NewProperties.addEqual(Condition, CI);
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000734 proceedToSuccessor(SI, SI->findCaseValue(CI), Copy, NewProperties);
735 } else
736 visitBasicBlock(BB, Copy);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000737 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000738}
739
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000740void PredicateSimplifier::visit(LoadInst *LI, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000741 Value *Ptr = LI->getPointerOperand();
742 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
743}
744
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000745void PredicateSimplifier::visit(StoreInst *SI, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000746 Value *Ptr = SI->getPointerOperand();
747 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
748}
749
Nick Lewyckyb9c54832006-09-18 21:09:35 +0000750void PredicateSimplifier::visit(BinaryOperator *BO, PropertySet &KP) {
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000751 Instruction::BinaryOps ops = BO->getOpcode();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000752
Nick Lewycky5f8f9af2006-08-30 02:46:48 +0000753 switch (ops) {
754 case Instruction::Div:
755 case Instruction::Rem: {
756 Value *Divisor = BO->getOperand(1);
757 KP.addNotEqual(Constant::getNullValue(Divisor->getType()), Divisor);
758 break;
759 }
760 default:
761 break;
762 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000763}