blob: 7d76bfb681f8fc01eaa57ebd0b32900e3a3a2367 [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"
Chris Lattner3dec1f22002-05-10 15:38:35 +000028#include "Support/StatisticReporter.h"
29
Chris Lattnera36e6c82002-05-16 04:37:07 +000030static Statistic<> NumLinear ("reassociate\t- Number of insts linearized");
Chris Lattner3dec1f22002-05-10 15:38:35 +000031static Statistic<> NumChanged("reassociate\t- Number of insts reassociated");
32static Statistic<> NumSwapped("reassociate\t- Number of insts with operands swapped");
Chris Lattner4fd56002002-05-08 22:19:27 +000033
34namespace {
35 class Reassociate : public FunctionPass {
Chris Lattner0c0edf82002-07-25 06:17:51 +000036 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner4fd56002002-05-08 22:19:27 +000037 public:
Chris Lattner7e708292002-06-25 16:13:24 +000038 bool runOnFunction(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000039
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.preservesCFG();
42 }
43 private:
Chris Lattner7e708292002-06-25 16:13:24 +000044 void BuildRankMap(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000045 unsigned getRank(Value *V);
46 bool ReassociateExpr(BinaryOperator *I);
47 bool ReassociateBB(BasicBlock *BB);
48 };
Chris Lattnerf6293092002-07-23 18:06:35 +000049
Chris Lattnera6275cc2002-07-26 21:12:46 +000050 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattner4fd56002002-05-08 22:19:27 +000051}
52
53Pass *createReassociatePass() { return new Reassociate(); }
54
Chris Lattner7e708292002-06-25 16:13:24 +000055void Reassociate::BuildRankMap(Function &F) {
Chris Lattner4fd56002002-05-08 22:19:27 +000056 unsigned i = 1;
Chris Lattner7e708292002-06-25 16:13:24 +000057 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattner4fd56002002-05-08 22:19:27 +000058 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
59 E = RPOT.end(); I != E; ++I)
60 RankMap[*I] = ++i;
61}
62
63unsigned Reassociate::getRank(Value *V) {
64 if (isa<Argument>(V)) return 1; // Function argument...
65 if (Instruction *I = dyn_cast<Instruction>(V)) {
66 // If this is an expression, return the MAX(rank(LHS), rank(RHS)) so that we
67 // can reassociate expressions for code motion! Since we do not recurse for
68 // PHI nodes, we cannot have infinite recursion here, because there cannot
69 // be loops in the value graph (except for PHI nodes).
70 //
71 if (I->getOpcode() == Instruction::PHINode ||
72 I->getOpcode() == Instruction::Alloca ||
73 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
74 I->hasSideEffects())
75 return RankMap[I->getParent()];
76
Chris Lattnera36e6c82002-05-16 04:37:07 +000077 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
78 for (unsigned i = 0, e = I->getNumOperands();
79 i != e && Rank != MaxRank; ++i)
Chris Lattner4fd56002002-05-08 22:19:27 +000080 Rank = std::max(Rank, getRank(I->getOperand(i)));
81
82 return Rank;
83 }
84
85 // Otherwise it's a global or constant, rank 0.
86 return 0;
87}
88
89
90// isCommutativeOperator - Return true if the specified instruction is
91// commutative and associative. If the instruction is not commutative and
92// associative, we can not reorder its operands!
93//
94static inline BinaryOperator *isCommutativeOperator(Instruction *I) {
95 // Floating point operations do not commute!
96 if (I->getType()->isFloatingPoint()) return 0;
97
98 if (I->getOpcode() == Instruction::Add ||
99 I->getOpcode() == Instruction::Mul ||
100 I->getOpcode() == Instruction::And ||
101 I->getOpcode() == Instruction::Or ||
102 I->getOpcode() == Instruction::Xor)
103 return cast<BinaryOperator>(I);
104 return 0;
105}
106
107
108bool Reassociate::ReassociateExpr(BinaryOperator *I) {
109 Value *LHS = I->getOperand(0);
110 Value *RHS = I->getOperand(1);
111 unsigned LHSRank = getRank(LHS);
112 unsigned RHSRank = getRank(RHS);
113
114 bool Changed = false;
115
116 // Make sure the LHS of the operand always has the greater rank...
117 if (LHSRank < RHSRank) {
118 I->swapOperands();
119 std::swap(LHS, RHS);
120 std::swap(LHSRank, RHSRank);
121 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000122 ++NumSwapped;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000123 DEBUG(std::cerr << "Transposed: " << I << " Result BB: " << I->getParent());
Chris Lattner4fd56002002-05-08 22:19:27 +0000124 }
125
126 // If the LHS is the same operator as the current one is, and if we are the
127 // only expression using it...
128 //
129 if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
130 if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) {
131 // If the rank of our current RHS is less than the rank of the LHS's LHS,
132 // then we reassociate the two instructions...
133 if (RHSRank < getRank(LHSI->getOperand(0))) {
134 unsigned TakeOp = 0;
135 if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
136 if (IOp->getOpcode() == LHSI->getOpcode())
137 TakeOp = 1; // Hoist out non-tree portion
138
139 // Convert ((a + 12) + 10) into (a + (12 + 10))
140 I->setOperand(0, LHSI->getOperand(TakeOp));
141 LHSI->setOperand(TakeOp, RHS);
142 I->setOperand(1, LHSI);
143
Chris Lattner3dec1f22002-05-10 15:38:35 +0000144 ++NumChanged;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000145 DEBUG(std::cerr << "Reassociated: " << I << " Result BB: "
146 << I->getParent());
Chris Lattner4fd56002002-05-08 22:19:27 +0000147
148 // Since we modified the RHS instruction, make sure that we recheck it.
149 ReassociateExpr(LHSI);
150 return true;
151 }
152 }
153
154 return Changed;
155}
156
157
Chris Lattnera36e6c82002-05-16 04:37:07 +0000158// NegateValue - Insert instructions before the instruction pointed to by BI,
159// that computes the negative version of the value specified. The negative
160// version of the value is returned, and BI is left pointing at the instruction
161// that should be processed next by the reassociation pass.
162//
163static Value *NegateValue(Value *V, BasicBlock *BB, BasicBlock::iterator &BI) {
164 // We are trying to expose opportunity for reassociation. One of the things
165 // that we want to do to achieve this is to push a negation as deep into an
166 // expression chain as possible, to expose the add instructions. In practice,
167 // this means that we turn this:
168 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
169 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
170 // the constants. We assume that instcombine will clean up the mess later if
171 // we introduce tons of unneccesary negation instructions...
172 //
173 if (Instruction *I = dyn_cast<Instruction>(V))
174 if (I->getOpcode() == Instruction::Add && I->use_size() == 1) {
175 Value *RHS = NegateValue(I->getOperand(1), BB, BI);
176 Value *LHS = NegateValue(I->getOperand(0), BB, BI);
177
178 // We must actually insert a new add instruction here, because the neg
179 // instructions do not dominate the old add instruction in general. By
180 // adding it now, we are assured that the neg instructions we just
181 // inserted dominate the instruction we are about to insert after them.
182 //
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000183 return BinaryOperator::create(Instruction::Add, LHS, RHS,
184 I->getName()+".neg",
185 cast<Instruction>(RHS)->getNext());
Chris Lattnera36e6c82002-05-16 04:37:07 +0000186 }
187
188 // Insert a 'neg' instruction that subtracts the value from zero to get the
189 // negation.
190 //
191 Instruction *Neg =
192 BinaryOperator::create(Instruction::Sub,
193 Constant::getNullValue(V->getType()), V,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000194 V->getName()+".neg", BI);
195 --BI;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000196 return Neg;
197}
198
199
Chris Lattner4fd56002002-05-08 22:19:27 +0000200bool Reassociate::ReassociateBB(BasicBlock *BB) {
201 bool Changed = false;
202 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000203
204 // If this instruction is a commutative binary operator, and the ranks of
205 // the two operands are sorted incorrectly, fix it now.
206 //
Chris Lattner7e708292002-06-25 16:13:24 +0000207 if (BinaryOperator *I = isCommutativeOperator(BI)) {
Chris Lattnera36e6c82002-05-16 04:37:07 +0000208 if (!I->use_empty()) {
209 // Make sure that we don't have a tree-shaped computation. If we do,
210 // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D
211 //
212 Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
213 Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
214 if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
215 RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
216 RHSI->use_size() == 1) {
217 // Insert a new temporary instruction... (A+B)+C
218 BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
219 RHSI->getOperand(0),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000220 RHSI->getName()+".ra",
221 BI);
222 BI = Tmp;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000223 I->setOperand(0, Tmp);
224 I->setOperand(1, RHSI->getOperand(1));
225
226 // Process the temporary instruction for reassociation now.
227 I = Tmp;
228 ++NumLinear;
229 Changed = true;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000230 DEBUG(std::cerr << "Linearized: " << I << " Result BB: " << BB);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000231 }
232
233 // Make sure that this expression is correctly reassociated with respect
234 // to it's used values...
235 //
236 Changed |= ReassociateExpr(I);
237 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000238
Chris Lattner7e708292002-06-25 16:13:24 +0000239 } else if (BI->getOpcode() == Instruction::Sub &&
240 BI->getOperand(0) != Constant::getNullValue(BI->getType())) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000241 // Convert a subtract into an add and a neg instruction... so that sub
242 // instructions can be commuted with other add instructions...
243 //
244 Instruction *New = BinaryOperator::create(Instruction::Add,
Chris Lattner7e708292002-06-25 16:13:24 +0000245 BI->getOperand(0),
246 BI->getOperand(1),
247 BI->getName());
248 Value *NegatedValue = BI->getOperand(1);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000249
Chris Lattner4fd56002002-05-08 22:19:27 +0000250 // Everyone now refers to the add instruction...
Chris Lattner7e708292002-06-25 16:13:24 +0000251 BI->replaceAllUsesWith(New);
Chris Lattner4fd56002002-05-08 22:19:27 +0000252
Chris Lattnera36e6c82002-05-16 04:37:07 +0000253 // Put the new add in the place of the subtract... deleting the subtract
Chris Lattner7e708292002-06-25 16:13:24 +0000254 BI = BB->getInstList().erase(BI);
255 BI = ++BB->getInstList().insert(BI, New);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000256
257 // Calculate the negative value of Operand 1 of the sub instruction...
258 // and set it as the RHS of the add instruction we just made...
259 New->setOperand(1, NegateValue(NegatedValue, BB, BI));
260 --BI;
Chris Lattner4fd56002002-05-08 22:19:27 +0000261 Changed = true;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000262 DEBUG(std::cerr << "Negated: " << New << " Result BB: " << BB);
Chris Lattner4fd56002002-05-08 22:19:27 +0000263 }
264 }
265
266 return Changed;
267}
268
269
Chris Lattner7e708292002-06-25 16:13:24 +0000270bool Reassociate::runOnFunction(Function &F) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000271 // Recalculate the rank map for F
272 BuildRankMap(F);
273
274 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000275 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
276 Changed |= ReassociateBB(FI);
Chris Lattner4fd56002002-05-08 22:19:27 +0000277
278 // We are done with the rank map...
279 RankMap.clear();
280 return Changed;
281}