blob: 41faae74962b9d85b30e568998b8658d3e63d98c [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 Lattnerdac58ad2006-01-22 23:32:06 +000036#include <iostream>
Chris Lattnerd7456022004-01-09 06:02:20 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Chris Lattner4fd56002002-05-08 22:19:27 +000039namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000040 Statistic<> NumLinear ("reassociate","Number of insts linearized");
41 Statistic<> NumChanged("reassociate","Number of insts reassociated");
42 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
Chris Lattner109d34d2005-05-08 18:59:37 +000043 Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated");
Chris Lattnera92f6962002-10-01 22:38:41 +000044
Chris Lattnerc0649ac2005-05-07 21:59:39 +000045 struct ValueEntry {
46 unsigned Rank;
47 Value *Op;
48 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
49 };
50 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
51 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
52 }
53
Chris Lattner4fd56002002-05-08 22:19:27 +000054 class Reassociate : public FunctionPass {
Chris Lattner0c0edf82002-07-25 06:17:51 +000055 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattnerfb5be092003-08-13 16:16:26 +000056 std::map<Value*, unsigned> ValueRankMap;
Chris Lattnerc0649ac2005-05-07 21:59:39 +000057 bool MadeChange;
Chris Lattner4fd56002002-05-08 22:19:27 +000058 public:
Chris Lattner7e708292002-06-25 16:13:24 +000059 bool runOnFunction(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000060
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000062 AU.setPreservesCFG();
Chris Lattner4fd56002002-05-08 22:19:27 +000063 }
64 private:
Chris Lattner7e708292002-06-25 16:13:24 +000065 void BuildRankMap(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000066 unsigned getRank(Value *V);
Chris Lattnerc0649ac2005-05-07 21:59:39 +000067 void RewriteExprTree(BinaryOperator *I, unsigned Idx,
68 std::vector<ValueEntry> &Ops);
Chris Lattner46900102005-05-08 00:19:31 +000069 void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
Chris Lattnerc0649ac2005-05-07 21:59:39 +000070 void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
71 void LinearizeExpr(BinaryOperator *I);
72 void ReassociateBB(BasicBlock *BB);
Chris Lattner4fd56002002-05-08 22:19:27 +000073 };
Chris Lattnerf6293092002-07-23 18:06:35 +000074
Chris Lattnera6275cc2002-07-26 21:12:46 +000075 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattner4fd56002002-05-08 22:19:27 +000076}
77
Brian Gaeked0fde302003-11-11 22:41:34 +000078// Public interface to the Reassociate pass
Chris Lattnerd7456022004-01-09 06:02:20 +000079FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
Chris Lattner4fd56002002-05-08 22:19:27 +000080
Chris Lattner9c723192005-05-08 20:57:04 +000081
82static bool isUnmovableInstruction(Instruction *I) {
83 if (I->getOpcode() == Instruction::PHI ||
84 I->getOpcode() == Instruction::Alloca ||
85 I->getOpcode() == Instruction::Load ||
86 I->getOpcode() == Instruction::Malloc ||
87 I->getOpcode() == Instruction::Invoke ||
88 I->getOpcode() == Instruction::Call ||
89 I->getOpcode() == Instruction::Div ||
90 I->getOpcode() == Instruction::Rem)
91 return true;
92 return false;
93}
94
Chris Lattner7e708292002-06-25 16:13:24 +000095void Reassociate::BuildRankMap(Function &F) {
Chris Lattner6007cb62003-08-12 20:14:27 +000096 unsigned i = 2;
Chris Lattnerfb5be092003-08-13 16:16:26 +000097
98 // Assign distinct ranks to function arguments
Chris Lattnere4d5c442005-03-15 04:54:21 +000099 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerfb5be092003-08-13 16:16:26 +0000100 ValueRankMap[I] = ++i;
101
Chris Lattner7e708292002-06-25 16:13:24 +0000102 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattner4fd56002002-05-08 22:19:27 +0000103 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
Chris Lattner9c723192005-05-08 20:57:04 +0000104 E = RPOT.end(); I != E; ++I) {
105 BasicBlock *BB = *I;
106 unsigned BBRank = RankMap[BB] = ++i << 16;
107
108 // Walk the basic block, adding precomputed ranks for any instructions that
109 // we cannot move. This ensures that the ranks for these instructions are
110 // all different in the block.
111 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
112 if (isUnmovableInstruction(I))
113 ValueRankMap[I] = ++BBRank;
114 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000115}
116
117unsigned Reassociate::getRank(Value *V) {
Chris Lattnerfb5be092003-08-13 16:16:26 +0000118 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
119
Chris Lattner08b43922005-05-07 04:08:02 +0000120 Instruction *I = dyn_cast<Instruction>(V);
121 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
Chris Lattner4fd56002002-05-08 22:19:27 +0000122
Chris Lattner08b43922005-05-07 04:08:02 +0000123 unsigned &CachedRank = ValueRankMap[I];
124 if (CachedRank) return CachedRank; // Rank already known?
Jeff Cohen00b168892005-07-27 06:12:32 +0000125
Chris Lattner08b43922005-05-07 04:08:02 +0000126 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
127 // we can reassociate expressions for code motion! Since we do not recurse
128 // for PHI nodes, we cannot have infinite recursion here, because there
129 // cannot be loops in the value graph that do not go through PHI nodes.
Chris Lattner08b43922005-05-07 04:08:02 +0000130 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
131 for (unsigned i = 0, e = I->getNumOperands();
132 i != e && Rank != MaxRank; ++i)
133 Rank = std::max(Rank, getRank(I->getOperand(i)));
Jeff Cohen00b168892005-07-27 06:12:32 +0000134
Chris Lattnercc8a2b92005-05-08 00:08:33 +0000135 // If this is a not or neg instruction, do not count it for rank. This
136 // assures us that X and ~X will have the same rank.
137 if (!I->getType()->isIntegral() ||
138 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
139 ++Rank;
140
Chris Lattner9c723192005-05-08 20:57:04 +0000141 //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
142 //<< Rank << "\n");
Jeff Cohen00b168892005-07-27 06:12:32 +0000143
Chris Lattnercc8a2b92005-05-08 00:08:33 +0000144 return CachedRank = Rank;
Chris Lattner4fd56002002-05-08 22:19:27 +0000145}
146
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000147/// isReassociableOp - Return true if V is an instruction of the specified
148/// opcode and if it only has one use.
149static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
150 if (V->hasOneUse() && isa<Instruction>(V) &&
151 cast<Instruction>(V)->getOpcode() == Opcode)
152 return cast<BinaryOperator>(V);
153 return 0;
154}
Chris Lattner4fd56002002-05-08 22:19:27 +0000155
Chris Lattnerf33151a2005-05-08 21:28:52 +0000156/// LowerNegateToMultiply - Replace 0-X with X*-1.
157///
158static Instruction *LowerNegateToMultiply(Instruction *Neg) {
159 Constant *Cst;
160 if (Neg->getType()->isFloatingPoint())
161 Cst = ConstantFP::get(Neg->getType(), -1);
162 else
163 Cst = ConstantInt::getAllOnesValue(Neg->getType());
164
165 std::string NegName = Neg->getName(); Neg->setName("");
166 Instruction *Res = BinaryOperator::createMul(Neg->getOperand(1), Cst, NegName,
167 Neg);
168 Neg->replaceAllUsesWith(Res);
169 Neg->eraseFromParent();
170 return Res;
171}
172
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000173// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
174// Note that if D is also part of the expression tree that we recurse to
175// linearize it as well. Besides that case, this does not recurse into A,B, or
176// C.
177void Reassociate::LinearizeExpr(BinaryOperator *I) {
178 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
179 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
Jeff Cohen00b168892005-07-27 06:12:32 +0000180 assert(isReassociableOp(LHS, I->getOpcode()) &&
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000181 isReassociableOp(RHS, I->getOpcode()) &&
182 "Not an expression that needs linearization?");
Misha Brukmanfd939082005-04-21 23:48:37 +0000183
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000184 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
Chris Lattner4fd56002002-05-08 22:19:27 +0000185
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000186 // Move the RHS instruction to live immediately before I, avoiding breaking
187 // dominator properties.
Chris Lattner4bc5f802005-08-08 19:11:57 +0000188 RHS->moveBefore(I);
Chris Lattnere4b73042002-10-31 17:12:59 +0000189
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000190 // Move operands around to do the linearization.
191 I->setOperand(1, RHS->getOperand(0));
192 RHS->setOperand(0, LHS);
193 I->setOperand(0, RHS);
Jeff Cohen00b168892005-07-27 06:12:32 +0000194
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000195 ++NumLinear;
196 MadeChange = true;
197 DEBUG(std::cerr << "Linearized: " << *I);
198
199 // If D is part of this expression tree, tail recurse.
200 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
201 LinearizeExpr(I);
202}
203
204
205/// LinearizeExprTree - Given an associative binary expression tree, traverse
206/// all of the uses putting it into canonical form. This forces a left-linear
207/// form of the the expression (((a+b)+c)+d), and collects information about the
208/// rank of the non-tree operands.
209///
210/// This returns the rank of the RHS operand, which is known to be the highest
211/// rank value in the expression tree.
212///
213void Reassociate::LinearizeExprTree(BinaryOperator *I,
214 std::vector<ValueEntry> &Ops) {
215 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
216 unsigned Opcode = I->getOpcode();
217
218 // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
219 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
220 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
221
Chris Lattnerf33151a2005-05-08 21:28:52 +0000222 // If this is a multiply expression tree and it contains internal negations,
223 // transform them into multiplies by -1 so they can be reassociated.
224 if (I->getOpcode() == Instruction::Mul) {
225 if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
226 LHS = LowerNegateToMultiply(cast<Instruction>(LHS));
227 LHSBO = isReassociableOp(LHS, Opcode);
228 }
229 if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
230 RHS = LowerNegateToMultiply(cast<Instruction>(RHS));
231 RHSBO = isReassociableOp(RHS, Opcode);
232 }
233 }
234
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000235 if (!LHSBO) {
236 if (!RHSBO) {
237 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As
238 // such, just remember these operands and their rank.
239 Ops.push_back(ValueEntry(getRank(LHS), LHS));
240 Ops.push_back(ValueEntry(getRank(RHS), RHS));
241 return;
242 } else {
243 // Turn X+(Y+Z) -> (Y+Z)+X
244 std::swap(LHSBO, RHSBO);
245 std::swap(LHS, RHS);
246 bool Success = !I->swapOperands();
247 assert(Success && "swapOperands failed");
248 MadeChange = true;
249 }
250 } else if (RHSBO) {
251 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
252 // part of the expression tree.
253 LinearizeExpr(I);
254 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
255 RHS = I->getOperand(1);
256 RHSBO = 0;
Chris Lattner4fd56002002-05-08 22:19:27 +0000257 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000258
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000259 // Okay, now we know that the LHS is a nested expression and that the RHS is
260 // not. Perform reassociation.
261 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
Chris Lattner4fd56002002-05-08 22:19:27 +0000262
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000263 // Move LHS right before I to make sure that the tree expression dominates all
264 // values.
Chris Lattner4bc5f802005-08-08 19:11:57 +0000265 LHSBO->moveBefore(I);
Chris Lattnere9608e32003-08-12 21:45:24 +0000266
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000267 // Linearize the expression tree on the LHS.
268 LinearizeExprTree(LHSBO, Ops);
Chris Lattnere4b73042002-10-31 17:12:59 +0000269
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000270 // Remember the RHS operand and its rank.
271 Ops.push_back(ValueEntry(getRank(RHS), RHS));
Chris Lattner4fd56002002-05-08 22:19:27 +0000272}
273
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000274// RewriteExprTree - Now that the operands for this expression tree are
275// linearized and optimized, emit them in-order. This function is written to be
276// tail recursive.
277void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
278 std::vector<ValueEntry> &Ops) {
279 if (i+2 == Ops.size()) {
280 if (I->getOperand(0) != Ops[i].Op ||
281 I->getOperand(1) != Ops[i+1].Op) {
282 DEBUG(std::cerr << "RA: " << *I);
283 I->setOperand(0, Ops[i].Op);
284 I->setOperand(1, Ops[i+1].Op);
285 DEBUG(std::cerr << "TO: " << *I);
286 MadeChange = true;
287 ++NumChanged;
288 }
289 return;
290 }
291 assert(i+2 < Ops.size() && "Ops index out of range!");
292
293 if (I->getOperand(1) != Ops[i].Op) {
294 DEBUG(std::cerr << "RA: " << *I);
295 I->setOperand(1, Ops[i].Op);
296 DEBUG(std::cerr << "TO: " << *I);
297 MadeChange = true;
298 ++NumChanged;
299 }
300 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
301}
302
303
Chris Lattner4fd56002002-05-08 22:19:27 +0000304
Chris Lattnera36e6c82002-05-16 04:37:07 +0000305// NegateValue - Insert instructions before the instruction pointed to by BI,
306// that computes the negative version of the value specified. The negative
307// version of the value is returned, and BI is left pointing at the instruction
308// that should be processed next by the reassociation pass.
309//
Chris Lattner08b43922005-05-07 04:08:02 +0000310static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattnera36e6c82002-05-16 04:37:07 +0000311 // We are trying to expose opportunity for reassociation. One of the things
312 // that we want to do to achieve this is to push a negation as deep into an
313 // expression chain as possible, to expose the add instructions. In practice,
314 // this means that we turn this:
315 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
316 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
317 // the constants. We assume that instcombine will clean up the mess later if
Misha Brukman5560c9d2003-08-18 14:43:39 +0000318 // we introduce tons of unnecessary negation instructions...
Chris Lattnera36e6c82002-05-16 04:37:07 +0000319 //
320 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerfd059242003-10-15 16:48:29 +0000321 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner2cd85da2005-09-02 06:38:04 +0000322 // Push the negates through the add.
323 I->setOperand(0, NegateValue(I->getOperand(0), BI));
324 I->setOperand(1, NegateValue(I->getOperand(1), BI));
Chris Lattnera36e6c82002-05-16 04:37:07 +0000325
Chris Lattner2cd85da2005-09-02 06:38:04 +0000326 // We must move the add instruction here, because the neg instructions do
327 // not dominate the old add instruction in general. By moving it, we are
328 // assured that the neg instructions we just inserted dominate the
329 // instruction we are about to insert after them.
Chris Lattnera36e6c82002-05-16 04:37:07 +0000330 //
Chris Lattner2cd85da2005-09-02 06:38:04 +0000331 I->moveBefore(BI);
332 I->setName(I->getName()+".neg");
333 return I;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000334 }
335
336 // Insert a 'neg' instruction that subtracts the value from zero to get the
337 // negation.
338 //
Chris Lattner08b43922005-05-07 04:08:02 +0000339 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
340}
341
Chris Lattner08b43922005-05-07 04:08:02 +0000342/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
343/// only used by an add, transform this into (X+(0-Y)) to promote better
344/// reassociation.
345static Instruction *BreakUpSubtract(Instruction *Sub) {
Chris Lattner08b43922005-05-07 04:08:02 +0000346 // Don't bother to break this up unless either the LHS is an associable add or
347 // if this is only used by one.
348 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
349 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
350 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
351 return 0;
352
353 // Convert a subtract into an add and a neg instruction... so that sub
354 // instructions can be commuted with other add instructions...
355 //
356 // Calculate the negative value of Operand 1 of the sub instruction...
357 // and set it as the RHS of the add instruction we just made...
358 //
359 std::string Name = Sub->getName();
360 Sub->setName("");
361 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
362 Instruction *New =
363 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
364
365 // Everyone now refers to the add instruction.
366 Sub->replaceAllUsesWith(New);
367 Sub->eraseFromParent();
Jeff Cohen00b168892005-07-27 06:12:32 +0000368
Chris Lattner08b43922005-05-07 04:08:02 +0000369 DEBUG(std::cerr << "Negated: " << *New);
370 return New;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000371}
372
Chris Lattner0975ed52005-05-07 04:24:13 +0000373/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
374/// by one, change this into a multiply by a constant to assist with further
375/// reassociation.
376static Instruction *ConvertShiftToMul(Instruction *Shl) {
377 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
378 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
379 return 0;
380
381 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
382 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
383
384 std::string Name = Shl->getName(); Shl->setName("");
385 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
386 Name, Shl);
387 Shl->replaceAllUsesWith(Mul);
388 Shl->eraseFromParent();
389 return Mul;
390}
391
Chris Lattner109d34d2005-05-08 18:59:37 +0000392// Scan backwards and forwards among values with the same rank as element i to
393// see if X exists. If X does not exist, return i.
394static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
395 Value *X) {
396 unsigned XRank = Ops[i].Rank;
397 unsigned e = Ops.size();
398 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
399 if (Ops[j].Op == X)
400 return j;
401 // Scan backwards
402 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
403 if (Ops[j].Op == X)
404 return j;
405 return i;
406}
407
Chris Lattner46900102005-05-08 00:19:31 +0000408void Reassociate::OptimizeExpression(unsigned Opcode,
409 std::vector<ValueEntry> &Ops) {
410 // Now that we have the linearized expression tree, try to optimize it.
411 // Start by folding any constants that we found.
Chris Lattner109d34d2005-05-08 18:59:37 +0000412 bool IterateOptimization = false;
Chris Lattner46900102005-05-08 00:19:31 +0000413 if (Ops.size() == 1) return;
414
415 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
416 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
417 Ops.pop_back();
418 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
Chris Lattner989f6222005-05-08 19:48:43 +0000419 OptimizeExpression(Opcode, Ops);
420 return;
Chris Lattner46900102005-05-08 00:19:31 +0000421 }
422
423 // Check for destructive annihilation due to a constant being used.
424 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
425 switch (Opcode) {
426 default: break;
427 case Instruction::And:
428 if (CstVal->isNullValue()) { // ... & 0 -> 0
429 Ops[0].Op = CstVal;
430 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner109d34d2005-05-08 18:59:37 +0000431 ++NumAnnihil;
432 return;
Chris Lattner46900102005-05-08 00:19:31 +0000433 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
434 Ops.pop_back();
435 }
436 break;
437 case Instruction::Mul:
438 if (CstVal->isNullValue()) { // ... * 0 -> 0
439 Ops[0].Op = CstVal;
440 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner109d34d2005-05-08 18:59:37 +0000441 ++NumAnnihil;
442 return;
Chris Lattner46900102005-05-08 00:19:31 +0000443 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
444 Ops.pop_back(); // ... * 1 -> ...
445 }
446 break;
447 case Instruction::Or:
448 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
449 Ops[0].Op = CstVal;
450 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner109d34d2005-05-08 18:59:37 +0000451 ++NumAnnihil;
452 return;
Chris Lattner46900102005-05-08 00:19:31 +0000453 }
454 // FALLTHROUGH!
455 case Instruction::Add:
456 case Instruction::Xor:
457 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
458 Ops.pop_back();
459 break;
460 }
Chris Lattner368a3aa2005-09-02 05:23:22 +0000461 if (Ops.size() == 1) return;
Chris Lattner46900102005-05-08 00:19:31 +0000462
463 // Handle destructive annihilation do to identities between elements in the
464 // argument list here.
Chris Lattner109d34d2005-05-08 18:59:37 +0000465 switch (Opcode) {
466 default: break;
467 case Instruction::And:
468 case Instruction::Or:
469 case Instruction::Xor:
470 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
471 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
472 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
473 // First, check for X and ~X in the operand list.
Chris Lattner368a3aa2005-09-02 05:23:22 +0000474 assert(i < Ops.size());
Chris Lattner109d34d2005-05-08 18:59:37 +0000475 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
476 Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
477 unsigned FoundX = FindInOperandList(Ops, i, X);
478 if (FoundX != i) {
479 if (Opcode == Instruction::And) { // ...&X&~X = 0
480 Ops[0].Op = Constant::getNullValue(X->getType());
481 Ops.erase(Ops.begin()+1, Ops.end());
482 ++NumAnnihil;
483 return;
484 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1
485 Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType());
486 Ops.erase(Ops.begin()+1, Ops.end());
487 ++NumAnnihil;
488 return;
489 }
490 }
491 }
492
493 // Next, check for duplicate pairs of values, which we assume are next to
494 // each other, due to our sorting criteria.
Chris Lattner368a3aa2005-09-02 05:23:22 +0000495 assert(i < Ops.size());
Chris Lattner109d34d2005-05-08 18:59:37 +0000496 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
497 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
498 // Drop duplicate values.
499 Ops.erase(Ops.begin()+i);
500 --i; --e;
501 IterateOptimization = true;
502 ++NumAnnihil;
503 } else {
504 assert(Opcode == Instruction::Xor);
Chris Lattnerac83b032005-08-24 17:55:32 +0000505 if (e == 2) {
506 Ops[0].Op = Constant::getNullValue(Ops[0].Op->getType());
507 Ops.erase(Ops.begin()+1, Ops.end());
508 ++NumAnnihil;
509 return;
510 }
Chris Lattner109d34d2005-05-08 18:59:37 +0000511 // ... X^X -> ...
512 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
Chris Lattnerac83b032005-08-24 17:55:32 +0000513 i -= 1; e -= 2;
Chris Lattner109d34d2005-05-08 18:59:37 +0000514 IterateOptimization = true;
515 ++NumAnnihil;
516 }
517 }
518 }
519 break;
520
521 case Instruction::Add:
522 // Scan the operand lists looking for X and -X pairs. If we find any, we
523 // can simplify the expression. X+-X == 0
524 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Chris Lattner368a3aa2005-09-02 05:23:22 +0000525 assert(i < Ops.size());
Chris Lattner109d34d2005-05-08 18:59:37 +0000526 // Check for X and -X in the operand list.
527 if (BinaryOperator::isNeg(Ops[i].Op)) {
528 Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
529 unsigned FoundX = FindInOperandList(Ops, i, X);
530 if (FoundX != i) {
531 // Remove X and -X from the operand list.
532 if (Ops.size() == 2) {
533 Ops[0].Op = Constant::getNullValue(X->getType());
Chris Lattner368a3aa2005-09-02 05:23:22 +0000534 Ops.pop_back();
Chris Lattner109d34d2005-05-08 18:59:37 +0000535 ++NumAnnihil;
536 return;
537 } else {
538 Ops.erase(Ops.begin()+i);
Chris Lattner368a3aa2005-09-02 05:23:22 +0000539 if (i < FoundX)
540 --FoundX;
541 else
542 --i; // Need to back up an extra one.
Chris Lattner109d34d2005-05-08 18:59:37 +0000543 Ops.erase(Ops.begin()+FoundX);
544 IterateOptimization = true;
545 ++NumAnnihil;
Chris Lattner368a3aa2005-09-02 05:23:22 +0000546 --i; // Revisit element.
547 e -= 2; // Removed two elements.
Chris Lattner109d34d2005-05-08 18:59:37 +0000548 }
549 }
550 }
551 }
552 break;
553 //case Instruction::Mul:
554 }
555
Jeff Cohen00b168892005-07-27 06:12:32 +0000556 if (IterateOptimization)
Chris Lattner989f6222005-05-08 19:48:43 +0000557 OptimizeExpression(Opcode, Ops);
Chris Lattner46900102005-05-08 00:19:31 +0000558}
559
Chris Lattnerc9fd0972005-05-08 20:09:57 +0000560/// PrintOps - Print out the expression identified in the Ops list.
561///
562static void PrintOps(unsigned Opcode, const std::vector<ValueEntry> &Ops,
563 BasicBlock *BB) {
564 Module *M = BB->getParent()->getParent();
565 std::cerr << Instruction::getOpcodeName(Opcode) << " "
566 << *Ops[0].Op->getType();
567 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
568 WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M)
569 << "," << Ops[i].Rank;
570}
Chris Lattnera36e6c82002-05-16 04:37:07 +0000571
Chris Lattner08b43922005-05-07 04:08:02 +0000572/// ReassociateBB - Inspect all of the instructions in this basic block,
573/// reassociating them as we go.
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000574void Reassociate::ReassociateBB(BasicBlock *BB) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000575 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattner641f02f2005-05-10 03:39:25 +0000576 if (BI->getOpcode() == Instruction::Shl &&
577 isa<ConstantInt>(BI->getOperand(1)))
578 if (Instruction *NI = ConvertShiftToMul(BI)) {
579 MadeChange = true;
580 BI = NI;
581 }
582
Chris Lattner6f156852005-05-08 21:33:47 +0000583 // Reject cases where it is pointless to do this.
584 if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint())
585 continue; // Floating point ops are not associative.
586
Chris Lattner08b43922005-05-07 04:08:02 +0000587 // If this is a subtract instruction which is not already in negate form,
588 // see if we can convert it to X+-Y.
Chris Lattnerf33151a2005-05-08 21:28:52 +0000589 if (BI->getOpcode() == Instruction::Sub) {
590 if (!BinaryOperator::isNeg(BI)) {
591 if (Instruction *NI = BreakUpSubtract(BI)) {
592 MadeChange = true;
593 BI = NI;
594 }
595 } else {
596 // Otherwise, this is a negation. See if the operand is a multiply tree
597 // and if this is not an inner node of a multiply tree.
598 if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
599 (!BI->hasOneUse() ||
600 !isReassociableOp(BI->use_back(), Instruction::Mul))) {
601 BI = LowerNegateToMultiply(BI);
602 MadeChange = true;
603 }
Chris Lattner08b43922005-05-07 04:08:02 +0000604 }
Chris Lattnerf33151a2005-05-08 21:28:52 +0000605 }
Chris Lattnere4b73042002-10-31 17:12:59 +0000606
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000607 // If this instruction is a commutative binary operator, process it.
608 if (!BI->isAssociative()) continue;
609 BinaryOperator *I = cast<BinaryOperator>(BI);
Jeff Cohen00b168892005-07-27 06:12:32 +0000610
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000611 // If this is an interior node of a reassociable tree, ignore it until we
612 // get to the root of the tree, to avoid N^2 analysis.
613 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
614 continue;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000615
Chris Lattner7b4ad942005-09-02 07:07:58 +0000616 // If this is an add tree that is used by a sub instruction, ignore it
617 // until we process the subtract.
618 if (I->hasOneUse() && I->getOpcode() == Instruction::Add &&
619 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub)
620 continue;
621
Jeff Cohen00b168892005-07-27 06:12:32 +0000622 // First, walk the expression tree, linearizing the tree, collecting
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000623 std::vector<ValueEntry> Ops;
624 LinearizeExprTree(I, Ops);
625
Chris Lattnerc9fd0972005-05-08 20:09:57 +0000626 DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB);
627 std::cerr << "\n");
628
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000629 // Now that we have linearized the tree to a list and have gathered all of
630 // the operands and their ranks, sort the operands by their rank. Use a
631 // stable_sort so that values with equal ranks will have their relative
632 // positions maintained (and so the compiler is deterministic). Note that
633 // this sorts so that the highest ranking values end up at the beginning of
634 // the vector.
635 std::stable_sort(Ops.begin(), Ops.end());
636
Chris Lattner46900102005-05-08 00:19:31 +0000637 // OptimizeExpression - Now that we have the expression tree in a convenient
638 // sorted form, optimize it globally if possible.
639 OptimizeExpression(I->getOpcode(), Ops);
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000640
Chris Lattner44b8c7d2005-05-08 21:41:35 +0000641 // We want to sink immediates as deeply as possible except in the case where
642 // this is a multiply tree used only by an add, and the immediate is a -1.
643 // In this case we reassociate to put the negation on the outside so that we
644 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
Jeff Cohen00b168892005-07-27 06:12:32 +0000645 if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
Chris Lattner44b8c7d2005-05-08 21:41:35 +0000646 cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
647 isa<ConstantInt>(Ops.back().Op) &&
648 cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
649 Ops.insert(Ops.begin(), Ops.back());
650 Ops.pop_back();
651 }
652
Chris Lattnerc9fd0972005-05-08 20:09:57 +0000653 DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB);
654 std::cerr << "\n");
655
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000656 if (Ops.size() == 1) {
657 // This expression tree simplified to something that isn't a tree,
658 // eliminate it.
659 I->replaceAllUsesWith(Ops[0].Op);
660 } else {
661 // Now that we ordered and optimized the expressions, splat them back into
662 // the expression tree, removing any unneeded nodes.
663 RewriteExprTree(I, 0, Ops);
Chris Lattner4fd56002002-05-08 22:19:27 +0000664 }
665 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000666}
667
668
Chris Lattner7e708292002-06-25 16:13:24 +0000669bool Reassociate::runOnFunction(Function &F) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000670 // Recalculate the rank map for F
671 BuildRankMap(F);
672
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000673 MadeChange = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000674 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000675 ReassociateBB(FI);
Chris Lattner4fd56002002-05-08 22:19:27 +0000676
677 // We are done with the rank map...
678 RankMap.clear();
Chris Lattnerfb5be092003-08-13 16:16:26 +0000679 ValueRankMap.clear();
Chris Lattnerc0649ac2005-05-07 21:59:39 +0000680 return MadeChange;
Chris Lattner4fd56002002-05-08 22:19:27 +0000681}
Brian Gaeked0fde302003-11-11 22:41:34 +0000682