1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===------------------------------------------------------------------===//
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:
14 // void test(int *p, int *q)
20 // foo(); // unreachable
23 //===------------------------------------------------------------------===//
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.
29 //===------------------------------------------------------------------===//
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"
44 typedef DominatorTree::Node DTNodeType;
48 NumVarsReplaced("predsimplify", "Number of argument substitutions");
50 NumInstruction("predsimplify", "Number of instructions removed");
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;
64 typedef unsigned iterator;
65 typedef const unsigned const_iterator;
67 Synonyms(PropertySet *PS) : PS(PS) {}
72 return leaders.empty();
75 typename std::vector<ElemTy>::size_type countLeaders() const {
76 return leaders.size();
79 iterator findLeader(ElemTy e) {
80 typename std::map<ElemTy, unsigned>::iterator MI = mapping.find(e);
81 if (MI == mapping.end()) return 0;
86 const_iterator findLeader(ElemTy e) const {
87 typename std::map<ElemTy, unsigned>::const_iterator MI =
89 if (MI == mapping.end()) return 0;
94 ElemTy &getLeader(iterator I) {
95 assert(I && I <= leaders.size() && "Illegal leader to get.");
99 const ElemTy &getLeader(const_iterator I) const {
100 assert(I && I <= leaders.size() && "Illegal leaders to get.");
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 << " ";
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);
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);
133 leaders.push_back(e);
140 /// Represents the set of equivalent Value*s and provides insertion
141 /// and fast lookup. Also stores the set of inequality relationships.
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)) {
150 } else if (isa<Argument>(V1)) {
151 if (!isa<Constant>(V2) && !isa<Argument>(V2)) {
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();
160 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
162 if (&*I == I1) return true;
163 if (&*I == I2) return false;
165 assert(0 && "Instructions not found in parent BasicBlock?");
167 return DT->getNode(BB1)->properlyDominates(DT->getNode(BB2));
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);
181 PropertySet(DominatorTree *DT) : union_find(this), DT(DT) {}
183 class Synonyms<Value *> union_find;
185 typedef std::vector<Property>::iterator PropertyIterator;
186 typedef std::vector<Property>::const_iterator ConstPropertyIterator;
187 typedef Synonyms<Value *>::iterator SynonymIterator;
194 Value *canonicalize(Value *V) const {
195 Value *C = lookup(V);
199 Value *lookup(Value *V) const {
200 SynonymIterator SI = union_find.findLeader(V);
201 if (!SI) return NULL;
202 return union_find.getLeader(SI);
206 return union_find.empty();
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;
215 if (isa<Constant>(V2)) return; // refuse to set false == true.
217 SynonymIterator deleted = union_find.unionSets(V1, V2);
219 SynonymIterator replacement = union_find.findLeader(V1);
221 for (PropertyIterator I = Properties.begin(), E = Properties.end();
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;
229 addImpliedProperties(EQ, V1, V2);
232 void addNotEqual(Value *V1, Value *V2) {
233 // If %x = NAN then seteq %x, %x is false.
234 if (V1->getType()->isFloatingPoint()) return;
236 // For example, %x = setne int 0, 0 causes "0 != 0".
237 if (isa<Constant>(V1) && isa<Constant>(V2)) return;
239 if (findProperty(NE, V1, V2) != Properties.end())
243 SynonymIterator I1 = union_find.findOrInsert(V1),
244 I2 = union_find.findOrInsert(V2);
246 // Technically this means that the block is unreachable.
247 if (I1 == I2) return;
249 Properties.push_back(Property(NE, I1, I2));
250 addImpliedProperties(NE, V1, V2);
253 PropertyIterator findProperty(Ops Opcode, Value *V1, Value *V2) {
254 assert(Opcode != EQ && "Can't findProperty on EQ."
255 "Use the lookup method instead.");
257 SynonymIterator I1 = union_find.findLeader(V1),
258 I2 = union_find.findLeader(V2);
259 if (!I1 || !I2) return Properties.end();
262 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
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.");
270 SynonymIterator I1 = union_find.findLeader(V1),
271 I2 = union_find.findLeader(V2);
272 if (!I1 || !I2) return Properties.end();
275 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
279 // Represents Head OP [Tail1, Tail2, ...]
280 // For example: %x != %a, %x != %b.
281 struct VISIBILITY_HIDDEN Property {
282 typedef SynonymIterator Iter;
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."); }
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));
299 void add(Ops Opcode, Value *V1, Value *V2, bool invert) {
302 if (invert) addNotEqual(V1, V2);
303 else addEqual(V1, V2);
306 if (invert) addEqual(V1, V2);
307 else addNotEqual(V1, V2);
310 assert(0 && "Unknown property opcode.");
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) {
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);
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);
334 case Instruction::SetLT:
335 case Instruction::SetGT:
336 if (V1 == ConstantBool::True)
337 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
339 case Instruction::SetLE:
340 case Instruction::SetGE:
341 if (V1 == ConstantBool::False)
342 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
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);
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);
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);
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);
373 } else if (SelectInst *SI = dyn_cast<SelectInst>(V2)) {
374 if (Opcode != EQ && Opcode != NE) return;
376 ConstantBool *True = (Opcode==EQ) ? ConstantBool::True
377 : ConstantBool::False,
378 *False = (Opcode==EQ) ? ConstantBool::False
379 : ConstantBool::True;
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.");
393 void debug(std::ostream &os) const {
394 static const char *OpcodeTable[] = { "EQ", "NE" };
396 unsigned int size = union_find.countLeaders();
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] << " "
408 std::vector<Property> Properties;
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 {
416 bool runOnFunction(Function &F);
417 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
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 &);
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);
433 // Visits each instruction in the basic block.
434 void visitBasicBlock(BasicBlock *Block, PropertySet &KnownProperties);
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.
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 &);
452 RegisterPass<PredicateSimplifier> X("predsimplify",
453 "Predicate Simplifier");
455 template <typename ElemTy>
456 typename Synonyms<ElemTy>::iterator
457 Synonyms<ElemTy>::unionSets(ElemTy E1, ElemTy E2) {
460 iterator I1 = findLeader(E1),
463 if (!I1 && !I2) { // neither entry is in yet
464 leaders.push_back(E1);
473 std::swap(getLeader(I2), E1);
482 if (I1 == I2) return 0;
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.
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;
496 leaders.erase(leaders.begin() + I2 - 1);
502 FunctionPass *llvm::createPredicateSimplifierPass() {
503 return new PredicateSimplifier();
506 bool PredicateSimplifier::runOnFunction(Function &F) {
507 DT = &getAnalysis<DominatorTree>();
510 PropertySet KnownProperties(DT);
511 visitBasicBlock(DT->getRootNode()->getBlock(), KnownProperties);
515 void PredicateSimplifier::getAnalysisUsage(AnalysisUsage &AU) const {
516 AU.addRequired<DominatorTree>();
517 AU.setPreservesCFG();
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.
527 Value *SCI0 = resolve(SCI->getOperand(0), KP),
528 *SCI1 = resolve(SCI->getOperand(1), KP);
530 PropertySet::ConstPropertyIterator NE =
531 KP.findProperty(PropertySet::NE, SCI0, SCI1);
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:
543 assert(0 && "Unknown opcode in SetCondInst.");
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);
555 ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(lhs);
556 ConstantIntegral *CI2 = dyn_cast<ConstantIntegral>(rhs);
558 if (CI1 && CI2) return ConstantExpr::get(BO->getOpcode(), CI1, CI2);
560 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BO))
561 return resolve(SCI, KP);
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);
575 Value *PredicateSimplifier::resolve(Value *V, const PropertySet &KP) {
576 if (isa<Constant>(V) || isa<BasicBlock>(V) || KP.empty()) return V;
578 V = KP.canonicalize(V);
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);
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);
595 void PredicateSimplifier::visitInstruction(Instruction *I,
596 PropertySet &KnownProperties) {
597 // Try to replace the whole instruction.
598 Value *V = resolve(I, KnownProperties);
602 DEBUG(std::cerr << "Removing " << *I);
603 I->replaceAllUsesWith(V);
604 I->eraseFromParent();
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);
615 DEBUG(std::cerr << "resolving " << *I);
617 DEBUG(std::cerr << "into " << *I);
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);
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,
635 PropertySet &CurrentPS,
636 PropertySet &NextPS) {
637 assert(edge < TI->getNumSuccessors() && "Invalid index for edge.");
639 BasicBlock *BB = TI->getParent(),
640 *BBNext = TI->getSuccessor(edge);
642 if (BBNext->getSinglePredecessor() == BB)
643 visitBasicBlock(BBNext, NextPS);
645 visitBasicBlock(BBNext, CurrentPS);
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();
653 PropertySet Copy(KP);
654 visitBasicBlock((*I)->getBlock(), Copy);
658 void PredicateSimplifier::visit(TerminatorInst *TI, PropertySet &KP) {
659 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
663 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
668 proceedToSuccessors(KP, TI->getParent());
671 void PredicateSimplifier::visit(BranchInst *BI, PropertySet &KP) {
672 BasicBlock *BB = BI->getParent();
674 if (BI->isUnconditional()) {
675 proceedToSuccessors(KP, BB);
679 Value *Condition = BI->getCondition();
681 BasicBlock *TrueDest = BI->getSuccessor(0),
682 *FalseDest = BI->getSuccessor(1);
684 if (Condition == ConstantBool::True || TrueDest == FalseDest) {
685 proceedToSuccessors(KP, BB);
687 } else if (Condition == ConstantBool::False) {
688 proceedToSuccessors(KP, BB);
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);
701 if ((*I)->getBlock() == FalseDest) {
702 PropertySet FalseProperties(KP);
703 FalseProperties.addEqual(ConstantBool::False, Condition);
704 proceedToSuccessor(BI, 1, KP, FalseProperties);
708 visitBasicBlock((*I)->getBlock(), KP);
712 void PredicateSimplifier::visit(SwitchInst *SI, PropertySet KP) {
713 Value *Condition = SI->getCondition();
715 // Set the EQProperty in each of the cases BBs,
716 // and the NEProperties in the default BB.
717 PropertySet DefaultProperties(KP);
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();
723 PropertySet Copy(KP);
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));
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);
736 visitBasicBlock(BB, Copy);
740 void PredicateSimplifier::visit(LoadInst *LI, PropertySet &KP) {
741 Value *Ptr = LI->getPointerOperand();
742 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
745 void PredicateSimplifier::visit(StoreInst *SI, PropertySet &KP) {
746 Value *Ptr = SI->getPointerOperand();
747 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
750 void PredicateSimplifier::visit(BinaryOperator *BO, PropertySet &KP) {
751 Instruction::BinaryOps ops = BO->getOpcode();
754 case Instruction::Div:
755 case Instruction::Rem: {
756 Value *Divisor = BO->getOperand(1);
757 KP.addNotEqual(Constant::getNullValue(Divisor->getType()), Divisor);