Make iostream #inclusion explicit
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2 //
3 //                     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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass reassociates commutative expressions in an order that is designed
11 // to promote better constant propagation, GCSE, LICM, PRE...
12 //
13 // For example: 4 + (x + 5) -> x + (4 + 5)
14 //
15 // 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
23 #define DEBUG_TYPE "reassociate"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Type.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/PostOrderIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include <algorithm>
36 #include <iostream>
37 using namespace llvm;
38
39 namespace {
40   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");
43   Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated");
44
45   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
54   class Reassociate : public FunctionPass {
55     std::map<BasicBlock*, unsigned> RankMap;
56     std::map<Value*, unsigned> ValueRankMap;
57     bool MadeChange;
58   public:
59     bool runOnFunction(Function &F);
60
61     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62       AU.setPreservesCFG();
63     }
64   private:
65     void BuildRankMap(Function &F);
66     unsigned getRank(Value *V);
67     void RewriteExprTree(BinaryOperator *I, unsigned Idx,
68                          std::vector<ValueEntry> &Ops);
69     void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
70     void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
71     void LinearizeExpr(BinaryOperator *I);
72     void ReassociateBB(BasicBlock *BB);
73   };
74
75   RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
76 }
77
78 // Public interface to the Reassociate pass
79 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
80
81
82 static 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
95 void Reassociate::BuildRankMap(Function &F) {
96   unsigned i = 2;
97
98   // Assign distinct ranks to function arguments
99   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
100     ValueRankMap[I] = ++i;
101
102   ReversePostOrderTraversal<Function*> RPOT(&F);
103   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
104          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   }
115 }
116
117 unsigned Reassociate::getRank(Value *V) {
118   if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
119
120   Instruction *I = dyn_cast<Instruction>(V);
121   if (I == 0) return 0;  // Otherwise it's a global or constant, rank 0.
122
123   unsigned &CachedRank = ValueRankMap[I];
124   if (CachedRank) return CachedRank;    // Rank already known?
125
126   // 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.
130   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)));
134
135   // 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
141   //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
142   //<< Rank << "\n");
143
144   return CachedRank = Rank;
145 }
146
147 /// isReassociableOp - Return true if V is an instruction of the specified
148 /// opcode and if it only has one use.
149 static 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 }
155
156 /// LowerNegateToMultiply - Replace 0-X with X*-1.
157 ///
158 static 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
173 // 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.
177 void Reassociate::LinearizeExpr(BinaryOperator *I) {
178   BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
179   BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
180   assert(isReassociableOp(LHS, I->getOpcode()) &&
181          isReassociableOp(RHS, I->getOpcode()) &&
182          "Not an expression that needs linearization?");
183
184   DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
185
186   // Move the RHS instruction to live immediately before I, avoiding breaking
187   // dominator properties.
188   RHS->moveBefore(I);
189
190   // Move operands around to do the linearization.
191   I->setOperand(1, RHS->getOperand(0));
192   RHS->setOperand(0, LHS);
193   I->setOperand(0, RHS);
194
195   ++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 ///
213 void 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
222   // 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
235   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;
257   }
258
259   // 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!");
262
263   // Move LHS right before I to make sure that the tree expression dominates all
264   // values.
265   LHSBO->moveBefore(I);
266
267   // Linearize the expression tree on the LHS.
268   LinearizeExprTree(LHSBO, Ops);
269
270   // Remember the RHS operand and its rank.
271   Ops.push_back(ValueEntry(getRank(RHS), RHS));
272 }
273
274 // 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.
277 void 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
304
305 // 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 //
310 static Value *NegateValue(Value *V, Instruction *BI) {
311   // 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
318   // we introduce tons of unnecessary negation instructions...
319   //
320   if (Instruction *I = dyn_cast<Instruction>(V))
321     if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
322       // Push the negates through the add.
323       I->setOperand(0, NegateValue(I->getOperand(0), BI));
324       I->setOperand(1, NegateValue(I->getOperand(1), BI));
325
326       // 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.
330       //
331       I->moveBefore(BI);
332       I->setName(I->getName()+".neg");
333       return I;
334     }
335
336   // Insert a 'neg' instruction that subtracts the value from zero to get the
337   // negation.
338   //
339   return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
340 }
341
342 /// 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.
345 static Instruction *BreakUpSubtract(Instruction *Sub) {
346   // 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();
368
369   DEBUG(std::cerr << "Negated: " << *New);
370   return New;
371 }
372
373 /// 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.
376 static 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
392 // 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.
394 static 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
408 void 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.
412   bool IterateOptimization = false;
413   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);
419       OptimizeExpression(Opcode, Ops);
420       return;
421     }
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());
431         ++NumAnnihil;
432         return;
433       } 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());
441         ++NumAnnihil;
442         return;
443       } 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());
451         ++NumAnnihil;
452         return;
453       }
454       // FALLTHROUGH!
455     case Instruction::Add:
456     case Instruction::Xor:
457       if (CstVal->isNullValue())             // ... [|^+] 0 -> ...
458         Ops.pop_back();
459       break;
460     }
461   if (Ops.size() == 1) return;
462
463   // Handle destructive annihilation do to identities between elements in the
464   // argument list here.
465   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.
474       assert(i < Ops.size());
475       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.
495       assert(i < Ops.size());
496       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);
505           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           }
511           // ... X^X -> ...
512           Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
513           i -= 1; e -= 2;
514           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) {
525       assert(i < Ops.size());
526       // 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());
534             Ops.pop_back();
535             ++NumAnnihil;
536             return;
537           } else {
538             Ops.erase(Ops.begin()+i);
539             if (i < FoundX)
540               --FoundX;
541             else
542               --i;   // Need to back up an extra one.
543             Ops.erase(Ops.begin()+FoundX);
544             IterateOptimization = true;
545             ++NumAnnihil;
546             --i;     // Revisit element.
547             e -= 2;  // Removed two elements.
548           }
549         }
550       }
551     }
552     break;
553   //case Instruction::Mul:
554   }
555
556   if (IterateOptimization)
557     OptimizeExpression(Opcode, Ops);
558 }
559
560 /// PrintOps - Print out the expression identified in the Ops list.
561 ///
562 static 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 }
571
572 /// ReassociateBB - Inspect all of the instructions in this basic block,
573 /// reassociating them as we go.
574 void Reassociate::ReassociateBB(BasicBlock *BB) {
575   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
576     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
583     // 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
587     // If this is a subtract instruction which is not already in negate form,
588     // see if we can convert it to X+-Y.
589     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         }
604       }
605     }
606
607     // If this instruction is a commutative binary operator, process it.
608     if (!BI->isAssociative()) continue;
609     BinaryOperator *I = cast<BinaryOperator>(BI);
610
611     // 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;
615
616     // 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
622     // First, walk the expression tree, linearizing the tree, collecting
623     std::vector<ValueEntry> Ops;
624     LinearizeExprTree(I, Ops);
625
626     DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB);
627           std::cerr << "\n");
628
629     // 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
637     // OptimizeExpression - Now that we have the expression tree in a convenient
638     // sorted form, optimize it globally if possible.
639     OptimizeExpression(I->getOpcode(), Ops);
640
641     // 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
645     if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
646         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
653     DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB);
654           std::cerr << "\n");
655
656     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);
664     }
665   }
666 }
667
668
669 bool Reassociate::runOnFunction(Function &F) {
670   // Recalculate the rank map for F
671   BuildRankMap(F);
672
673   MadeChange = false;
674   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
675     ReassociateBB(FI);
676
677   // We are done with the rank map...
678   RankMap.clear();
679   ValueRankMap.clear();
680   return MadeChange;
681 }
682