Reassociate.cpp revision ac83b0301ea5ce0e1092fad8f294fe7f046832ff
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>
36using namespace llvm;
37
38namespace {
39  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");
42  Statistic<> NumAnnihil("reassociate","Number of expr tree annihilated");
43
44  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
53  class Reassociate : public FunctionPass {
54    std::map<BasicBlock*, unsigned> RankMap;
55    std::map<Value*, unsigned> ValueRankMap;
56    bool MadeChange;
57  public:
58    bool runOnFunction(Function &F);
59
60    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61      AU.setPreservesCFG();
62    }
63  private:
64    void BuildRankMap(Function &F);
65    unsigned getRank(Value *V);
66    void RewriteExprTree(BinaryOperator *I, unsigned Idx,
67                         std::vector<ValueEntry> &Ops);
68    void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
69    void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
70    void LinearizeExpr(BinaryOperator *I);
71    void ReassociateBB(BasicBlock *BB);
72  };
73
74  RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
75}
76
77// Public interface to the Reassociate pass
78FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
79
80
81static bool isUnmovableInstruction(Instruction *I) {
82  if (I->getOpcode() == Instruction::PHI ||
83      I->getOpcode() == Instruction::Alloca ||
84      I->getOpcode() == Instruction::Load ||
85      I->getOpcode() == Instruction::Malloc ||
86      I->getOpcode() == Instruction::Invoke ||
87      I->getOpcode() == Instruction::Call ||
88      I->getOpcode() == Instruction::Div ||
89      I->getOpcode() == Instruction::Rem)
90    return true;
91  return false;
92}
93
94void Reassociate::BuildRankMap(Function &F) {
95  unsigned i = 2;
96
97  // Assign distinct ranks to function arguments
98  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
99    ValueRankMap[I] = ++i;
100
101  ReversePostOrderTraversal<Function*> RPOT(&F);
102  for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
103         E = RPOT.end(); I != E; ++I) {
104    BasicBlock *BB = *I;
105    unsigned BBRank = RankMap[BB] = ++i << 16;
106
107    // Walk the basic block, adding precomputed ranks for any instructions that
108    // we cannot move.  This ensures that the ranks for these instructions are
109    // all different in the block.
110    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
111      if (isUnmovableInstruction(I))
112        ValueRankMap[I] = ++BBRank;
113  }
114}
115
116unsigned Reassociate::getRank(Value *V) {
117  if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
118
119  Instruction *I = dyn_cast<Instruction>(V);
120  if (I == 0) return 0;  // Otherwise it's a global or constant, rank 0.
121
122  unsigned &CachedRank = ValueRankMap[I];
123  if (CachedRank) return CachedRank;    // Rank already known?
124
125  // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
126  // we can reassociate expressions for code motion!  Since we do not recurse
127  // for PHI nodes, we cannot have infinite recursion here, because there
128  // cannot be loops in the value graph that do not go through PHI nodes.
129  unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
130  for (unsigned i = 0, e = I->getNumOperands();
131       i != e && Rank != MaxRank; ++i)
132    Rank = std::max(Rank, getRank(I->getOperand(i)));
133
134  // If this is a not or neg instruction, do not count it for rank.  This
135  // assures us that X and ~X will have the same rank.
136  if (!I->getType()->isIntegral() ||
137      (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
138    ++Rank;
139
140  //DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
141  //<< Rank << "\n");
142
143  return CachedRank = Rank;
144}
145
146/// isReassociableOp - Return true if V is an instruction of the specified
147/// opcode and if it only has one use.
148static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
149  if (V->hasOneUse() && isa<Instruction>(V) &&
150      cast<Instruction>(V)->getOpcode() == Opcode)
151    return cast<BinaryOperator>(V);
152  return 0;
153}
154
155/// LowerNegateToMultiply - Replace 0-X with X*-1.
156///
157static Instruction *LowerNegateToMultiply(Instruction *Neg) {
158  Constant *Cst;
159  if (Neg->getType()->isFloatingPoint())
160    Cst = ConstantFP::get(Neg->getType(), -1);
161  else
162    Cst = ConstantInt::getAllOnesValue(Neg->getType());
163
164  std::string NegName = Neg->getName(); Neg->setName("");
165  Instruction *Res = BinaryOperator::createMul(Neg->getOperand(1), Cst, NegName,
166                                               Neg);
167  Neg->replaceAllUsesWith(Res);
168  Neg->eraseFromParent();
169  return Res;
170}
171
172// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
173// Note that if D is also part of the expression tree that we recurse to
174// linearize it as well.  Besides that case, this does not recurse into A,B, or
175// C.
176void Reassociate::LinearizeExpr(BinaryOperator *I) {
177  BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
178  BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
179  assert(isReassociableOp(LHS, I->getOpcode()) &&
180         isReassociableOp(RHS, I->getOpcode()) &&
181         "Not an expression that needs linearization?");
182
183  DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
184
185  // Move the RHS instruction to live immediately before I, avoiding breaking
186  // dominator properties.
187  RHS->moveBefore(I);
188
189  // Move operands around to do the linearization.
190  I->setOperand(1, RHS->getOperand(0));
191  RHS->setOperand(0, LHS);
192  I->setOperand(0, RHS);
193
194  ++NumLinear;
195  MadeChange = true;
196  DEBUG(std::cerr << "Linearized: " << *I);
197
198  // If D is part of this expression tree, tail recurse.
199  if (isReassociableOp(I->getOperand(1), I->getOpcode()))
200    LinearizeExpr(I);
201}
202
203
204/// LinearizeExprTree - Given an associative binary expression tree, traverse
205/// all of the uses putting it into canonical form.  This forces a left-linear
206/// form of the the expression (((a+b)+c)+d), and collects information about the
207/// rank of the non-tree operands.
208///
209/// This returns the rank of the RHS operand, which is known to be the highest
210/// rank value in the expression tree.
211///
212void Reassociate::LinearizeExprTree(BinaryOperator *I,
213                                    std::vector<ValueEntry> &Ops) {
214  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
215  unsigned Opcode = I->getOpcode();
216
217  // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
218  BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
219  BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
220
221  // If this is a multiply expression tree and it contains internal negations,
222  // transform them into multiplies by -1 so they can be reassociated.
223  if (I->getOpcode() == Instruction::Mul) {
224    if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
225      LHS = LowerNegateToMultiply(cast<Instruction>(LHS));
226      LHSBO = isReassociableOp(LHS, Opcode);
227    }
228    if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
229      RHS = LowerNegateToMultiply(cast<Instruction>(RHS));
230      RHSBO = isReassociableOp(RHS, Opcode);
231    }
232  }
233
234  if (!LHSBO) {
235    if (!RHSBO) {
236      // Neither the LHS or RHS as part of the tree, thus this is a leaf.  As
237      // such, just remember these operands and their rank.
238      Ops.push_back(ValueEntry(getRank(LHS), LHS));
239      Ops.push_back(ValueEntry(getRank(RHS), RHS));
240      return;
241    } else {
242      // Turn X+(Y+Z) -> (Y+Z)+X
243      std::swap(LHSBO, RHSBO);
244      std::swap(LHS, RHS);
245      bool Success = !I->swapOperands();
246      assert(Success && "swapOperands failed");
247      MadeChange = true;
248    }
249  } else if (RHSBO) {
250    // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the the RHS is not
251    // part of the expression tree.
252    LinearizeExpr(I);
253    LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
254    RHS = I->getOperand(1);
255    RHSBO = 0;
256  }
257
258  // Okay, now we know that the LHS is a nested expression and that the RHS is
259  // not.  Perform reassociation.
260  assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
261
262  // Move LHS right before I to make sure that the tree expression dominates all
263  // values.
264  LHSBO->moveBefore(I);
265
266  // Linearize the expression tree on the LHS.
267  LinearizeExprTree(LHSBO, Ops);
268
269  // Remember the RHS operand and its rank.
270  Ops.push_back(ValueEntry(getRank(RHS), RHS));
271}
272
273// RewriteExprTree - Now that the operands for this expression tree are
274// linearized and optimized, emit them in-order.  This function is written to be
275// tail recursive.
276void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
277                                  std::vector<ValueEntry> &Ops) {
278  if (i+2 == Ops.size()) {
279    if (I->getOperand(0) != Ops[i].Op ||
280        I->getOperand(1) != Ops[i+1].Op) {
281      DEBUG(std::cerr << "RA: " << *I);
282      I->setOperand(0, Ops[i].Op);
283      I->setOperand(1, Ops[i+1].Op);
284      DEBUG(std::cerr << "TO: " << *I);
285      MadeChange = true;
286      ++NumChanged;
287    }
288    return;
289  }
290  assert(i+2 < Ops.size() && "Ops index out of range!");
291
292  if (I->getOperand(1) != Ops[i].Op) {
293    DEBUG(std::cerr << "RA: " << *I);
294    I->setOperand(1, Ops[i].Op);
295    DEBUG(std::cerr << "TO: " << *I);
296    MadeChange = true;
297    ++NumChanged;
298  }
299  RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
300}
301
302
303
304// NegateValue - Insert instructions before the instruction pointed to by BI,
305// that computes the negative version of the value specified.  The negative
306// version of the value is returned, and BI is left pointing at the instruction
307// that should be processed next by the reassociation pass.
308//
309static Value *NegateValue(Value *V, Instruction *BI) {
310  // We are trying to expose opportunity for reassociation.  One of the things
311  // that we want to do to achieve this is to push a negation as deep into an
312  // expression chain as possible, to expose the add instructions.  In practice,
313  // this means that we turn this:
314  //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
315  // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
316  // the constants.  We assume that instcombine will clean up the mess later if
317  // we introduce tons of unnecessary negation instructions...
318  //
319  if (Instruction *I = dyn_cast<Instruction>(V))
320    if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
321      Value *RHS = NegateValue(I->getOperand(1), BI);
322      Value *LHS = NegateValue(I->getOperand(0), BI);
323
324      // We must actually insert a new add instruction here, because the neg
325      // instructions do not dominate the old add instruction in general.  By
326      // adding it now, we are assured that the neg instructions we just
327      // inserted dominate the instruction we are about to insert after them.
328      //
329      return BinaryOperator::create(Instruction::Add, LHS, RHS,
330                                    I->getName()+".neg", BI);
331    }
332
333  // Insert a 'neg' instruction that subtracts the value from zero to get the
334  // negation.
335  //
336  return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
337}
338
339/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
340/// only used by an add, transform this into (X+(0-Y)) to promote better
341/// reassociation.
342static Instruction *BreakUpSubtract(Instruction *Sub) {
343  // Don't bother to break this up unless either the LHS is an associable add or
344  // if this is only used by one.
345  if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
346      !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
347      !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
348    return 0;
349
350  // Convert a subtract into an add and a neg instruction... so that sub
351  // instructions can be commuted with other add instructions...
352  //
353  // Calculate the negative value of Operand 1 of the sub instruction...
354  // and set it as the RHS of the add instruction we just made...
355  //
356  std::string Name = Sub->getName();
357  Sub->setName("");
358  Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
359  Instruction *New =
360    BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
361
362  // Everyone now refers to the add instruction.
363  Sub->replaceAllUsesWith(New);
364  Sub->eraseFromParent();
365
366  DEBUG(std::cerr << "Negated: " << *New);
367  return New;
368}
369
370/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
371/// by one, change this into a multiply by a constant to assist with further
372/// reassociation.
373static Instruction *ConvertShiftToMul(Instruction *Shl) {
374  if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
375      !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
376    return 0;
377
378  Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
379  MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
380
381  std::string Name = Shl->getName();  Shl->setName("");
382  Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
383                                               Name, Shl);
384  Shl->replaceAllUsesWith(Mul);
385  Shl->eraseFromParent();
386  return Mul;
387}
388
389// Scan backwards and forwards among values with the same rank as element i to
390// see if X exists.  If X does not exist, return i.
391static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
392                                  Value *X) {
393  unsigned XRank = Ops[i].Rank;
394  unsigned e = Ops.size();
395  for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
396    if (Ops[j].Op == X)
397      return j;
398  // Scan backwards
399  for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
400    if (Ops[j].Op == X)
401      return j;
402  return i;
403}
404
405void Reassociate::OptimizeExpression(unsigned Opcode,
406                                     std::vector<ValueEntry> &Ops) {
407  // Now that we have the linearized expression tree, try to optimize it.
408  // Start by folding any constants that we found.
409  bool IterateOptimization = false;
410  if (Ops.size() == 1) return;
411
412  if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
413    if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
414      Ops.pop_back();
415      Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
416      OptimizeExpression(Opcode, Ops);
417      return;
418    }
419
420  // Check for destructive annihilation due to a constant being used.
421  if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
422    switch (Opcode) {
423    default: break;
424    case Instruction::And:
425      if (CstVal->isNullValue()) {           // ... & 0 -> 0
426        Ops[0].Op = CstVal;
427        Ops.erase(Ops.begin()+1, Ops.end());
428        ++NumAnnihil;
429        return;
430      } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
431        Ops.pop_back();
432      }
433      break;
434    case Instruction::Mul:
435      if (CstVal->isNullValue()) {           // ... * 0 -> 0
436        Ops[0].Op = CstVal;
437        Ops.erase(Ops.begin()+1, Ops.end());
438        ++NumAnnihil;
439        return;
440      } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
441        Ops.pop_back();                      // ... * 1 -> ...
442      }
443      break;
444    case Instruction::Or:
445      if (CstVal->isAllOnesValue()) {        // ... | -1 -> -1
446        Ops[0].Op = CstVal;
447        Ops.erase(Ops.begin()+1, Ops.end());
448        ++NumAnnihil;
449        return;
450      }
451      // FALLTHROUGH!
452    case Instruction::Add:
453    case Instruction::Xor:
454      if (CstVal->isNullValue())             // ... [|^+] 0 -> ...
455        Ops.pop_back();
456      break;
457    }
458
459  // Handle destructive annihilation do to identities between elements in the
460  // argument list here.
461  switch (Opcode) {
462  default: break;
463  case Instruction::And:
464  case Instruction::Or:
465  case Instruction::Xor:
466    // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
467    // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
468    for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
469      // First, check for X and ~X in the operand list.
470      if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
471        Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
472        unsigned FoundX = FindInOperandList(Ops, i, X);
473        if (FoundX != i) {
474          if (Opcode == Instruction::And) {   // ...&X&~X = 0
475            Ops[0].Op = Constant::getNullValue(X->getType());
476            Ops.erase(Ops.begin()+1, Ops.end());
477            ++NumAnnihil;
478            return;
479          } else if (Opcode == Instruction::Or) {   // ...|X|~X = -1
480            Ops[0].Op = ConstantIntegral::getAllOnesValue(X->getType());
481            Ops.erase(Ops.begin()+1, Ops.end());
482            ++NumAnnihil;
483            return;
484          }
485        }
486      }
487
488      // Next, check for duplicate pairs of values, which we assume are next to
489      // each other, due to our sorting criteria.
490      if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
491        if (Opcode == Instruction::And || Opcode == Instruction::Or) {
492          // Drop duplicate values.
493          Ops.erase(Ops.begin()+i);
494          --i; --e;
495          IterateOptimization = true;
496          ++NumAnnihil;
497        } else {
498          assert(Opcode == Instruction::Xor);
499          if (e == 2) {
500            Ops[0].Op = Constant::getNullValue(Ops[0].Op->getType());
501            Ops.erase(Ops.begin()+1, Ops.end());
502            ++NumAnnihil;
503            return;
504          }
505          // ... X^X -> ...
506          Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
507          i -= 1; e -= 2;
508          IterateOptimization = true;
509          ++NumAnnihil;
510        }
511      }
512    }
513    break;
514
515  case Instruction::Add:
516    // Scan the operand lists looking for X and -X pairs.  If we find any, we
517    // can simplify the expression. X+-X == 0
518    for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
519      // Check for X and -X in the operand list.
520      if (BinaryOperator::isNeg(Ops[i].Op)) {
521        Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
522        unsigned FoundX = FindInOperandList(Ops, i, X);
523        if (FoundX != i) {
524          // Remove X and -X from the operand list.
525          if (Ops.size() == 2) {
526            Ops[0].Op = Constant::getNullValue(X->getType());
527            Ops.erase(Ops.begin()+1);
528            ++NumAnnihil;
529            return;
530          } else {
531            Ops.erase(Ops.begin()+i);
532            if (i < FoundX) --FoundX;
533            Ops.erase(Ops.begin()+FoundX);
534            IterateOptimization = true;
535            ++NumAnnihil;
536          }
537        }
538      }
539    }
540    break;
541  //case Instruction::Mul:
542  }
543
544  if (IterateOptimization)
545    OptimizeExpression(Opcode, Ops);
546}
547
548/// PrintOps - Print out the expression identified in the Ops list.
549///
550static void PrintOps(unsigned Opcode, const std::vector<ValueEntry> &Ops,
551                     BasicBlock *BB) {
552  Module *M = BB->getParent()->getParent();
553  std::cerr << Instruction::getOpcodeName(Opcode) << " "
554            << *Ops[0].Op->getType();
555  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
556    WriteAsOperand(std::cerr << " ", Ops[i].Op, false, true, M)
557      << "," << Ops[i].Rank;
558}
559
560/// ReassociateBB - Inspect all of the instructions in this basic block,
561/// reassociating them as we go.
562void Reassociate::ReassociateBB(BasicBlock *BB) {
563  for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
564    if (BI->getOpcode() == Instruction::Shl &&
565        isa<ConstantInt>(BI->getOperand(1)))
566      if (Instruction *NI = ConvertShiftToMul(BI)) {
567        MadeChange = true;
568        BI = NI;
569      }
570
571    // Reject cases where it is pointless to do this.
572    if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint())
573      continue;  // Floating point ops are not associative.
574
575    // If this is a subtract instruction which is not already in negate form,
576    // see if we can convert it to X+-Y.
577    if (BI->getOpcode() == Instruction::Sub) {
578      if (!BinaryOperator::isNeg(BI)) {
579        if (Instruction *NI = BreakUpSubtract(BI)) {
580          MadeChange = true;
581          BI = NI;
582        }
583      } else {
584        // Otherwise, this is a negation.  See if the operand is a multiply tree
585        // and if this is not an inner node of a multiply tree.
586        if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
587            (!BI->hasOneUse() ||
588             !isReassociableOp(BI->use_back(), Instruction::Mul))) {
589          BI = LowerNegateToMultiply(BI);
590          MadeChange = true;
591        }
592      }
593    }
594
595    // If this instruction is a commutative binary operator, process it.
596    if (!BI->isAssociative()) continue;
597    BinaryOperator *I = cast<BinaryOperator>(BI);
598
599    // If this is an interior node of a reassociable tree, ignore it until we
600    // get to the root of the tree, to avoid N^2 analysis.
601    if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
602      continue;
603
604    // First, walk the expression tree, linearizing the tree, collecting
605    std::vector<ValueEntry> Ops;
606    LinearizeExprTree(I, Ops);
607
608    DEBUG(std::cerr << "RAIn:\t"; PrintOps(I->getOpcode(), Ops, BB);
609          std::cerr << "\n");
610
611    // Now that we have linearized the tree to a list and have gathered all of
612    // the operands and their ranks, sort the operands by their rank.  Use a
613    // stable_sort so that values with equal ranks will have their relative
614    // positions maintained (and so the compiler is deterministic).  Note that
615    // this sorts so that the highest ranking values end up at the beginning of
616    // the vector.
617    std::stable_sort(Ops.begin(), Ops.end());
618
619    // OptimizeExpression - Now that we have the expression tree in a convenient
620    // sorted form, optimize it globally if possible.
621    OptimizeExpression(I->getOpcode(), Ops);
622
623    // We want to sink immediates as deeply as possible except in the case where
624    // this is a multiply tree used only by an add, and the immediate is a -1.
625    // In this case we reassociate to put the negation on the outside so that we
626    // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
627    if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
628        cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
629        isa<ConstantInt>(Ops.back().Op) &&
630        cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
631      Ops.insert(Ops.begin(), Ops.back());
632      Ops.pop_back();
633    }
634
635    DEBUG(std::cerr << "RAOut:\t"; PrintOps(I->getOpcode(), Ops, BB);
636          std::cerr << "\n");
637
638    if (Ops.size() == 1) {
639      // This expression tree simplified to something that isn't a tree,
640      // eliminate it.
641      I->replaceAllUsesWith(Ops[0].Op);
642    } else {
643      // Now that we ordered and optimized the expressions, splat them back into
644      // the expression tree, removing any unneeded nodes.
645      RewriteExprTree(I, 0, Ops);
646    }
647  }
648}
649
650
651bool Reassociate::runOnFunction(Function &F) {
652  // Recalculate the rank map for F
653  BuildRankMap(F);
654
655  MadeChange = false;
656  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
657    ReassociateBB(FI);
658
659  // We are done with the rank map...
660  RankMap.clear();
661  ValueRankMap.clear();
662  return MadeChange;
663}
664
665