blob: 7d34df48eb43051fcc93a046bf9ec5ba214f8d8e [file] [log] [blame]
Chris Lattnerc0f58002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2//
3// This pass reassociates commutative expressions in an order that is designed
Chris Lattner36663782003-05-02 19:26:34 +00004// to promote better constant propagation, GCSE, LICM, PRE...
Chris Lattnerc0f58002002-05-08 22:19:27 +00005//
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"
Chris Lattnerc0f58002002-05-08 22:19:27 +000021#include "llvm/iOperators.h"
22#include "llvm/Type.h"
23#include "llvm/Pass.h"
24#include "llvm/Constant.h"
25#include "llvm/Support/CFG.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000026#include "Support/Debug.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000027#include "Support/PostOrderIterator.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000028#include "Support/Statistic.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000029
30namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000031 Statistic<> NumLinear ("reassociate","Number of insts linearized");
32 Statistic<> NumChanged("reassociate","Number of insts reassociated");
33 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
34
Chris Lattnerc0f58002002-05-08 22:19:27 +000035 class Reassociate : public FunctionPass {
Chris Lattner10073a92002-07-25 06:17:51 +000036 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner8ac196d2003-08-13 16:16:26 +000037 std::map<Value*, unsigned> ValueRankMap;
Chris Lattnerc0f58002002-05-08 22:19:27 +000038 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000039 bool runOnFunction(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000040
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000042 AU.setPreservesCFG();
Chris Lattnerc0f58002002-05-08 22:19:27 +000043 }
44 private:
Chris Lattner113f4f42002-06-25 16:13:24 +000045 void BuildRankMap(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000046 unsigned getRank(Value *V);
47 bool ReassociateExpr(BinaryOperator *I);
48 bool ReassociateBB(BasicBlock *BB);
49 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000050
Chris Lattnerc8b70922002-07-26 21:12:46 +000051 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattnerc0f58002002-05-08 22:19:27 +000052}
53
54Pass *createReassociatePass() { return new Reassociate(); }
55
Chris Lattner113f4f42002-06-25 16:13:24 +000056void Reassociate::BuildRankMap(Function &F) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000057 unsigned i = 2;
Chris Lattner8ac196d2003-08-13 16:16:26 +000058
59 // Assign distinct ranks to function arguments
60 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
61 ValueRankMap[I] = ++i;
62
Chris Lattner113f4f42002-06-25 16:13:24 +000063 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000064 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
65 E = RPOT.end(); I != E; ++I)
Chris Lattner58c7eb62003-08-12 20:14:27 +000066 RankMap[*I] = ++i << 16;
Chris Lattnerc0f58002002-05-08 22:19:27 +000067}
68
69unsigned Reassociate::getRank(Value *V) {
Chris Lattner8ac196d2003-08-13 16:16:26 +000070 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
71
Chris Lattnerc0f58002002-05-08 22:19:27 +000072 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000073 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
74 // we can reassociate expressions for code motion! Since we do not recurse
75 // for PHI nodes, we cannot have infinite recursion here, because there
76 // cannot be loops in the value graph that do not go through PHI nodes.
Chris Lattnerc0f58002002-05-08 22:19:27 +000077 //
Chris Lattnerb94550e2003-10-19 21:34:28 +000078 if (I->getOpcode() == Instruction::PHI ||
Chris Lattnerc0f58002002-05-08 22:19:27 +000079 I->getOpcode() == Instruction::Alloca ||
80 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
Chris Lattner4869f372003-02-24 20:48:32 +000081 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
Chris Lattnerc0f58002002-05-08 22:19:27 +000082 return RankMap[I->getParent()];
83
Chris Lattner8ac196d2003-08-13 16:16:26 +000084 unsigned &CachedRank = ValueRankMap[I];
Chris Lattner3aa77672002-12-15 03:56:00 +000085 if (CachedRank) return CachedRank; // Rank already known?
86
87 // If not, compute it!
Chris Lattner7bc532d2002-05-16 04:37:07 +000088 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
89 for (unsigned i = 0, e = I->getNumOperands();
90 i != e && Rank != MaxRank; ++i)
Chris Lattnerc0f58002002-05-08 22:19:27 +000091 Rank = std::max(Rank, getRank(I->getOperand(i)));
92
Chris Lattner58c7eb62003-08-12 20:14:27 +000093 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
94 << Rank+1 << "\n");
95
96 return CachedRank = Rank+1;
Chris Lattnerc0f58002002-05-08 22:19:27 +000097 }
98
99 // Otherwise it's a global or constant, rank 0.
100 return 0;
101}
102
103
Chris Lattnerc0f58002002-05-08 22:19:27 +0000104bool 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) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000114 bool Success = !I->swapOperands();
115 assert(Success && "swapOperands failed");
116
Chris Lattnerc0f58002002-05-08 22:19:27 +0000117 std::swap(LHS, RHS);
118 std::swap(LHSRank, RHSRank);
119 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000120 ++NumSwapped;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000121 DEBUG(std::cerr << "Transposed: " << I
122 /* << " Result BB: " << I->getParent()*/);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000123 }
124
125 // If the LHS is the same operator as the current one is, and if we are the
126 // only expression using it...
127 //
128 if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000129 if (LHSI->getOpcode() == I->getOpcode() && LHSI->hasOneUse()) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000130 // If the rank of our current RHS is less than the rank of the LHS's LHS,
131 // then we reassociate the two instructions...
Chris Lattnerc0f58002002-05-08 22:19:27 +0000132
Chris Lattner98b3ecd2003-08-12 21:45:24 +0000133 unsigned TakeOp = 0;
134 if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
135 if (IOp->getOpcode() == LHSI->getOpcode())
136 TakeOp = 1; // Hoist out non-tree portion
137
138 if (RHSRank < getRank(LHSI->getOperand(TakeOp))) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000139 // Convert ((a + 12) + 10) into (a + (12 + 10))
140 I->setOperand(0, LHSI->getOperand(TakeOp));
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000141 LHSI->setOperand(TakeOp, RHS);
142 I->setOperand(1, LHSI);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000143
144 // Move the LHS expression forward, to ensure that it is dominated by
145 // its operands.
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000146 LHSI->getParent()->getInstList().remove(LHSI);
147 I->getParent()->getInstList().insert(I, LHSI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000148
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000149 ++NumChanged;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000150 DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: "
151 << I->getParent()*/);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000152
153 // Since we modified the RHS instruction, make sure that we recheck it.
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000154 ReassociateExpr(LHSI);
Chris Lattner58c7eb62003-08-12 20:14:27 +0000155 ReassociateExpr(I);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000156 return true;
157 }
158 }
159
160 return Changed;
161}
162
163
Chris Lattner7bc532d2002-05-16 04:37:07 +0000164// NegateValue - Insert instructions before the instruction pointed to by BI,
165// that computes the negative version of the value specified. The negative
166// version of the value is returned, and BI is left pointing at the instruction
167// that should be processed next by the reassociation pass.
168//
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000169static Value *NegateValue(Value *V, BasicBlock::iterator &BI) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000170 // We are trying to expose opportunity for reassociation. One of the things
171 // that we want to do to achieve this is to push a negation as deep into an
172 // expression chain as possible, to expose the add instructions. In practice,
173 // this means that we turn this:
174 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
175 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
176 // the constants. We assume that instcombine will clean up the mess later if
Misha Brukman7eb05a12003-08-18 14:43:39 +0000177 // we introduce tons of unnecessary negation instructions...
Chris Lattner7bc532d2002-05-16 04:37:07 +0000178 //
179 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000180 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000181 Value *RHS = NegateValue(I->getOperand(1), BI);
182 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000183
184 // We must actually insert a new add instruction here, because the neg
185 // instructions do not dominate the old add instruction in general. By
186 // adding it now, we are assured that the neg instructions we just
187 // inserted dominate the instruction we are about to insert after them.
188 //
Chris Lattner28a8d242002-09-10 17:04:02 +0000189 return BinaryOperator::create(Instruction::Add, LHS, RHS,
190 I->getName()+".neg",
191 cast<Instruction>(RHS)->getNext());
Chris Lattner7bc532d2002-05-16 04:37:07 +0000192 }
193
194 // Insert a 'neg' instruction that subtracts the value from zero to get the
195 // negation.
196 //
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000197 return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000198}
199
200
Chris Lattnerc0f58002002-05-08 22:19:27 +0000201bool Reassociate::ReassociateBB(BasicBlock *BB) {
202 bool Changed = false;
203 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000204
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000205 DEBUG(std::cerr << "Processing: " << *BI);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000206 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) {
207 // Convert a subtract into an add and a neg instruction... so that sub
208 // instructions can be commuted with other add instructions...
209 //
210 // Calculate the negative value of Operand 1 of the sub instruction...
211 // and set it as the RHS of the add instruction we just made...
212 //
213 std::string Name = BI->getName();
214 BI->setName("");
215 Instruction *New =
216 BinaryOperator::create(Instruction::Add, BI->getOperand(0),
217 BI->getOperand(1), Name, BI);
218
219 // Everyone now refers to the add instruction...
220 BI->replaceAllUsesWith(New);
221
222 // Put the new add in the place of the subtract... deleting the subtract
223 BB->getInstList().erase(BI);
224
225 BI = New;
226 New->setOperand(1, NegateValue(New->getOperand(1), BI));
227
228 Changed = true;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000229 DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000230 }
231
Chris Lattnerc0f58002002-05-08 22:19:27 +0000232 // If this instruction is a commutative binary operator, and the ranks of
233 // the two operands are sorted incorrectly, fix it now.
234 //
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000235 if (BI->isAssociative()) {
Chris Lattner889f6202003-04-23 16:37:45 +0000236 BinaryOperator *I = cast<BinaryOperator>(BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000237 if (!I->use_empty()) {
238 // Make sure that we don't have a tree-shaped computation. If we do,
239 // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D
240 //
241 Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
242 Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
243 if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
244 RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000245 RHSI->hasOneUse()) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000246 // Insert a new temporary instruction... (A+B)+C
247 BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
248 RHSI->getOperand(0),
Chris Lattner28a8d242002-09-10 17:04:02 +0000249 RHSI->getName()+".ra",
250 BI);
251 BI = Tmp;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000252 I->setOperand(0, Tmp);
253 I->setOperand(1, RHSI->getOperand(1));
254
255 // Process the temporary instruction for reassociation now.
256 I = Tmp;
257 ++NumLinear;
258 Changed = true;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000259 DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000260 }
261
262 // Make sure that this expression is correctly reassociated with respect
263 // to it's used values...
264 //
265 Changed |= ReassociateExpr(I);
266 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000267 }
268 }
269
270 return Changed;
271}
272
273
Chris Lattner113f4f42002-06-25 16:13:24 +0000274bool Reassociate::runOnFunction(Function &F) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000275 // Recalculate the rank map for F
276 BuildRankMap(F);
277
278 bool Changed = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000279 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
280 Changed |= ReassociateBB(FI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000281
282 // We are done with the rank map...
283 RankMap.clear();
Chris Lattner8ac196d2003-08-13 16:16:26 +0000284 ValueRankMap.clear();
Chris Lattnerc0f58002002-05-08 22:19:27 +0000285 return Changed;
286}