LLVM API Documentation

Reassociate.cpp
Go to the documentation of this file.
00001 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass reassociates commutative expressions in an order that is designed
00011 // to promote better constant propagation, GCSE, LICM, PRE, etc.
00012 //
00013 // For example: 4 + (x + 5) -> x + (4 + 5)
00014 //
00015 // In the implementation of this algorithm, constants are assigned rank = 0,
00016 // function arguments are rank = 1, and other values are assigned ranks
00017 // corresponding to the reverse post order traversal of current function
00018 // (starting at 2), which effectively gives values in deep loops higher rank
00019 // than values not in loops.
00020 //
00021 //===----------------------------------------------------------------------===//
00022 
00023 #define DEBUG_TYPE "reassociate"
00024 #include "llvm/Transforms/Scalar.h"
00025 #include "llvm/ADT/DenseMap.h"
00026 #include "llvm/ADT/PostOrderIterator.h"
00027 #include "llvm/ADT/STLExtras.h"
00028 #include "llvm/ADT/SetVector.h"
00029 #include "llvm/ADT/Statistic.h"
00030 #include "llvm/IR/CFG.h"
00031 #include "llvm/IR/Constants.h"
00032 #include "llvm/IR/DerivedTypes.h"
00033 #include "llvm/IR/Function.h"
00034 #include "llvm/IR/IRBuilder.h"
00035 #include "llvm/IR/Instructions.h"
00036 #include "llvm/IR/IntrinsicInst.h"
00037 #include "llvm/IR/ValueHandle.h"
00038 #include "llvm/Pass.h"
00039 #include "llvm/Support/Debug.h"
00040 #include "llvm/Support/raw_ostream.h"
00041 #include "llvm/Transforms/Utils/Local.h"
00042 #include <algorithm>
00043 using namespace llvm;
00044 
00045 STATISTIC(NumChanged, "Number of insts reassociated");
00046 STATISTIC(NumAnnihil, "Number of expr tree annihilated");
00047 STATISTIC(NumFactor , "Number of multiplies factored");
00048 
00049 namespace {
00050   struct ValueEntry {
00051     unsigned Rank;
00052     Value *Op;
00053     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
00054   };
00055   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
00056     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
00057   }
00058 }
00059 
00060 #ifndef NDEBUG
00061 /// PrintOps - Print out the expression identified in the Ops list.
00062 ///
00063 static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
00064   Module *M = I->getParent()->getParent()->getParent();
00065   dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
00066        << *Ops[0].Op->getType() << '\t';
00067   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00068     dbgs() << "[ ";
00069     Ops[i].Op->printAsOperand(dbgs(), false, M);
00070     dbgs() << ", #" << Ops[i].Rank << "] ";
00071   }
00072 }
00073 #endif
00074 
00075 namespace {
00076   /// \brief Utility class representing a base and exponent pair which form one
00077   /// factor of some product.
00078   struct Factor {
00079     Value *Base;
00080     unsigned Power;
00081 
00082     Factor(Value *Base, unsigned Power) : Base(Base), Power(Power) {}
00083 
00084     /// \brief Sort factors by their Base.
00085     struct BaseSorter {
00086       bool operator()(const Factor &LHS, const Factor &RHS) {
00087         return LHS.Base < RHS.Base;
00088       }
00089     };
00090 
00091     /// \brief Compare factors for equal bases.
00092     struct BaseEqual {
00093       bool operator()(const Factor &LHS, const Factor &RHS) {
00094         return LHS.Base == RHS.Base;
00095       }
00096     };
00097 
00098     /// \brief Sort factors in descending order by their power.
00099     struct PowerDescendingSorter {
00100       bool operator()(const Factor &LHS, const Factor &RHS) {
00101         return LHS.Power > RHS.Power;
00102       }
00103     };
00104 
00105     /// \brief Compare factors for equal powers.
00106     struct PowerEqual {
00107       bool operator()(const Factor &LHS, const Factor &RHS) {
00108         return LHS.Power == RHS.Power;
00109       }
00110     };
00111   };
00112   
00113   /// Utility class representing a non-constant Xor-operand. We classify
00114   /// non-constant Xor-Operands into two categories:
00115   ///  C1) The operand is in the form "X & C", where C is a constant and C != ~0
00116   ///  C2)
00117   ///    C2.1) The operand is in the form of "X | C", where C is a non-zero
00118   ///          constant.
00119   ///    C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
00120   ///          operand as "E | 0"
00121   class XorOpnd {
00122   public:
00123     XorOpnd(Value *V);
00124 
00125     bool isInvalid() const { return SymbolicPart == 0; }
00126     bool isOrExpr() const { return isOr; }
00127     Value *getValue() const { return OrigVal; }
00128     Value *getSymbolicPart() const { return SymbolicPart; }
00129     unsigned getSymbolicRank() const { return SymbolicRank; }
00130     const APInt &getConstPart() const { return ConstPart; }
00131 
00132     void Invalidate() { SymbolicPart = OrigVal = 0; }
00133     void setSymbolicRank(unsigned R) { SymbolicRank = R; }
00134 
00135     // Sort the XorOpnd-Pointer in ascending order of symbolic-value-rank.
00136     // The purpose is twofold:
00137     // 1) Cluster together the operands sharing the same symbolic-value.
00138     // 2) Operand having smaller symbolic-value-rank is permuted earlier, which 
00139     //   could potentially shorten crital path, and expose more loop-invariants.
00140     //   Note that values' rank are basically defined in RPO order (FIXME). 
00141     //   So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier 
00142     //   than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
00143     //   "z" in the order of X-Y-Z is better than any other orders.
00144     struct PtrSortFunctor {
00145       bool operator()(XorOpnd * const &LHS, XorOpnd * const &RHS) {
00146         return LHS->getSymbolicRank() < RHS->getSymbolicRank();
00147       }
00148     };
00149   private:
00150     Value *OrigVal;
00151     Value *SymbolicPart;
00152     APInt ConstPart;
00153     unsigned SymbolicRank;
00154     bool isOr;
00155   };
00156 }
00157 
00158 namespace {
00159   class Reassociate : public FunctionPass {
00160     DenseMap<BasicBlock*, unsigned> RankMap;
00161     DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
00162     SetVector<AssertingVH<Instruction> > RedoInsts;
00163     bool MadeChange;
00164   public:
00165     static char ID; // Pass identification, replacement for typeid
00166     Reassociate() : FunctionPass(ID) {
00167       initializeReassociatePass(*PassRegistry::getPassRegistry());
00168     }
00169 
00170     bool runOnFunction(Function &F) override;
00171 
00172     void getAnalysisUsage(AnalysisUsage &AU) const override {
00173       AU.setPreservesCFG();
00174     }
00175   private:
00176     void BuildRankMap(Function &F);
00177     unsigned getRank(Value *V);
00178     void ReassociateExpression(BinaryOperator *I);
00179     void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
00180     Value *OptimizeExpression(BinaryOperator *I,
00181                               SmallVectorImpl<ValueEntry> &Ops);
00182     Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
00183     Value *OptimizeXor(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
00184     bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, APInt &ConstOpnd,
00185                         Value *&Res);
00186     bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
00187                         APInt &ConstOpnd, Value *&Res);
00188     bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
00189                                 SmallVectorImpl<Factor> &Factors);
00190     Value *buildMinimalMultiplyDAG(IRBuilder<> &Builder,
00191                                    SmallVectorImpl<Factor> &Factors);
00192     Value *OptimizeMul(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
00193     Value *RemoveFactorFromExpression(Value *V, Value *Factor);
00194     void EraseInst(Instruction *I);
00195     void OptimizeInst(Instruction *I);
00196   };
00197 }
00198 
00199 XorOpnd::XorOpnd(Value *V) {
00200   assert(!isa<ConstantInt>(V) && "No ConstantInt");
00201   OrigVal = V;
00202   Instruction *I = dyn_cast<Instruction>(V);
00203   SymbolicRank = 0;
00204 
00205   if (I && (I->getOpcode() == Instruction::Or ||
00206             I->getOpcode() == Instruction::And)) {
00207     Value *V0 = I->getOperand(0);
00208     Value *V1 = I->getOperand(1);
00209     if (isa<ConstantInt>(V0))
00210       std::swap(V0, V1);
00211 
00212     if (ConstantInt *C = dyn_cast<ConstantInt>(V1)) {
00213       ConstPart = C->getValue();
00214       SymbolicPart = V0;
00215       isOr = (I->getOpcode() == Instruction::Or);
00216       return;
00217     }
00218   }
00219 
00220   // view the operand as "V | 0"
00221   SymbolicPart = V;
00222   ConstPart = APInt::getNullValue(V->getType()->getIntegerBitWidth());
00223   isOr = true;
00224 }
00225 
00226 char Reassociate::ID = 0;
00227 INITIALIZE_PASS(Reassociate, "reassociate",
00228                 "Reassociate expressions", false, false)
00229 
00230 // Public interface to the Reassociate pass
00231 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
00232 
00233 /// isReassociableOp - Return true if V is an instruction of the specified
00234 /// opcode and if it only has one use.
00235 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
00236   if (V->hasOneUse() && isa<Instruction>(V) &&
00237       cast<Instruction>(V)->getOpcode() == Opcode)
00238     return cast<BinaryOperator>(V);
00239   return 0;
00240 }
00241 
00242 static bool isUnmovableInstruction(Instruction *I) {
00243   switch (I->getOpcode()) {
00244   case Instruction::PHI:
00245   case Instruction::LandingPad:
00246   case Instruction::Alloca:
00247   case Instruction::Load:
00248   case Instruction::Invoke:
00249   case Instruction::UDiv:
00250   case Instruction::SDiv:
00251   case Instruction::FDiv:
00252   case Instruction::URem:
00253   case Instruction::SRem:
00254   case Instruction::FRem:
00255     return true;
00256   case Instruction::Call:
00257     return !isa<DbgInfoIntrinsic>(I);
00258   default:
00259     return false;
00260   }
00261 }
00262 
00263 void Reassociate::BuildRankMap(Function &F) {
00264   unsigned i = 2;
00265 
00266   // Assign distinct ranks to function arguments
00267   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
00268     ValueRankMap[&*I] = ++i;
00269 
00270   ReversePostOrderTraversal<Function*> RPOT(&F);
00271   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
00272          E = RPOT.end(); I != E; ++I) {
00273     BasicBlock *BB = *I;
00274     unsigned BBRank = RankMap[BB] = ++i << 16;
00275 
00276     // Walk the basic block, adding precomputed ranks for any instructions that
00277     // we cannot move.  This ensures that the ranks for these instructions are
00278     // all different in the block.
00279     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00280       if (isUnmovableInstruction(I))
00281         ValueRankMap[&*I] = ++BBRank;
00282   }
00283 }
00284 
00285 unsigned Reassociate::getRank(Value *V) {
00286   Instruction *I = dyn_cast<Instruction>(V);
00287   if (I == 0) {
00288     if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
00289     return 0;  // Otherwise it's a global or constant, rank 0.
00290   }
00291 
00292   if (unsigned Rank = ValueRankMap[I])
00293     return Rank;    // Rank already known?
00294 
00295   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
00296   // we can reassociate expressions for code motion!  Since we do not recurse
00297   // for PHI nodes, we cannot have infinite recursion here, because there
00298   // cannot be loops in the value graph that do not go through PHI nodes.
00299   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
00300   for (unsigned i = 0, e = I->getNumOperands();
00301        i != e && Rank != MaxRank; ++i)
00302     Rank = std::max(Rank, getRank(I->getOperand(i)));
00303 
00304   // If this is a not or neg instruction, do not count it for rank.  This
00305   // assures us that X and ~X will have the same rank.
00306   if (!I->getType()->isIntegerTy() ||
00307       (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
00308     ++Rank;
00309 
00310   //DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
00311   //     << Rank << "\n");
00312 
00313   return ValueRankMap[I] = Rank;
00314 }
00315 
00316 /// LowerNegateToMultiply - Replace 0-X with X*-1.
00317 ///
00318 static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
00319   Constant *Cst = Constant::getAllOnesValue(Neg->getType());
00320 
00321   BinaryOperator *Res =
00322     BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
00323   Neg->setOperand(1, Constant::getNullValue(Neg->getType())); // Drop use of op.
00324   Res->takeName(Neg);
00325   Neg->replaceAllUsesWith(Res);
00326   Res->setDebugLoc(Neg->getDebugLoc());
00327   return Res;
00328 }
00329 
00330 /// CarmichaelShift - Returns k such that lambda(2^Bitwidth) = 2^k, where lambda
00331 /// is the Carmichael function. This means that x^(2^k) === 1 mod 2^Bitwidth for
00332 /// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
00333 /// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
00334 /// even x in Bitwidth-bit arithmetic.
00335 static unsigned CarmichaelShift(unsigned Bitwidth) {
00336   if (Bitwidth < 3)
00337     return Bitwidth - 1;
00338   return Bitwidth - 2;
00339 }
00340 
00341 /// IncorporateWeight - Add the extra weight 'RHS' to the existing weight 'LHS',
00342 /// reducing the combined weight using any special properties of the operation.
00343 /// The existing weight LHS represents the computation X op X op ... op X where
00344 /// X occurs LHS times.  The combined weight represents  X op X op ... op X with
00345 /// X occurring LHS + RHS times.  If op is "Xor" for example then the combined
00346 /// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
00347 /// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
00348 static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
00349   // If we were working with infinite precision arithmetic then the combined
00350   // weight would be LHS + RHS.  But we are using finite precision arithmetic,
00351   // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
00352   // for nilpotent operations and addition, but not for idempotent operations
00353   // and multiplication), so it is important to correctly reduce the combined
00354   // weight back into range if wrapping would be wrong.
00355 
00356   // If RHS is zero then the weight didn't change.
00357   if (RHS.isMinValue())
00358     return;
00359   // If LHS is zero then the combined weight is RHS.
00360   if (LHS.isMinValue()) {
00361     LHS = RHS;
00362     return;
00363   }
00364   // From this point on we know that neither LHS nor RHS is zero.
00365 
00366   if (Instruction::isIdempotent(Opcode)) {
00367     // Idempotent means X op X === X, so any non-zero weight is equivalent to a
00368     // weight of 1.  Keeping weights at zero or one also means that wrapping is
00369     // not a problem.
00370     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
00371     return; // Return a weight of 1.
00372   }
00373   if (Instruction::isNilpotent(Opcode)) {
00374     // Nilpotent means X op X === 0, so reduce weights modulo 2.
00375     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
00376     LHS = 0; // 1 + 1 === 0 modulo 2.
00377     return;
00378   }
00379   if (Opcode == Instruction::Add) {
00380     // TODO: Reduce the weight by exploiting nsw/nuw?
00381     LHS += RHS;
00382     return;
00383   }
00384 
00385   assert(Opcode == Instruction::Mul && "Unknown associative operation!");
00386   unsigned Bitwidth = LHS.getBitWidth();
00387   // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
00388   // can be replaced with W-CM.  That's because x^W=x^(W-CM) for every Bitwidth
00389   // bit number x, since either x is odd in which case x^CM = 1, or x is even in
00390   // which case both x^W and x^(W - CM) are zero.  By subtracting off multiples
00391   // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
00392   // which by a happy accident means that they can always be represented using
00393   // Bitwidth bits.
00394   // TODO: Reduce the weight by exploiting nsw/nuw?  (Could do much better than
00395   // the Carmichael number).
00396   if (Bitwidth > 3) {
00397     /// CM - The value of Carmichael's lambda function.
00398     APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
00399     // Any weight W >= Threshold can be replaced with W - CM.
00400     APInt Threshold = CM + Bitwidth;
00401     assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
00402     // For Bitwidth 4 or more the following sum does not overflow.
00403     LHS += RHS;
00404     while (LHS.uge(Threshold))
00405       LHS -= CM;
00406   } else {
00407     // To avoid problems with overflow do everything the same as above but using
00408     // a larger type.
00409     unsigned CM = 1U << CarmichaelShift(Bitwidth);
00410     unsigned Threshold = CM + Bitwidth;
00411     assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
00412            "Weights not reduced!");
00413     unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
00414     while (Total >= Threshold)
00415       Total -= CM;
00416     LHS = Total;
00417   }
00418 }
00419 
00420 typedef std::pair<Value*, APInt> RepeatedValue;
00421 
00422 /// LinearizeExprTree - Given an associative binary expression, return the leaf
00423 /// nodes in Ops along with their weights (how many times the leaf occurs).  The
00424 /// original expression is the same as
00425 ///   (Ops[0].first op Ops[0].first op ... Ops[0].first)  <- Ops[0].second times
00426 /// op
00427 ///   (Ops[1].first op Ops[1].first op ... Ops[1].first)  <- Ops[1].second times
00428 /// op
00429 ///   ...
00430 /// op
00431 ///   (Ops[N].first op Ops[N].first op ... Ops[N].first)  <- Ops[N].second times
00432 ///
00433 /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
00434 ///
00435 /// This routine may modify the function, in which case it returns 'true'.  The
00436 /// changes it makes may well be destructive, changing the value computed by 'I'
00437 /// to something completely different.  Thus if the routine returns 'true' then
00438 /// you MUST either replace I with a new expression computed from the Ops array,
00439 /// or use RewriteExprTree to put the values back in.
00440 ///
00441 /// A leaf node is either not a binary operation of the same kind as the root
00442 /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
00443 /// opcode), or is the same kind of binary operator but has a use which either
00444 /// does not belong to the expression, or does belong to the expression but is
00445 /// a leaf node.  Every leaf node has at least one use that is a non-leaf node
00446 /// of the expression, while for non-leaf nodes (except for the root 'I') every
00447 /// use is a non-leaf node of the expression.
00448 ///
00449 /// For example:
00450 ///           expression graph        node names
00451 ///
00452 ///                     +        |        I
00453 ///                    / \       |
00454 ///                   +   +      |      A,  B
00455 ///                  / \ / \     |
00456 ///                 *   +   *    |    C,  D,  E
00457 ///                / \ / \ / \   |
00458 ///                   +   *      |      F,  G
00459 ///
00460 /// The leaf nodes are C, E, F and G.  The Ops array will contain (maybe not in
00461 /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
00462 ///
00463 /// The expression is maximal: if some instruction is a binary operator of the
00464 /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
00465 /// then the instruction also belongs to the expression, is not a leaf node of
00466 /// it, and its operands also belong to the expression (but may be leaf nodes).
00467 ///
00468 /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
00469 /// order to ensure that every non-root node in the expression has *exactly one*
00470 /// use by a non-leaf node of the expression.  This destruction means that the
00471 /// caller MUST either replace 'I' with a new expression or use something like
00472 /// RewriteExprTree to put the values back in if the routine indicates that it
00473 /// made a change by returning 'true'.
00474 ///
00475 /// In the above example either the right operand of A or the left operand of B
00476 /// will be replaced by undef.  If it is B's operand then this gives:
00477 ///
00478 ///                     +        |        I
00479 ///                    / \       |
00480 ///                   +   +      |      A,  B - operand of B replaced with undef
00481 ///                  / \   \     |
00482 ///                 *   +   *    |    C,  D,  E
00483 ///                / \ / \ / \   |
00484 ///                   +   *      |      F,  G
00485 ///
00486 /// Note that such undef operands can only be reached by passing through 'I'.
00487 /// For example, if you visit operands recursively starting from a leaf node
00488 /// then you will never see such an undef operand unless you get back to 'I',
00489 /// which requires passing through a phi node.
00490 ///
00491 /// Note that this routine may also mutate binary operators of the wrong type
00492 /// that have all uses inside the expression (i.e. only used by non-leaf nodes
00493 /// of the expression) if it can turn them into binary operators of the right
00494 /// type and thus make the expression bigger.
00495 
00496 static bool LinearizeExprTree(BinaryOperator *I,
00497                               SmallVectorImpl<RepeatedValue> &Ops) {
00498   DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
00499   unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
00500   unsigned Opcode = I->getOpcode();
00501   assert(Instruction::isAssociative(Opcode) &&
00502          Instruction::isCommutative(Opcode) &&
00503          "Expected an associative and commutative operation!");
00504 
00505   // Visit all operands of the expression, keeping track of their weight (the
00506   // number of paths from the expression root to the operand, or if you like
00507   // the number of times that operand occurs in the linearized expression).
00508   // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
00509   // while A has weight two.
00510 
00511   // Worklist of non-leaf nodes (their operands are in the expression too) along
00512   // with their weights, representing a certain number of paths to the operator.
00513   // If an operator occurs in the worklist multiple times then we found multiple
00514   // ways to get to it.
00515   SmallVector<std::pair<BinaryOperator*, APInt>, 8> Worklist; // (Op, Weight)
00516   Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
00517   bool MadeChange = false;
00518 
00519   // Leaves of the expression are values that either aren't the right kind of
00520   // operation (eg: a constant, or a multiply in an add tree), or are, but have
00521   // some uses that are not inside the expression.  For example, in I = X + X,
00522   // X = A + B, the value X has two uses (by I) that are in the expression.  If
00523   // X has any other uses, for example in a return instruction, then we consider
00524   // X to be a leaf, and won't analyze it further.  When we first visit a value,
00525   // if it has more than one use then at first we conservatively consider it to
00526   // be a leaf.  Later, as the expression is explored, we may discover some more
00527   // uses of the value from inside the expression.  If all uses turn out to be
00528   // from within the expression (and the value is a binary operator of the right
00529   // kind) then the value is no longer considered to be a leaf, and its operands
00530   // are explored.
00531 
00532   // Leaves - Keeps track of the set of putative leaves as well as the number of
00533   // paths to each leaf seen so far.
00534   typedef DenseMap<Value*, APInt> LeafMap;
00535   LeafMap Leaves; // Leaf -> Total weight so far.
00536   SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
00537 
00538 #ifndef NDEBUG
00539   SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
00540 #endif
00541   while (!Worklist.empty()) {
00542     std::pair<BinaryOperator*, APInt> P = Worklist.pop_back_val();
00543     I = P.first; // We examine the operands of this binary operator.
00544 
00545     for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
00546       Value *Op = I->getOperand(OpIdx);
00547       APInt Weight = P.second; // Number of paths to this operand.
00548       DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
00549       assert(!Op->use_empty() && "No uses, so how did we get to it?!");
00550 
00551       // If this is a binary operation of the right kind with only one use then
00552       // add its operands to the expression.
00553       if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
00554         assert(Visited.insert(Op) && "Not first visit!");
00555         DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
00556         Worklist.push_back(std::make_pair(BO, Weight));
00557         continue;
00558       }
00559 
00560       // Appears to be a leaf.  Is the operand already in the set of leaves?
00561       LeafMap::iterator It = Leaves.find(Op);
00562       if (It == Leaves.end()) {
00563         // Not in the leaf map.  Must be the first time we saw this operand.
00564         assert(Visited.insert(Op) && "Not first visit!");
00565         if (!Op->hasOneUse()) {
00566           // This value has uses not accounted for by the expression, so it is
00567           // not safe to modify.  Mark it as being a leaf.
00568           DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
00569           LeafOrder.push_back(Op);
00570           Leaves[Op] = Weight;
00571           continue;
00572         }
00573         // No uses outside the expression, try morphing it.
00574       } else if (It != Leaves.end()) {
00575         // Already in the leaf map.
00576         assert(Visited.count(Op) && "In leaf map but not visited!");
00577 
00578         // Update the number of paths to the leaf.
00579         IncorporateWeight(It->second, Weight, Opcode);
00580 
00581 #if 0   // TODO: Re-enable once PR13021 is fixed.
00582         // The leaf already has one use from inside the expression.  As we want
00583         // exactly one such use, drop this new use of the leaf.
00584         assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
00585         I->setOperand(OpIdx, UndefValue::get(I->getType()));
00586         MadeChange = true;
00587 
00588         // If the leaf is a binary operation of the right kind and we now see
00589         // that its multiple original uses were in fact all by nodes belonging
00590         // to the expression, then no longer consider it to be a leaf and add
00591         // its operands to the expression.
00592         if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
00593           DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
00594           Worklist.push_back(std::make_pair(BO, It->second));
00595           Leaves.erase(It);
00596           continue;
00597         }
00598 #endif
00599 
00600         // If we still have uses that are not accounted for by the expression
00601         // then it is not safe to modify the value.
00602         if (!Op->hasOneUse())
00603           continue;
00604 
00605         // No uses outside the expression, try morphing it.
00606         Weight = It->second;
00607         Leaves.erase(It); // Since the value may be morphed below.
00608       }
00609 
00610       // At this point we have a value which, first of all, is not a binary
00611       // expression of the right kind, and secondly, is only used inside the
00612       // expression.  This means that it can safely be modified.  See if we
00613       // can usefully morph it into an expression of the right kind.
00614       assert((!isa<Instruction>(Op) ||
00615               cast<Instruction>(Op)->getOpcode() != Opcode) &&
00616              "Should have been handled above!");
00617       assert(Op->hasOneUse() && "Has uses outside the expression tree!");
00618 
00619       // If this is a multiply expression, turn any internal negations into
00620       // multiplies by -1 so they can be reassociated.
00621       BinaryOperator *BO = dyn_cast<BinaryOperator>(Op);
00622       if (Opcode == Instruction::Mul && BO && BinaryOperator::isNeg(BO)) {
00623         DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
00624         BO = LowerNegateToMultiply(BO);
00625         DEBUG(dbgs() << *BO << 'n');
00626         Worklist.push_back(std::make_pair(BO, Weight));
00627         MadeChange = true;
00628         continue;
00629       }
00630 
00631       // Failed to morph into an expression of the right type.  This really is
00632       // a leaf.
00633       DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
00634       assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
00635       LeafOrder.push_back(Op);
00636       Leaves[Op] = Weight;
00637     }
00638   }
00639 
00640   // The leaves, repeated according to their weights, represent the linearized
00641   // form of the expression.
00642   for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
00643     Value *V = LeafOrder[i];
00644     LeafMap::iterator It = Leaves.find(V);
00645     if (It == Leaves.end())
00646       // Node initially thought to be a leaf wasn't.
00647       continue;
00648     assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
00649     APInt Weight = It->second;
00650     if (Weight.isMinValue())
00651       // Leaf already output or weight reduction eliminated it.
00652       continue;
00653     // Ensure the leaf is only output once.
00654     It->second = 0;
00655     Ops.push_back(std::make_pair(V, Weight));
00656   }
00657 
00658   // For nilpotent operations or addition there may be no operands, for example
00659   // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
00660   // in both cases the weight reduces to 0 causing the value to be skipped.
00661   if (Ops.empty()) {
00662     Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
00663     assert(Identity && "Associative operation without identity!");
00664     Ops.push_back(std::make_pair(Identity, APInt(Bitwidth, 1)));
00665   }
00666 
00667   return MadeChange;
00668 }
00669 
00670 // RewriteExprTree - Now that the operands for this expression tree are
00671 // linearized and optimized, emit them in-order.
00672 void Reassociate::RewriteExprTree(BinaryOperator *I,
00673                                   SmallVectorImpl<ValueEntry> &Ops) {
00674   assert(Ops.size() > 1 && "Single values should be used directly!");
00675 
00676   // Since our optimizations should never increase the number of operations, the
00677   // new expression can usually be written reusing the existing binary operators
00678   // from the original expression tree, without creating any new instructions,
00679   // though the rewritten expression may have a completely different topology.
00680   // We take care to not change anything if the new expression will be the same
00681   // as the original.  If more than trivial changes (like commuting operands)
00682   // were made then we are obliged to clear out any optional subclass data like
00683   // nsw flags.
00684 
00685   /// NodesToRewrite - Nodes from the original expression available for writing
00686   /// the new expression into.
00687   SmallVector<BinaryOperator*, 8> NodesToRewrite;
00688   unsigned Opcode = I->getOpcode();
00689   BinaryOperator *Op = I;
00690 
00691   /// NotRewritable - The operands being written will be the leaves of the new
00692   /// expression and must not be used as inner nodes (via NodesToRewrite) by
00693   /// mistake.  Inner nodes are always reassociable, and usually leaves are not
00694   /// (if they were they would have been incorporated into the expression and so
00695   /// would not be leaves), so most of the time there is no danger of this.  But
00696   /// in rare cases a leaf may become reassociable if an optimization kills uses
00697   /// of it, or it may momentarily become reassociable during rewriting (below)
00698   /// due it being removed as an operand of one of its uses.  Ensure that misuse
00699   /// of leaf nodes as inner nodes cannot occur by remembering all of the future
00700   /// leaves and refusing to reuse any of them as inner nodes.
00701   SmallPtrSet<Value*, 8> NotRewritable;
00702   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00703     NotRewritable.insert(Ops[i].Op);
00704 
00705   // ExpressionChanged - Non-null if the rewritten expression differs from the
00706   // original in some non-trivial way, requiring the clearing of optional flags.
00707   // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
00708   BinaryOperator *ExpressionChanged = 0;
00709   for (unsigned i = 0; ; ++i) {
00710     // The last operation (which comes earliest in the IR) is special as both
00711     // operands will come from Ops, rather than just one with the other being
00712     // a subexpression.
00713     if (i+2 == Ops.size()) {
00714       Value *NewLHS = Ops[i].Op;
00715       Value *NewRHS = Ops[i+1].Op;
00716       Value *OldLHS = Op->getOperand(0);
00717       Value *OldRHS = Op->getOperand(1);
00718 
00719       if (NewLHS == OldLHS && NewRHS == OldRHS)
00720         // Nothing changed, leave it alone.
00721         break;
00722 
00723       if (NewLHS == OldRHS && NewRHS == OldLHS) {
00724         // The order of the operands was reversed.  Swap them.
00725         DEBUG(dbgs() << "RA: " << *Op << '\n');
00726         Op->swapOperands();
00727         DEBUG(dbgs() << "TO: " << *Op << '\n');
00728         MadeChange = true;
00729         ++NumChanged;
00730         break;
00731       }
00732 
00733       // The new operation differs non-trivially from the original. Overwrite
00734       // the old operands with the new ones.
00735       DEBUG(dbgs() << "RA: " << *Op << '\n');
00736       if (NewLHS != OldLHS) {
00737         BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
00738         if (BO && !NotRewritable.count(BO))
00739           NodesToRewrite.push_back(BO);
00740         Op->setOperand(0, NewLHS);
00741       }
00742       if (NewRHS != OldRHS) {
00743         BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
00744         if (BO && !NotRewritable.count(BO))
00745           NodesToRewrite.push_back(BO);
00746         Op->setOperand(1, NewRHS);
00747       }
00748       DEBUG(dbgs() << "TO: " << *Op << '\n');
00749 
00750       ExpressionChanged = Op;
00751       MadeChange = true;
00752       ++NumChanged;
00753 
00754       break;
00755     }
00756 
00757     // Not the last operation.  The left-hand side will be a sub-expression
00758     // while the right-hand side will be the current element of Ops.
00759     Value *NewRHS = Ops[i].Op;
00760     if (NewRHS != Op->getOperand(1)) {
00761       DEBUG(dbgs() << "RA: " << *Op << '\n');
00762       if (NewRHS == Op->getOperand(0)) {
00763         // The new right-hand side was already present as the left operand.  If
00764         // we are lucky then swapping the operands will sort out both of them.
00765         Op->swapOperands();
00766       } else {
00767         // Overwrite with the new right-hand side.
00768         BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
00769         if (BO && !NotRewritable.count(BO))
00770           NodesToRewrite.push_back(BO);
00771         Op->setOperand(1, NewRHS);
00772         ExpressionChanged = Op;
00773       }
00774       DEBUG(dbgs() << "TO: " << *Op << '\n');
00775       MadeChange = true;
00776       ++NumChanged;
00777     }
00778 
00779     // Now deal with the left-hand side.  If this is already an operation node
00780     // from the original expression then just rewrite the rest of the expression
00781     // into it.
00782     BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
00783     if (BO && !NotRewritable.count(BO)) {
00784       Op = BO;
00785       continue;
00786     }
00787 
00788     // Otherwise, grab a spare node from the original expression and use that as
00789     // the left-hand side.  If there are no nodes left then the optimizers made
00790     // an expression with more nodes than the original!  This usually means that
00791     // they did something stupid but it might mean that the problem was just too
00792     // hard (finding the mimimal number of multiplications needed to realize a
00793     // multiplication expression is NP-complete).  Whatever the reason, smart or
00794     // stupid, create a new node if there are none left.
00795     BinaryOperator *NewOp;
00796     if (NodesToRewrite.empty()) {
00797       Constant *Undef = UndefValue::get(I->getType());
00798       NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
00799                                      Undef, Undef, "", I);
00800     } else {
00801       NewOp = NodesToRewrite.pop_back_val();
00802     }
00803 
00804     DEBUG(dbgs() << "RA: " << *Op << '\n');
00805     Op->setOperand(0, NewOp);
00806     DEBUG(dbgs() << "TO: " << *Op << '\n');
00807     ExpressionChanged = Op;
00808     MadeChange = true;
00809     ++NumChanged;
00810     Op = NewOp;
00811   }
00812 
00813   // If the expression changed non-trivially then clear out all subclass data
00814   // starting from the operator specified in ExpressionChanged, and compactify
00815   // the operators to just before the expression root to guarantee that the
00816   // expression tree is dominated by all of Ops.
00817   if (ExpressionChanged)
00818     do {
00819       ExpressionChanged->clearSubclassOptionalData();
00820       if (ExpressionChanged == I)
00821         break;
00822       ExpressionChanged->moveBefore(I);
00823       ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->user_begin());
00824     } while (1);
00825 
00826   // Throw away any left over nodes from the original expression.
00827   for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
00828     RedoInsts.insert(NodesToRewrite[i]);
00829 }
00830 
00831 /// NegateValue - Insert instructions before the instruction pointed to by BI,
00832 /// that computes the negative version of the value specified.  The negative
00833 /// version of the value is returned, and BI is left pointing at the instruction
00834 /// that should be processed next by the reassociation pass.
00835 static Value *NegateValue(Value *V, Instruction *BI) {
00836   if (Constant *C = dyn_cast<Constant>(V))
00837     return ConstantExpr::getNeg(C);
00838 
00839   // We are trying to expose opportunity for reassociation.  One of the things
00840   // that we want to do to achieve this is to push a negation as deep into an
00841   // expression chain as possible, to expose the add instructions.  In practice,
00842   // this means that we turn this:
00843   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
00844   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
00845   // the constants.  We assume that instcombine will clean up the mess later if
00846   // we introduce tons of unnecessary negation instructions.
00847   //
00848   if (BinaryOperator *I = isReassociableOp(V, Instruction::Add)) {
00849     // Push the negates through the add.
00850     I->setOperand(0, NegateValue(I->getOperand(0), BI));
00851     I->setOperand(1, NegateValue(I->getOperand(1), BI));
00852 
00853     // We must move the add instruction here, because the neg instructions do
00854     // not dominate the old add instruction in general.  By moving it, we are
00855     // assured that the neg instructions we just inserted dominate the
00856     // instruction we are about to insert after them.
00857     //
00858     I->moveBefore(BI);
00859     I->setName(I->getName()+".neg");
00860     return I;
00861   }
00862 
00863   // Okay, we need to materialize a negated version of V with an instruction.
00864   // Scan the use lists of V to see if we have one already.
00865   for (User *U : V->users()) {
00866     if (!BinaryOperator::isNeg(U)) continue;
00867 
00868     // We found one!  Now we have to make sure that the definition dominates
00869     // this use.  We do this by moving it to the entry block (if it is a
00870     // non-instruction value) or right after the definition.  These negates will
00871     // be zapped by reassociate later, so we don't need much finesse here.
00872     BinaryOperator *TheNeg = cast<BinaryOperator>(U);
00873 
00874     // Verify that the negate is in this function, V might be a constant expr.
00875     if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
00876       continue;
00877 
00878     BasicBlock::iterator InsertPt;
00879     if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
00880       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
00881         InsertPt = II->getNormalDest()->begin();
00882       } else {
00883         InsertPt = InstInput;
00884         ++InsertPt;
00885       }
00886       while (isa<PHINode>(InsertPt)) ++InsertPt;
00887     } else {
00888       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
00889     }
00890     TheNeg->moveBefore(InsertPt);
00891     return TheNeg;
00892   }
00893 
00894   // Insert a 'neg' instruction that subtracts the value from zero to get the
00895   // negation.
00896   return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
00897 }
00898 
00899 /// ShouldBreakUpSubtract - Return true if we should break up this subtract of
00900 /// X-Y into (X + -Y).
00901 static bool ShouldBreakUpSubtract(Instruction *Sub) {
00902   // If this is a negation, we can't split it up!
00903   if (BinaryOperator::isNeg(Sub))
00904     return false;
00905 
00906   // Don't bother to break this up unless either the LHS is an associable add or
00907   // subtract or if this is only used by one.
00908   if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
00909       isReassociableOp(Sub->getOperand(0), Instruction::Sub))
00910     return true;
00911   if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
00912       isReassociableOp(Sub->getOperand(1), Instruction::Sub))
00913     return true;
00914   if (Sub->hasOneUse() &&
00915       (isReassociableOp(Sub->user_back(), Instruction::Add) ||
00916        isReassociableOp(Sub->user_back(), Instruction::Sub)))
00917     return true;
00918 
00919   return false;
00920 }
00921 
00922 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
00923 /// only used by an add, transform this into (X+(0-Y)) to promote better
00924 /// reassociation.
00925 static BinaryOperator *BreakUpSubtract(Instruction *Sub) {
00926   // Convert a subtract into an add and a neg instruction. This allows sub
00927   // instructions to be commuted with other add instructions.
00928   //
00929   // Calculate the negative value of Operand 1 of the sub instruction,
00930   // and set it as the RHS of the add instruction we just made.
00931   //
00932   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
00933   BinaryOperator *New =
00934     BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
00935   Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
00936   Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
00937   New->takeName(Sub);
00938 
00939   // Everyone now refers to the add instruction.
00940   Sub->replaceAllUsesWith(New);
00941   New->setDebugLoc(Sub->getDebugLoc());
00942 
00943   DEBUG(dbgs() << "Negated: " << *New << '\n');
00944   return New;
00945 }
00946 
00947 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
00948 /// by one, change this into a multiply by a constant to assist with further
00949 /// reassociation.
00950 static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
00951   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
00952   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
00953 
00954   BinaryOperator *Mul =
00955     BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
00956   Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
00957   Mul->takeName(Shl);
00958   Shl->replaceAllUsesWith(Mul);
00959   Mul->setDebugLoc(Shl->getDebugLoc());
00960   return Mul;
00961 }
00962 
00963 /// FindInOperandList - Scan backwards and forwards among values with the same
00964 /// rank as element i to see if X exists.  If X does not exist, return i.  This
00965 /// is useful when scanning for 'x' when we see '-x' because they both get the
00966 /// same rank.
00967 static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
00968                                   Value *X) {
00969   unsigned XRank = Ops[i].Rank;
00970   unsigned e = Ops.size();
00971   for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
00972     if (Ops[j].Op == X)
00973       return j;
00974   // Scan backwards.
00975   for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
00976     if (Ops[j].Op == X)
00977       return j;
00978   return i;
00979 }
00980 
00981 /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
00982 /// and returning the result.  Insert the tree before I.
00983 static Value *EmitAddTreeOfValues(Instruction *I,
00984                                   SmallVectorImpl<WeakVH> &Ops){
00985   if (Ops.size() == 1) return Ops.back();
00986 
00987   Value *V1 = Ops.back();
00988   Ops.pop_back();
00989   Value *V2 = EmitAddTreeOfValues(I, Ops);
00990   return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
00991 }
00992 
00993 /// RemoveFactorFromExpression - If V is an expression tree that is a
00994 /// multiplication sequence, and if this sequence contains a multiply by Factor,
00995 /// remove Factor from the tree and return the new tree.
00996 Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
00997   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
00998   if (!BO) return 0;
00999 
01000   SmallVector<RepeatedValue, 8> Tree;
01001   MadeChange |= LinearizeExprTree(BO, Tree);
01002   SmallVector<ValueEntry, 8> Factors;
01003   Factors.reserve(Tree.size());
01004   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
01005     RepeatedValue E = Tree[i];
01006     Factors.append(E.second.getZExtValue(),
01007                    ValueEntry(getRank(E.first), E.first));
01008   }
01009 
01010   bool FoundFactor = false;
01011   bool NeedsNegate = false;
01012   for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
01013     if (Factors[i].Op == Factor) {
01014       FoundFactor = true;
01015       Factors.erase(Factors.begin()+i);
01016       break;
01017     }
01018 
01019     // If this is a negative version of this factor, remove it.
01020     if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
01021       if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
01022         if (FC1->getValue() == -FC2->getValue()) {
01023           FoundFactor = NeedsNegate = true;
01024           Factors.erase(Factors.begin()+i);
01025           break;
01026         }
01027   }
01028 
01029   if (!FoundFactor) {
01030     // Make sure to restore the operands to the expression tree.
01031     RewriteExprTree(BO, Factors);
01032     return 0;
01033   }
01034 
01035   BasicBlock::iterator InsertPt = BO; ++InsertPt;
01036 
01037   // If this was just a single multiply, remove the multiply and return the only
01038   // remaining operand.
01039   if (Factors.size() == 1) {
01040     RedoInsts.insert(BO);
01041     V = Factors[0].Op;
01042   } else {
01043     RewriteExprTree(BO, Factors);
01044     V = BO;
01045   }
01046 
01047   if (NeedsNegate)
01048     V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
01049 
01050   return V;
01051 }
01052 
01053 /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
01054 /// add its operands as factors, otherwise add V to the list of factors.
01055 ///
01056 /// Ops is the top-level list of add operands we're trying to factor.
01057 static void FindSingleUseMultiplyFactors(Value *V,
01058                                          SmallVectorImpl<Value*> &Factors,
01059                                        const SmallVectorImpl<ValueEntry> &Ops) {
01060   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
01061   if (!BO) {
01062     Factors.push_back(V);
01063     return;
01064   }
01065 
01066   // Otherwise, add the LHS and RHS to the list of factors.
01067   FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
01068   FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
01069 }
01070 
01071 /// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
01072 /// instruction.  This optimizes based on identities.  If it can be reduced to
01073 /// a single Value, it is returned, otherwise the Ops list is mutated as
01074 /// necessary.
01075 static Value *OptimizeAndOrXor(unsigned Opcode,
01076                                SmallVectorImpl<ValueEntry> &Ops) {
01077   // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
01078   // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
01079   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01080     // First, check for X and ~X in the operand list.
01081     assert(i < Ops.size());
01082     if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
01083       Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
01084       unsigned FoundX = FindInOperandList(Ops, i, X);
01085       if (FoundX != i) {
01086         if (Opcode == Instruction::And)   // ...&X&~X = 0
01087           return Constant::getNullValue(X->getType());
01088 
01089         if (Opcode == Instruction::Or)    // ...|X|~X = -1
01090           return Constant::getAllOnesValue(X->getType());
01091       }
01092     }
01093 
01094     // Next, check for duplicate pairs of values, which we assume are next to
01095     // each other, due to our sorting criteria.
01096     assert(i < Ops.size());
01097     if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
01098       if (Opcode == Instruction::And || Opcode == Instruction::Or) {
01099         // Drop duplicate values for And and Or.
01100         Ops.erase(Ops.begin()+i);
01101         --i; --e;
01102         ++NumAnnihil;
01103         continue;
01104       }
01105 
01106       // Drop pairs of values for Xor.
01107       assert(Opcode == Instruction::Xor);
01108       if (e == 2)
01109         return Constant::getNullValue(Ops[0].Op->getType());
01110 
01111       // Y ^ X^X -> Y
01112       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
01113       i -= 1; e -= 2;
01114       ++NumAnnihil;
01115     }
01116   }
01117   return 0;
01118 }
01119 
01120 /// Helper funciton of CombineXorOpnd(). It creates a bitwise-and
01121 /// instruction with the given two operands, and return the resulting
01122 /// instruction. There are two special cases: 1) if the constant operand is 0,
01123 /// it will return NULL. 2) if the constant is ~0, the symbolic operand will
01124 /// be returned.
01125 static Value *createAndInstr(Instruction *InsertBefore, Value *Opnd, 
01126                              const APInt &ConstOpnd) {
01127   if (ConstOpnd != 0) {
01128     if (!ConstOpnd.isAllOnesValue()) {
01129       LLVMContext &Ctx = Opnd->getType()->getContext();
01130       Instruction *I;
01131       I = BinaryOperator::CreateAnd(Opnd, ConstantInt::get(Ctx, ConstOpnd),
01132                                     "and.ra", InsertBefore);
01133       I->setDebugLoc(InsertBefore->getDebugLoc());
01134       return I;
01135     }
01136     return Opnd;
01137   }
01138   return 0;
01139 }
01140 
01141 // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
01142 // into "R ^ C", where C would be 0, and R is a symbolic value.
01143 //
01144 // If it was successful, true is returned, and the "R" and "C" is returned
01145 // via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
01146 // and both "Res" and "ConstOpnd" remain unchanged.
01147 //  
01148 bool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
01149                                  APInt &ConstOpnd, Value *&Res) {
01150   // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2 
01151   //                       = ((x | c1) ^ c1) ^ (c1 ^ c2)
01152   //                       = (x & ~c1) ^ (c1 ^ c2)
01153   // It is useful only when c1 == c2.
01154   if (Opnd1->isOrExpr() && Opnd1->getConstPart() != 0) {
01155     if (!Opnd1->getValue()->hasOneUse())
01156       return false;
01157 
01158     const APInt &C1 = Opnd1->getConstPart();
01159     if (C1 != ConstOpnd)
01160       return false;
01161 
01162     Value *X = Opnd1->getSymbolicPart();
01163     Res = createAndInstr(I, X, ~C1);
01164     // ConstOpnd was C2, now C1 ^ C2.
01165     ConstOpnd ^= C1;
01166 
01167     if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
01168       RedoInsts.insert(T);
01169     return true;
01170   }
01171   return false;
01172 }
01173 
01174                            
01175 // Helper function of OptimizeXor(). It tries to simplify
01176 // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
01177 // symbolic value. 
01178 // 
01179 // If it was successful, true is returned, and the "R" and "C" is returned 
01180 // via "Res" and "ConstOpnd", respectively (If the entire expression is
01181 // evaluated to a constant, the Res is set to NULL); otherwise, false is
01182 // returned, and both "Res" and "ConstOpnd" remain unchanged.
01183 bool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
01184                                  APInt &ConstOpnd, Value *&Res) {
01185   Value *X = Opnd1->getSymbolicPart();
01186   if (X != Opnd2->getSymbolicPart())
01187     return false;
01188 
01189   // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
01190   int DeadInstNum = 1;
01191   if (Opnd1->getValue()->hasOneUse())
01192     DeadInstNum++;
01193   if (Opnd2->getValue()->hasOneUse())
01194     DeadInstNum++;
01195 
01196   // Xor-Rule 2:
01197   //  (x | c1) ^ (x & c2)
01198   //   = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
01199   //   = (x & ~c1) ^ (x & c2) ^ c1               // Xor-Rule 1
01200   //   = (x & c3) ^ c1, where c3 = ~c1 ^ c2      // Xor-rule 3
01201   //
01202   if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
01203     if (Opnd2->isOrExpr())
01204       std::swap(Opnd1, Opnd2);
01205 
01206     const APInt &C1 = Opnd1->getConstPart();
01207     const APInt &C2 = Opnd2->getConstPart();
01208     APInt C3((~C1) ^ C2);
01209 
01210     // Do not increase code size!
01211     if (C3 != 0 && !C3.isAllOnesValue()) {
01212       int NewInstNum = ConstOpnd != 0 ? 1 : 2;
01213       if (NewInstNum > DeadInstNum)
01214         return false;
01215     }
01216 
01217     Res = createAndInstr(I, X, C3);
01218     ConstOpnd ^= C1;
01219 
01220   } else if (Opnd1->isOrExpr()) {
01221     // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
01222     //
01223     const APInt &C1 = Opnd1->getConstPart();
01224     const APInt &C2 = Opnd2->getConstPart();
01225     APInt C3 = C1 ^ C2;
01226     
01227     // Do not increase code size
01228     if (C3 != 0 && !C3.isAllOnesValue()) {
01229       int NewInstNum = ConstOpnd != 0 ? 1 : 2;
01230       if (NewInstNum > DeadInstNum)
01231         return false;
01232     }
01233 
01234     Res = createAndInstr(I, X, C3);
01235     ConstOpnd ^= C3;
01236   } else {
01237     // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
01238     //
01239     const APInt &C1 = Opnd1->getConstPart();
01240     const APInt &C2 = Opnd2->getConstPart();
01241     APInt C3 = C1 ^ C2;
01242     Res = createAndInstr(I, X, C3);
01243   }
01244 
01245   // Put the original operands in the Redo list; hope they will be deleted
01246   // as dead code.
01247   if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
01248     RedoInsts.insert(T);
01249   if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
01250     RedoInsts.insert(T);
01251 
01252   return true;
01253 }
01254 
01255 /// Optimize a series of operands to an 'xor' instruction. If it can be reduced
01256 /// to a single Value, it is returned, otherwise the Ops list is mutated as
01257 /// necessary.
01258 Value *Reassociate::OptimizeXor(Instruction *I,
01259                                 SmallVectorImpl<ValueEntry> &Ops) {
01260   if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
01261     return V;
01262       
01263   if (Ops.size() == 1)
01264     return 0;
01265 
01266   SmallVector<XorOpnd, 8> Opnds;
01267   SmallVector<XorOpnd*, 8> OpndPtrs;
01268   Type *Ty = Ops[0].Op->getType();
01269   APInt ConstOpnd(Ty->getIntegerBitWidth(), 0);
01270 
01271   // Step 1: Convert ValueEntry to XorOpnd
01272   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01273     Value *V = Ops[i].Op;
01274     if (!isa<ConstantInt>(V)) {
01275       XorOpnd O(V);
01276       O.setSymbolicRank(getRank(O.getSymbolicPart()));
01277       Opnds.push_back(O);
01278     } else
01279       ConstOpnd ^= cast<ConstantInt>(V)->getValue();
01280   }
01281 
01282   // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
01283   //  It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
01284   //  the "OpndPtrs" as well. For the similar reason, do not fuse this loop
01285   //  with the previous loop --- the iterator of the "Opnds" may be invalidated
01286   //  when new elements are added to the vector.
01287   for (unsigned i = 0, e = Opnds.size(); i != e; ++i)
01288     OpndPtrs.push_back(&Opnds[i]);
01289 
01290   // Step 2: Sort the Xor-Operands in a way such that the operands containing
01291   //  the same symbolic value cluster together. For instance, the input operand
01292   //  sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
01293   //  ("x | 123", "x & 789", "y & 456").
01294   std::stable_sort(OpndPtrs.begin(), OpndPtrs.end(), XorOpnd::PtrSortFunctor());
01295 
01296   // Step 3: Combine adjacent operands
01297   XorOpnd *PrevOpnd = 0;
01298   bool Changed = false;
01299   for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
01300     XorOpnd *CurrOpnd = OpndPtrs[i];
01301     // The combined value
01302     Value *CV;
01303 
01304     // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
01305     if (ConstOpnd != 0 && CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
01306       Changed = true;
01307       if (CV)
01308         *CurrOpnd = XorOpnd(CV);
01309       else {
01310         CurrOpnd->Invalidate();
01311         continue;
01312       }
01313     }
01314 
01315     if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
01316       PrevOpnd = CurrOpnd;
01317       continue;
01318     }
01319 
01320     // step 3.2: When previous and current operands share the same symbolic
01321     //  value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd" 
01322     //    
01323     if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
01324       // Remove previous operand
01325       PrevOpnd->Invalidate();
01326       if (CV) {
01327         *CurrOpnd = XorOpnd(CV);
01328         PrevOpnd = CurrOpnd;
01329       } else {
01330         CurrOpnd->Invalidate();
01331         PrevOpnd = 0;
01332       }
01333       Changed = true;
01334     }
01335   }
01336 
01337   // Step 4: Reassemble the Ops
01338   if (Changed) {
01339     Ops.clear();
01340     for (unsigned int i = 0, e = Opnds.size(); i < e; i++) {
01341       XorOpnd &O = Opnds[i];
01342       if (O.isInvalid())
01343         continue;
01344       ValueEntry VE(getRank(O.getValue()), O.getValue());
01345       Ops.push_back(VE);
01346     }
01347     if (ConstOpnd != 0) {
01348       Value *C = ConstantInt::get(Ty->getContext(), ConstOpnd);
01349       ValueEntry VE(getRank(C), C);
01350       Ops.push_back(VE);
01351     }
01352     int Sz = Ops.size();
01353     if (Sz == 1)
01354       return Ops.back().Op;
01355     else if (Sz == 0) {
01356       assert(ConstOpnd == 0);
01357       return ConstantInt::get(Ty->getContext(), ConstOpnd);
01358     }
01359   }
01360 
01361   return 0;
01362 }
01363 
01364 /// OptimizeAdd - Optimize a series of operands to an 'add' instruction.  This
01365 /// optimizes based on identities.  If it can be reduced to a single Value, it
01366 /// is returned, otherwise the Ops list is mutated as necessary.
01367 Value *Reassociate::OptimizeAdd(Instruction *I,
01368                                 SmallVectorImpl<ValueEntry> &Ops) {
01369   // Scan the operand lists looking for X and -X pairs.  If we find any, we
01370   // can simplify the expression. X+-X == 0.  While we're at it, scan for any
01371   // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
01372   //
01373   // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
01374   //
01375   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01376     Value *TheOp = Ops[i].Op;
01377     // Check to see if we've seen this operand before.  If so, we factor all
01378     // instances of the operand together.  Due to our sorting criteria, we know
01379     // that these need to be next to each other in the vector.
01380     if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
01381       // Rescan the list, remove all instances of this operand from the expr.
01382       unsigned NumFound = 0;
01383       do {
01384         Ops.erase(Ops.begin()+i);
01385         ++NumFound;
01386       } while (i != Ops.size() && Ops[i].Op == TheOp);
01387 
01388       DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
01389       ++NumFactor;
01390 
01391       // Insert a new multiply.
01392       Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
01393       Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
01394 
01395       // Now that we have inserted a multiply, optimize it. This allows us to
01396       // handle cases that require multiple factoring steps, such as this:
01397       // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
01398       RedoInsts.insert(cast<Instruction>(Mul));
01399 
01400       // If every add operand was a duplicate, return the multiply.
01401       if (Ops.empty())
01402         return Mul;
01403 
01404       // Otherwise, we had some input that didn't have the dupe, such as
01405       // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
01406       // things being added by this operation.
01407       Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
01408 
01409       --i;
01410       e = Ops.size();
01411       continue;
01412     }
01413 
01414     // Check for X and -X in the operand list.
01415     if (!BinaryOperator::isNeg(TheOp))
01416       continue;
01417 
01418     Value *X = BinaryOperator::getNegArgument(TheOp);
01419     unsigned FoundX = FindInOperandList(Ops, i, X);
01420     if (FoundX == i)
01421       continue;
01422 
01423     // Remove X and -X from the operand list.
01424     if (Ops.size() == 2)
01425       return Constant::getNullValue(X->getType());
01426 
01427     Ops.erase(Ops.begin()+i);
01428     if (i < FoundX)
01429       --FoundX;
01430     else
01431       --i;   // Need to back up an extra one.
01432     Ops.erase(Ops.begin()+FoundX);
01433     ++NumAnnihil;
01434     --i;     // Revisit element.
01435     e -= 2;  // Removed two elements.
01436   }
01437 
01438   // Scan the operand list, checking to see if there are any common factors
01439   // between operands.  Consider something like A*A+A*B*C+D.  We would like to
01440   // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
01441   // To efficiently find this, we count the number of times a factor occurs
01442   // for any ADD operands that are MULs.
01443   DenseMap<Value*, unsigned> FactorOccurrences;
01444 
01445   // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
01446   // where they are actually the same multiply.
01447   unsigned MaxOcc = 0;
01448   Value *MaxOccVal = 0;
01449   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01450     BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
01451     if (!BOp)
01452       continue;
01453 
01454     // Compute all of the factors of this added value.
01455     SmallVector<Value*, 8> Factors;
01456     FindSingleUseMultiplyFactors(BOp, Factors, Ops);
01457     assert(Factors.size() > 1 && "Bad linearize!");
01458 
01459     // Add one to FactorOccurrences for each unique factor in this op.
01460     SmallPtrSet<Value*, 8> Duplicates;
01461     for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
01462       Value *Factor = Factors[i];
01463       if (!Duplicates.insert(Factor)) continue;
01464 
01465       unsigned Occ = ++FactorOccurrences[Factor];
01466       if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
01467 
01468       // If Factor is a negative constant, add the negated value as a factor
01469       // because we can percolate the negate out.  Watch for minint, which
01470       // cannot be positivified.
01471       if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
01472         if (CI->isNegative() && !CI->isMinValue(true)) {
01473           Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
01474           assert(!Duplicates.count(Factor) &&
01475                  "Shouldn't have two constant factors, missed a canonicalize");
01476 
01477           unsigned Occ = ++FactorOccurrences[Factor];
01478           if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
01479         }
01480     }
01481   }
01482 
01483   // If any factor occurred more than one time, we can pull it out.
01484   if (MaxOcc > 1) {
01485     DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
01486     ++NumFactor;
01487 
01488     // Create a new instruction that uses the MaxOccVal twice.  If we don't do
01489     // this, we could otherwise run into situations where removing a factor
01490     // from an expression will drop a use of maxocc, and this can cause
01491     // RemoveFactorFromExpression on successive values to behave differently.
01492     Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
01493     SmallVector<WeakVH, 4> NewMulOps;
01494     for (unsigned i = 0; i != Ops.size(); ++i) {
01495       // Only try to remove factors from expressions we're allowed to.
01496       BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
01497       if (!BOp)
01498         continue;
01499 
01500       if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
01501         // The factorized operand may occur several times.  Convert them all in
01502         // one fell swoop.
01503         for (unsigned j = Ops.size(); j != i;) {
01504           --j;
01505           if (Ops[j].Op == Ops[i].Op) {
01506             NewMulOps.push_back(V);
01507             Ops.erase(Ops.begin()+j);
01508           }
01509         }
01510         --i;
01511       }
01512     }
01513 
01514     // No need for extra uses anymore.
01515     delete DummyInst;
01516 
01517     unsigned NumAddedValues = NewMulOps.size();
01518     Value *V = EmitAddTreeOfValues(I, NewMulOps);
01519 
01520     // Now that we have inserted the add tree, optimize it. This allows us to
01521     // handle cases that require multiple factoring steps, such as this:
01522     // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
01523     assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
01524     (void)NumAddedValues;
01525     if (Instruction *VI = dyn_cast<Instruction>(V))
01526       RedoInsts.insert(VI);
01527 
01528     // Create the multiply.
01529     Instruction *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
01530 
01531     // Rerun associate on the multiply in case the inner expression turned into
01532     // a multiply.  We want to make sure that we keep things in canonical form.
01533     RedoInsts.insert(V2);
01534 
01535     // If every add operand included the factor (e.g. "A*B + A*C"), then the
01536     // entire result expression is just the multiply "A*(B+C)".
01537     if (Ops.empty())
01538       return V2;
01539 
01540     // Otherwise, we had some input that didn't have the factor, such as
01541     // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
01542     // things being added by this operation.
01543     Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
01544   }
01545 
01546   return 0;
01547 }
01548 
01549 /// \brief Build up a vector of value/power pairs factoring a product.
01550 ///
01551 /// Given a series of multiplication operands, build a vector of factors and
01552 /// the powers each is raised to when forming the final product. Sort them in
01553 /// the order of descending power.
01554 ///
01555 ///      (x*x)          -> [(x, 2)]
01556 ///     ((x*x)*x)       -> [(x, 3)]
01557 ///   ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
01558 ///
01559 /// \returns Whether any factors have a power greater than one.
01560 bool Reassociate::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
01561                                          SmallVectorImpl<Factor> &Factors) {
01562   // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
01563   // Compute the sum of powers of simplifiable factors.
01564   unsigned FactorPowerSum = 0;
01565   for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
01566     Value *Op = Ops[Idx-1].Op;
01567 
01568     // Count the number of occurrences of this value.
01569     unsigned Count = 1;
01570     for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
01571       ++Count;
01572     // Track for simplification all factors which occur 2 or more times.
01573     if (Count > 1)
01574       FactorPowerSum += Count;
01575   }
01576 
01577   // We can only simplify factors if the sum of the powers of our simplifiable
01578   // factors is 4 or higher. When that is the case, we will *always* have
01579   // a simplification. This is an important invariant to prevent cyclicly
01580   // trying to simplify already minimal formations.
01581   if (FactorPowerSum < 4)
01582     return false;
01583 
01584   // Now gather the simplifiable factors, removing them from Ops.
01585   FactorPowerSum = 0;
01586   for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
01587     Value *Op = Ops[Idx-1].Op;
01588 
01589     // Count the number of occurrences of this value.
01590     unsigned Count = 1;
01591     for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
01592       ++Count;
01593     if (Count == 1)
01594       continue;
01595     // Move an even number of occurrences to Factors.
01596     Count &= ~1U;
01597     Idx -= Count;
01598     FactorPowerSum += Count;
01599     Factors.push_back(Factor(Op, Count));
01600     Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
01601   }
01602 
01603   // None of the adjustments above should have reduced the sum of factor powers
01604   // below our mininum of '4'.
01605   assert(FactorPowerSum >= 4);
01606 
01607   std::stable_sort(Factors.begin(), Factors.end(), Factor::PowerDescendingSorter());
01608   return true;
01609 }
01610 
01611 /// \brief Build a tree of multiplies, computing the product of Ops.
01612 static Value *buildMultiplyTree(IRBuilder<> &Builder,
01613                                 SmallVectorImpl<Value*> &Ops) {
01614   if (Ops.size() == 1)
01615     return Ops.back();
01616 
01617   Value *LHS = Ops.pop_back_val();
01618   do {
01619     LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
01620   } while (!Ops.empty());
01621 
01622   return LHS;
01623 }
01624 
01625 /// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
01626 ///
01627 /// Given a vector of values raised to various powers, where no two values are
01628 /// equal and the powers are sorted in decreasing order, compute the minimal
01629 /// DAG of multiplies to compute the final product, and return that product
01630 /// value.
01631 Value *Reassociate::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
01632                                             SmallVectorImpl<Factor> &Factors) {
01633   assert(Factors[0].Power);
01634   SmallVector<Value *, 4> OuterProduct;
01635   for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
01636        Idx < Size && Factors[Idx].Power > 0; ++Idx) {
01637     if (Factors[Idx].Power != Factors[LastIdx].Power) {
01638       LastIdx = Idx;
01639       continue;
01640     }
01641 
01642     // We want to multiply across all the factors with the same power so that
01643     // we can raise them to that power as a single entity. Build a mini tree
01644     // for that.
01645     SmallVector<Value *, 4> InnerProduct;
01646     InnerProduct.push_back(Factors[LastIdx].Base);
01647     do {
01648       InnerProduct.push_back(Factors[Idx].Base);
01649       ++Idx;
01650     } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
01651 
01652     // Reset the base value of the first factor to the new expression tree.
01653     // We'll remove all the factors with the same power in a second pass.
01654     Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
01655     if (Instruction *MI = dyn_cast<Instruction>(M))
01656       RedoInsts.insert(MI);
01657 
01658     LastIdx = Idx;
01659   }
01660   // Unique factors with equal powers -- we've folded them into the first one's
01661   // base.
01662   Factors.erase(std::unique(Factors.begin(), Factors.end(),
01663                             Factor::PowerEqual()),
01664                 Factors.end());
01665 
01666   // Iteratively collect the base of each factor with an add power into the
01667   // outer product, and halve each power in preparation for squaring the
01668   // expression.
01669   for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
01670     if (Factors[Idx].Power & 1)
01671       OuterProduct.push_back(Factors[Idx].Base);
01672     Factors[Idx].Power >>= 1;
01673   }
01674   if (Factors[0].Power) {
01675     Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
01676     OuterProduct.push_back(SquareRoot);
01677     OuterProduct.push_back(SquareRoot);
01678   }
01679   if (OuterProduct.size() == 1)
01680     return OuterProduct.front();
01681 
01682   Value *V = buildMultiplyTree(Builder, OuterProduct);
01683   return V;
01684 }
01685 
01686 Value *Reassociate::OptimizeMul(BinaryOperator *I,
01687                                 SmallVectorImpl<ValueEntry> &Ops) {
01688   // We can only optimize the multiplies when there is a chain of more than
01689   // three, such that a balanced tree might require fewer total multiplies.
01690   if (Ops.size() < 4)
01691     return 0;
01692 
01693   // Try to turn linear trees of multiplies without other uses of the
01694   // intermediate stages into minimal multiply DAGs with perfect sub-expression
01695   // re-use.
01696   SmallVector<Factor, 4> Factors;
01697   if (!collectMultiplyFactors(Ops, Factors))
01698     return 0; // All distinct factors, so nothing left for us to do.
01699 
01700   IRBuilder<> Builder(I);
01701   Value *V = buildMinimalMultiplyDAG(Builder, Factors);
01702   if (Ops.empty())
01703     return V;
01704 
01705   ValueEntry NewEntry = ValueEntry(getRank(V), V);
01706   Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
01707   return 0;
01708 }
01709 
01710 Value *Reassociate::OptimizeExpression(BinaryOperator *I,
01711                                        SmallVectorImpl<ValueEntry> &Ops) {
01712   // Now that we have the linearized expression tree, try to optimize it.
01713   // Start by folding any constants that we found.
01714   Constant *Cst = 0;
01715   unsigned Opcode = I->getOpcode();
01716   while (!Ops.empty() && isa<Constant>(Ops.back().Op)) {
01717     Constant *C = cast<Constant>(Ops.pop_back_val().Op);
01718     Cst = Cst ? ConstantExpr::get(Opcode, C, Cst) : C;
01719   }
01720   // If there was nothing but constants then we are done.
01721   if (Ops.empty())
01722     return Cst;
01723 
01724   // Put the combined constant back at the end of the operand list, except if
01725   // there is no point.  For example, an add of 0 gets dropped here, while a
01726   // multiplication by zero turns the whole expression into zero.
01727   if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
01728     if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
01729       return Cst;
01730     Ops.push_back(ValueEntry(0, Cst));
01731   }
01732 
01733   if (Ops.size() == 1) return Ops[0].Op;
01734 
01735   // Handle destructive annihilation due to identities between elements in the
01736   // argument list here.
01737   unsigned NumOps = Ops.size();
01738   switch (Opcode) {
01739   default: break;
01740   case Instruction::And:
01741   case Instruction::Or:
01742     if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
01743       return Result;
01744     break;
01745 
01746   case Instruction::Xor:
01747     if (Value *Result = OptimizeXor(I, Ops))
01748       return Result;
01749     break;
01750 
01751   case Instruction::Add:
01752     if (Value *Result = OptimizeAdd(I, Ops))
01753       return Result;
01754     break;
01755 
01756   case Instruction::Mul:
01757     if (Value *Result = OptimizeMul(I, Ops))
01758       return Result;
01759     break;
01760   }
01761 
01762   if (Ops.size() != NumOps)
01763     return OptimizeExpression(I, Ops);
01764   return 0;
01765 }
01766 
01767 /// EraseInst - Zap the given instruction, adding interesting operands to the
01768 /// work list.
01769 void Reassociate::EraseInst(Instruction *I) {
01770   assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
01771   SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
01772   // Erase the dead instruction.
01773   ValueRankMap.erase(I);
01774   RedoInsts.remove(I);
01775   I->eraseFromParent();
01776   // Optimize its operands.
01777   SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
01778   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01779     if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
01780       // If this is a node in an expression tree, climb to the expression root
01781       // and add that since that's where optimization actually happens.
01782       unsigned Opcode = Op->getOpcode();
01783       while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
01784              Visited.insert(Op))
01785         Op = Op->user_back();
01786       RedoInsts.insert(Op);
01787     }
01788 }
01789 
01790 /// OptimizeInst - Inspect and optimize the given instruction. Note that erasing
01791 /// instructions is not allowed.
01792 void Reassociate::OptimizeInst(Instruction *I) {
01793   // Only consider operations that we understand.
01794   if (!isa<BinaryOperator>(I))
01795     return;
01796 
01797   if (I->getOpcode() == Instruction::Shl &&
01798       isa<ConstantInt>(I->getOperand(1)))
01799     // If an operand of this shift is a reassociable multiply, or if the shift
01800     // is used by a reassociable multiply or add, turn into a multiply.
01801     if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
01802         (I->hasOneUse() &&
01803          (isReassociableOp(I->user_back(), Instruction::Mul) ||
01804           isReassociableOp(I->user_back(), Instruction::Add)))) {
01805       Instruction *NI = ConvertShiftToMul(I);
01806       RedoInsts.insert(I);
01807       MadeChange = true;
01808       I = NI;
01809     }
01810 
01811   // Floating point binary operators are not associative, but we can still
01812   // commute (some) of them, to canonicalize the order of their operands.
01813   // This can potentially expose more CSE opportunities, and makes writing
01814   // other transformations simpler.
01815   if ((I->getType()->isFloatingPointTy() || I->getType()->isVectorTy())) {
01816     // FAdd and FMul can be commuted.
01817     if (I->getOpcode() != Instruction::FMul &&
01818         I->getOpcode() != Instruction::FAdd)
01819       return;
01820 
01821     Value *LHS = I->getOperand(0);
01822     Value *RHS = I->getOperand(1);
01823     unsigned LHSRank = getRank(LHS);
01824     unsigned RHSRank = getRank(RHS);
01825 
01826     // Sort the operands by rank.
01827     if (RHSRank < LHSRank) {
01828       I->setOperand(0, RHS);
01829       I->setOperand(1, LHS);
01830     }
01831 
01832     return;
01833   }
01834 
01835   // Do not reassociate boolean (i1) expressions.  We want to preserve the
01836   // original order of evaluation for short-circuited comparisons that
01837   // SimplifyCFG has folded to AND/OR expressions.  If the expression
01838   // is not further optimized, it is likely to be transformed back to a
01839   // short-circuited form for code gen, and the source order may have been
01840   // optimized for the most likely conditions.
01841   if (I->getType()->isIntegerTy(1))
01842     return;
01843 
01844   // If this is a subtract instruction which is not already in negate form,
01845   // see if we can convert it to X+-Y.
01846   if (I->getOpcode() == Instruction::Sub) {
01847     if (ShouldBreakUpSubtract(I)) {
01848       Instruction *NI = BreakUpSubtract(I);
01849       RedoInsts.insert(I);
01850       MadeChange = true;
01851       I = NI;
01852     } else if (BinaryOperator::isNeg(I)) {
01853       // Otherwise, this is a negation.  See if the operand is a multiply tree
01854       // and if this is not an inner node of a multiply tree.
01855       if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
01856           (!I->hasOneUse() ||
01857            !isReassociableOp(I->user_back(), Instruction::Mul))) {
01858         Instruction *NI = LowerNegateToMultiply(I);
01859         RedoInsts.insert(I);
01860         MadeChange = true;
01861         I = NI;
01862       }
01863     }
01864   }
01865 
01866   // If this instruction is an associative binary operator, process it.
01867   if (!I->isAssociative()) return;
01868   BinaryOperator *BO = cast<BinaryOperator>(I);
01869 
01870   // If this is an interior node of a reassociable tree, ignore it until we
01871   // get to the root of the tree, to avoid N^2 analysis.
01872   unsigned Opcode = BO->getOpcode();
01873   if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode)
01874     return;
01875 
01876   // If this is an add tree that is used by a sub instruction, ignore it
01877   // until we process the subtract.
01878   if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
01879       cast<Instruction>(BO->user_back())->getOpcode() == Instruction::Sub)
01880     return;
01881 
01882   ReassociateExpression(BO);
01883 }
01884 
01885 void Reassociate::ReassociateExpression(BinaryOperator *I) {
01886 
01887   // First, walk the expression tree, linearizing the tree, collecting the
01888   // operand information.
01889   SmallVector<RepeatedValue, 8> Tree;
01890   MadeChange |= LinearizeExprTree(I, Tree);
01891   SmallVector<ValueEntry, 8> Ops;
01892   Ops.reserve(Tree.size());
01893   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
01894     RepeatedValue E = Tree[i];
01895     Ops.append(E.second.getZExtValue(),
01896                ValueEntry(getRank(E.first), E.first));
01897   }
01898 
01899   DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
01900 
01901   // Now that we have linearized the tree to a list and have gathered all of
01902   // the operands and their ranks, sort the operands by their rank.  Use a
01903   // stable_sort so that values with equal ranks will have their relative
01904   // positions maintained (and so the compiler is deterministic).  Note that
01905   // this sorts so that the highest ranking values end up at the beginning of
01906   // the vector.
01907   std::stable_sort(Ops.begin(), Ops.end());
01908 
01909   // OptimizeExpression - Now that we have the expression tree in a convenient
01910   // sorted form, optimize it globally if possible.
01911   if (Value *V = OptimizeExpression(I, Ops)) {
01912     if (V == I)
01913       // Self-referential expression in unreachable code.
01914       return;
01915     // This expression tree simplified to something that isn't a tree,
01916     // eliminate it.
01917     DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
01918     I->replaceAllUsesWith(V);
01919     if (Instruction *VI = dyn_cast<Instruction>(V))
01920       VI->setDebugLoc(I->getDebugLoc());
01921     RedoInsts.insert(I);
01922     ++NumAnnihil;
01923     return;
01924   }
01925 
01926   // We want to sink immediates as deeply as possible except in the case where
01927   // this is a multiply tree used only by an add, and the immediate is a -1.
01928   // In this case we reassociate to put the negation on the outside so that we
01929   // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
01930   if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
01931       cast<Instruction>(I->user_back())->getOpcode() == Instruction::Add &&
01932       isa<ConstantInt>(Ops.back().Op) &&
01933       cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
01934     ValueEntry Tmp = Ops.pop_back_val();
01935     Ops.insert(Ops.begin(), Tmp);
01936   }
01937 
01938   DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
01939 
01940   if (Ops.size() == 1) {
01941     if (Ops[0].Op == I)
01942       // Self-referential expression in unreachable code.
01943       return;
01944 
01945     // This expression tree simplified to something that isn't a tree,
01946     // eliminate it.
01947     I->replaceAllUsesWith(Ops[0].Op);
01948     if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
01949       OI->setDebugLoc(I->getDebugLoc());
01950     RedoInsts.insert(I);
01951     return;
01952   }
01953 
01954   // Now that we ordered and optimized the expressions, splat them back into
01955   // the expression tree, removing any unneeded nodes.
01956   RewriteExprTree(I, Ops);
01957 }
01958 
01959 bool Reassociate::runOnFunction(Function &F) {
01960   if (skipOptnoneFunction(F))
01961     return false;
01962 
01963   // Calculate the rank map for F
01964   BuildRankMap(F);
01965 
01966   MadeChange = false;
01967   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
01968     // Optimize every instruction in the basic block.
01969     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
01970       if (isInstructionTriviallyDead(II)) {
01971         EraseInst(II++);
01972       } else {
01973         OptimizeInst(II);
01974         assert(II->getParent() == BI && "Moved to a different block!");
01975         ++II;
01976       }
01977 
01978     // If this produced extra instructions to optimize, handle them now.
01979     while (!RedoInsts.empty()) {
01980       Instruction *I = RedoInsts.pop_back_val();
01981       if (isInstructionTriviallyDead(I))
01982         EraseInst(I);
01983       else
01984         OptimizeInst(I);
01985     }
01986   }
01987 
01988   // We are done with the rank map.
01989   RankMap.clear();
01990   ValueRankMap.clear();
01991 
01992   return MadeChange;
01993 }