Don't rewrite ConstantExpr::get.
[oota-llvm.git] / lib / Transforms / Scalar / PredicateSimplifier.cpp
1 //===-- 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
26 // conditional that assures us of that fact. Properties are stored as
27 // relationships between two values.
28 //
29 //===------------------------------------------------------------------===//
30
31 #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>
42 using namespace llvm;
43
44 typedef DominatorTree::Node DTNodeType;
45
46 namespace {
47   Statistic<>
48   NumVarsReplaced("predsimplify", "Number of argument substitutions");
49   Statistic<>
50   NumInstruction("predsimplify", "Number of instructions removed");
51
52   class PropertySet;
53
54   /// Similar to EquivalenceClasses, this stores the set of equivalent
55   /// types. Beyond EquivalenceClasses, it allows us to specify which
56   /// element will act as leader.
57   template<typename ElemTy>
58   class VISIBILITY_HIDDEN Synonyms {
59     std::map<ElemTy, unsigned> mapping;
60     std::vector<ElemTy> leaders;
61     PropertySet *PS;
62
63   public:
64     typedef unsigned iterator;
65     typedef const unsigned const_iterator;
66
67     Synonyms(PropertySet *PS) : PS(PS) {}
68
69     // Inspection
70
71     bool empty() const {
72       return leaders.empty();
73     }
74
75     typename std::vector<ElemTy>::size_type countLeaders() const {
76       return leaders.size();
77     }
78
79     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) {
95       assert(I && I <= leaders.size() && "Illegal leader to get.");
96       return leaders[I-1];
97     }
98
99     const ElemTy &getLeader(const_iterator I) const {
100       assert(I && I <= leaders.size() && "Illegal leaders to get.");
101       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) {
107         os << i << ". " << *getLeader(i) << ": [";
108         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 << "  ";
112           }
113         }
114         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
124     /// points to the no longer existing element.
125     iterator unionSets(ElemTy E1, ElemTy E2);
126
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
140   /// Represents the set of equivalent Value*s and provides insertion
141   /// and fast lookup. Also stores the set of inequality relationships.
142   class PropertySet {
143     /// 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
173     struct Property;
174   public:
175     /// 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;
184
185     typedef std::vector<Property>::iterator       PropertyIterator;
186     typedef std::vector<Property>::const_iterator ConstPropertyIterator;
187     typedef Synonyms<Value *>::iterator  SynonymIterator;
188
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 {
200       SynonymIterator SI = union_find.findLeader(V);
201       if (!SI) return NULL;
202       return union_find.getLeader(SI);
203     }
204
205     bool empty() const {
206       return union_find.empty();
207     }
208
209     void addEqual(Value *V1, Value *V2) {
210       // If %x = 0. and %y = -0., seteq %x, %y is true, but
211       // copysign(%x) is not the same as copysign(%y).
212       if (V1->getType()->isFloatingPoint()) return;
213
214       order(V1, V2);
215       if (isa<Constant>(V2)) return; // refuse to set false == true.
216
217       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       }
229       addImpliedProperties(EQ, V1, V2);
230     }
231
232     void addNotEqual(Value *V1, Value *V2) {
233       // If %x = NAN then seteq %x, %x is false.
234       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;
238
239       if (findProperty(NE, V1, V2) != Properties.end())
240         return; // found.
241
242       // Add the property.
243       SynonymIterator I1 = union_find.findOrInsert(V1),
244                       I2 = union_find.findOrInsert(V2);
245
246       // Technically this means that the block is unreachable.
247       if (I1 == I2) return;
248
249       Properties.push_back(Property(NE, I1, I2));
250       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
257       SynonymIterator I1 = union_find.findLeader(V1),
258                       I2 = union_find.findLeader(V2);
259       if (!I1 || !I2) return Properties.end();
260
261       return
262       find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
263     }
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
270       SynonymIterator I1 = union_find.findLeader(V1),
271                       I2 = union_find.findLeader(V2);
272       if (!I1 || !I2) return Properties.end();
273
274       return
275       find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
276     }
277
278   private:
279     // Represents Head OP [Tail1, Tail2, ...]
280     // For example: %x != %a, %x != %b.
281     struct VISIBILITY_HIDDEN Property {
282       typedef SynonymIterator Iter;
283
284       Property(Ops opcode, Iter i1, Iter i2)
285         : Opcode(opcode), I1(i1), I2(i2)
286       { assert(opcode != EQ && "Equality belongs in the synonym set, "
287                                "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       }
294
295       Ops Opcode;
296       Iter I1, I2;
297     };
298
299     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
314     // Finds the properties implied by an equivalence and adds them too.
315     // 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         }
373       } 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.");
387       }
388     }
389
390     DominatorTree *DT;
391   public:
392 #ifdef DEBUG
393     void debug(std::ostream &os) const {
394       static const char *OpcodeTable[] = { "EQ", "NE" };
395
396       unsigned int size = union_find.countLeaders();
397
398       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";
403       }
404       os << "\n";
405     }
406 #endif
407
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 &);
423     Value *resolve(SelectInst *SI, const PropertySet &);
424     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.
429     void proceedToSuccessor(TerminatorInst *TI, unsigned edge,
430                             PropertySet &CurrentPS, PropertySet &NextPS);
431     void proceedToSuccessors(PropertySet &CurrentPS, BasicBlock *Current);
432
433     // Visits each instruction in the basic block.
434     void visitBasicBlock(BasicBlock *Block, PropertySet &KnownProperties);
435
436     // Tries to simplify each Instruction and add new properties to
437     // the PropertySet. Returns true if it erase the instruction.
438     void visitInstruction(Instruction *I, PropertySet &);
439     // For each instruction, add the properties to KnownProperties.
440
441     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 &);
447
448     DominatorTree *DT;
449     bool modified;
450   };
451
452   RegisterPass<PredicateSimplifier> X("predsimplify",
453                                       "Predicate Simplifier");
454
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   }
500 }
501
502 FunctionPass *llvm::createPredicateSimplifierPass() {
503   return new PredicateSimplifier();
504 }
505
506 bool PredicateSimplifier::runOnFunction(Function &F) {
507   DT = &getAnalysis<DominatorTree>();
508
509   modified = false;
510   PropertySet KnownProperties(DT);
511   visitBasicBlock(DT->getRootNode()->getBlock(), KnownProperties);
512   return modified;
513 }
514
515 void PredicateSimplifier::getAnalysisUsage(AnalysisUsage &AU) const {
516   AU.addRequired<DominatorTree>();
517   AU.setPreservesCFG();
518 }
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
522 // was defined outside of the scope that the properties apply to.
523 Value *PredicateSimplifier::resolve(SetCondInst *SCI,
524                                     const PropertySet &KP) {
525   // Attempt to resolve the SetCondInst to a boolean.
526
527   Value *SCI0 = resolve(SCI->getOperand(0), KP),
528         *SCI1 = resolve(SCI->getOperand(1), KP);
529
530   PropertySet::ConstPropertyIterator NE =
531       KP.findProperty(PropertySet::NE, SCI0, SCI1);
532
533   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;
545     }
546   }
547   return SCI;
548 }
549
550 Value *PredicateSimplifier::resolve(BinaryOperator *BO,
551                                     const PropertySet &KP) {
552   Value *lhs = resolve(BO->getOperand(0), KP),
553         *rhs = resolve(BO->getOperand(1), KP);
554
555   ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(lhs);
556   ConstantIntegral *CI2 = dyn_cast<ConstantIntegral>(rhs);
557
558   if (CI1 && CI2) return ConstantExpr::get(BO->getOpcode(), CI1, CI2);
559
560   if (SetCondInst *SCI = dyn_cast<SetCondInst>(BO))
561     return resolve(SCI, KP);
562
563   return BO;
564 }
565
566 Value *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
575 Value *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);
582   else if (SelectInst *SI = dyn_cast<SelectInst>(V))
583     return resolve(SI, KP);
584
585   return V;
586 }
587
588 void PredicateSimplifier::visitBasicBlock(BasicBlock *BB,
589                                           PropertySet &KnownProperties) {
590   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
591     visitInstruction(I++, KnownProperties);
592   }
593 }
594
595 void PredicateSimplifier::visitInstruction(Instruction *I,
596                                            PropertySet &KnownProperties) {
597   // Try to replace the whole instruction.
598   Value *V = resolve(I, KnownProperties);
599   if (V != I) {
600     modified = true;
601     ++NumInstruction;
602     DEBUG(std::cerr << "Removing " << *I);
603     I->replaceAllUsesWith(V);
604     I->eraseFromParent();
605     return;
606   }
607
608   // Try to substitute operands.
609   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
610     Value *Oper = I->getOperand(i);
611     Value *V = resolve(Oper, KnownProperties);
612     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
621   if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I))
622     visit(TI, KnownProperties);
623   else if (LoadInst *LI = dyn_cast<LoadInst>(I))
624     visit(LI, KnownProperties);
625   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
626     visit(SI, KnownProperties);
627   else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
628     visit(BO, KnownProperties);
629 }
630
631 // The basic block on the target of the specified edge must be known
632 // to be immediately dominated by the parent of the TerminatorInst.
633 void 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);
644   else
645     visitBasicBlock(BBNext, CurrentPS);
646 }
647
648 void 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   }
656 }
657
658 void PredicateSimplifier::visit(TerminatorInst *TI, PropertySet &KP) {
659   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
660     visit(BI, KP);
661     return;
662   }
663   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
664     visit(SI, KP);
665     return;
666   }
667
668   proceedToSuccessors(KP, TI->getParent());
669 }
670
671 void PredicateSimplifier::visit(BranchInst *BI, PropertySet &KP) {
672   BasicBlock *BB = BI->getParent();
673
674   if (BI->isUnconditional()) {
675     proceedToSuccessors(KP, BB);
676     return;
677   }
678
679   Value *Condition = BI->getCondition();
680
681   BasicBlock *TrueDest  = BI->getSuccessor(0),
682              *FalseDest = BI->getSuccessor(1);
683
684   if (Condition == ConstantBool::True || TrueDest == FalseDest) {
685     proceedToSuccessors(KP, BB);
686     return;
687   } else if (Condition == ConstantBool::False) {
688     proceedToSuccessors(KP, BB);
689     return;
690   }
691
692   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     }
700
701     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   }
710 }
711
712 void PredicateSimplifier::visit(SwitchInst *SI, PropertySet KP) {
713   Value *Condition = SI->getCondition();
714
715   // Set the EQProperty in each of the cases BBs,
716   // and the NEProperties in the default BB.
717   PropertySet DefaultProperties(KP);
718
719   DTNodeType *Node = DT->getNode(SI->getParent());
720   for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
721     BasicBlock *BB = (*I)->getBlock();
722
723     PropertySet Copy(KP);
724
725     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)) {
732       PropertySet NewProperties(KP);
733       NewProperties.addEqual(Condition, CI);
734       proceedToSuccessor(SI, SI->findCaseValue(CI), Copy, NewProperties);
735     } else 
736       visitBasicBlock(BB, Copy);
737   }
738 }
739
740 void PredicateSimplifier::visit(LoadInst *LI, PropertySet &KP) {
741   Value *Ptr = LI->getPointerOperand();
742   KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
743 }
744
745 void PredicateSimplifier::visit(StoreInst *SI, PropertySet &KP) {
746   Value *Ptr = SI->getPointerOperand();
747   KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
748 }
749
750 void PredicateSimplifier::visit(BinaryOperator *BO, PropertySet &KP) {
751   Instruction::BinaryOps ops = BO->getOpcode();
752
753   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   }
763 }