blob: a9b0ea6cbbafd5de0ed171533a4dcf840bd80faf [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 Lattner9187f392005-05-08 20:09:57 +000030#include "llvm/Assembly/Writer.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000031#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/Statistic.h"
Chris Lattner1e506502005-05-07 21:59:39 +000035#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Chris Lattnerc0f58002002-05-08 22:19:27 +000038namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000039 Statistic<> NumLinear ("reassociate","Number of insts linearized");
40 Statistic<> NumChanged("reassociate","Number of insts reassociated");
41 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
Chris Lattner5847e5e2005-05-08 18:59:37 +000042 Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000043
Chris Lattner1e506502005-05-07 21:59:39 +000044 struct ValueEntry {
45 unsigned Rank;
46 Value *Op;
47 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
48 };
49 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
50 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
51 }
52
Chris Lattnerc0f58002002-05-08 22:19:27 +000053 class Reassociate : public FunctionPass {
Chris Lattner10073a92002-07-25 06:17:51 +000054 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner8ac196d2003-08-13 16:16:26 +000055 std::map<Value*, unsigned> ValueRankMap;
Chris Lattner1e506502005-05-07 21:59:39 +000056 bool MadeChange;
Chris Lattnerc0f58002002-05-08 22:19:27 +000057 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000058 bool runOnFunction(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000059
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000061 AU.setPreservesCFG();
Chris Lattnerc0f58002002-05-08 22:19:27 +000062 }
63 private:
Chris Lattner113f4f42002-06-25 16:13:24 +000064 void BuildRankMap(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000065 unsigned getRank(Value *V);
Chris Lattner1e506502005-05-07 21:59:39 +000066 void RewriteExprTree(BinaryOperator *I, unsigned Idx,
67 std::vector<ValueEntry> &Ops);
Chris Lattnere1850b82005-05-08 00:19:31 +000068 void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
Chris Lattner1e506502005-05-07 21:59:39 +000069 void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
70 void LinearizeExpr(BinaryOperator *I);
71 void ReassociateBB(BasicBlock *BB);
Chris Lattnerc0f58002002-05-08 22:19:27 +000072 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000073
Chris Lattnerc8b70922002-07-26 21:12:46 +000074 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattnerc0f58002002-05-08 22:19:27 +000075}
76
Brian Gaeke960707c2003-11-11 22:41:34 +000077// Public interface to the Reassociate pass
Chris Lattner49525f82004-01-09 06:02:20 +000078FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
Chris Lattnerc0f58002002-05-08 22:19:27 +000079
Chris Lattner9f284e02005-05-08 20:57:04 +000080
81static bool isUnmovableInstruction(Instruction *I) {
82 if (I->getOpcode() == Instruction::PHI ||
83 I->getOpcode() == Instruction::Alloca ||
84 I->getOpcode() == Instruction::Load ||
85 I->getOpcode() == Instruction::Malloc ||
86 I->getOpcode() == Instruction::Invoke ||
87 I->getOpcode() == Instruction::Call ||
88 I->getOpcode() == Instruction::Div ||
89 I->getOpcode() == Instruction::Rem)
90 return true;
91 return false;
92}
93
Chris Lattner113f4f42002-06-25 16:13:24 +000094void Reassociate::BuildRankMap(Function &F) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000095 unsigned i = 2;
Chris Lattner8ac196d2003-08-13 16:16:26 +000096
97 // Assign distinct ranks to function arguments
Chris Lattner531f9e92005-03-15 04:54:21 +000098 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner8ac196d2003-08-13 16:16:26 +000099 ValueRankMap[I] = ++i;
100
Chris Lattner113f4f42002-06-25 16:13:24 +0000101 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000102 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
Chris Lattner9f284e02005-05-08 20:57:04 +0000103 E = RPOT.end(); I != E; ++I) {
104 BasicBlock *BB = *I;
105 unsigned BBRank = RankMap[BB] = ++i << 16;
106
107 // Walk the basic block, adding precomputed ranks for any instructions that
108 // we cannot move. This ensures that the ranks for these instructions are
109 // all different in the block.
110 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
111 if (isUnmovableInstruction(I))
112 ValueRankMap[I] = ++BBRank;
113 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000114}
115
116unsigned Reassociate::getRank(Value *V) {
Chris Lattner8ac196d2003-08-13 16:16:26 +0000117 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
118
Chris Lattnerf43e9742005-05-07 04:08:02 +0000119 Instruction *I = dyn_cast<Instruction>(V);
120 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
Chris Lattnerc0f58002002-05-08 22:19:27 +0000121
Chris Lattnerf43e9742005-05-07 04:08:02 +0000122 unsigned &CachedRank = ValueRankMap[I];
123 if (CachedRank) return CachedRank; // Rank already known?
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000124
Chris Lattnerf43e9742005-05-07 04:08:02 +0000125 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
126 // we can reassociate expressions for code motion! Since we do not recurse
127 // for PHI nodes, we cannot have infinite recursion here, because there
128 // cannot be loops in the value graph that do not go through PHI nodes.
Chris Lattnerf43e9742005-05-07 04:08:02 +0000129 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
130 for (unsigned i = 0, e = I->getNumOperands();
131 i != e && Rank != MaxRank; ++i)
132 Rank = std::max(Rank, getRank(I->getOperand(i)));
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000133
Chris Lattner6e2086d2005-05-08 00:08:33 +0000134 // If this is a not or neg instruction, do not count it for rank. This
135 // assures us that X and ~X will have the same rank.
136 if (!I->getType()->isIntegral() ||
137 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
138 ++Rank;
139
Chris Lattner9f284e02005-05-08 20:57:04 +0000140 //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
141 //<< Rank << "\n");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000142
Chris Lattner6e2086d2005-05-08 00:08:33 +0000143 return CachedRank = Rank;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000144}
145
Chris Lattner1e506502005-05-07 21:59:39 +0000146/// isReassociableOp - Return true if V is an instruction of the specified
147/// opcode and if it only has one use.
148static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
149 if (V->hasOneUse() && isa<Instruction>(V) &&
150 cast<Instruction>(V)->getOpcode() == Opcode)
151 return cast<BinaryOperator>(V);
152 return 0;
153}
Chris Lattnerc0f58002002-05-08 22:19:27 +0000154
Chris Lattner877b1142005-05-08 21:28:52 +0000155/// LowerNegateToMultiply - Replace 0-X with X*-1.
156///
157static Instruction *LowerNegateToMultiply(Instruction *Neg) {
158 Constant *Cst;
159 if (Neg->getType()->isFloatingPoint())
160 Cst = ConstantFP::get(Neg->getType(), -1);
161 else
162 Cst = ConstantInt::getAllOnesValue(Neg->getType());
163
164 std::string NegName = Neg->getName(); Neg->setName("");
165 Instruction *Res = BinaryOperator::createMul(Neg->getOperand(1), Cst, NegName,
166 Neg);
167 Neg->replaceAllUsesWith(Res);
168 Neg->eraseFromParent();
169 return Res;
170}
171
Chris Lattner1e506502005-05-07 21:59:39 +0000172// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
173// Note that if D is also part of the expression tree that we recurse to
174// linearize it as well. Besides that case, this does not recurse into A,B, or
175// C.
176void Reassociate::LinearizeExpr(BinaryOperator *I) {
177 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
178 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000179 assert(isReassociableOp(LHS, I->getOpcode()) &&
Chris Lattner1e506502005-05-07 21:59:39 +0000180 isReassociableOp(RHS, I->getOpcode()) &&
181 "Not an expression that needs linearization?");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000182
Chris Lattner1e506502005-05-07 21:59:39 +0000183 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000184
Chris Lattner1e506502005-05-07 21:59:39 +0000185 // Move the RHS instruction to live immediately before I, avoiding breaking
186 // dominator properties.
Chris Lattner9f269e42005-08-08 19:11:57 +0000187 RHS->moveBefore(I);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000188
Chris Lattner1e506502005-05-07 21:59:39 +0000189 // Move operands around to do the linearization.
190 I->setOperand(1, RHS->getOperand(0));
191 RHS->setOperand(0, LHS);
192 I->setOperand(0, RHS);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000193
Chris Lattner1e506502005-05-07 21:59:39 +0000194 ++NumLinear;
195 MadeChange = true;
196 DEBUG(std::cerr << "Linearized: " << *I);
197
198 // If D is part of this expression tree, tail recurse.
199 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
200 LinearizeExpr(I);
201}
202
203
204/// LinearizeExprTree - Given an associative binary expression tree, traverse
205/// all of the uses putting it into canonical form. This forces a left-linear
206/// form of the the expression (((a+b)+c)+d), and collects information about the
207/// rank of the non-tree operands.
208///
209/// This returns the rank of the RHS operand, which is known to be the highest
210/// rank value in the expression tree.
211///
212void Reassociate::LinearizeExprTree(BinaryOperator *I,
213 std::vector<ValueEntry> &Ops) {
214 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
215 unsigned Opcode = I->getOpcode();
216
217 // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
218 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
219 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
220
Chris Lattner877b1142005-05-08 21:28:52 +0000221 // If this is a multiply expression tree and it contains internal negations,
222 // transform them into multiplies by -1 so they can be reassociated.
223 if (I->getOpcode() == Instruction::Mul) {
224 if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
225 LHS = LowerNegateToMultiply(cast<Instruction>(LHS));
226 LHSBO = isReassociableOp(LHS, Opcode);
227 }
228 if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
229 RHS = LowerNegateToMultiply(cast<Instruction>(RHS));
230 RHSBO = isReassociableOp(RHS, Opcode);
231 }
232 }
233
Chris Lattner1e506502005-05-07 21:59:39 +0000234 if (!LHSBO) {
235 if (!RHSBO) {
236 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As
237 // such, just remember these operands and their rank.
238 Ops.push_back(ValueEntry(getRank(LHS), LHS));
239 Ops.push_back(ValueEntry(getRank(RHS), RHS));
240 return;
241 } else {
242 // Turn X+(Y+Z) -> (Y+Z)+X
243 std::swap(LHSBO, RHSBO);
244 std::swap(LHS, RHS);
245 bool Success = !I->swapOperands();
246 assert(Success && "swapOperands failed");
247 MadeChange = true;
248 }
249 } else if (RHSBO) {
250 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
251 // part of the expression tree.
252 LinearizeExpr(I);
253 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
254 RHS = I->getOperand(1);
255 RHSBO = 0;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000256 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000257
Chris Lattner1e506502005-05-07 21:59:39 +0000258 // Okay, now we know that the LHS is a nested expression and that the RHS is
259 // not. Perform reassociation.
260 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
Chris Lattnerc0f58002002-05-08 22:19:27 +0000261
Chris Lattner1e506502005-05-07 21:59:39 +0000262 // Move LHS right before I to make sure that the tree expression dominates all
263 // values.
Chris Lattner9f269e42005-08-08 19:11:57 +0000264 LHSBO->moveBefore(I);
Chris Lattner98b3ecd2003-08-12 21:45:24 +0000265
Chris Lattner1e506502005-05-07 21:59:39 +0000266 // Linearize the expression tree on the LHS.
267 LinearizeExprTree(LHSBO, Ops);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000268
Chris Lattner1e506502005-05-07 21:59:39 +0000269 // Remember the RHS operand and its rank.
270 Ops.push_back(ValueEntry(getRank(RHS), RHS));
Chris Lattnerc0f58002002-05-08 22:19:27 +0000271}
272
Chris Lattner1e506502005-05-07 21:59:39 +0000273// RewriteExprTree - Now that the operands for this expression tree are
274// linearized and optimized, emit them in-order. This function is written to be
275// tail recursive.
276void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
277 std::vector<ValueEntry> &Ops) {
278 if (i+2 == Ops.size()) {
279 if (I->getOperand(0) != Ops[i].Op ||
280 I->getOperand(1) != Ops[i+1].Op) {
281 DEBUG(std::cerr << "RA: " << *I);
282 I->setOperand(0, Ops[i].Op);
283 I->setOperand(1, Ops[i+1].Op);
284 DEBUG(std::cerr << "TO: " << *I);
285 MadeChange = true;
286 ++NumChanged;
287 }
288 return;
289 }
290 assert(i+2 < Ops.size() && "Ops index out of range!");
291
292 if (I->getOperand(1) != Ops[i].Op) {
293 DEBUG(std::cerr << "RA: " << *I);
294 I->setOperand(1, Ops[i].Op);
295 DEBUG(std::cerr << "TO: " << *I);
296 MadeChange = true;
297 ++NumChanged;
298 }
299 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
300}
301
302
Chris Lattnerc0f58002002-05-08 22:19:27 +0000303
Chris Lattner7bc532d2002-05-16 04:37:07 +0000304// NegateValue - Insert instructions before the instruction pointed to by BI,
305// that computes the negative version of the value specified. The negative
306// version of the value is returned, and BI is left pointing at the instruction
307// that should be processed next by the reassociation pass.
308//
Chris Lattnerf43e9742005-05-07 04:08:02 +0000309static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000310 // We are trying to expose opportunity for reassociation. One of the things
311 // that we want to do to achieve this is to push a negation as deep into an
312 // expression chain as possible, to expose the add instructions. In practice,
313 // this means that we turn this:
314 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
315 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
316 // the constants. We assume that instcombine will clean up the mess later if
Misha Brukman7eb05a12003-08-18 14:43:39 +0000317 // we introduce tons of unnecessary negation instructions...
Chris Lattner7bc532d2002-05-16 04:37:07 +0000318 //
319 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000320 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000321 Value *RHS = NegateValue(I->getOperand(1), BI);
322 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000323
324 // We must actually insert a new add instruction here, because the neg
325 // instructions do not dominate the old add instruction in general. By
326 // adding it now, we are assured that the neg instructions we just
327 // inserted dominate the instruction we are about to insert after them.
328 //
Chris Lattner28a8d242002-09-10 17:04:02 +0000329 return BinaryOperator::create(Instruction::Add, LHS, RHS,
Chris Lattnerf43e9742005-05-07 04:08:02 +0000330 I->getName()+".neg", BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000331 }
332
333 // Insert a 'neg' instruction that subtracts the value from zero to get the
334 // negation.
335 //
Chris Lattnerf43e9742005-05-07 04:08:02 +0000336 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
337}
338
Chris Lattnerf43e9742005-05-07 04:08:02 +0000339/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
340/// only used by an add, transform this into (X+(0-Y)) to promote better
341/// reassociation.
342static Instruction *BreakUpSubtract(Instruction *Sub) {
Chris Lattnerf43e9742005-05-07 04:08:02 +0000343 // Don't bother to break this up unless either the LHS is an associable add or
344 // if this is only used by one.
345 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
346 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
347 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
348 return 0;
349
350 // Convert a subtract into an add and a neg instruction... so that sub
351 // instructions can be commuted with other add instructions...
352 //
353 // Calculate the negative value of Operand 1 of the sub instruction...
354 // and set it as the RHS of the add instruction we just made...
355 //
356 std::string Name = Sub->getName();
357 Sub->setName("");
358 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
359 Instruction *New =
360 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
361
362 // Everyone now refers to the add instruction.
363 Sub->replaceAllUsesWith(New);
364 Sub->eraseFromParent();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000365
Chris Lattnerf43e9742005-05-07 04:08:02 +0000366 DEBUG(std::cerr << "Negated: " << *New);
367 return New;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000368}
369
Chris Lattnercea57992005-05-07 04:24:13 +0000370/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
371/// by one, change this into a multiply by a constant to assist with further
372/// reassociation.
373static Instruction *ConvertShiftToMul(Instruction *Shl) {
374 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
375 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
376 return 0;
377
378 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
379 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
380
381 std::string Name = Shl->getName(); Shl->setName("");
382 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
383 Name, Shl);
384 Shl->replaceAllUsesWith(Mul);
385 Shl->eraseFromParent();
386 return Mul;
387}
388
Chris Lattner5847e5e2005-05-08 18:59:37 +0000389// Scan backwards and forwards among values with the same rank as element i to
390// see if X exists. If X does not exist, return i.
391static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
392 Value *X) {
393 unsigned XRank = Ops[i].Rank;
394 unsigned e = Ops.size();
395 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
396 if (Ops[j].Op == X)
397 return j;
398 // Scan backwards
399 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
400 if (Ops[j].Op == X)
401 return j;
402 return i;
403}
404
Chris Lattnere1850b82005-05-08 00:19:31 +0000405void Reassociate::OptimizeExpression(unsigned Opcode,
406 std::vector<ValueEntry> &Ops) {
407 // Now that we have the linearized expression tree, try to optimize it.
408 // Start by folding any constants that we found.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000409 bool IterateOptimization = false;
Chris Lattnere1850b82005-05-08 00:19:31 +0000410 if (Ops.size() == 1) return;
411
412 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
413 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
414 Ops.pop_back();
415 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
Chris Lattner08582be2005-05-08 19:48:43 +0000416 OptimizeExpression(Opcode, Ops);
417 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000418 }
419
420 // Check for destructive annihilation due to a constant being used.
421 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
422 switch (Opcode) {
423 default: break;
424 case Instruction::And:
425 if (CstVal->isNullValue()) { // ... & 0 -> 0
426 Ops[0].Op = CstVal;
427 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000428 ++NumAnnihil;
429 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000430 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
431 Ops.pop_back();
432 }
433 break;
434 case Instruction::Mul:
435 if (CstVal->isNullValue()) { // ... * 0 -> 0
436 Ops[0].Op = CstVal;
437 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000438 ++NumAnnihil;
439 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000440 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
441 Ops.pop_back(); // ... * 1 -> ...
442 }
443 break;
444 case Instruction::Or:
445 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
446 Ops[0].Op = CstVal;
447 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000448 ++NumAnnihil;
449 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000450 }
451 // FALLTHROUGH!
452 case Instruction::Add:
453 case Instruction::Xor:
454 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
455 Ops.pop_back();
456 break;
457 }
Chris Lattnerd1325da2005-09-02 05:23:22 +0000458 if (Ops.size() == 1) return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000459
460 // Handle destructive annihilation do to identities between elements in the
461 // argument list here.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000462 switch (Opcode) {
463 default: break;
464 case Instruction::And:
465 case Instruction::Or:
466 case Instruction::Xor:
467 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
468 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
469 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
470 // First, check for X and ~X in the operand list.
Chris Lattnerd1325da2005-09-02 05:23:22 +0000471 assert(i < Ops.size());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000472 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
473 Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
474 unsigned FoundX = FindInOperandList(Ops, i, X);
475 if (FoundX != i) {
476 if (Opcode == Instruction::And) { // ...&X&~X = 0
477 Ops[0].Op = Constant::getNullValue(X->getType());
478 Ops.erase(Ops.begin()+1, Ops.end());
479 ++NumAnnihil;
480 return;
481 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1
482 Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType());
483 Ops.erase(Ops.begin()+1, Ops.end());
484 ++NumAnnihil;
485 return;
486 }
487 }
488 }
489
490 // Next, check for duplicate pairs of values, which we assume are next to
491 // each other, due to our sorting criteria.
Chris Lattnerd1325da2005-09-02 05:23:22 +0000492 assert(i < Ops.size());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000493 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
494 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
495 // Drop duplicate values.
496 Ops.erase(Ops.begin()+i);
497 --i; --e;
498 IterateOptimization = true;
499 ++NumAnnihil;
500 } else {
501 assert(Opcode == Instruction::Xor);
Chris Lattner8ca5b2a2005-08-24 17:55:32 +0000502 if (e == 2) {
503 Ops[0].Op = Constant::getNullValue(Ops[0].Op->getType());
504 Ops.erase(Ops.begin()+1, Ops.end());
505 ++NumAnnihil;
506 return;
507 }
Chris Lattner5847e5e2005-05-08 18:59:37 +0000508 // ... X^X -> ...
509 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
Chris Lattner8ca5b2a2005-08-24 17:55:32 +0000510 i -= 1; e -= 2;
Chris Lattner5847e5e2005-05-08 18:59:37 +0000511 IterateOptimization = true;
512 ++NumAnnihil;
513 }
514 }
515 }
516 break;
517
518 case Instruction::Add:
519 // Scan the operand lists looking for X and -X pairs. If we find any, we
520 // can simplify the expression. X+-X == 0
521 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Chris Lattnerd1325da2005-09-02 05:23:22 +0000522 assert(i < Ops.size());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000523 // Check for X and -X in the operand list.
524 if (BinaryOperator::isNeg(Ops[i].Op)) {
525 Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
526 unsigned FoundX = FindInOperandList(Ops, i, X);
527 if (FoundX != i) {
528 // Remove X and -X from the operand list.
529 if (Ops.size() == 2) {
530 Ops[0].Op = Constant::getNullValue(X->getType());
Chris Lattnerd1325da2005-09-02 05:23:22 +0000531 Ops.pop_back();
Chris Lattner5847e5e2005-05-08 18:59:37 +0000532 ++NumAnnihil;
533 return;
534 } else {
535 Ops.erase(Ops.begin()+i);
Chris Lattnerd1325da2005-09-02 05:23:22 +0000536 if (i < FoundX)
537 --FoundX;
538 else
539 --i; // Need to back up an extra one.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000540 Ops.erase(Ops.begin()+FoundX);
541 IterateOptimization = true;
542 ++NumAnnihil;
Chris Lattnerd1325da2005-09-02 05:23:22 +0000543 --i; // Revisit element.
544 e -= 2; // Removed two elements.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000545 }
546 }
547 }
548 }
549 break;
550 //case Instruction::Mul:
551 }
552
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000553 if (IterateOptimization)
Chris Lattner08582be2005-05-08 19:48:43 +0000554 OptimizeExpression(Opcode, Ops);
Chris Lattnere1850b82005-05-08 00:19:31 +0000555}
556
Chris Lattner9187f392005-05-08 20:09:57 +0000557/// PrintOps - Print out the expression identified in the Ops list.
558///
559static void PrintOps(unsigned Opcode, const std::vector<ValueEntry> &Ops,
560 BasicBlock *BB) {
561 Module *M = BB->getParent()->getParent();
562 std::cerr << Instruction::getOpcodeName(Opcode) << " "
563 << *Ops[0].Op->getType();
564 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
565 WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M)
566 << "," << Ops[i].Rank;
567}
Chris Lattner7bc532d2002-05-16 04:37:07 +0000568
Chris Lattnerf43e9742005-05-07 04:08:02 +0000569/// ReassociateBB - Inspect all of the instructions in this basic block,
570/// reassociating them as we go.
Chris Lattner1e506502005-05-07 21:59:39 +0000571void Reassociate::ReassociateBB(BasicBlock *BB) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000572 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattner31c667e2005-05-10 03:39:25 +0000573 if (BI->getOpcode() == Instruction::Shl &&
574 isa<ConstantInt>(BI->getOperand(1)))
575 if (Instruction *NI = ConvertShiftToMul(BI)) {
576 MadeChange = true;
577 BI = NI;
578 }
579
Chris Lattnerc4f8e2b2005-05-08 21:33:47 +0000580 // Reject cases where it is pointless to do this.
581 if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint())
582 continue; // Floating point ops are not associative.
583
Chris Lattnerf43e9742005-05-07 04:08:02 +0000584 // If this is a subtract instruction which is not already in negate form,
585 // see if we can convert it to X+-Y.
Chris Lattner877b1142005-05-08 21:28:52 +0000586 if (BI->getOpcode() == Instruction::Sub) {
587 if (!BinaryOperator::isNeg(BI)) {
588 if (Instruction *NI = BreakUpSubtract(BI)) {
589 MadeChange = true;
590 BI = NI;
591 }
592 } else {
593 // Otherwise, this is a negation. See if the operand is a multiply tree
594 // and if this is not an inner node of a multiply tree.
595 if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
596 (!BI->hasOneUse() ||
597 !isReassociableOp(BI->use_back(), Instruction::Mul))) {
598 BI = LowerNegateToMultiply(BI);
599 MadeChange = true;
600 }
Chris Lattnerf43e9742005-05-07 04:08:02 +0000601 }
Chris Lattner877b1142005-05-08 21:28:52 +0000602 }
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000603
Chris Lattner1e506502005-05-07 21:59:39 +0000604 // If this instruction is a commutative binary operator, process it.
605 if (!BI->isAssociative()) continue;
606 BinaryOperator *I = cast<BinaryOperator>(BI);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000607
Chris Lattner1e506502005-05-07 21:59:39 +0000608 // If this is an interior node of a reassociable tree, ignore it until we
609 // get to the root of the tree, to avoid N^2 analysis.
610 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
611 continue;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000612
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000613 // First, walk the expression tree, linearizing the tree, collecting
Chris Lattner1e506502005-05-07 21:59:39 +0000614 std::vector<ValueEntry> Ops;
615 LinearizeExprTree(I, Ops);
616
Chris Lattner9187f392005-05-08 20:09:57 +0000617 DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB);
618 std::cerr << "\n");
619
Chris Lattner1e506502005-05-07 21:59:39 +0000620 // Now that we have linearized the tree to a list and have gathered all of
621 // the operands and their ranks, sort the operands by their rank. Use a
622 // stable_sort so that values with equal ranks will have their relative
623 // positions maintained (and so the compiler is deterministic). Note that
624 // this sorts so that the highest ranking values end up at the beginning of
625 // the vector.
626 std::stable_sort(Ops.begin(), Ops.end());
627
Chris Lattnere1850b82005-05-08 00:19:31 +0000628 // OptimizeExpression - Now that we have the expression tree in a convenient
629 // sorted form, optimize it globally if possible.
630 OptimizeExpression(I->getOpcode(), Ops);
Chris Lattner1e506502005-05-07 21:59:39 +0000631
Chris Lattnerdf333262005-05-08 21:41:35 +0000632 // We want to sink immediates as deeply as possible except in the case where
633 // this is a multiply tree used only by an add, and the immediate is a -1.
634 // In this case we reassociate to put the negation on the outside so that we
635 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000636 if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
Chris Lattnerdf333262005-05-08 21:41:35 +0000637 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
638 isa<ConstantInt>(Ops.back().Op) &&
639 cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
640 Ops.insert(Ops.begin(), Ops.back());
641 Ops.pop_back();
642 }
643
Chris Lattner9187f392005-05-08 20:09:57 +0000644 DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB);
645 std::cerr << "\n");
646
Chris Lattner1e506502005-05-07 21:59:39 +0000647 if (Ops.size() == 1) {
648 // This expression tree simplified to something that isn't a tree,
649 // eliminate it.
650 I->replaceAllUsesWith(Ops[0].Op);
651 } else {
652 // Now that we ordered and optimized the expressions, splat them back into
653 // the expression tree, removing any unneeded nodes.
654 RewriteExprTree(I, 0, Ops);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000655 }
656 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000657}
658
659
Chris Lattner113f4f42002-06-25 16:13:24 +0000660bool Reassociate::runOnFunction(Function &F) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000661 // Recalculate the rank map for F
662 BuildRankMap(F);
663
Chris Lattner1e506502005-05-07 21:59:39 +0000664 MadeChange = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000665 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
Chris Lattner1e506502005-05-07 21:59:39 +0000666 ReassociateBB(FI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000667
668 // We are done with the rank map...
669 RankMap.clear();
Chris Lattner8ac196d2003-08-13 16:16:26 +0000670 ValueRankMap.clear();
Chris Lattner1e506502005-05-07 21:59:39 +0000671 return MadeChange;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000672}
Brian Gaeke960707c2003-11-11 22:41:34 +0000673