blob: cb7f47b9884fa238fd919ae327b8e30e2f082a23 [file] [log] [blame]
Chris Lattner4fd56002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2//
3// This pass reassociates commutative expressions in an order that is designed
4// to promote better constant propogation, GCSE, LICM, PRE...
5//
6// For example: 4 + (x + 5) -> x + (4 + 5)
7//
8// Note that this pass works best if left shifts have been promoted to explicit
9// multiplies before this pass executes.
10//
11// In the implementation of this algorithm, constants are assigned rank = 0,
12// function arguments are rank = 1, and other values are assigned ranks
13// corresponding to the reverse post order traversal of current function
14// (starting at 2), which effectively gives values in deep loops higher rank
15// than values not in loops.
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Transforms/Scalar.h"
20#include "llvm/Function.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/iOperators.h"
23#include "llvm/Type.h"
24#include "llvm/Pass.h"
25#include "llvm/Constant.h"
26#include "llvm/Support/CFG.h"
27#include "Support/PostOrderIterator.h"
28
29namespace {
30 class Reassociate : public FunctionPass {
31 map<BasicBlock*, unsigned> RankMap;
32 public:
33 const char *getPassName() const {
34 return "Expression Reassociation";
35 }
36
37 bool runOnFunction(Function *F);
38
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.preservesCFG();
41 }
42 private:
43 void BuildRankMap(Function *F);
44 unsigned getRank(Value *V);
45 bool ReassociateExpr(BinaryOperator *I);
46 bool ReassociateBB(BasicBlock *BB);
47 };
48}
49
50Pass *createReassociatePass() { return new Reassociate(); }
51
52void Reassociate::BuildRankMap(Function *F) {
53 unsigned i = 1;
54 ReversePostOrderTraversal<Function*> RPOT(F);
55 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
56 E = RPOT.end(); I != E; ++I)
57 RankMap[*I] = ++i;
58}
59
60unsigned Reassociate::getRank(Value *V) {
61 if (isa<Argument>(V)) return 1; // Function argument...
62 if (Instruction *I = dyn_cast<Instruction>(V)) {
63 // If this is an expression, return the MAX(rank(LHS), rank(RHS)) so that we
64 // can reassociate expressions for code motion! Since we do not recurse for
65 // PHI nodes, we cannot have infinite recursion here, because there cannot
66 // be loops in the value graph (except for PHI nodes).
67 //
68 if (I->getOpcode() == Instruction::PHINode ||
69 I->getOpcode() == Instruction::Alloca ||
70 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
71 I->hasSideEffects())
72 return RankMap[I->getParent()];
73
74 unsigned Rank = 0;
75 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
76 Rank = std::max(Rank, getRank(I->getOperand(i)));
77
78 return Rank;
79 }
80
81 // Otherwise it's a global or constant, rank 0.
82 return 0;
83}
84
85
86// isCommutativeOperator - Return true if the specified instruction is
87// commutative and associative. If the instruction is not commutative and
88// associative, we can not reorder its operands!
89//
90static inline BinaryOperator *isCommutativeOperator(Instruction *I) {
91 // Floating point operations do not commute!
92 if (I->getType()->isFloatingPoint()) return 0;
93
94 if (I->getOpcode() == Instruction::Add ||
95 I->getOpcode() == Instruction::Mul ||
96 I->getOpcode() == Instruction::And ||
97 I->getOpcode() == Instruction::Or ||
98 I->getOpcode() == Instruction::Xor)
99 return cast<BinaryOperator>(I);
100 return 0;
101}
102
103
104bool Reassociate::ReassociateExpr(BinaryOperator *I) {
105 Value *LHS = I->getOperand(0);
106 Value *RHS = I->getOperand(1);
107 unsigned LHSRank = getRank(LHS);
108 unsigned RHSRank = getRank(RHS);
109
110 bool Changed = false;
111
112 // Make sure the LHS of the operand always has the greater rank...
113 if (LHSRank < RHSRank) {
114 I->swapOperands();
115 std::swap(LHS, RHS);
116 std::swap(LHSRank, RHSRank);
117 Changed = true;
118 //cerr << "Transposed: " << I << " Result BB: " << I->getParent();
119 }
120
121 // If the LHS is the same operator as the current one is, and if we are the
122 // only expression using it...
123 //
124 if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
125 if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) {
126 // If the rank of our current RHS is less than the rank of the LHS's LHS,
127 // then we reassociate the two instructions...
128 if (RHSRank < getRank(LHSI->getOperand(0))) {
129 unsigned TakeOp = 0;
130 if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
131 if (IOp->getOpcode() == LHSI->getOpcode())
132 TakeOp = 1; // Hoist out non-tree portion
133
134 // Convert ((a + 12) + 10) into (a + (12 + 10))
135 I->setOperand(0, LHSI->getOperand(TakeOp));
136 LHSI->setOperand(TakeOp, RHS);
137 I->setOperand(1, LHSI);
138
139 //cerr << "Reassociated: " << I << " Result BB: " << I->getParent();
140
141 // Since we modified the RHS instruction, make sure that we recheck it.
142 ReassociateExpr(LHSI);
143 return true;
144 }
145 }
146
147 return Changed;
148}
149
150
151bool Reassociate::ReassociateBB(BasicBlock *BB) {
152 bool Changed = false;
153 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
154 Instruction *Inst = *BI;
155
156 // If this instruction is a commutative binary operator, and the ranks of
157 // the two operands are sorted incorrectly, fix it now.
158 //
159 if (BinaryOperator *I = isCommutativeOperator(Inst)) {
160 // Make sure that this expression is correctly reassociated with respect
161 // to it's used values...
162 //
163 Changed |= ReassociateExpr(I);
164
165 } else if (Inst->getOpcode() == Instruction::Sub &&
166 Inst->getOperand(0) != Constant::getNullValue(Inst->getType())) {
167 // Convert a subtract into an add and a neg instruction... so that sub
168 // instructions can be commuted with other add instructions...
169 //
170 Instruction *New = BinaryOperator::create(Instruction::Add,
171 Inst->getOperand(0), Inst,
Chris Lattner0aa7cd62002-05-09 20:11:23 +0000172 Inst->getName());
Chris Lattner4fd56002002-05-08 22:19:27 +0000173 // Everyone now refers to the add instruction...
174 Inst->replaceAllUsesWith(New);
Chris Lattner0aa7cd62002-05-09 20:11:23 +0000175 Inst->setName(Inst->getOperand(1)->getName()+".neg");
Chris Lattner4fd56002002-05-08 22:19:27 +0000176 New->setOperand(1, Inst); // Except for the add inst itself!
177
178 BI = BB->getInstList().insert(BI+1, New)-1; // Add to the basic block...
179 Inst->setOperand(0, Constant::getNullValue(Inst->getType()));
180 Changed = true;
181 }
182 }
183
184 return Changed;
185}
186
187
188bool Reassociate::runOnFunction(Function *F) {
189 // Recalculate the rank map for F
190 BuildRankMap(F);
191
192 bool Changed = false;
193 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
194 Changed |= ReassociateBB(*FI);
195
196 // We are done with the rank map...
197 RankMap.clear();
198 return Changed;
199}