blob: d00423edf5affd14d22c3af61780be5c14699cf5 [file] [log] [blame]
Chris Lattnerc0f58002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerc0f58002002-05-08 22:19:27 +00009//
10// This pass reassociates commutative expressions in an order that is designed
Chris Lattner36663782003-05-02 19:26:34 +000011// to promote better constant propagation, GCSE, LICM, PRE...
Chris Lattnerc0f58002002-05-08 22:19:27 +000012//
13// For example: 4 + (x + 5) -> x + (4 + 5)
14//
Chris Lattnerc0f58002002-05-08 22:19:27 +000015// In the implementation of this algorithm, constants are assigned rank = 0,
16// function arguments are rank = 1, and other values are assigned ranks
17// corresponding to the reverse post order traversal of current function
18// (starting at 2), which effectively gives values in deep loops higher rank
19// than values not in loops.
20//
21//===----------------------------------------------------------------------===//
22
Chris Lattnerf43e9742005-05-07 04:08:02 +000023#define DEBUG_TYPE "reassociate"
Chris Lattnerc0f58002002-05-08 22:19:27 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattnercea57992005-05-07 04:24:13 +000025#include "llvm/Constants.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000026#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000027#include "llvm/Instructions.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000028#include "llvm/Pass.h"
Chris Lattnercea57992005-05-07 04:24:13 +000029#include "llvm/Type.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000030#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
32#include "llvm/ADT/PostOrderIterator.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner49525f82004-01-09 06:02:20 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattnerc0f58002002-05-08 22:19:27 +000036namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000037 Statistic<> NumLinear ("reassociate","Number of insts linearized");
38 Statistic<> NumChanged("reassociate","Number of insts reassociated");
39 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
40
Chris Lattnerc0f58002002-05-08 22:19:27 +000041 class Reassociate : public FunctionPass {
Chris Lattner10073a92002-07-25 06:17:51 +000042 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner8ac196d2003-08-13 16:16:26 +000043 std::map<Value*, unsigned> ValueRankMap;
Chris Lattnerc0f58002002-05-08 22:19:27 +000044 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000045 bool runOnFunction(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000046
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000048 AU.setPreservesCFG();
Chris Lattnerc0f58002002-05-08 22:19:27 +000049 }
50 private:
Chris Lattner113f4f42002-06-25 16:13:24 +000051 void BuildRankMap(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000052 unsigned getRank(Value *V);
53 bool ReassociateExpr(BinaryOperator *I);
54 bool ReassociateBB(BasicBlock *BB);
55 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000056
Chris Lattnerc8b70922002-07-26 21:12:46 +000057 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattnerc0f58002002-05-08 22:19:27 +000058}
59
Brian Gaeke960707c2003-11-11 22:41:34 +000060// Public interface to the Reassociate pass
Chris Lattner49525f82004-01-09 06:02:20 +000061FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
Chris Lattnerc0f58002002-05-08 22:19:27 +000062
Chris Lattner113f4f42002-06-25 16:13:24 +000063void Reassociate::BuildRankMap(Function &F) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000064 unsigned i = 2;
Chris Lattner8ac196d2003-08-13 16:16:26 +000065
66 // Assign distinct ranks to function arguments
Chris Lattner531f9e92005-03-15 04:54:21 +000067 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner8ac196d2003-08-13 16:16:26 +000068 ValueRankMap[I] = ++i;
69
Chris Lattner113f4f42002-06-25 16:13:24 +000070 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000071 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
72 E = RPOT.end(); I != E; ++I)
Chris Lattner58c7eb62003-08-12 20:14:27 +000073 RankMap[*I] = ++i << 16;
Chris Lattnerc0f58002002-05-08 22:19:27 +000074}
75
76unsigned Reassociate::getRank(Value *V) {
Chris Lattner8ac196d2003-08-13 16:16:26 +000077 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
78
Chris Lattnerf43e9742005-05-07 04:08:02 +000079 Instruction *I = dyn_cast<Instruction>(V);
80 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
Chris Lattnerc0f58002002-05-08 22:19:27 +000081
Chris Lattnerf43e9742005-05-07 04:08:02 +000082 unsigned &CachedRank = ValueRankMap[I];
83 if (CachedRank) return CachedRank; // Rank already known?
84
85 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
86 // we can reassociate expressions for code motion! Since we do not recurse
87 // for PHI nodes, we cannot have infinite recursion here, because there
88 // cannot be loops in the value graph that do not go through PHI nodes.
89 //
90 if (I->getOpcode() == Instruction::PHI ||
91 I->getOpcode() == Instruction::Alloca ||
92 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
93 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
94 return RankMap[I->getParent()];
95
96 // If not, compute it!
97 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
98 for (unsigned i = 0, e = I->getNumOperands();
99 i != e && Rank != MaxRank; ++i)
100 Rank = std::max(Rank, getRank(I->getOperand(i)));
101
102 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
103 << Rank+1 << "\n");
104
105 return CachedRank = Rank+1;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000106}
107
108
Chris Lattnerc0f58002002-05-08 22:19:27 +0000109bool Reassociate::ReassociateExpr(BinaryOperator *I) {
110 Value *LHS = I->getOperand(0);
111 Value *RHS = I->getOperand(1);
112 unsigned LHSRank = getRank(LHS);
113 unsigned RHSRank = getRank(RHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000114
Chris Lattnerc0f58002002-05-08 22:19:27 +0000115 bool Changed = false;
116
117 // Make sure the LHS of the operand always has the greater rank...
118 if (LHSRank < RHSRank) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000119 bool Success = !I->swapOperands();
120 assert(Success && "swapOperands failed");
121
Chris Lattnerc0f58002002-05-08 22:19:27 +0000122 std::swap(LHS, RHS);
123 std::swap(LHSRank, RHSRank);
124 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000125 ++NumSwapped;
Chris Lattner9a63520b2004-07-15 01:50:47 +0000126 DEBUG(std::cerr << "Transposed: " << *I
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000127 /* << " Result BB: " << I->getParent()*/);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000128 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000129
Chris Lattnerc0f58002002-05-08 22:19:27 +0000130 // If the LHS is the same operator as the current one is, and if we are the
131 // only expression using it...
132 //
133 if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000134 if (LHSI->getOpcode() == I->getOpcode() && LHSI->hasOneUse()) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000135 // If the rank of our current RHS is less than the rank of the LHS's LHS,
136 // then we reassociate the two instructions...
Chris Lattnerc0f58002002-05-08 22:19:27 +0000137
Chris Lattner98b3ecd2003-08-12 21:45:24 +0000138 unsigned TakeOp = 0;
139 if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
140 if (IOp->getOpcode() == LHSI->getOpcode())
141 TakeOp = 1; // Hoist out non-tree portion
142
143 if (RHSRank < getRank(LHSI->getOperand(TakeOp))) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000144 // Convert ((a + 12) + 10) into (a + (12 + 10))
145 I->setOperand(0, LHSI->getOperand(TakeOp));
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000146 LHSI->setOperand(TakeOp, RHS);
147 I->setOperand(1, LHSI);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000148
149 // Move the LHS expression forward, to ensure that it is dominated by
150 // its operands.
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000151 LHSI->getParent()->getInstList().remove(LHSI);
152 I->getParent()->getInstList().insert(I, LHSI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000153
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000154 ++NumChanged;
Chris Lattner9a63520b2004-07-15 01:50:47 +0000155 DEBUG(std::cerr << "Reassociated: " << *I/* << " Result BB: "
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000156 << I->getParent()*/);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000157
158 // Since we modified the RHS instruction, make sure that we recheck it.
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000159 ReassociateExpr(LHSI);
Chris Lattner58c7eb62003-08-12 20:14:27 +0000160 ReassociateExpr(I);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000161 return true;
162 }
163 }
164
165 return Changed;
166}
167
168
Chris Lattner7bc532d2002-05-16 04:37:07 +0000169// NegateValue - Insert instructions before the instruction pointed to by BI,
170// that computes the negative version of the value specified. The negative
171// version of the value is returned, and BI is left pointing at the instruction
172// that should be processed next by the reassociation pass.
173//
Chris Lattnerf43e9742005-05-07 04:08:02 +0000174static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000175 // We are trying to expose opportunity for reassociation. One of the things
176 // that we want to do to achieve this is to push a negation as deep into an
177 // expression chain as possible, to expose the add instructions. In practice,
178 // this means that we turn this:
179 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
180 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
181 // the constants. We assume that instcombine will clean up the mess later if
Misha Brukman7eb05a12003-08-18 14:43:39 +0000182 // we introduce tons of unnecessary negation instructions...
Chris Lattner7bc532d2002-05-16 04:37:07 +0000183 //
184 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000185 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000186 Value *RHS = NegateValue(I->getOperand(1), BI);
187 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000188
189 // We must actually insert a new add instruction here, because the neg
190 // instructions do not dominate the old add instruction in general. By
191 // adding it now, we are assured that the neg instructions we just
192 // inserted dominate the instruction we are about to insert after them.
193 //
Chris Lattner28a8d242002-09-10 17:04:02 +0000194 return BinaryOperator::create(Instruction::Add, LHS, RHS,
Chris Lattnerf43e9742005-05-07 04:08:02 +0000195 I->getName()+".neg", BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000196 }
197
198 // Insert a 'neg' instruction that subtracts the value from zero to get the
199 // negation.
200 //
Chris Lattnerf43e9742005-05-07 04:08:02 +0000201 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
202}
203
204/// isReassociableOp - Return true if V is an instruction of the specified
205/// opcode and if it only has one use.
206static bool isReassociableOp(Value *V, unsigned Opcode) {
207 return V->hasOneUse() && isa<Instruction>(V) &&
208 cast<Instruction>(V)->getOpcode() == Opcode;
209}
210
211/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
212/// only used by an add, transform this into (X+(0-Y)) to promote better
213/// reassociation.
214static Instruction *BreakUpSubtract(Instruction *Sub) {
215 // Reject cases where it is pointless to do this.
216 if (Sub->getType()->isFloatingPoint())
217 return 0; // Floating point adds are not associative.
218
219 // Don't bother to break this up unless either the LHS is an associable add or
220 // if this is only used by one.
221 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
222 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
223 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
224 return 0;
225
226 // Convert a subtract into an add and a neg instruction... so that sub
227 // instructions can be commuted with other add instructions...
228 //
229 // Calculate the negative value of Operand 1 of the sub instruction...
230 // and set it as the RHS of the add instruction we just made...
231 //
232 std::string Name = Sub->getName();
233 Sub->setName("");
234 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
235 Instruction *New =
236 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
237
238 // Everyone now refers to the add instruction.
239 Sub->replaceAllUsesWith(New);
240 Sub->eraseFromParent();
241
242 DEBUG(std::cerr << "Negated: " << *New);
243 return New;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000244}
245
Chris Lattnercea57992005-05-07 04:24:13 +0000246/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
247/// by one, change this into a multiply by a constant to assist with further
248/// reassociation.
249static Instruction *ConvertShiftToMul(Instruction *Shl) {
250 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
251 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
252 return 0;
253
254 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
255 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
256
257 std::string Name = Shl->getName(); Shl->setName("");
258 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
259 Name, Shl);
260 Shl->replaceAllUsesWith(Mul);
261 Shl->eraseFromParent();
262 return Mul;
263}
264
Chris Lattner7bc532d2002-05-16 04:37:07 +0000265
Chris Lattnerf43e9742005-05-07 04:08:02 +0000266/// ReassociateBB - Inspect all of the instructions in this basic block,
267/// reassociating them as we go.
Chris Lattnerc0f58002002-05-08 22:19:27 +0000268bool Reassociate::ReassociateBB(BasicBlock *BB) {
269 bool Changed = false;
270 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattnerf43e9742005-05-07 04:08:02 +0000271 // If this is a subtract instruction which is not already in negate form,
272 // see if we can convert it to X+-Y.
273 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
274 if (Instruction *NI = BreakUpSubtract(BI)) {
275 Changed = true;
276 BI = NI;
277 }
Chris Lattnercea57992005-05-07 04:24:13 +0000278 if (BI->getOpcode() == Instruction::Shl &&
279 isa<ConstantInt>(BI->getOperand(1)))
280 if (Instruction *NI = ConvertShiftToMul(BI)) {
281 Changed = true;
282 BI = NI;
283 }
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000284
Chris Lattnerc0f58002002-05-08 22:19:27 +0000285 // If this instruction is a commutative binary operator, and the ranks of
286 // the two operands are sorted incorrectly, fix it now.
287 //
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000288 if (BI->isAssociative()) {
Chris Lattnerf43e9742005-05-07 04:08:02 +0000289 DEBUG(std::cerr << "Reassociating: " << *BI);
Chris Lattner889f6202003-04-23 16:37:45 +0000290 BinaryOperator *I = cast<BinaryOperator>(BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000291 if (!I->use_empty()) {
292 // Make sure that we don't have a tree-shaped computation. If we do,
293 // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D
294 //
295 Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
296 Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
297 if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
298 RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000299 RHSI->hasOneUse()) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000300 // Insert a new temporary instruction... (A+B)+C
301 BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
302 RHSI->getOperand(0),
Chris Lattner28a8d242002-09-10 17:04:02 +0000303 RHSI->getName()+".ra",
304 BI);
305 BI = Tmp;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000306 I->setOperand(0, Tmp);
307 I->setOperand(1, RHSI->getOperand(1));
308
309 // Process the temporary instruction for reassociation now.
310 I = Tmp;
311 ++NumLinear;
312 Changed = true;
Chris Lattner9a63520b2004-07-15 01:50:47 +0000313 DEBUG(std::cerr << "Linearized: " << *I/* << " Result BB: " << BB*/);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000314 }
315
316 // Make sure that this expression is correctly reassociated with respect
317 // to it's used values...
318 //
319 Changed |= ReassociateExpr(I);
320 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000321 }
322 }
323
324 return Changed;
325}
326
327
Chris Lattner113f4f42002-06-25 16:13:24 +0000328bool Reassociate::runOnFunction(Function &F) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000329 // Recalculate the rank map for F
330 BuildRankMap(F);
331
332 bool Changed = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000333 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
334 Changed |= ReassociateBB(FI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000335
336 // We are done with the rank map...
337 RankMap.clear();
Chris Lattner8ac196d2003-08-13 16:16:26 +0000338 ValueRankMap.clear();
Chris Lattnerc0f58002002-05-08 22:19:27 +0000339 return Changed;
340}
Brian Gaeke960707c2003-11-11 22:41:34 +0000341