blob: 840b8f2e81310508d470552452277d050fcb5cd2 [file] [log] [blame]
Chris Lattnerc0f58002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerc0f58002002-05-08 22:19:27 +00009//
10// This pass reassociates commutative expressions in an order that is designed
Chris Lattner36663782003-05-02 19:26:34 +000011// to promote better constant propagation, GCSE, LICM, PRE...
Chris Lattnerc0f58002002-05-08 22:19:27 +000012//
13// For example: 4 + (x + 5) -> x + (4 + 5)
14//
Chris Lattnerc0f58002002-05-08 22:19:27 +000015// In the implementation of this algorithm, constants are assigned rank = 0,
16// function arguments are rank = 1, and other values are assigned ranks
17// corresponding to the reverse post order traversal of current function
18// (starting at 2), which effectively gives values in deep loops higher rank
19// than values not in loops.
20//
21//===----------------------------------------------------------------------===//
22
Chris Lattnerf43e9742005-05-07 04:08:02 +000023#define DEBUG_TYPE "reassociate"
Chris Lattnerc0f58002002-05-08 22:19:27 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattnercea57992005-05-07 04:24:13 +000025#include "llvm/Constants.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000026#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000027#include "llvm/Instructions.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000028#include "llvm/Pass.h"
Chris Lattnercea57992005-05-07 04:24:13 +000029#include "llvm/Type.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000030#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
32#include "llvm/ADT/PostOrderIterator.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner1e506502005-05-07 21:59:39 +000034#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000035using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000036
Chris Lattnerc0f58002002-05-08 22:19:27 +000037namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000038 Statistic<> NumLinear ("reassociate","Number of insts linearized");
39 Statistic<> NumChanged("reassociate","Number of insts reassociated");
40 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
Chris Lattner5847e5e2005-05-08 18:59:37 +000041 Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000042
Chris Lattner1e506502005-05-07 21:59:39 +000043 struct ValueEntry {
44 unsigned Rank;
45 Value *Op;
46 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
47 };
48 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
49 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
50 }
51
Chris Lattnerc0f58002002-05-08 22:19:27 +000052 class Reassociate : public FunctionPass {
Chris Lattner10073a92002-07-25 06:17:51 +000053 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner8ac196d2003-08-13 16:16:26 +000054 std::map<Value*, unsigned> ValueRankMap;
Chris Lattner1e506502005-05-07 21:59:39 +000055 bool MadeChange;
Chris Lattnerc0f58002002-05-08 22:19:27 +000056 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000057 bool runOnFunction(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000058
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000060 AU.setPreservesCFG();
Chris Lattnerc0f58002002-05-08 22:19:27 +000061 }
62 private:
Chris Lattner113f4f42002-06-25 16:13:24 +000063 void BuildRankMap(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000064 unsigned getRank(Value *V);
Chris Lattner1e506502005-05-07 21:59:39 +000065 void RewriteExprTree(BinaryOperator *I, unsigned Idx,
66 std::vector<ValueEntry> &Ops);
Chris Lattnere1850b82005-05-08 00:19:31 +000067 void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
Chris Lattner1e506502005-05-07 21:59:39 +000068 void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
69 void LinearizeExpr(BinaryOperator *I);
70 void ReassociateBB(BasicBlock *BB);
Chris Lattnerc0f58002002-05-08 22:19:27 +000071 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000072
Chris Lattnerc8b70922002-07-26 21:12:46 +000073 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattnerc0f58002002-05-08 22:19:27 +000074}
75
Brian Gaeke960707c2003-11-11 22:41:34 +000076// Public interface to the Reassociate pass
Chris Lattner49525f82004-01-09 06:02:20 +000077FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
Chris Lattnerc0f58002002-05-08 22:19:27 +000078
Chris Lattner113f4f42002-06-25 16:13:24 +000079void Reassociate::BuildRankMap(Function &F) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000080 unsigned i = 2;
Chris Lattner8ac196d2003-08-13 16:16:26 +000081
82 // Assign distinct ranks to function arguments
Chris Lattner531f9e92005-03-15 04:54:21 +000083 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner8ac196d2003-08-13 16:16:26 +000084 ValueRankMap[I] = ++i;
85
Chris Lattner113f4f42002-06-25 16:13:24 +000086 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000087 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
88 E = RPOT.end(); I != E; ++I)
Chris Lattner58c7eb62003-08-12 20:14:27 +000089 RankMap[*I] = ++i << 16;
Chris Lattnerc0f58002002-05-08 22:19:27 +000090}
91
92unsigned Reassociate::getRank(Value *V) {
Chris Lattner8ac196d2003-08-13 16:16:26 +000093 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
94
Chris Lattnerf43e9742005-05-07 04:08:02 +000095 Instruction *I = dyn_cast<Instruction>(V);
96 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
Chris Lattnerc0f58002002-05-08 22:19:27 +000097
Chris Lattnerf43e9742005-05-07 04:08:02 +000098 unsigned &CachedRank = ValueRankMap[I];
99 if (CachedRank) return CachedRank; // Rank already known?
100
101 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
102 // we can reassociate expressions for code motion! Since we do not recurse
103 // for PHI nodes, we cannot have infinite recursion here, because there
104 // cannot be loops in the value graph that do not go through PHI nodes.
105 //
106 if (I->getOpcode() == Instruction::PHI ||
107 I->getOpcode() == Instruction::Alloca ||
108 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
109 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
110 return RankMap[I->getParent()];
111
112 // If not, compute it!
113 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
114 for (unsigned i = 0, e = I->getNumOperands();
115 i != e && Rank != MaxRank; ++i)
116 Rank = std::max(Rank, getRank(I->getOperand(i)));
117
Chris Lattner6e2086d2005-05-08 00:08:33 +0000118 // If this is a not or neg instruction, do not count it for rank. This
119 // assures us that X and ~X will have the same rank.
120 if (!I->getType()->isIntegral() ||
121 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
122 ++Rank;
123
Chris Lattnerf43e9742005-05-07 04:08:02 +0000124 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
Chris Lattner6e2086d2005-05-08 00:08:33 +0000125 << Rank << "\n");
Chris Lattnerf43e9742005-05-07 04:08:02 +0000126
Chris Lattner6e2086d2005-05-08 00:08:33 +0000127 return CachedRank = Rank;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000128}
129
Chris Lattner1e506502005-05-07 21:59:39 +0000130/// isReassociableOp - Return true if V is an instruction of the specified
131/// opcode and if it only has one use.
132static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
133 if (V->hasOneUse() && isa<Instruction>(V) &&
134 cast<Instruction>(V)->getOpcode() == Opcode)
135 return cast<BinaryOperator>(V);
136 return 0;
137}
Chris Lattnerc0f58002002-05-08 22:19:27 +0000138
Chris Lattner1e506502005-05-07 21:59:39 +0000139// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
140// Note that if D is also part of the expression tree that we recurse to
141// linearize it as well. Besides that case, this does not recurse into A,B, or
142// C.
143void Reassociate::LinearizeExpr(BinaryOperator *I) {
144 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
145 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
146 assert(isReassociableOp(LHS, I->getOpcode()) &&
147 isReassociableOp(RHS, I->getOpcode()) &&
148 "Not an expression that needs linearization?");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000149
Chris Lattner1e506502005-05-07 21:59:39 +0000150 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000151
Chris Lattner1e506502005-05-07 21:59:39 +0000152 // Move the RHS instruction to live immediately before I, avoiding breaking
153 // dominator properties.
154 I->getParent()->getInstList().splice(I, RHS->getParent()->getInstList(), RHS);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000155
Chris Lattner1e506502005-05-07 21:59:39 +0000156 // Move operands around to do the linearization.
157 I->setOperand(1, RHS->getOperand(0));
158 RHS->setOperand(0, LHS);
159 I->setOperand(0, RHS);
160
161 ++NumLinear;
162 MadeChange = true;
163 DEBUG(std::cerr << "Linearized: " << *I);
164
165 // If D is part of this expression tree, tail recurse.
166 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
167 LinearizeExpr(I);
168}
169
170
171/// LinearizeExprTree - Given an associative binary expression tree, traverse
172/// all of the uses putting it into canonical form. This forces a left-linear
173/// form of the the expression (((a+b)+c)+d), and collects information about the
174/// rank of the non-tree operands.
175///
176/// This returns the rank of the RHS operand, which is known to be the highest
177/// rank value in the expression tree.
178///
179void Reassociate::LinearizeExprTree(BinaryOperator *I,
180 std::vector<ValueEntry> &Ops) {
181 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
182 unsigned Opcode = I->getOpcode();
183
184 // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
185 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
186 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
187
188 if (!LHSBO) {
189 if (!RHSBO) {
190 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As
191 // such, just remember these operands and their rank.
192 Ops.push_back(ValueEntry(getRank(LHS), LHS));
193 Ops.push_back(ValueEntry(getRank(RHS), RHS));
194 return;
195 } else {
196 // Turn X+(Y+Z) -> (Y+Z)+X
197 std::swap(LHSBO, RHSBO);
198 std::swap(LHS, RHS);
199 bool Success = !I->swapOperands();
200 assert(Success && "swapOperands failed");
201 MadeChange = true;
202 }
203 } else if (RHSBO) {
204 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
205 // part of the expression tree.
206 LinearizeExpr(I);
207 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
208 RHS = I->getOperand(1);
209 RHSBO = 0;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000210 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000211
Chris Lattner1e506502005-05-07 21:59:39 +0000212 // Okay, now we know that the LHS is a nested expression and that the RHS is
213 // not. Perform reassociation.
214 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
Chris Lattnerc0f58002002-05-08 22:19:27 +0000215
Chris Lattner1e506502005-05-07 21:59:39 +0000216 // Move LHS right before I to make sure that the tree expression dominates all
217 // values.
218 I->getParent()->getInstList().splice(I,
219 LHSBO->getParent()->getInstList(), LHSBO);
Chris Lattner98b3ecd2003-08-12 21:45:24 +0000220
Chris Lattner1e506502005-05-07 21:59:39 +0000221 // Linearize the expression tree on the LHS.
222 LinearizeExprTree(LHSBO, Ops);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000223
Chris Lattner1e506502005-05-07 21:59:39 +0000224 // Remember the RHS operand and its rank.
225 Ops.push_back(ValueEntry(getRank(RHS), RHS));
Chris Lattnerc0f58002002-05-08 22:19:27 +0000226}
227
Chris Lattner1e506502005-05-07 21:59:39 +0000228// RewriteExprTree - Now that the operands for this expression tree are
229// linearized and optimized, emit them in-order. This function is written to be
230// tail recursive.
231void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
232 std::vector<ValueEntry> &Ops) {
233 if (i+2 == Ops.size()) {
234 if (I->getOperand(0) != Ops[i].Op ||
235 I->getOperand(1) != Ops[i+1].Op) {
236 DEBUG(std::cerr << "RA: " << *I);
237 I->setOperand(0, Ops[i].Op);
238 I->setOperand(1, Ops[i+1].Op);
239 DEBUG(std::cerr << "TO: " << *I);
240 MadeChange = true;
241 ++NumChanged;
242 }
243 return;
244 }
245 assert(i+2 < Ops.size() && "Ops index out of range!");
246
247 if (I->getOperand(1) != Ops[i].Op) {
248 DEBUG(std::cerr << "RA: " << *I);
249 I->setOperand(1, Ops[i].Op);
250 DEBUG(std::cerr << "TO: " << *I);
251 MadeChange = true;
252 ++NumChanged;
253 }
254 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
255}
256
257
Chris Lattnerc0f58002002-05-08 22:19:27 +0000258
Chris Lattner7bc532d2002-05-16 04:37:07 +0000259// NegateValue - Insert instructions before the instruction pointed to by BI,
260// that computes the negative version of the value specified. The negative
261// version of the value is returned, and BI is left pointing at the instruction
262// that should be processed next by the reassociation pass.
263//
Chris Lattnerf43e9742005-05-07 04:08:02 +0000264static Value *NegateValue(Value *V, Instruction *BI) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000265 // We are trying to expose opportunity for reassociation. One of the things
266 // that we want to do to achieve this is to push a negation as deep into an
267 // expression chain as possible, to expose the add instructions. In practice,
268 // this means that we turn this:
269 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
270 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
271 // the constants. We assume that instcombine will clean up the mess later if
Misha Brukman7eb05a12003-08-18 14:43:39 +0000272 // we introduce tons of unnecessary negation instructions...
Chris Lattner7bc532d2002-05-16 04:37:07 +0000273 //
274 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000275 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000276 Value *RHS = NegateValue(I->getOperand(1), BI);
277 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000278
279 // We must actually insert a new add instruction here, because the neg
280 // instructions do not dominate the old add instruction in general. By
281 // adding it now, we are assured that the neg instructions we just
282 // inserted dominate the instruction we are about to insert after them.
283 //
Chris Lattner28a8d242002-09-10 17:04:02 +0000284 return BinaryOperator::create(Instruction::Add, LHS, RHS,
Chris Lattnerf43e9742005-05-07 04:08:02 +0000285 I->getName()+".neg", BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000286 }
287
288 // Insert a 'neg' instruction that subtracts the value from zero to get the
289 // negation.
290 //
Chris Lattnerf43e9742005-05-07 04:08:02 +0000291 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
292}
293
Chris Lattnerf43e9742005-05-07 04:08:02 +0000294/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
295/// only used by an add, transform this into (X+(0-Y)) to promote better
296/// reassociation.
297static Instruction *BreakUpSubtract(Instruction *Sub) {
298 // Reject cases where it is pointless to do this.
299 if (Sub->getType()->isFloatingPoint())
300 return 0; // Floating point adds are not associative.
301
302 // Don't bother to break this up unless either the LHS is an associable add or
303 // if this is only used by one.
304 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
305 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
306 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
307 return 0;
308
309 // Convert a subtract into an add and a neg instruction... so that sub
310 // instructions can be commuted with other add instructions...
311 //
312 // Calculate the negative value of Operand 1 of the sub instruction...
313 // and set it as the RHS of the add instruction we just made...
314 //
315 std::string Name = Sub->getName();
316 Sub->setName("");
317 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
318 Instruction *New =
319 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
320
321 // Everyone now refers to the add instruction.
322 Sub->replaceAllUsesWith(New);
323 Sub->eraseFromParent();
324
325 DEBUG(std::cerr << "Negated: " << *New);
326 return New;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000327}
328
Chris Lattnercea57992005-05-07 04:24:13 +0000329/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
330/// by one, change this into a multiply by a constant to assist with further
331/// reassociation.
332static Instruction *ConvertShiftToMul(Instruction *Shl) {
333 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
334 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
335 return 0;
336
337 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
338 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
339
340 std::string Name = Shl->getName(); Shl->setName("");
341 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
342 Name, Shl);
343 Shl->replaceAllUsesWith(Mul);
344 Shl->eraseFromParent();
345 return Mul;
346}
347
Chris Lattner5847e5e2005-05-08 18:59:37 +0000348// Scan backwards and forwards among values with the same rank as element i to
349// see if X exists. If X does not exist, return i.
350static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
351 Value *X) {
352 unsigned XRank = Ops[i].Rank;
353 unsigned e = Ops.size();
354 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
355 if (Ops[j].Op == X)
356 return j;
357 // Scan backwards
358 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
359 if (Ops[j].Op == X)
360 return j;
361 return i;
362}
363
Chris Lattnere1850b82005-05-08 00:19:31 +0000364void Reassociate::OptimizeExpression(unsigned Opcode,
365 std::vector<ValueEntry> &Ops) {
366 // Now that we have the linearized expression tree, try to optimize it.
367 // Start by folding any constants that we found.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000368 bool IterateOptimization = false;
Chris Lattnere1850b82005-05-08 00:19:31 +0000369 if (Ops.size() == 1) return;
370
371 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
372 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
373 Ops.pop_back();
374 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
Chris Lattner08582be2005-05-08 19:48:43 +0000375 OptimizeExpression(Opcode, Ops);
376 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000377 }
378
379 // Check for destructive annihilation due to a constant being used.
380 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
381 switch (Opcode) {
382 default: break;
383 case Instruction::And:
384 if (CstVal->isNullValue()) { // ... & 0 -> 0
385 Ops[0].Op = CstVal;
386 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000387 ++NumAnnihil;
388 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000389 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
390 Ops.pop_back();
391 }
392 break;
393 case Instruction::Mul:
394 if (CstVal->isNullValue()) { // ... * 0 -> 0
395 Ops[0].Op = CstVal;
396 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000397 ++NumAnnihil;
398 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000399 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
400 Ops.pop_back(); // ... * 1 -> ...
401 }
402 break;
403 case Instruction::Or:
404 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
405 Ops[0].Op = CstVal;
406 Ops.erase(Ops.begin()+1, Ops.end());
Chris Lattner5847e5e2005-05-08 18:59:37 +0000407 ++NumAnnihil;
408 return;
Chris Lattnere1850b82005-05-08 00:19:31 +0000409 }
410 // FALLTHROUGH!
411 case Instruction::Add:
412 case Instruction::Xor:
413 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
414 Ops.pop_back();
415 break;
416 }
417
418 // Handle destructive annihilation do to identities between elements in the
419 // argument list here.
Chris Lattner5847e5e2005-05-08 18:59:37 +0000420 switch (Opcode) {
421 default: break;
422 case Instruction::And:
423 case Instruction::Or:
424 case Instruction::Xor:
425 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
426 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
427 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
428 // First, check for X and ~X in the operand list.
429 if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
430 Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
431 unsigned FoundX = FindInOperandList(Ops, i, X);
432 if (FoundX != i) {
433 if (Opcode == Instruction::And) { // ...&X&~X = 0
434 Ops[0].Op = Constant::getNullValue(X->getType());
435 Ops.erase(Ops.begin()+1, Ops.end());
436 ++NumAnnihil;
437 return;
438 } else if (Opcode == Instruction::Or) { // ...|X|~X = -1
439 Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType());
440 Ops.erase(Ops.begin()+1, Ops.end());
441 ++NumAnnihil;
442 return;
443 }
444 }
445 }
446
447 // Next, check for duplicate pairs of values, which we assume are next to
448 // each other, due to our sorting criteria.
449 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
450 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
451 // Drop duplicate values.
452 Ops.erase(Ops.begin()+i);
453 --i; --e;
454 IterateOptimization = true;
455 ++NumAnnihil;
456 } else {
457 assert(Opcode == Instruction::Xor);
458 // ... X^X -> ...
459 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
460 i -= 2; e -= 2;
461 IterateOptimization = true;
462 ++NumAnnihil;
463 }
464 }
465 }
466 break;
467
468 case Instruction::Add:
469 // Scan the operand lists looking for X and -X pairs. If we find any, we
470 // can simplify the expression. X+-X == 0
471 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
472 // Check for X and -X in the operand list.
473 if (BinaryOperator::isNeg(Ops[i].Op)) {
474 Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
475 unsigned FoundX = FindInOperandList(Ops, i, X);
476 if (FoundX != i) {
477 // Remove X and -X from the operand list.
478 if (Ops.size() == 2) {
479 Ops[0].Op = Constant::getNullValue(X->getType());
480 Ops.erase(Ops.begin()+1);
481 ++NumAnnihil;
482 return;
483 } else {
484 Ops.erase(Ops.begin()+i);
485 if (i < FoundX) --FoundX;
486 Ops.erase(Ops.begin()+FoundX);
487 IterateOptimization = true;
488 ++NumAnnihil;
489 }
490 }
491 }
492 }
493 break;
494 //case Instruction::Mul:
495 }
496
Chris Lattner08582be2005-05-08 19:48:43 +0000497 if (IterateOptimization)
498 OptimizeExpression(Opcode, Ops);
Chris Lattnere1850b82005-05-08 00:19:31 +0000499}
500
Chris Lattner7bc532d2002-05-16 04:37:07 +0000501
Chris Lattnerf43e9742005-05-07 04:08:02 +0000502/// ReassociateBB - Inspect all of the instructions in this basic block,
503/// reassociating them as we go.
Chris Lattner1e506502005-05-07 21:59:39 +0000504void Reassociate::ReassociateBB(BasicBlock *BB) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000505 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattnerf43e9742005-05-07 04:08:02 +0000506 // If this is a subtract instruction which is not already in negate form,
507 // see if we can convert it to X+-Y.
508 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
509 if (Instruction *NI = BreakUpSubtract(BI)) {
Chris Lattner1e506502005-05-07 21:59:39 +0000510 MadeChange = true;
Chris Lattnerf43e9742005-05-07 04:08:02 +0000511 BI = NI;
512 }
Chris Lattnercea57992005-05-07 04:24:13 +0000513 if (BI->getOpcode() == Instruction::Shl &&
514 isa<ConstantInt>(BI->getOperand(1)))
515 if (Instruction *NI = ConvertShiftToMul(BI)) {
Chris Lattner1e506502005-05-07 21:59:39 +0000516 MadeChange = true;
Chris Lattnercea57992005-05-07 04:24:13 +0000517 BI = NI;
518 }
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000519
Chris Lattner1e506502005-05-07 21:59:39 +0000520 // If this instruction is a commutative binary operator, process it.
521 if (!BI->isAssociative()) continue;
522 BinaryOperator *I = cast<BinaryOperator>(BI);
523
524 // If this is an interior node of a reassociable tree, ignore it until we
525 // get to the root of the tree, to avoid N^2 analysis.
526 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
527 continue;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000528
Chris Lattner1e506502005-05-07 21:59:39 +0000529 // First, walk the expression tree, linearizing the tree, collecting
530 std::vector<ValueEntry> Ops;
531 LinearizeExprTree(I, Ops);
532
533 // Now that we have linearized the tree to a list and have gathered all of
534 // the operands and their ranks, sort the operands by their rank. Use a
535 // stable_sort so that values with equal ranks will have their relative
536 // positions maintained (and so the compiler is deterministic). Note that
537 // this sorts so that the highest ranking values end up at the beginning of
538 // the vector.
539 std::stable_sort(Ops.begin(), Ops.end());
540
Chris Lattnere1850b82005-05-08 00:19:31 +0000541 // OptimizeExpression - Now that we have the expression tree in a convenient
542 // sorted form, optimize it globally if possible.
543 OptimizeExpression(I->getOpcode(), Ops);
Chris Lattner1e506502005-05-07 21:59:39 +0000544
545 if (Ops.size() == 1) {
546 // This expression tree simplified to something that isn't a tree,
547 // eliminate it.
548 I->replaceAllUsesWith(Ops[0].Op);
549 } else {
550 // Now that we ordered and optimized the expressions, splat them back into
551 // the expression tree, removing any unneeded nodes.
552 RewriteExprTree(I, 0, Ops);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000553 }
554 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000555}
556
557
Chris Lattner113f4f42002-06-25 16:13:24 +0000558bool Reassociate::runOnFunction(Function &F) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000559 // Recalculate the rank map for F
560 BuildRankMap(F);
561
Chris Lattner1e506502005-05-07 21:59:39 +0000562 MadeChange = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000563 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
Chris Lattner1e506502005-05-07 21:59:39 +0000564 ReassociateBB(FI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000565
566 // We are done with the rank map...
567 RankMap.clear();
Chris Lattner8ac196d2003-08-13 16:16:26 +0000568 ValueRankMap.clear();
Chris Lattner1e506502005-05-07 21:59:39 +0000569 return MadeChange;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000570}
Brian Gaeke960707c2003-11-11 22:41:34 +0000571