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