blob: ffa7c84c6cca823a665cf9b92504d3b86050e331 [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 Lattner113f4f42002-06-25 16:13:24 +000080void Reassociate::BuildRankMap(Function &F) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000081 unsigned i = 2;
Chris Lattner8ac196d2003-08-13 16:16:26 +000082
83 // Assign distinct ranks to function arguments
Chris Lattner531f9e92005-03-15 04:54:21 +000084 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner8ac196d2003-08-13 16:16:26 +000085 ValueRankMap[I] = ++i;
86
Chris Lattner113f4f42002-06-25 16:13:24 +000087 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000088 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
89 E = RPOT.end(); I != E; ++I)
Chris Lattner58c7eb62003-08-12 20:14:27 +000090 RankMap[*I] = ++i << 16;
Chris Lattnerc0f58002002-05-08 22:19:27 +000091}
92
93unsigned Reassociate::getRank(Value *V) {
Chris Lattner8ac196d2003-08-13 16:16:26 +000094 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
95
Chris Lattnerf43e9742005-05-07 04:08:02 +000096 Instruction *I = dyn_cast<Instruction>(V);
97 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
Chris Lattnerc0f58002002-05-08 22:19:27 +000098
Chris Lattnerf43e9742005-05-07 04:08:02 +000099 unsigned &CachedRank = ValueRankMap[I];
100 if (CachedRank) return CachedRank; // Rank already known?
101
102 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
103 // we can reassociate expressions for code motion! Since we do not recurse
104 // for PHI nodes, we cannot have infinite recursion here, because there
105 // cannot be loops in the value graph that do not go through PHI nodes.
106 //
107 if (I->getOpcode() == Instruction::PHI ||
108 I->getOpcode() == Instruction::Alloca ||
109 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
110 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
111 return RankMap[I->getParent()];
112
113 // If not, compute it!
114 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
115 for (unsigned i = 0, e = I->getNumOperands();
116 i != e && Rank != MaxRank; ++i)
117 Rank = std::max(Rank, getRank(I->getOperand(i)));
118
Chris Lattner6e2086d2005-05-08 00:08:33 +0000119 // If this is a not or neg instruction, do not count it for rank. This
120 // assures us that X and ~X will have the same rank.
121 if (!I->getType()->isIntegral() ||
122 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
123 ++Rank;
124
Chris Lattnerf43e9742005-05-07 04:08:02 +0000125 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
Chris Lattner6e2086d2005-05-08 00:08:33 +0000126 << Rank << "\n");
Chris Lattnerf43e9742005-05-07 04:08:02 +0000127
Chris Lattner6e2086d2005-05-08 00:08:33 +0000128 return CachedRank = Rank;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000129}
130
Chris Lattner1e506502005-05-07 21:59:39 +0000131/// isReassociableOp - Return true if V is an instruction of the specified
132/// opcode and if it only has one use.
133static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
134 if (V->hasOneUse() && isa<Instruction>(V) &&
135 cast<Instruction>(V)->getOpcode() == Opcode)
136 return cast<BinaryOperator>(V);
137 return 0;
138}
Chris Lattnerc0f58002002-05-08 22:19:27 +0000139
Chris Lattner1e506502005-05-07 21:59:39 +0000140// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
141// Note that if D is also part of the expression tree that we recurse to
142// linearize it as well. Besides that case, this does not recurse into A,B, or
143// C.
144void Reassociate::LinearizeExpr(BinaryOperator *I) {
145 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
146 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
147 assert(isReassociableOp(LHS, I->getOpcode()) &&
148 isReassociableOp(RHS, I->getOpcode()) &&
149 "Not an expression that needs linearization?");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000150
Chris Lattner1e506502005-05-07 21:59:39 +0000151 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000152
Chris Lattner1e506502005-05-07 21:59:39 +0000153 // Move the RHS instruction to live immediately before I, avoiding breaking
154 // dominator properties.
155 I->getParent()->getInstList().splice(I, RHS->getParent()->getInstList(), RHS);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000156
Chris Lattner1e506502005-05-07 21:59:39 +0000157 // Move operands around to do the linearization.
158 I->setOperand(1, RHS->getOperand(0));
159 RHS->setOperand(0, LHS);
160 I->setOperand(0, RHS);
161
162 ++NumLinear;
163 MadeChange = true;
164 DEBUG(std::cerr << "Linearized: " << *I);
165
166 // If D is part of this expression tree, tail recurse.
167 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
168 LinearizeExpr(I);
169}
170
171
172/// LinearizeExprTree - Given an associative binary expression tree, traverse
173/// all of the uses putting it into canonical form. This forces a left-linear
174/// form of the the expression (((a+b)+c)+d), and collects information about the
175/// rank of the non-tree operands.
176///
177/// This returns the rank of the RHS operand, which is known to be the highest
178/// rank value in the expression tree.
179///
180void Reassociate::LinearizeExprTree(BinaryOperator *I,
181 std::vector<ValueEntry> &Ops) {
182 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
183 unsigned Opcode = I->getOpcode();
184
185 // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
186 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
187 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
188
189 if (!LHSBO) {
190 if (!RHSBO) {
191 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As
192 // such, just remember these operands and their rank.
193 Ops.push_back(ValueEntry(getRank(LHS), LHS));
194 Ops.push_back(ValueEntry(getRank(RHS), RHS));
195 return;
196 } else {
197 // Turn X+(Y+Z) -> (Y+Z)+X
198 std::swap(LHSBO, RHSBO);
199 std::swap(LHS, RHS);
200 bool Success = !I->swapOperands();
201 assert(Success && "swapOperands failed");
202 MadeChange = true;
203 }
204 } else if (RHSBO) {
205 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
206 // part of the expression tree.
207 LinearizeExpr(I);
208 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
209 RHS = I->getOperand(1);
210 RHSBO = 0;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000211 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212
Chris Lattner1e506502005-05-07 21:59:39 +0000213 // Okay, now we know that the LHS is a nested expression and that the RHS is
214 // not. Perform reassociation.
215 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
Chris Lattnerc0f58002002-05-08 22:19:27 +0000216
Chris Lattner1e506502005-05-07 21:59:39 +0000217 // Move LHS right before I to make sure that the tree expression dominates all
218 // values.
219 I->getParent()->getInstList().splice(I,
220 LHSBO->getParent()->getInstList(), LHSBO);
Chris Lattner98b3ecd2003-08-12 21:45:24 +0000221
Chris Lattner1e506502005-05-07 21:59:39 +0000222 // Linearize the expression tree on the LHS.
223 LinearizeExprTree(LHSBO, Ops);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000224
Chris Lattner1e506502005-05-07 21:59:39 +0000225 // Remember the RHS operand and its rank.
226 Ops.push_back(ValueEntry(getRank(RHS), RHS));
Chris Lattnerc0f58002002-05-08 22:19:27 +0000227}
228
Chris Lattner1e506502005-05-07 21:59:39 +0000229// RewriteExprTree - Now that the operands for this expression tree are
230// linearized and optimized, emit them in-order. This function is written to be
231// tail recursive.
232void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
233 std::vector<ValueEntry> &Ops) {
234 if (i+2 == Ops.size()) {
235 if (I->getOperand(0) != Ops[i].Op ||
236 I->getOperand(1) != Ops[i+1].Op) {
237 DEBUG(std::cerr << "RA: " << *I);
238 I->setOperand(0, Ops[i].Op);
239 I->setOperand(1, Ops[i+1].Op);
240 DEBUG(std::cerr << "TO: " << *I);
241 MadeChange = true;
242 ++NumChanged;
243 }
244 return;
245 }
246 assert(i+2 < Ops.size() && "Ops index out of range!");
247
248 if (I->getOperand(1) != Ops[i].Op) {
249 DEBUG(std::cerr << "RA: " << *I);
250 I->setOperand(1, Ops[i].Op);
251 DEBUG(std::cerr << "TO: " << *I);
252 MadeChange = true;
253 ++NumChanged;
254 }
255 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
256}
257
258
Chris Lattnerc0f58002002-05-08 22:19:27 +0000259
Chris Lattner7bc532d2002-05-16 04:37:07 +0000260// NegateValue - Insert instructions before the instruction pointed to by BI,
261// that computes the negative version of the value specified. The negative
262// version of the value is returned, and BI is left pointing at the instruction
263// that should be processed next by the reassociation pass.
264//
Chris Lattnerf43e9742005-05-07 04:08:02 +0000265static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000266 // We are trying to expose opportunity for reassociation. One of the things
267 // that we want to do to achieve this is to push a negation as deep into an
268 // expression chain as possible, to expose the add instructions. In practice,
269 // this means that we turn this:
270 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
271 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
272 // the constants. We assume that instcombine will clean up the mess later if
Misha Brukman7eb05a12003-08-18 14:43:39 +0000273 // we introduce tons of unnecessary negation instructions...
Chris Lattner7bc532d2002-05-16 04:37:07 +0000274 //
275 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000276 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000277 Value *RHS = NegateValue(I->getOperand(1), BI);
278 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000279
280 // We must actually insert a new add instruction here, because the neg
281 // instructions do not dominate the old add instruction in general. By
282 // adding it now, we are assured that the neg instructions we just
283 // inserted dominate the instruction we are about to insert after them.
284 //
Chris Lattner28a8d242002-09-10 17:04:02 +0000285 return BinaryOperator::create(Instruction::Add, LHS, RHS,
Chris Lattnerf43e9742005-05-07 04:08:02 +0000286 I->getName()+".neg", BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000287 }
288
289 // Insert a 'neg' instruction that subtracts the value from zero to get the
290 // negation.
291 //
Chris Lattnerf43e9742005-05-07 04:08:02 +0000292 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
293}
294
Chris Lattnerf43e9742005-05-07 04:08:02 +0000295/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
296/// only used by an add, transform this into (X+(0-Y)) to promote better
297/// reassociation.
298static Instruction *BreakUpSubtract(Instruction *Sub) {
299 // Reject cases where it is pointless to do this.
300 if (Sub->getType()->isFloatingPoint())
301 return 0; // Floating point adds are not associative.
302
303 // Don't bother to break this up unless either the LHS is an associable add or
304 // if this is only used by one.
305 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
306 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
307 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
308 return 0;
309
310 // Convert a subtract into an add and a neg instruction... so that sub
311 // instructions can be commuted with other add instructions...
312 //
313 // Calculate the negative value of Operand 1 of the sub instruction...
314 // and set it as the RHS of the add instruction we just made...
315 //
316 std::string Name = Sub->getName();
317 Sub->setName("");
318 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
319 Instruction *New =
320 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
321
322 // Everyone now refers to the add instruction.
323 Sub->replaceAllUsesWith(New);
324 Sub->eraseFromParent();
325
326 DEBUG(std::cerr << "Negated: " << *New);
327 return New;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000328}
329
Chris Lattnercea57992005-05-07 04:24:13 +0000330/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
331/// by one, change this into a multiply by a constant to assist with further
332/// reassociation.
333static Instruction *ConvertShiftToMul(Instruction *Shl) {
334 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
335 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
336 return 0;
337
338 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
339 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
340
341 std::string Name = Shl->getName(); Shl->setName("");
342 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
343 Name, Shl);
344 Shl->replaceAllUsesWith(Mul);
345 Shl->eraseFromParent();
346 return Mul;
347}
348
Chris Lattner5847e5e2005-05-08 18:59:37 +0000349// Scan backwards and forwards among values with the same rank as element i to
350// see if X exists. If X does not exist, return i.
351static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
352 Value *X) {
353 unsigned XRank = Ops[i].Rank;
354 unsigned e = Ops.size();
355 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
356 if (Ops[j].Op == X)
357 return j;
358 // Scan backwards
359 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
360 if (Ops[j].Op == X)
361 return j;
362 return i;
363}
364
Chris Lattnere1850b82005-05-08 00:19:31 +0000365void Reassociate::OptimizeExpression(unsigned Opcode,
366 std::vector<ValueEntry> &Ops) {
367 // Now that we have the linearized expression tree, try to optimize it.
368 // Start by folding any constants that we found.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000369 bool IterateOptimization = false;
Chris Lattnere1850b82005-05-08 00:19:31 +0000370 if (Ops.size() == 1) return;
371
372 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
373 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
374 Ops.pop_back();
375 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
Chris Lattner08582be2005-05-08 19:48:43 +0000376 OptimizeExpression(Opcode, Ops);
377 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000378 }
379
380 // Check for destructive annihilation due to a constant being used.
381 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
382 switch (Opcode) {
383 default: break;
384 case Instruction::And:
385 if (CstVal->isNullValue()) { // ... & 0 -> 0
386 Ops[0].Op = CstVal;
387 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000388 ++NumAnnihil;
389 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000390 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
391 Ops.pop_back();
392 }
393 break;
394 case Instruction::Mul:
395 if (CstVal->isNullValue()) { // ... * 0 -> 0
396 Ops[0].Op = CstVal;
397 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000398 ++NumAnnihil;
399 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000400 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
401 Ops.pop_back(); // ... * 1 -> ...
402 }
403 break;
404 case Instruction::Or:
405 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
406 Ops[0].Op = CstVal;
407 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000408 ++NumAnnihil;
409 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000410 }
411 // FALLTHROUGH!
412 case Instruction::Add:
413 case Instruction::Xor:
414 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
415 Ops.pop_back();
416 break;
417 }
418
419 // Handle destructive annihilation do to identities between elements in the
420 // argument list here.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000421 switch (Opcode) {
422 default: break;
423 case Instruction::And:
424 case Instruction::Or:
425 case Instruction::Xor:
426 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
427 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
428 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
429 // First, check for X and ~X in the operand list.
430 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
431 Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
432 unsigned FoundX = FindInOperandList(Ops, i, X);
433 if (FoundX != i) {
434 if (Opcode == Instruction::And) { // ...&X&~X = 0
435 Ops[0].Op = Constant::getNullValue(X->getType());
436 Ops.erase(Ops.begin()+1, Ops.end());
437 ++NumAnnihil;
438 return;
439 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1
440 Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType());
441 Ops.erase(Ops.begin()+1, Ops.end());
442 ++NumAnnihil;
443 return;
444 }
445 }
446 }
447
448 // Next, check for duplicate pairs of values, which we assume are next to
449 // each other, due to our sorting criteria.
450 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
451 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
452 // Drop duplicate values.
453 Ops.erase(Ops.begin()+i);
454 --i; --e;
455 IterateOptimization = true;
456 ++NumAnnihil;
457 } else {
458 assert(Opcode == Instruction::Xor);
459 // ... X^X -> ...
460 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
461 i -= 2; e -= 2;
462 IterateOptimization = true;
463 ++NumAnnihil;
464 }
465 }
466 }
467 break;
468
469 case Instruction::Add:
470 // Scan the operand lists looking for X and -X pairs. If we find any, we
471 // can simplify the expression. X+-X == 0
472 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
473 // Check for X and -X in the operand list.
474 if (BinaryOperator::isNeg(Ops[i].Op)) {
475 Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
476 unsigned FoundX = FindInOperandList(Ops, i, X);
477 if (FoundX != i) {
478 // Remove X and -X from the operand list.
479 if (Ops.size() == 2) {
480 Ops[0].Op = Constant::getNullValue(X->getType());
481 Ops.erase(Ops.begin()+1);
482 ++NumAnnihil;
483 return;
484 } else {
485 Ops.erase(Ops.begin()+i);
486 if (i < FoundX) --FoundX;
487 Ops.erase(Ops.begin()+FoundX);
488 IterateOptimization = true;
489 ++NumAnnihil;
490 }
491 }
492 }
493 }
494 break;
495 //case Instruction::Mul:
496 }
497
Chris Lattner08582be2005-05-08 19:48:43 +0000498 if (IterateOptimization)
499 OptimizeExpression(Opcode, Ops);
Chris Lattnere1850b82005-05-08 00:19:31 +0000500}
501
Chris Lattner9187f392005-05-08 20:09:57 +0000502/// PrintOps - Print out the expression identified in the Ops list.
503///
504static void PrintOps(unsigned Opcode, const std::vector<ValueEntry> &Ops,
505 BasicBlock *BB) {
506 Module *M = BB->getParent()->getParent();
507 std::cerr << Instruction::getOpcodeName(Opcode) << " "
508 << *Ops[0].Op->getType();
509 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
510 WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M)
511 << "," << Ops[i].Rank;
512}
Chris Lattner7bc532d2002-05-16 04:37:07 +0000513
Chris Lattnerf43e9742005-05-07 04:08:02 +0000514/// ReassociateBB - Inspect all of the instructions in this basic block,
515/// reassociating them as we go.
Chris Lattner1e506502005-05-07 21:59:39 +0000516void Reassociate::ReassociateBB(BasicBlock *BB) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000517 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattnerf43e9742005-05-07 04:08:02 +0000518 // If this is a subtract instruction which is not already in negate form,
519 // see if we can convert it to X+-Y.
520 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
521 if (Instruction *NI = BreakUpSubtract(BI)) {
Chris Lattner1e506502005-05-07 21:59:39 +0000522 MadeChange = true;
Chris Lattnerf43e9742005-05-07 04:08:02 +0000523 BI = NI;
524 }
Chris Lattnercea57992005-05-07 04:24:13 +0000525 if (BI->getOpcode() == Instruction::Shl &&
526 isa<ConstantInt>(BI->getOperand(1)))
527 if (Instruction *NI = ConvertShiftToMul(BI)) {
Chris Lattner1e506502005-05-07 21:59:39 +0000528 MadeChange = true;
Chris Lattnercea57992005-05-07 04:24:13 +0000529 BI = NI;
530 }
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000531
Chris Lattner1e506502005-05-07 21:59:39 +0000532 // If this instruction is a commutative binary operator, process it.
533 if (!BI->isAssociative()) continue;
534 BinaryOperator *I = cast<BinaryOperator>(BI);
535
536 // If this is an interior node of a reassociable tree, ignore it until we
537 // get to the root of the tree, to avoid N^2 analysis.
538 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
539 continue;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000540
Chris Lattner1e506502005-05-07 21:59:39 +0000541 // First, walk the expression tree, linearizing the tree, collecting
542 std::vector<ValueEntry> Ops;
543 LinearizeExprTree(I, Ops);
544
Chris Lattner9187f392005-05-08 20:09:57 +0000545 DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB);
546 std::cerr << "\n");
547
Chris Lattner1e506502005-05-07 21:59:39 +0000548 // Now that we have linearized the tree to a list and have gathered all of
549 // the operands and their ranks, sort the operands by their rank. Use a
550 // stable_sort so that values with equal ranks will have their relative
551 // positions maintained (and so the compiler is deterministic). Note that
552 // this sorts so that the highest ranking values end up at the beginning of
553 // the vector.
554 std::stable_sort(Ops.begin(), Ops.end());
555
Chris Lattnere1850b82005-05-08 00:19:31 +0000556 // OptimizeExpression - Now that we have the expression tree in a convenient
557 // sorted form, optimize it globally if possible.
558 OptimizeExpression(I->getOpcode(), Ops);
Chris Lattner1e506502005-05-07 21:59:39 +0000559
Chris Lattner9187f392005-05-08 20:09:57 +0000560 DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB);
561 std::cerr << "\n");
562
Chris Lattner1e506502005-05-07 21:59:39 +0000563 if (Ops.size() == 1) {
564 // This expression tree simplified to something that isn't a tree,
565 // eliminate it.
566 I->replaceAllUsesWith(Ops[0].Op);
567 } else {
568 // Now that we ordered and optimized the expressions, splat them back into
569 // the expression tree, removing any unneeded nodes.
570 RewriteExprTree(I, 0, Ops);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000571 }
572 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000573}
574
575
Chris Lattner113f4f42002-06-25 16:13:24 +0000576bool Reassociate::runOnFunction(Function &F) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000577 // Recalculate the rank map for F
578 BuildRankMap(F);
579
Chris Lattner1e506502005-05-07 21:59:39 +0000580 MadeChange = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000581 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
Chris Lattner1e506502005-05-07 21:59:39 +0000582 ReassociateBB(FI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000583
584 // We are done with the rank map...
585 RankMap.clear();
Chris Lattner8ac196d2003-08-13 16:16:26 +0000586 ValueRankMap.clear();
Chris Lattner1e506502005-05-07 21:59:39 +0000587 return MadeChange;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000588}
Brian Gaeke960707c2003-11-11 22:41:34 +0000589