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