blob: 142ede38e1ca6e77ae6f7a8430e9e6cc86c65533 [file] [log] [blame]
Chris Lattner4fd56002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4fd56002002-05-08 22:19:27 +00009//
10// This pass reassociates commutative expressions in an order that is designed
Chris Lattnere96fda32003-05-02 19:26:34 +000011// to promote better constant propagation, GCSE, LICM, PRE...
Chris Lattner4fd56002002-05-08 22:19:27 +000012//
13// For example: 4 + (x + 5) -> x + (4 + 5)
14//
Chris Lattner4fd56002002-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 Lattner08b43922005-05-07 04:08:02 +000023#define DEBUG_TYPE "reassociate"
Chris Lattner4fd56002002-05-08 22:19:27 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattner0975ed52005-05-07 04:24:13 +000025#include "llvm/Constants.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000026#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000027#include "llvm/Instructions.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000028#include "llvm/Pass.h"
Chris Lattner0975ed52005-05-07 04:24:13 +000029#include "llvm/Type.h"
Chris Lattnerc9fd0972005-05-08 20:09:57 +000030#include "llvm/Assembly/Writer.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000031#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/Statistic.h"
Chris Lattnerc0649ac2005-05-07 21:59:39 +000035#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Chris Lattner4fd56002002-05-08 22:19:27 +000038namespace {
Chris Lattnera92f6962002-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 Lattner109d34d2005-05-08 18:59:37 +000042 Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated");
Chris Lattnera92f6962002-10-01 22:38:41 +000043
Chris Lattnerc0649ac2005-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 Lattner4fd56002002-05-08 22:19:27 +000053 class Reassociate : public FunctionPass {
Chris Lattner0c0edf82002-07-25 06:17:51 +000054 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattnerfb5be092003-08-13 16:16:26 +000055 std::map<Value*, unsigned> ValueRankMap;
Chris Lattnerc0649ac2005-05-07 21:59:39 +000056 bool MadeChange;
Chris Lattner4fd56002002-05-08 22:19:27 +000057 public:
Chris Lattner7e708292002-06-25 16:13:24 +000058 bool runOnFunction(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000059
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000061 AU.setPreservesCFG();
Chris Lattner4fd56002002-05-08 22:19:27 +000062 }
63 private:
Chris Lattner7e708292002-06-25 16:13:24 +000064 void BuildRankMap(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000065 unsigned getRank(Value *V);
Chris Lattnerc0649ac2005-05-07 21:59:39 +000066 void RewriteExprTree(BinaryOperator *I, unsigned Idx,
67 std::vector<ValueEntry> &Ops);
Chris Lattner46900102005-05-08 00:19:31 +000068 void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
Chris Lattnerc0649ac2005-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 Lattner4fd56002002-05-08 22:19:27 +000072 };
Chris Lattnerf6293092002-07-23 18:06:35 +000073
Chris Lattnera6275cc2002-07-26 21:12:46 +000074 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattner4fd56002002-05-08 22:19:27 +000075}
76
Brian Gaeked0fde302003-11-11 22:41:34 +000077// Public interface to the Reassociate pass
Chris Lattnerd7456022004-01-09 06:02:20 +000078FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
Chris Lattner4fd56002002-05-08 22:19:27 +000079
Chris Lattner9c723192005-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 Lattner7e708292002-06-25 16:13:24 +000094void Reassociate::BuildRankMap(Function &F) {
Chris Lattner6007cb62003-08-12 20:14:27 +000095 unsigned i = 2;
Chris Lattnerfb5be092003-08-13 16:16:26 +000096
97 // Assign distinct ranks to function arguments
Chris Lattnere4d5c442005-03-15 04:54:21 +000098 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerfb5be092003-08-13 16:16:26 +000099 ValueRankMap[I] = ++i;
100
Chris Lattner7e708292002-06-25 16:13:24 +0000101 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattner4fd56002002-05-08 22:19:27 +0000102 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
Chris Lattner9c723192005-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 Lattner4fd56002002-05-08 22:19:27 +0000114}
115
116unsigned Reassociate::getRank(Value *V) {
Chris Lattnerfb5be092003-08-13 16:16:26 +0000117 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
118
Chris Lattner08b43922005-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 Lattner4fd56002002-05-08 22:19:27 +0000121
Chris Lattner08b43922005-05-07 04:08:02 +0000122 unsigned &CachedRank = ValueRankMap[I];
123 if (CachedRank) return CachedRank; // Rank already known?
Jeff Cohen00b168892005-07-27 06:12:32 +0000124
Chris Lattner08b43922005-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 Lattner08b43922005-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 Cohen00b168892005-07-27 06:12:32 +0000133
Chris Lattnercc8a2b92005-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 Lattner9c723192005-05-08 20:57:04 +0000140 //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
141 //<< Rank << "\n");
Jeff Cohen00b168892005-07-27 06:12:32 +0000142
Chris Lattnercc8a2b92005-05-08 00:08:33 +0000143 return CachedRank = Rank;
Chris Lattner4fd56002002-05-08 22:19:27 +0000144}
145
Chris Lattnerc0649ac2005-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 Lattner4fd56002002-05-08 22:19:27 +0000154
Chris Lattnerf33151a2005-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 Lattnerc0649ac2005-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 Cohen00b168892005-07-27 06:12:32 +0000179 assert(isReassociableOp(LHS, I->getOpcode()) &&
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000180 isReassociableOp(RHS, I->getOpcode()) &&
181 "Not an expression that needs linearization?");
Misha Brukmanfd939082005-04-21 23:48:37 +0000182
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000183 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
Chris Lattner4fd56002002-05-08 22:19:27 +0000184
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000185 // Move the RHS instruction to live immediately before I, avoiding breaking
186 // dominator properties.
Chris Lattner4bc5f802005-08-08 19:11:57 +0000187 RHS->moveBefore(I);
Chris Lattnere4b73042002-10-31 17:12:59 +0000188
Chris Lattnerc0649ac2005-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 Cohen00b168892005-07-27 06:12:32 +0000193
Chris Lattnerc0649ac2005-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 Lattnerf33151a2005-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 Lattnerc0649ac2005-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 Lattner4fd56002002-05-08 22:19:27 +0000256 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000257
Chris Lattnerc0649ac2005-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 Lattner4fd56002002-05-08 22:19:27 +0000261
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000262 // Move LHS right before I to make sure that the tree expression dominates all
263 // values.
Chris Lattner4bc5f802005-08-08 19:11:57 +0000264 LHSBO->moveBefore(I);
Chris Lattnere9608e32003-08-12 21:45:24 +0000265
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000266 // Linearize the expression tree on the LHS.
267 LinearizeExprTree(LHSBO, Ops);
Chris Lattnere4b73042002-10-31 17:12:59 +0000268
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000269 // Remember the RHS operand and its rank.
270 Ops.push_back(ValueEntry(getRank(RHS), RHS));
Chris Lattner4fd56002002-05-08 22:19:27 +0000271}
272
Chris Lattnerc0649ac2005-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 Lattner4fd56002002-05-08 22:19:27 +0000303
Chris Lattnera36e6c82002-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 Lattner08b43922005-05-07 04:08:02 +0000309static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattnera36e6c82002-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 Brukman5560c9d2003-08-18 14:43:39 +0000317 // we introduce tons of unnecessary negation instructions...
Chris Lattnera36e6c82002-05-16 04:37:07 +0000318 //
319 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerfd059242003-10-15 16:48:29 +0000320 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner2cd85da2005-09-02 06:38:04 +0000321 // Push the negates through the add.
322 I->setOperand(0, NegateValue(I->getOperand(0), BI));
323 I->setOperand(1, NegateValue(I->getOperand(1), BI));
Chris Lattnera36e6c82002-05-16 04:37:07 +0000324
Chris Lattner2cd85da2005-09-02 06:38:04 +0000325 // We must move the add instruction here, because the neg instructions do
326 // not dominate the old add instruction in general. By moving it, we are
327 // assured that the neg instructions we just inserted dominate the
328 // instruction we are about to insert after them.
Chris Lattnera36e6c82002-05-16 04:37:07 +0000329 //
Chris Lattner2cd85da2005-09-02 06:38:04 +0000330 I->moveBefore(BI);
331 I->setName(I->getName()+".neg");
332 return I;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000333 }
334
335 // Insert a 'neg' instruction that subtracts the value from zero to get the
336 // negation.
337 //
Chris Lattner08b43922005-05-07 04:08:02 +0000338 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
339}
340
Chris Lattner08b43922005-05-07 04:08:02 +0000341/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
342/// only used by an add, transform this into (X+(0-Y)) to promote better
343/// reassociation.
344static Instruction *BreakUpSubtract(Instruction *Sub) {
Chris Lattner08b43922005-05-07 04:08:02 +0000345 // Don't bother to break this up unless either the LHS is an associable add or
346 // if this is only used by one.
347 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
348 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
349 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
350 return 0;
351
352 // Convert a subtract into an add and a neg instruction... so that sub
353 // instructions can be commuted with other add instructions...
354 //
355 // Calculate the negative value of Operand 1 of the sub instruction...
356 // and set it as the RHS of the add instruction we just made...
357 //
358 std::string Name = Sub->getName();
359 Sub->setName("");
360 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
361 Instruction *New =
362 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
363
364 // Everyone now refers to the add instruction.
365 Sub->replaceAllUsesWith(New);
366 Sub->eraseFromParent();
Jeff Cohen00b168892005-07-27 06:12:32 +0000367
Chris Lattner08b43922005-05-07 04:08:02 +0000368 DEBUG(std::cerr << "Negated: " << *New);
369 return New;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000370}
371
Chris Lattner0975ed52005-05-07 04:24:13 +0000372/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
373/// by one, change this into a multiply by a constant to assist with further
374/// reassociation.
375static Instruction *ConvertShiftToMul(Instruction *Shl) {
376 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
377 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
378 return 0;
379
380 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
381 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
382
383 std::string Name = Shl->getName(); Shl->setName("");
384 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
385 Name, Shl);
386 Shl->replaceAllUsesWith(Mul);
387 Shl->eraseFromParent();
388 return Mul;
389}
390
Chris Lattner109d34d2005-05-08 18:59:37 +0000391// Scan backwards and forwards among values with the same rank as element i to
392// see if X exists. If X does not exist, return i.
393static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
394 Value *X) {
395 unsigned XRank = Ops[i].Rank;
396 unsigned e = Ops.size();
397 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
398 if (Ops[j].Op == X)
399 return j;
400 // Scan backwards
401 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
402 if (Ops[j].Op == X)
403 return j;
404 return i;
405}
406
Chris Lattner46900102005-05-08 00:19:31 +0000407void Reassociate::OptimizeExpression(unsigned Opcode,
408 std::vector<ValueEntry> &Ops) {
409 // Now that we have the linearized expression tree, try to optimize it.
410 // Start by folding any constants that we found.
Chris Lattner109d34d2005-05-08 18:59:37 +0000411 bool IterateOptimization = false;
Chris Lattner46900102005-05-08 00:19:31 +0000412 if (Ops.size() == 1) return;
413
414 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
415 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
416 Ops.pop_back();
417 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
Chris Lattner989f6222005-05-08 19:48:43 +0000418 OptimizeExpression(Opcode, Ops);
419 return;
Chris Lattner46900102005-05-08 00:19:31 +0000420 }
421
422 // Check for destructive annihilation due to a constant being used.
423 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
424 switch (Opcode) {
425 default: break;
426 case Instruction::And:
427 if (CstVal->isNullValue()) { // ... & 0 -> 0
428 Ops[0].Op = CstVal;
429 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner109d34d2005-05-08 18:59:37 +0000430 ++NumAnnihil;
431 return;
Chris Lattner46900102005-05-08 00:19:31 +0000432 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
433 Ops.pop_back();
434 }
435 break;
436 case Instruction::Mul:
437 if (CstVal->isNullValue()) { // ... * 0 -> 0
438 Ops[0].Op = CstVal;
439 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner109d34d2005-05-08 18:59:37 +0000440 ++NumAnnihil;
441 return;
Chris Lattner46900102005-05-08 00:19:31 +0000442 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
443 Ops.pop_back(); // ... * 1 -> ...
444 }
445 break;
446 case Instruction::Or:
447 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
448 Ops[0].Op = CstVal;
449 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner109d34d2005-05-08 18:59:37 +0000450 ++NumAnnihil;
451 return;
Chris Lattner46900102005-05-08 00:19:31 +0000452 }
453 // FALLTHROUGH!
454 case Instruction::Add:
455 case Instruction::Xor:
456 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
457 Ops.pop_back();
458 break;
459 }
Chris Lattner368a3aa2005-09-02 05:23:22 +0000460 if (Ops.size() == 1) return;
Chris Lattner46900102005-05-08 00:19:31 +0000461
462 // Handle destructive annihilation do to identities between elements in the
463 // argument list here.
Chris Lattner109d34d2005-05-08 18:59:37 +0000464 switch (Opcode) {
465 default: break;
466 case Instruction::And:
467 case Instruction::Or:
468 case Instruction::Xor:
469 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
470 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
471 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
472 // First, check for X and ~X in the operand list.
Chris Lattner368a3aa2005-09-02 05:23:22 +0000473 assert(i < Ops.size());
Chris Lattner109d34d2005-05-08 18:59:37 +0000474 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
475 Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
476 unsigned FoundX = FindInOperandList(Ops, i, X);
477 if (FoundX != i) {
478 if (Opcode == Instruction::And) { // ...&X&~X = 0
479 Ops[0].Op = Constant::getNullValue(X->getType());
480 Ops.erase(Ops.begin()+1, Ops.end());
481 ++NumAnnihil;
482 return;
483 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1
484 Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType());
485 Ops.erase(Ops.begin()+1, Ops.end());
486 ++NumAnnihil;
487 return;
488 }
489 }
490 }
491
492 // Next, check for duplicate pairs of values, which we assume are next to
493 // each other, due to our sorting criteria.
Chris Lattner368a3aa2005-09-02 05:23:22 +0000494 assert(i < Ops.size());
Chris Lattner109d34d2005-05-08 18:59:37 +0000495 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
496 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
497 // Drop duplicate values.
498 Ops.erase(Ops.begin()+i);
499 --i; --e;
500 IterateOptimization = true;
501 ++NumAnnihil;
502 } else {
503 assert(Opcode == Instruction::Xor);
Chris Lattnerac83b032005-08-24 17:55:32 +0000504 if (e == 2) {
505 Ops[0].Op = Constant::getNullValue(Ops[0].Op->getType());
506 Ops.erase(Ops.begin()+1, Ops.end());
507 ++NumAnnihil;
508 return;
509 }
Chris Lattner109d34d2005-05-08 18:59:37 +0000510 // ... X^X -> ...
511 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
Chris Lattnerac83b032005-08-24 17:55:32 +0000512 i -= 1; e -= 2;
Chris Lattner109d34d2005-05-08 18:59:37 +0000513 IterateOptimization = true;
514 ++NumAnnihil;
515 }
516 }
517 }
518 break;
519
520 case Instruction::Add:
521 // Scan the operand lists looking for X and -X pairs. If we find any, we
522 // can simplify the expression. X+-X == 0
523 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Chris Lattner368a3aa2005-09-02 05:23:22 +0000524 assert(i < Ops.size());
Chris Lattner109d34d2005-05-08 18:59:37 +0000525 // Check for X and -X in the operand list.
526 if (BinaryOperator::isNeg(Ops[i].Op)) {
527 Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
528 unsigned FoundX = FindInOperandList(Ops, i, X);
529 if (FoundX != i) {
530 // Remove X and -X from the operand list.
531 if (Ops.size() == 2) {
532 Ops[0].Op = Constant::getNullValue(X->getType());
Chris Lattner368a3aa2005-09-02 05:23:22 +0000533 Ops.pop_back();
Chris Lattner109d34d2005-05-08 18:59:37 +0000534 ++NumAnnihil;
535 return;
536 } else {
537 Ops.erase(Ops.begin()+i);
Chris Lattner368a3aa2005-09-02 05:23:22 +0000538 if (i < FoundX)
539 --FoundX;
540 else
541 --i; // Need to back up an extra one.
Chris Lattner109d34d2005-05-08 18:59:37 +0000542 Ops.erase(Ops.begin()+FoundX);
543 IterateOptimization = true;
544 ++NumAnnihil;
Chris Lattner368a3aa2005-09-02 05:23:22 +0000545 --i; // Revisit element.
546 e -= 2; // Removed two elements.
Chris Lattner109d34d2005-05-08 18:59:37 +0000547 }
548 }
549 }
550 }
551 break;
552 //case Instruction::Mul:
553 }
554
Jeff Cohen00b168892005-07-27 06:12:32 +0000555 if (IterateOptimization)
Chris Lattner989f6222005-05-08 19:48:43 +0000556 OptimizeExpression(Opcode, Ops);
Chris Lattner46900102005-05-08 00:19:31 +0000557}
558
Chris Lattnerc9fd0972005-05-08 20:09:57 +0000559/// PrintOps - Print out the expression identified in the Ops list.
560///
561static void PrintOps(unsigned Opcode, const std::vector<ValueEntry> &Ops,
562 BasicBlock *BB) {
563 Module *M = BB->getParent()->getParent();
564 std::cerr << Instruction::getOpcodeName(Opcode) << " "
565 << *Ops[0].Op->getType();
566 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
567 WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M)
568 << "," << Ops[i].Rank;
569}
Chris Lattnera36e6c82002-05-16 04:37:07 +0000570
Chris Lattner08b43922005-05-07 04:08:02 +0000571/// ReassociateBB - Inspect all of the instructions in this basic block,
572/// reassociating them as we go.
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000573void Reassociate::ReassociateBB(BasicBlock *BB) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000574 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattner641f02f2005-05-10 03:39:25 +0000575 if (BI->getOpcode() == Instruction::Shl &&
576 isa<ConstantInt>(BI->getOperand(1)))
577 if (Instruction *NI = ConvertShiftToMul(BI)) {
578 MadeChange = true;
579 BI = NI;
580 }
581
Chris Lattner6f156852005-05-08 21:33:47 +0000582 // Reject cases where it is pointless to do this.
583 if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint())
584 continue; // Floating point ops are not associative.
585
Chris Lattner08b43922005-05-07 04:08:02 +0000586 // If this is a subtract instruction which is not already in negate form,
587 // see if we can convert it to X+-Y.
Chris Lattnerf33151a2005-05-08 21:28:52 +0000588 if (BI->getOpcode() == Instruction::Sub) {
589 if (!BinaryOperator::isNeg(BI)) {
590 if (Instruction *NI = BreakUpSubtract(BI)) {
591 MadeChange = true;
592 BI = NI;
593 }
594 } else {
595 // Otherwise, this is a negation. See if the operand is a multiply tree
596 // and if this is not an inner node of a multiply tree.
597 if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
598 (!BI->hasOneUse() ||
599 !isReassociableOp(BI->use_back(), Instruction::Mul))) {
600 BI = LowerNegateToMultiply(BI);
601 MadeChange = true;
602 }
Chris Lattner08b43922005-05-07 04:08:02 +0000603 }
Chris Lattnerf33151a2005-05-08 21:28:52 +0000604 }
Chris Lattnere4b73042002-10-31 17:12:59 +0000605
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000606 // If this instruction is a commutative binary operator, process it.
607 if (!BI->isAssociative()) continue;
608 BinaryOperator *I = cast<BinaryOperator>(BI);
Jeff Cohen00b168892005-07-27 06:12:32 +0000609
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000610 // If this is an interior node of a reassociable tree, ignore it until we
611 // get to the root of the tree, to avoid N^2 analysis.
612 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
613 continue;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000614
Chris Lattner7b4ad942005-09-02 07:07:58 +0000615 // If this is an add tree that is used by a sub instruction, ignore it
616 // until we process the subtract.
617 if (I->hasOneUse() && I->getOpcode() == Instruction::Add &&
618 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub)
619 continue;
620
Jeff Cohen00b168892005-07-27 06:12:32 +0000621 // First, walk the expression tree, linearizing the tree, collecting
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000622 std::vector<ValueEntry> Ops;
623 LinearizeExprTree(I, Ops);
624
Chris Lattnerc9fd0972005-05-08 20:09:57 +0000625 DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB);
626 std::cerr << "\n");
627
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000628 // Now that we have linearized the tree to a list and have gathered all of
629 // the operands and their ranks, sort the operands by their rank. Use a
630 // stable_sort so that values with equal ranks will have their relative
631 // positions maintained (and so the compiler is deterministic). Note that
632 // this sorts so that the highest ranking values end up at the beginning of
633 // the vector.
634 std::stable_sort(Ops.begin(), Ops.end());
635
Chris Lattner46900102005-05-08 00:19:31 +0000636 // OptimizeExpression - Now that we have the expression tree in a convenient
637 // sorted form, optimize it globally if possible.
638 OptimizeExpression(I->getOpcode(), Ops);
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000639
Chris Lattner44b8c7d2005-05-08 21:41:35 +0000640 // We want to sink immediates as deeply as possible except in the case where
641 // this is a multiply tree used only by an add, and the immediate is a -1.
642 // In this case we reassociate to put the negation on the outside so that we
643 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
Jeff Cohen00b168892005-07-27 06:12:32 +0000644 if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
Chris Lattner44b8c7d2005-05-08 21:41:35 +0000645 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
646 isa<ConstantInt>(Ops.back().Op) &&
647 cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
648 Ops.insert(Ops.begin(), Ops.back());
649 Ops.pop_back();
650 }
651
Chris Lattnerc9fd0972005-05-08 20:09:57 +0000652 DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB);
653 std::cerr << "\n");
654
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000655 if (Ops.size() == 1) {
656 // This expression tree simplified to something that isn't a tree,
657 // eliminate it.
658 I->replaceAllUsesWith(Ops[0].Op);
659 } else {
660 // Now that we ordered and optimized the expressions, splat them back into
661 // the expression tree, removing any unneeded nodes.
662 RewriteExprTree(I, 0, Ops);
Chris Lattner4fd56002002-05-08 22:19:27 +0000663 }
664 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000665}
666
667
Chris Lattner7e708292002-06-25 16:13:24 +0000668bool Reassociate::runOnFunction(Function &F) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000669 // Recalculate the rank map for F
670 BuildRankMap(F);
671
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000672 MadeChange = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000673 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000674 ReassociateBB(FI);
Chris Lattner4fd56002002-05-08 22:19:27 +0000675
676 // We are done with the rank map...
677 RankMap.clear();
Chris Lattnerfb5be092003-08-13 16:16:26 +0000678 ValueRankMap.clear();
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000679 return MadeChange;
Chris Lattner4fd56002002-05-08 22:19:27 +0000680}
Brian Gaeked0fde302003-11-11 22:41:34 +0000681