1193323Sed//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This pass reassociates commutative expressions in an order that is designed
11201360Srdivacky// to promote better constant propagation, GCSE, LICM, PRE, etc.
12193323Sed//
13193323Sed// For example: 4 + (x + 5) -> x + (4 + 5)
14193323Sed//
15193323Sed// In the implementation of this algorithm, constants are assigned rank = 0,
16193323Sed// function arguments are rank = 1, and other values are assigned ranks
17193323Sed// corresponding to the reverse post order traversal of current function
18193323Sed// (starting at 2), which effectively gives values in deep loops higher rank
19193323Sed// than values not in loops.
20193323Sed//
21193323Sed//===----------------------------------------------------------------------===//
22193323Sed
23193323Sed#define DEBUG_TYPE "reassociate"
24193323Sed#include "llvm/Transforms/Scalar.h"
25239462Sdim#include "llvm/ADT/DenseMap.h"
26239462Sdim#include "llvm/ADT/PostOrderIterator.h"
27239462Sdim#include "llvm/ADT/STLExtras.h"
28239462Sdim#include "llvm/ADT/SetVector.h"
29239462Sdim#include "llvm/ADT/Statistic.h"
30193323Sed#include "llvm/Assembly/Writer.h"
31249423Sdim#include "llvm/IR/Constants.h"
32249423Sdim#include "llvm/IR/DerivedTypes.h"
33249423Sdim#include "llvm/IR/Function.h"
34249423Sdim#include "llvm/IR/IRBuilder.h"
35249423Sdim#include "llvm/IR/Instructions.h"
36249423Sdim#include "llvm/IR/IntrinsicInst.h"
37249423Sdim#include "llvm/Pass.h"
38193323Sed#include "llvm/Support/CFG.h"
39193323Sed#include "llvm/Support/Debug.h"
40193323Sed#include "llvm/Support/ValueHandle.h"
41198090Srdivacky#include "llvm/Support/raw_ostream.h"
42249423Sdim#include "llvm/Transforms/Utils/Local.h"
43193323Sed#include <algorithm>
44193323Sedusing namespace llvm;
45193323Sed
46193323SedSTATISTIC(NumChanged, "Number of insts reassociated");
47193323SedSTATISTIC(NumAnnihil, "Number of expr tree annihilated");
48193323SedSTATISTIC(NumFactor , "Number of multiplies factored");
49193323Sed
50193323Sednamespace {
51198090Srdivacky  struct ValueEntry {
52193323Sed    unsigned Rank;
53193323Sed    Value *Op;
54193323Sed    ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
55193323Sed  };
56193323Sed  inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
57193323Sed    return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
58193323Sed  }
59193323Sed}
60193323Sed
61193323Sed#ifndef NDEBUG
62193323Sed/// PrintOps - Print out the expression identified in the Ops list.
63193323Sed///
64201360Srdivackystatic void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
65193323Sed  Module *M = I->getParent()->getParent()->getParent();
66202375Srdivacky  dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
67201360Srdivacky       << *Ops[0].Op->getType() << '\t';
68193323Sed  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
69202375Srdivacky    dbgs() << "[ ";
70202375Srdivacky    WriteAsOperand(dbgs(), Ops[i].Op, false, M);
71202375Srdivacky    dbgs() << ", #" << Ops[i].Rank << "] ";
72193323Sed  }
73193323Sed}
74193323Sed#endif
75239462Sdim
76193323Sednamespace {
77239462Sdim  /// \brief Utility class representing a base and exponent pair which form one
78239462Sdim  /// factor of some product.
79239462Sdim  struct Factor {
80239462Sdim    Value *Base;
81239462Sdim    unsigned Power;
82239462Sdim
83239462Sdim    Factor(Value *Base, unsigned Power) : Base(Base), Power(Power) {}
84239462Sdim
85239462Sdim    /// \brief Sort factors by their Base.
86239462Sdim    struct BaseSorter {
87239462Sdim      bool operator()(const Factor &LHS, const Factor &RHS) {
88239462Sdim        return LHS.Base < RHS.Base;
89239462Sdim      }
90239462Sdim    };
91239462Sdim
92239462Sdim    /// \brief Compare factors for equal bases.
93239462Sdim    struct BaseEqual {
94239462Sdim      bool operator()(const Factor &LHS, const Factor &RHS) {
95239462Sdim        return LHS.Base == RHS.Base;
96239462Sdim      }
97239462Sdim    };
98239462Sdim
99239462Sdim    /// \brief Sort factors in descending order by their power.
100239462Sdim    struct PowerDescendingSorter {
101239462Sdim      bool operator()(const Factor &LHS, const Factor &RHS) {
102239462Sdim        return LHS.Power > RHS.Power;
103239462Sdim      }
104239462Sdim    };
105239462Sdim
106239462Sdim    /// \brief Compare factors for equal powers.
107239462Sdim    struct PowerEqual {
108239462Sdim      bool operator()(const Factor &LHS, const Factor &RHS) {
109239462Sdim        return LHS.Power == RHS.Power;
110239462Sdim      }
111239462Sdim    };
112239462Sdim  };
113249423Sdim
114249423Sdim  /// Utility class representing a non-constant Xor-operand. We classify
115249423Sdim  /// non-constant Xor-Operands into two categories:
116249423Sdim  ///  C1) The operand is in the form "X & C", where C is a constant and C != ~0
117249423Sdim  ///  C2)
118249423Sdim  ///    C2.1) The operand is in the form of "X | C", where C is a non-zero
119249423Sdim  ///          constant.
120249423Sdim  ///    C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
121249423Sdim  ///          operand as "E | 0"
122249423Sdim  class XorOpnd {
123249423Sdim  public:
124249423Sdim    XorOpnd(Value *V);
125249423Sdim
126249423Sdim    bool isInvalid() const { return SymbolicPart == 0; }
127249423Sdim    bool isOrExpr() const { return isOr; }
128249423Sdim    Value *getValue() const { return OrigVal; }
129249423Sdim    Value *getSymbolicPart() const { return SymbolicPart; }
130249423Sdim    unsigned getSymbolicRank() const { return SymbolicRank; }
131249423Sdim    const APInt &getConstPart() const { return ConstPart; }
132249423Sdim
133249423Sdim    void Invalidate() { SymbolicPart = OrigVal = 0; }
134249423Sdim    void setSymbolicRank(unsigned R) { SymbolicRank = R; }
135249423Sdim
136249423Sdim    // Sort the XorOpnd-Pointer in ascending order of symbolic-value-rank.
137249423Sdim    // The purpose is twofold:
138249423Sdim    // 1) Cluster together the operands sharing the same symbolic-value.
139249423Sdim    // 2) Operand having smaller symbolic-value-rank is permuted earlier, which
140249423Sdim    //   could potentially shorten crital path, and expose more loop-invariants.
141249423Sdim    //   Note that values' rank are basically defined in RPO order (FIXME).
142249423Sdim    //   So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier
143249423Sdim    //   than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
144249423Sdim    //   "z" in the order of X-Y-Z is better than any other orders.
145251662Sdim    struct PtrSortFunctor {
146251662Sdim      bool operator()(XorOpnd * const &LHS, XorOpnd * const &RHS) {
147251662Sdim        return LHS->getSymbolicRank() < RHS->getSymbolicRank();
148249423Sdim      }
149249423Sdim    };
150249423Sdim  private:
151249423Sdim    Value *OrigVal;
152249423Sdim    Value *SymbolicPart;
153249423Sdim    APInt ConstPart;
154249423Sdim    unsigned SymbolicRank;
155249423Sdim    bool isOr;
156249423Sdim  };
157239462Sdim}
158239462Sdim
159239462Sdimnamespace {
160198090Srdivacky  class Reassociate : public FunctionPass {
161201360Srdivacky    DenseMap<BasicBlock*, unsigned> RankMap;
162234353Sdim    DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
163239462Sdim    SetVector<AssertingVH<Instruction> > RedoInsts;
164193323Sed    bool MadeChange;
165193323Sed  public:
166193323Sed    static char ID; // Pass identification, replacement for typeid
167218893Sdim    Reassociate() : FunctionPass(ID) {
168218893Sdim      initializeReassociatePass(*PassRegistry::getPassRegistry());
169218893Sdim    }
170193323Sed
171193323Sed    bool runOnFunction(Function &F);
172193323Sed
173193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
174193323Sed      AU.setPreservesCFG();
175193323Sed    }
176193323Sed  private:
177193323Sed    void BuildRankMap(Function &F);
178193323Sed    unsigned getRank(Value *V);
179239462Sdim    void ReassociateExpression(BinaryOperator *I);
180239462Sdim    void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
181201360Srdivacky    Value *OptimizeExpression(BinaryOperator *I,
182201360Srdivacky                              SmallVectorImpl<ValueEntry> &Ops);
183201360Srdivacky    Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
184249423Sdim    Value *OptimizeXor(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
185249423Sdim    bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, APInt &ConstOpnd,
186249423Sdim                        Value *&Res);
187249423Sdim    bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
188249423Sdim                        APInt &ConstOpnd, Value *&Res);
189239462Sdim    bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
190239462Sdim                                SmallVectorImpl<Factor> &Factors);
191239462Sdim    Value *buildMinimalMultiplyDAG(IRBuilder<> &Builder,
192239462Sdim                                   SmallVectorImpl<Factor> &Factors);
193239462Sdim    Value *OptimizeMul(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
194193323Sed    Value *RemoveFactorFromExpression(Value *V, Value *Factor);
195239462Sdim    void EraseInst(Instruction *I);
196239462Sdim    void OptimizeInst(Instruction *I);
197193323Sed  };
198193323Sed}
199193323Sed
200249423SdimXorOpnd::XorOpnd(Value *V) {
201249423Sdim  assert(!isa<ConstantInt>(V) && "No ConstantInt");
202249423Sdim  OrigVal = V;
203249423Sdim  Instruction *I = dyn_cast<Instruction>(V);
204249423Sdim  SymbolicRank = 0;
205249423Sdim
206249423Sdim  if (I && (I->getOpcode() == Instruction::Or ||
207249423Sdim            I->getOpcode() == Instruction::And)) {
208249423Sdim    Value *V0 = I->getOperand(0);
209249423Sdim    Value *V1 = I->getOperand(1);
210249423Sdim    if (isa<ConstantInt>(V0))
211249423Sdim      std::swap(V0, V1);
212249423Sdim
213249423Sdim    if (ConstantInt *C = dyn_cast<ConstantInt>(V1)) {
214249423Sdim      ConstPart = C->getValue();
215249423Sdim      SymbolicPart = V0;
216249423Sdim      isOr = (I->getOpcode() == Instruction::Or);
217249423Sdim      return;
218249423Sdim    }
219249423Sdim  }
220249423Sdim
221249423Sdim  // view the operand as "V | 0"
222249423Sdim  SymbolicPart = V;
223249423Sdim  ConstPart = APInt::getNullValue(V->getType()->getIntegerBitWidth());
224249423Sdim  isOr = true;
225249423Sdim}
226249423Sdim
227193323Sedchar Reassociate::ID = 0;
228212904SdimINITIALIZE_PASS(Reassociate, "reassociate",
229218893Sdim                "Reassociate expressions", false, false)
230193323Sed
231193323Sed// Public interface to the Reassociate pass
232193323SedFunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
233193323Sed
234239462Sdim/// isReassociableOp - Return true if V is an instruction of the specified
235239462Sdim/// opcode and if it only has one use.
236239462Sdimstatic BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
237239462Sdim  if (V->hasOneUse() && isa<Instruction>(V) &&
238239462Sdim      cast<Instruction>(V)->getOpcode() == Opcode)
239239462Sdim    return cast<BinaryOperator>(V);
240239462Sdim  return 0;
241193323Sed}
242193323Sed
243193323Sedstatic bool isUnmovableInstruction(Instruction *I) {
244263508Sdim  switch (I->getOpcode()) {
245263508Sdim  case Instruction::PHI:
246263508Sdim  case Instruction::LandingPad:
247263508Sdim  case Instruction::Alloca:
248263508Sdim  case Instruction::Load:
249263508Sdim  case Instruction::Invoke:
250263508Sdim  case Instruction::UDiv:
251263508Sdim  case Instruction::SDiv:
252263508Sdim  case Instruction::FDiv:
253263508Sdim  case Instruction::URem:
254263508Sdim  case Instruction::SRem:
255263508Sdim  case Instruction::FRem:
256193323Sed    return true;
257263508Sdim  case Instruction::Call:
258263508Sdim    return !isa<DbgInfoIntrinsic>(I);
259263508Sdim  default:
260263508Sdim    return false;
261263508Sdim  }
262193323Sed}
263193323Sed
264193323Sedvoid Reassociate::BuildRankMap(Function &F) {
265193323Sed  unsigned i = 2;
266193323Sed
267193323Sed  // Assign distinct ranks to function arguments
268193323Sed  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
269193323Sed    ValueRankMap[&*I] = ++i;
270193323Sed
271193323Sed  ReversePostOrderTraversal<Function*> RPOT(&F);
272193323Sed  for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
273193323Sed         E = RPOT.end(); I != E; ++I) {
274193323Sed    BasicBlock *BB = *I;
275193323Sed    unsigned BBRank = RankMap[BB] = ++i << 16;
276193323Sed
277193323Sed    // Walk the basic block, adding precomputed ranks for any instructions that
278193323Sed    // we cannot move.  This ensures that the ranks for these instructions are
279193323Sed    // all different in the block.
280193323Sed    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
281193323Sed      if (isUnmovableInstruction(I))
282193323Sed        ValueRankMap[&*I] = ++BBRank;
283193323Sed  }
284193323Sed}
285193323Sed
286193323Sedunsigned Reassociate::getRank(Value *V) {
287193323Sed  Instruction *I = dyn_cast<Instruction>(V);
288201360Srdivacky  if (I == 0) {
289201360Srdivacky    if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
290201360Srdivacky    return 0;  // Otherwise it's a global or constant, rank 0.
291201360Srdivacky  }
292193323Sed
293201360Srdivacky  if (unsigned Rank = ValueRankMap[I])
294201360Srdivacky    return Rank;    // Rank already known?
295193323Sed
296193323Sed  // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
297193323Sed  // we can reassociate expressions for code motion!  Since we do not recurse
298193323Sed  // for PHI nodes, we cannot have infinite recursion here, because there
299193323Sed  // cannot be loops in the value graph that do not go through PHI nodes.
300193323Sed  unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
301193323Sed  for (unsigned i = 0, e = I->getNumOperands();
302193323Sed       i != e && Rank != MaxRank; ++i)
303193323Sed    Rank = std::max(Rank, getRank(I->getOperand(i)));
304193323Sed
305193323Sed  // If this is a not or neg instruction, do not count it for rank.  This
306193323Sed  // assures us that X and ~X will have the same rank.
307203954Srdivacky  if (!I->getType()->isIntegerTy() ||
308193323Sed      (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
309193323Sed    ++Rank;
310193323Sed
311202375Srdivacky  //DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
312198090Srdivacky  //     << Rank << "\n");
313193323Sed
314201360Srdivacky  return ValueRankMap[I] = Rank;
315193323Sed}
316193323Sed
317193323Sed/// LowerNegateToMultiply - Replace 0-X with X*-1.
318193323Sed///
319239462Sdimstatic BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
320198090Srdivacky  Constant *Cst = Constant::getAllOnesValue(Neg->getType());
321193323Sed
322239462Sdim  BinaryOperator *Res =
323239462Sdim    BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
324239462Sdim  Neg->setOperand(1, Constant::getNullValue(Neg->getType())); // Drop use of op.
325193323Sed  Res->takeName(Neg);
326193323Sed  Neg->replaceAllUsesWith(Res);
327221345Sdim  Res->setDebugLoc(Neg->getDebugLoc());
328193323Sed  return Res;
329193323Sed}
330193323Sed
331239462Sdim/// CarmichaelShift - Returns k such that lambda(2^Bitwidth) = 2^k, where lambda
332239462Sdim/// is the Carmichael function. This means that x^(2^k) === 1 mod 2^Bitwidth for
333239462Sdim/// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
334239462Sdim/// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
335239462Sdim/// even x in Bitwidth-bit arithmetic.
336239462Sdimstatic unsigned CarmichaelShift(unsigned Bitwidth) {
337239462Sdim  if (Bitwidth < 3)
338239462Sdim    return Bitwidth - 1;
339239462Sdim  return Bitwidth - 2;
340239462Sdim}
341193323Sed
342239462Sdim/// IncorporateWeight - Add the extra weight 'RHS' to the existing weight 'LHS',
343239462Sdim/// reducing the combined weight using any special properties of the operation.
344239462Sdim/// The existing weight LHS represents the computation X op X op ... op X where
345239462Sdim/// X occurs LHS times.  The combined weight represents  X op X op ... op X with
346239462Sdim/// X occurring LHS + RHS times.  If op is "Xor" for example then the combined
347239462Sdim/// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
348239462Sdim/// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
349239462Sdimstatic void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
350239462Sdim  // If we were working with infinite precision arithmetic then the combined
351239462Sdim  // weight would be LHS + RHS.  But we are using finite precision arithmetic,
352239462Sdim  // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
353239462Sdim  // for nilpotent operations and addition, but not for idempotent operations
354239462Sdim  // and multiplication), so it is important to correctly reduce the combined
355239462Sdim  // weight back into range if wrapping would be wrong.
356193323Sed
357239462Sdim  // If RHS is zero then the weight didn't change.
358239462Sdim  if (RHS.isMinValue())
359239462Sdim    return;
360239462Sdim  // If LHS is zero then the combined weight is RHS.
361239462Sdim  if (LHS.isMinValue()) {
362239462Sdim    LHS = RHS;
363239462Sdim    return;
364239462Sdim  }
365239462Sdim  // From this point on we know that neither LHS nor RHS is zero.
366193323Sed
367239462Sdim  if (Instruction::isIdempotent(Opcode)) {
368239462Sdim    // Idempotent means X op X === X, so any non-zero weight is equivalent to a
369239462Sdim    // weight of 1.  Keeping weights at zero or one also means that wrapping is
370239462Sdim    // not a problem.
371239462Sdim    assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
372239462Sdim    return; // Return a weight of 1.
373239462Sdim  }
374239462Sdim  if (Instruction::isNilpotent(Opcode)) {
375239462Sdim    // Nilpotent means X op X === 0, so reduce weights modulo 2.
376239462Sdim    assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
377239462Sdim    LHS = 0; // 1 + 1 === 0 modulo 2.
378239462Sdim    return;
379239462Sdim  }
380239462Sdim  if (Opcode == Instruction::Add) {
381239462Sdim    // TODO: Reduce the weight by exploiting nsw/nuw?
382239462Sdim    LHS += RHS;
383239462Sdim    return;
384239462Sdim  }
385193323Sed
386239462Sdim  assert(Opcode == Instruction::Mul && "Unknown associative operation!");
387239462Sdim  unsigned Bitwidth = LHS.getBitWidth();
388239462Sdim  // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
389239462Sdim  // can be replaced with W-CM.  That's because x^W=x^(W-CM) for every Bitwidth
390239462Sdim  // bit number x, since either x is odd in which case x^CM = 1, or x is even in
391239462Sdim  // which case both x^W and x^(W - CM) are zero.  By subtracting off multiples
392239462Sdim  // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
393239462Sdim  // which by a happy accident means that they can always be represented using
394239462Sdim  // Bitwidth bits.
395239462Sdim  // TODO: Reduce the weight by exploiting nsw/nuw?  (Could do much better than
396239462Sdim  // the Carmichael number).
397239462Sdim  if (Bitwidth > 3) {
398239462Sdim    /// CM - The value of Carmichael's lambda function.
399239462Sdim    APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
400239462Sdim    // Any weight W >= Threshold can be replaced with W - CM.
401239462Sdim    APInt Threshold = CM + Bitwidth;
402239462Sdim    assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
403239462Sdim    // For Bitwidth 4 or more the following sum does not overflow.
404239462Sdim    LHS += RHS;
405239462Sdim    while (LHS.uge(Threshold))
406239462Sdim      LHS -= CM;
407239462Sdim  } else {
408239462Sdim    // To avoid problems with overflow do everything the same as above but using
409239462Sdim    // a larger type.
410239462Sdim    unsigned CM = 1U << CarmichaelShift(Bitwidth);
411239462Sdim    unsigned Threshold = CM + Bitwidth;
412239462Sdim    assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
413239462Sdim           "Weights not reduced!");
414239462Sdim    unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
415239462Sdim    while (Total >= Threshold)
416239462Sdim      Total -= CM;
417239462Sdim    LHS = Total;
418239462Sdim  }
419239462Sdim}
420218893Sdim
421239462Sdimtypedef std::pair<Value*, APInt> RepeatedValue;
422193323Sed
423239462Sdim/// LinearizeExprTree - Given an associative binary expression, return the leaf
424239462Sdim/// nodes in Ops along with their weights (how many times the leaf occurs).  The
425239462Sdim/// original expression is the same as
426239462Sdim///   (Ops[0].first op Ops[0].first op ... Ops[0].first)  <- Ops[0].second times
427239462Sdim/// op
428239462Sdim///   (Ops[1].first op Ops[1].first op ... Ops[1].first)  <- Ops[1].second times
429239462Sdim/// op
430239462Sdim///   ...
431239462Sdim/// op
432239462Sdim///   (Ops[N].first op Ops[N].first op ... Ops[N].first)  <- Ops[N].second times
433193323Sed///
434243830Sdim/// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
435193323Sed///
436239462Sdim/// This routine may modify the function, in which case it returns 'true'.  The
437239462Sdim/// changes it makes may well be destructive, changing the value computed by 'I'
438239462Sdim/// to something completely different.  Thus if the routine returns 'true' then
439239462Sdim/// you MUST either replace I with a new expression computed from the Ops array,
440239462Sdim/// or use RewriteExprTree to put the values back in.
441239462Sdim///
442239462Sdim/// A leaf node is either not a binary operation of the same kind as the root
443239462Sdim/// node 'I' (i.e. is not a binary operator at all, or is, but with a different
444239462Sdim/// opcode), or is the same kind of binary operator but has a use which either
445239462Sdim/// does not belong to the expression, or does belong to the expression but is
446239462Sdim/// a leaf node.  Every leaf node has at least one use that is a non-leaf node
447239462Sdim/// of the expression, while for non-leaf nodes (except for the root 'I') every
448239462Sdim/// use is a non-leaf node of the expression.
449239462Sdim///
450239462Sdim/// For example:
451239462Sdim///           expression graph        node names
452239462Sdim///
453239462Sdim///                     +        |        I
454239462Sdim///                    / \       |
455239462Sdim///                   +   +      |      A,  B
456239462Sdim///                  / \ / \     |
457239462Sdim///                 *   +   *    |    C,  D,  E
458239462Sdim///                / \ / \ / \   |
459239462Sdim///                   +   *      |      F,  G
460239462Sdim///
461239462Sdim/// The leaf nodes are C, E, F and G.  The Ops array will contain (maybe not in
462239462Sdim/// that order) (C, 1), (E, 1), (F, 2), (G, 2).
463239462Sdim///
464239462Sdim/// The expression is maximal: if some instruction is a binary operator of the
465239462Sdim/// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
466239462Sdim/// then the instruction also belongs to the expression, is not a leaf node of
467239462Sdim/// it, and its operands also belong to the expression (but may be leaf nodes).
468239462Sdim///
469239462Sdim/// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
470239462Sdim/// order to ensure that every non-root node in the expression has *exactly one*
471239462Sdim/// use by a non-leaf node of the expression.  This destruction means that the
472239462Sdim/// caller MUST either replace 'I' with a new expression or use something like
473239462Sdim/// RewriteExprTree to put the values back in if the routine indicates that it
474239462Sdim/// made a change by returning 'true'.
475239462Sdim///
476239462Sdim/// In the above example either the right operand of A or the left operand of B
477239462Sdim/// will be replaced by undef.  If it is B's operand then this gives:
478239462Sdim///
479239462Sdim///                     +        |        I
480239462Sdim///                    / \       |
481239462Sdim///                   +   +      |      A,  B - operand of B replaced with undef
482239462Sdim///                  / \   \     |
483239462Sdim///                 *   +   *    |    C,  D,  E
484239462Sdim///                / \ / \ / \   |
485239462Sdim///                   +   *      |      F,  G
486239462Sdim///
487239462Sdim/// Note that such undef operands can only be reached by passing through 'I'.
488239462Sdim/// For example, if you visit operands recursively starting from a leaf node
489239462Sdim/// then you will never see such an undef operand unless you get back to 'I',
490239462Sdim/// which requires passing through a phi node.
491239462Sdim///
492239462Sdim/// Note that this routine may also mutate binary operators of the wrong type
493239462Sdim/// that have all uses inside the expression (i.e. only used by non-leaf nodes
494239462Sdim/// of the expression) if it can turn them into binary operators of the right
495239462Sdim/// type and thus make the expression bigger.
496239462Sdim
497239462Sdimstatic bool LinearizeExprTree(BinaryOperator *I,
498239462Sdim                              SmallVectorImpl<RepeatedValue> &Ops) {
499239462Sdim  DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
500239462Sdim  unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
501193323Sed  unsigned Opcode = I->getOpcode();
502239462Sdim  assert(Instruction::isAssociative(Opcode) &&
503239462Sdim         Instruction::isCommutative(Opcode) &&
504239462Sdim         "Expected an associative and commutative operation!");
505193323Sed
506239462Sdim  // Visit all operands of the expression, keeping track of their weight (the
507239462Sdim  // number of paths from the expression root to the operand, or if you like
508239462Sdim  // the number of times that operand occurs in the linearized expression).
509239462Sdim  // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
510239462Sdim  // while A has weight two.
511193323Sed
512239462Sdim  // Worklist of non-leaf nodes (their operands are in the expression too) along
513239462Sdim  // with their weights, representing a certain number of paths to the operator.
514239462Sdim  // If an operator occurs in the worklist multiple times then we found multiple
515239462Sdim  // ways to get to it.
516239462Sdim  SmallVector<std::pair<BinaryOperator*, APInt>, 8> Worklist; // (Op, Weight)
517239462Sdim  Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
518239462Sdim  bool MadeChange = false;
519239462Sdim
520239462Sdim  // Leaves of the expression are values that either aren't the right kind of
521239462Sdim  // operation (eg: a constant, or a multiply in an add tree), or are, but have
522239462Sdim  // some uses that are not inside the expression.  For example, in I = X + X,
523239462Sdim  // X = A + B, the value X has two uses (by I) that are in the expression.  If
524239462Sdim  // X has any other uses, for example in a return instruction, then we consider
525239462Sdim  // X to be a leaf, and won't analyze it further.  When we first visit a value,
526239462Sdim  // if it has more than one use then at first we conservatively consider it to
527239462Sdim  // be a leaf.  Later, as the expression is explored, we may discover some more
528239462Sdim  // uses of the value from inside the expression.  If all uses turn out to be
529239462Sdim  // from within the expression (and the value is a binary operator of the right
530239462Sdim  // kind) then the value is no longer considered to be a leaf, and its operands
531239462Sdim  // are explored.
532239462Sdim
533239462Sdim  // Leaves - Keeps track of the set of putative leaves as well as the number of
534239462Sdim  // paths to each leaf seen so far.
535239462Sdim  typedef DenseMap<Value*, APInt> LeafMap;
536239462Sdim  LeafMap Leaves; // Leaf -> Total weight so far.
537239462Sdim  SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
538239462Sdim
539239462Sdim#ifndef NDEBUG
540239462Sdim  SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
541239462Sdim#endif
542239462Sdim  while (!Worklist.empty()) {
543239462Sdim    std::pair<BinaryOperator*, APInt> P = Worklist.pop_back_val();
544239462Sdim    I = P.first; // We examine the operands of this binary operator.
545239462Sdim
546239462Sdim    for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
547239462Sdim      Value *Op = I->getOperand(OpIdx);
548239462Sdim      APInt Weight = P.second; // Number of paths to this operand.
549239462Sdim      DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
550239462Sdim      assert(!Op->use_empty() && "No uses, so how did we get to it?!");
551239462Sdim
552239462Sdim      // If this is a binary operation of the right kind with only one use then
553239462Sdim      // add its operands to the expression.
554239462Sdim      if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
555239462Sdim        assert(Visited.insert(Op) && "Not first visit!");
556239462Sdim        DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
557239462Sdim        Worklist.push_back(std::make_pair(BO, Weight));
558239462Sdim        continue;
559239462Sdim      }
560239462Sdim
561239462Sdim      // Appears to be a leaf.  Is the operand already in the set of leaves?
562239462Sdim      LeafMap::iterator It = Leaves.find(Op);
563239462Sdim      if (It == Leaves.end()) {
564239462Sdim        // Not in the leaf map.  Must be the first time we saw this operand.
565239462Sdim        assert(Visited.insert(Op) && "Not first visit!");
566239462Sdim        if (!Op->hasOneUse()) {
567239462Sdim          // This value has uses not accounted for by the expression, so it is
568239462Sdim          // not safe to modify.  Mark it as being a leaf.
569239462Sdim          DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
570239462Sdim          LeafOrder.push_back(Op);
571239462Sdim          Leaves[Op] = Weight;
572239462Sdim          continue;
573239462Sdim        }
574239462Sdim        // No uses outside the expression, try morphing it.
575239462Sdim      } else if (It != Leaves.end()) {
576239462Sdim        // Already in the leaf map.
577239462Sdim        assert(Visited.count(Op) && "In leaf map but not visited!");
578239462Sdim
579239462Sdim        // Update the number of paths to the leaf.
580239462Sdim        IncorporateWeight(It->second, Weight, Opcode);
581239462Sdim
582239462Sdim#if 0   // TODO: Re-enable once PR13021 is fixed.
583239462Sdim        // The leaf already has one use from inside the expression.  As we want
584239462Sdim        // exactly one such use, drop this new use of the leaf.
585239462Sdim        assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
586239462Sdim        I->setOperand(OpIdx, UndefValue::get(I->getType()));
587239462Sdim        MadeChange = true;
588239462Sdim
589239462Sdim        // If the leaf is a binary operation of the right kind and we now see
590239462Sdim        // that its multiple original uses were in fact all by nodes belonging
591239462Sdim        // to the expression, then no longer consider it to be a leaf and add
592239462Sdim        // its operands to the expression.
593239462Sdim        if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
594239462Sdim          DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
595239462Sdim          Worklist.push_back(std::make_pair(BO, It->second));
596239462Sdim          Leaves.erase(It);
597239462Sdim          continue;
598239462Sdim        }
599239462Sdim#endif
600239462Sdim
601239462Sdim        // If we still have uses that are not accounted for by the expression
602239462Sdim        // then it is not safe to modify the value.
603239462Sdim        if (!Op->hasOneUse())
604239462Sdim          continue;
605239462Sdim
606239462Sdim        // No uses outside the expression, try morphing it.
607239462Sdim        Weight = It->second;
608239462Sdim        Leaves.erase(It); // Since the value may be morphed below.
609239462Sdim      }
610239462Sdim
611239462Sdim      // At this point we have a value which, first of all, is not a binary
612239462Sdim      // expression of the right kind, and secondly, is only used inside the
613239462Sdim      // expression.  This means that it can safely be modified.  See if we
614239462Sdim      // can usefully morph it into an expression of the right kind.
615239462Sdim      assert((!isa<Instruction>(Op) ||
616239462Sdim              cast<Instruction>(Op)->getOpcode() != Opcode) &&
617239462Sdim             "Should have been handled above!");
618239462Sdim      assert(Op->hasOneUse() && "Has uses outside the expression tree!");
619239462Sdim
620239462Sdim      // If this is a multiply expression, turn any internal negations into
621239462Sdim      // multiplies by -1 so they can be reassociated.
622239462Sdim      BinaryOperator *BO = dyn_cast<BinaryOperator>(Op);
623239462Sdim      if (Opcode == Instruction::Mul && BO && BinaryOperator::isNeg(BO)) {
624239462Sdim        DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
625239462Sdim        BO = LowerNegateToMultiply(BO);
626239462Sdim        DEBUG(dbgs() << *BO << 'n');
627239462Sdim        Worklist.push_back(std::make_pair(BO, Weight));
628239462Sdim        MadeChange = true;
629239462Sdim        continue;
630239462Sdim      }
631239462Sdim
632239462Sdim      // Failed to morph into an expression of the right type.  This really is
633239462Sdim      // a leaf.
634239462Sdim      DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
635239462Sdim      assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
636239462Sdim      LeafOrder.push_back(Op);
637239462Sdim      Leaves[Op] = Weight;
638193323Sed    }
639193323Sed  }
640193323Sed
641239462Sdim  // The leaves, repeated according to their weights, represent the linearized
642239462Sdim  // form of the expression.
643239462Sdim  for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
644239462Sdim    Value *V = LeafOrder[i];
645239462Sdim    LeafMap::iterator It = Leaves.find(V);
646239462Sdim    if (It == Leaves.end())
647239462Sdim      // Node initially thought to be a leaf wasn't.
648239462Sdim      continue;
649239462Sdim    assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
650239462Sdim    APInt Weight = It->second;
651239462Sdim    if (Weight.isMinValue())
652239462Sdim      // Leaf already output or weight reduction eliminated it.
653239462Sdim      continue;
654239462Sdim    // Ensure the leaf is only output once.
655239462Sdim    It->second = 0;
656239462Sdim    Ops.push_back(std::make_pair(V, Weight));
657193323Sed  }
658193323Sed
659239462Sdim  // For nilpotent operations or addition there may be no operands, for example
660239462Sdim  // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
661239462Sdim  // in both cases the weight reduces to 0 causing the value to be skipped.
662239462Sdim  if (Ops.empty()) {
663243830Sdim    Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
664239462Sdim    assert(Identity && "Associative operation without identity!");
665239462Sdim    Ops.push_back(std::make_pair(Identity, APInt(Bitwidth, 1)));
666239462Sdim  }
667193323Sed
668239462Sdim  return MadeChange;
669193323Sed}
670193323Sed
671193323Sed// RewriteExprTree - Now that the operands for this expression tree are
672239462Sdim// linearized and optimized, emit them in-order.
673193323Sedvoid Reassociate::RewriteExprTree(BinaryOperator *I,
674239462Sdim                                  SmallVectorImpl<ValueEntry> &Ops) {
675239462Sdim  assert(Ops.size() > 1 && "Single values should be used directly!");
676218893Sdim
677243830Sdim  // Since our optimizations should never increase the number of operations, the
678243830Sdim  // new expression can usually be written reusing the existing binary operators
679239462Sdim  // from the original expression tree, without creating any new instructions,
680239462Sdim  // though the rewritten expression may have a completely different topology.
681239462Sdim  // We take care to not change anything if the new expression will be the same
682239462Sdim  // as the original.  If more than trivial changes (like commuting operands)
683239462Sdim  // were made then we are obliged to clear out any optional subclass data like
684239462Sdim  // nsw flags.
685218893Sdim
686239462Sdim  /// NodesToRewrite - Nodes from the original expression available for writing
687239462Sdim  /// the new expression into.
688239462Sdim  SmallVector<BinaryOperator*, 8> NodesToRewrite;
689239462Sdim  unsigned Opcode = I->getOpcode();
690239462Sdim  BinaryOperator *Op = I;
691239462Sdim
692243830Sdim  /// NotRewritable - The operands being written will be the leaves of the new
693243830Sdim  /// expression and must not be used as inner nodes (via NodesToRewrite) by
694243830Sdim  /// mistake.  Inner nodes are always reassociable, and usually leaves are not
695243830Sdim  /// (if they were they would have been incorporated into the expression and so
696243830Sdim  /// would not be leaves), so most of the time there is no danger of this.  But
697243830Sdim  /// in rare cases a leaf may become reassociable if an optimization kills uses
698243830Sdim  /// of it, or it may momentarily become reassociable during rewriting (below)
699243830Sdim  /// due it being removed as an operand of one of its uses.  Ensure that misuse
700243830Sdim  /// of leaf nodes as inner nodes cannot occur by remembering all of the future
701243830Sdim  /// leaves and refusing to reuse any of them as inner nodes.
702243830Sdim  SmallPtrSet<Value*, 8> NotRewritable;
703243830Sdim  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
704243830Sdim    NotRewritable.insert(Ops[i].Op);
705243830Sdim
706239462Sdim  // ExpressionChanged - Non-null if the rewritten expression differs from the
707239462Sdim  // original in some non-trivial way, requiring the clearing of optional flags.
708239462Sdim  // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
709239462Sdim  BinaryOperator *ExpressionChanged = 0;
710239462Sdim  for (unsigned i = 0; ; ++i) {
711239462Sdim    // The last operation (which comes earliest in the IR) is special as both
712239462Sdim    // operands will come from Ops, rather than just one with the other being
713239462Sdim    // a subexpression.
714239462Sdim    if (i+2 == Ops.size()) {
715239462Sdim      Value *NewLHS = Ops[i].Op;
716239462Sdim      Value *NewRHS = Ops[i+1].Op;
717239462Sdim      Value *OldLHS = Op->getOperand(0);
718239462Sdim      Value *OldRHS = Op->getOperand(1);
719239462Sdim
720239462Sdim      if (NewLHS == OldLHS && NewRHS == OldRHS)
721239462Sdim        // Nothing changed, leave it alone.
722239462Sdim        break;
723239462Sdim
724239462Sdim      if (NewLHS == OldRHS && NewRHS == OldLHS) {
725239462Sdim        // The order of the operands was reversed.  Swap them.
726239462Sdim        DEBUG(dbgs() << "RA: " << *Op << '\n');
727239462Sdim        Op->swapOperands();
728239462Sdim        DEBUG(dbgs() << "TO: " << *Op << '\n');
729239462Sdim        MadeChange = true;
730239462Sdim        ++NumChanged;
731239462Sdim        break;
732239462Sdim      }
733239462Sdim
734239462Sdim      // The new operation differs non-trivially from the original. Overwrite
735239462Sdim      // the old operands with the new ones.
736239462Sdim      DEBUG(dbgs() << "RA: " << *Op << '\n');
737239462Sdim      if (NewLHS != OldLHS) {
738243830Sdim        BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
739243830Sdim        if (BO && !NotRewritable.count(BO))
740239462Sdim          NodesToRewrite.push_back(BO);
741239462Sdim        Op->setOperand(0, NewLHS);
742239462Sdim      }
743239462Sdim      if (NewRHS != OldRHS) {
744243830Sdim        BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
745243830Sdim        if (BO && !NotRewritable.count(BO))
746239462Sdim          NodesToRewrite.push_back(BO);
747239462Sdim        Op->setOperand(1, NewRHS);
748239462Sdim      }
749239462Sdim      DEBUG(dbgs() << "TO: " << *Op << '\n');
750239462Sdim
751239462Sdim      ExpressionChanged = Op;
752193323Sed      MadeChange = true;
753193323Sed      ++NumChanged;
754239462Sdim
755239462Sdim      break;
756193323Sed    }
757193323Sed
758239462Sdim    // Not the last operation.  The left-hand side will be a sub-expression
759239462Sdim    // while the right-hand side will be the current element of Ops.
760239462Sdim    Value *NewRHS = Ops[i].Op;
761239462Sdim    if (NewRHS != Op->getOperand(1)) {
762239462Sdim      DEBUG(dbgs() << "RA: " << *Op << '\n');
763239462Sdim      if (NewRHS == Op->getOperand(0)) {
764239462Sdim        // The new right-hand side was already present as the left operand.  If
765239462Sdim        // we are lucky then swapping the operands will sort out both of them.
766239462Sdim        Op->swapOperands();
767239462Sdim      } else {
768239462Sdim        // Overwrite with the new right-hand side.
769243830Sdim        BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
770243830Sdim        if (BO && !NotRewritable.count(BO))
771239462Sdim          NodesToRewrite.push_back(BO);
772239462Sdim        Op->setOperand(1, NewRHS);
773239462Sdim        ExpressionChanged = Op;
774239462Sdim      }
775239462Sdim      DEBUG(dbgs() << "TO: " << *Op << '\n');
776239462Sdim      MadeChange = true;
777239462Sdim      ++NumChanged;
778239462Sdim    }
779218893Sdim
780239462Sdim    // Now deal with the left-hand side.  If this is already an operation node
781239462Sdim    // from the original expression then just rewrite the rest of the expression
782239462Sdim    // into it.
783243830Sdim    BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
784243830Sdim    if (BO && !NotRewritable.count(BO)) {
785239462Sdim      Op = BO;
786239462Sdim      continue;
787239462Sdim    }
788218893Sdim
789239462Sdim    // Otherwise, grab a spare node from the original expression and use that as
790239462Sdim    // the left-hand side.  If there are no nodes left then the optimizers made
791239462Sdim    // an expression with more nodes than the original!  This usually means that
792239462Sdim    // they did something stupid but it might mean that the problem was just too
793239462Sdim    // hard (finding the mimimal number of multiplications needed to realize a
794239462Sdim    // multiplication expression is NP-complete).  Whatever the reason, smart or
795239462Sdim    // stupid, create a new node if there are none left.
796239462Sdim    BinaryOperator *NewOp;
797239462Sdim    if (NodesToRewrite.empty()) {
798239462Sdim      Constant *Undef = UndefValue::get(I->getType());
799239462Sdim      NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
800239462Sdim                                     Undef, Undef, "", I);
801239462Sdim    } else {
802239462Sdim      NewOp = NodesToRewrite.pop_back_val();
803239462Sdim    }
804239462Sdim
805239462Sdim    DEBUG(dbgs() << "RA: " << *Op << '\n');
806239462Sdim    Op->setOperand(0, NewOp);
807239462Sdim    DEBUG(dbgs() << "TO: " << *Op << '\n');
808239462Sdim    ExpressionChanged = Op;
809193323Sed    MadeChange = true;
810193323Sed    ++NumChanged;
811239462Sdim    Op = NewOp;
812193323Sed  }
813193323Sed
814239462Sdim  // If the expression changed non-trivially then clear out all subclass data
815239462Sdim  // starting from the operator specified in ExpressionChanged, and compactify
816239462Sdim  // the operators to just before the expression root to guarantee that the
817239462Sdim  // expression tree is dominated by all of Ops.
818239462Sdim  if (ExpressionChanged)
819239462Sdim    do {
820239462Sdim      ExpressionChanged->clearSubclassOptionalData();
821239462Sdim      if (ExpressionChanged == I)
822239462Sdim        break;
823239462Sdim      ExpressionChanged->moveBefore(I);
824239462Sdim      ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->use_begin());
825239462Sdim    } while (1);
826193323Sed
827239462Sdim  // Throw away any left over nodes from the original expression.
828239462Sdim  for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
829239462Sdim    RedoInsts.insert(NodesToRewrite[i]);
830239462Sdim}
831193323Sed
832239462Sdim/// NegateValue - Insert instructions before the instruction pointed to by BI,
833239462Sdim/// that computes the negative version of the value specified.  The negative
834239462Sdim/// version of the value is returned, and BI is left pointing at the instruction
835239462Sdim/// that should be processed next by the reassociation pass.
836199481Srdivackystatic Value *NegateValue(Value *V, Instruction *BI) {
837201360Srdivacky  if (Constant *C = dyn_cast<Constant>(V))
838201360Srdivacky    return ConstantExpr::getNeg(C);
839239462Sdim
840193323Sed  // We are trying to expose opportunity for reassociation.  One of the things
841193323Sed  // that we want to do to achieve this is to push a negation as deep into an
842193323Sed  // expression chain as possible, to expose the add instructions.  In practice,
843193323Sed  // this means that we turn this:
844193323Sed  //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
845193323Sed  // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
846193323Sed  // the constants.  We assume that instcombine will clean up the mess later if
847201360Srdivacky  // we introduce tons of unnecessary negation instructions.
848193323Sed  //
849239462Sdim  if (BinaryOperator *I = isReassociableOp(V, Instruction::Add)) {
850239462Sdim    // Push the negates through the add.
851239462Sdim    I->setOperand(0, NegateValue(I->getOperand(0), BI));
852239462Sdim    I->setOperand(1, NegateValue(I->getOperand(1), BI));
853193323Sed
854239462Sdim    // We must move the add instruction here, because the neg instructions do
855239462Sdim    // not dominate the old add instruction in general.  By moving it, we are
856239462Sdim    // assured that the neg instructions we just inserted dominate the
857239462Sdim    // instruction we are about to insert after them.
858239462Sdim    //
859239462Sdim    I->moveBefore(BI);
860239462Sdim    I->setName(I->getName()+".neg");
861239462Sdim    return I;
862239462Sdim  }
863239462Sdim
864201360Srdivacky  // Okay, we need to materialize a negated version of V with an instruction.
865201360Srdivacky  // Scan the use lists of V to see if we have one already.
866201360Srdivacky  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
867210299Sed    User *U = *UI;
868210299Sed    if (!BinaryOperator::isNeg(U)) continue;
869193323Sed
870201360Srdivacky    // We found one!  Now we have to make sure that the definition dominates
871201360Srdivacky    // this use.  We do this by moving it to the entry block (if it is a
872201360Srdivacky    // non-instruction value) or right after the definition.  These negates will
873201360Srdivacky    // be zapped by reassociate later, so we don't need much finesse here.
874210299Sed    BinaryOperator *TheNeg = cast<BinaryOperator>(U);
875202375Srdivacky
876202375Srdivacky    // Verify that the negate is in this function, V might be a constant expr.
877202375Srdivacky    if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
878202375Srdivacky      continue;
879239462Sdim
880201360Srdivacky    BasicBlock::iterator InsertPt;
881201360Srdivacky    if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
882201360Srdivacky      if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
883201360Srdivacky        InsertPt = II->getNormalDest()->begin();
884201360Srdivacky      } else {
885201360Srdivacky        InsertPt = InstInput;
886201360Srdivacky        ++InsertPt;
887201360Srdivacky      }
888201360Srdivacky      while (isa<PHINode>(InsertPt)) ++InsertPt;
889201360Srdivacky    } else {
890201360Srdivacky      InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
891201360Srdivacky    }
892201360Srdivacky    TheNeg->moveBefore(InsertPt);
893201360Srdivacky    return TheNeg;
894201360Srdivacky  }
895201360Srdivacky
896193323Sed  // Insert a 'neg' instruction that subtracts the value from zero to get the
897193323Sed  // negation.
898193323Sed  return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
899193323Sed}
900193323Sed
901193323Sed/// ShouldBreakUpSubtract - Return true if we should break up this subtract of
902193323Sed/// X-Y into (X + -Y).
903199481Srdivackystatic bool ShouldBreakUpSubtract(Instruction *Sub) {
904193323Sed  // If this is a negation, we can't split it up!
905193323Sed  if (BinaryOperator::isNeg(Sub))
906193323Sed    return false;
907239462Sdim
908193323Sed  // Don't bother to break this up unless either the LHS is an associable add or
909193323Sed  // subtract or if this is only used by one.
910193323Sed  if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
911193323Sed      isReassociableOp(Sub->getOperand(0), Instruction::Sub))
912193323Sed    return true;
913193323Sed  if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
914193323Sed      isReassociableOp(Sub->getOperand(1), Instruction::Sub))
915193323Sed    return true;
916239462Sdim  if (Sub->hasOneUse() &&
917193323Sed      (isReassociableOp(Sub->use_back(), Instruction::Add) ||
918193323Sed       isReassociableOp(Sub->use_back(), Instruction::Sub)))
919193323Sed    return true;
920239462Sdim
921193323Sed  return false;
922193323Sed}
923193323Sed
924193323Sed/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
925193323Sed/// only used by an add, transform this into (X+(0-Y)) to promote better
926193323Sed/// reassociation.
927239462Sdimstatic BinaryOperator *BreakUpSubtract(Instruction *Sub) {
928201360Srdivacky  // Convert a subtract into an add and a neg instruction. This allows sub
929201360Srdivacky  // instructions to be commuted with other add instructions.
930193323Sed  //
931201360Srdivacky  // Calculate the negative value of Operand 1 of the sub instruction,
932201360Srdivacky  // and set it as the RHS of the add instruction we just made.
933193323Sed  //
934199481Srdivacky  Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
935239462Sdim  BinaryOperator *New =
936193323Sed    BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
937239462Sdim  Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
938239462Sdim  Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
939193323Sed  New->takeName(Sub);
940193323Sed
941193323Sed  // Everyone now refers to the add instruction.
942193323Sed  Sub->replaceAllUsesWith(New);
943221345Sdim  New->setDebugLoc(Sub->getDebugLoc());
944193323Sed
945202375Srdivacky  DEBUG(dbgs() << "Negated: " << *New << '\n');
946193323Sed  return New;
947193323Sed}
948193323Sed
949193323Sed/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
950193323Sed/// by one, change this into a multiply by a constant to assist with further
951193323Sed/// reassociation.
952239462Sdimstatic BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
953239462Sdim  Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
954239462Sdim  MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
955239462Sdim
956239462Sdim  BinaryOperator *Mul =
957239462Sdim    BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
958239462Sdim  Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
959239462Sdim  Mul->takeName(Shl);
960239462Sdim  Shl->replaceAllUsesWith(Mul);
961239462Sdim  Mul->setDebugLoc(Shl->getDebugLoc());
962239462Sdim  return Mul;
963193323Sed}
964193323Sed
965239462Sdim/// FindInOperandList - Scan backwards and forwards among values with the same
966239462Sdim/// rank as element i to see if X exists.  If X does not exist, return i.  This
967239462Sdim/// is useful when scanning for 'x' when we see '-x' because they both get the
968239462Sdim/// same rank.
969201360Srdivackystatic unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
970193323Sed                                  Value *X) {
971193323Sed  unsigned XRank = Ops[i].Rank;
972193323Sed  unsigned e = Ops.size();
973193323Sed  for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
974193323Sed    if (Ops[j].Op == X)
975193323Sed      return j;
976201360Srdivacky  // Scan backwards.
977193323Sed  for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
978193323Sed    if (Ops[j].Op == X)
979193323Sed      return j;
980193323Sed  return i;
981193323Sed}
982193323Sed
983193323Sed/// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
984193323Sed/// and returning the result.  Insert the tree before I.
985234982Sdimstatic Value *EmitAddTreeOfValues(Instruction *I,
986234982Sdim                                  SmallVectorImpl<WeakVH> &Ops){
987193323Sed  if (Ops.size() == 1) return Ops.back();
988239462Sdim
989193323Sed  Value *V1 = Ops.back();
990193323Sed  Ops.pop_back();
991193323Sed  Value *V2 = EmitAddTreeOfValues(I, Ops);
992193323Sed  return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
993193323Sed}
994193323Sed
995239462Sdim/// RemoveFactorFromExpression - If V is an expression tree that is a
996193323Sed/// multiplication sequence, and if this sequence contains a multiply by Factor,
997193323Sed/// remove Factor from the tree and return the new tree.
998193323SedValue *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
999193323Sed  BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
1000193323Sed  if (!BO) return 0;
1001239462Sdim
1002239462Sdim  SmallVector<RepeatedValue, 8> Tree;
1003239462Sdim  MadeChange |= LinearizeExprTree(BO, Tree);
1004201360Srdivacky  SmallVector<ValueEntry, 8> Factors;
1005239462Sdim  Factors.reserve(Tree.size());
1006239462Sdim  for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
1007239462Sdim    RepeatedValue E = Tree[i];
1008239462Sdim    Factors.append(E.second.getZExtValue(),
1009239462Sdim                   ValueEntry(getRank(E.first), E.first));
1010239462Sdim  }
1011193323Sed
1012193323Sed  bool FoundFactor = false;
1013201360Srdivacky  bool NeedsNegate = false;
1014201360Srdivacky  for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1015193323Sed    if (Factors[i].Op == Factor) {
1016193323Sed      FoundFactor = true;
1017193323Sed      Factors.erase(Factors.begin()+i);
1018193323Sed      break;
1019193323Sed    }
1020239462Sdim
1021201360Srdivacky    // If this is a negative version of this factor, remove it.
1022201360Srdivacky    if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
1023201360Srdivacky      if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
1024201360Srdivacky        if (FC1->getValue() == -FC2->getValue()) {
1025201360Srdivacky          FoundFactor = NeedsNegate = true;
1026201360Srdivacky          Factors.erase(Factors.begin()+i);
1027201360Srdivacky          break;
1028201360Srdivacky        }
1029201360Srdivacky  }
1030239462Sdim
1031193323Sed  if (!FoundFactor) {
1032193323Sed    // Make sure to restore the operands to the expression tree.
1033193323Sed    RewriteExprTree(BO, Factors);
1034193323Sed    return 0;
1035193323Sed  }
1036239462Sdim
1037201360Srdivacky  BasicBlock::iterator InsertPt = BO; ++InsertPt;
1038239462Sdim
1039201360Srdivacky  // If this was just a single multiply, remove the multiply and return the only
1040201360Srdivacky  // remaining operand.
1041201360Srdivacky  if (Factors.size() == 1) {
1042239462Sdim    RedoInsts.insert(BO);
1043201360Srdivacky    V = Factors[0].Op;
1044201360Srdivacky  } else {
1045201360Srdivacky    RewriteExprTree(BO, Factors);
1046201360Srdivacky    V = BO;
1047201360Srdivacky  }
1048239462Sdim
1049201360Srdivacky  if (NeedsNegate)
1050201360Srdivacky    V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
1051239462Sdim
1052201360Srdivacky  return V;
1053193323Sed}
1054193323Sed
1055193323Sed/// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
1056193323Sed/// add its operands as factors, otherwise add V to the list of factors.
1057204792Srdivacky///
1058204792Srdivacky/// Ops is the top-level list of add operands we're trying to factor.
1059193323Sedstatic void FindSingleUseMultiplyFactors(Value *V,
1060204792Srdivacky                                         SmallVectorImpl<Value*> &Factors,
1061239462Sdim                                       const SmallVectorImpl<ValueEntry> &Ops) {
1062239462Sdim  BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
1063239462Sdim  if (!BO) {
1064193323Sed    Factors.push_back(V);
1065193323Sed    return;
1066193323Sed  }
1067239462Sdim
1068193323Sed  // Otherwise, add the LHS and RHS to the list of factors.
1069239462Sdim  FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
1070239462Sdim  FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
1071193323Sed}
1072193323Sed
1073201360Srdivacky/// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
1074201360Srdivacky/// instruction.  This optimizes based on identities.  If it can be reduced to
1075201360Srdivacky/// a single Value, it is returned, otherwise the Ops list is mutated as
1076201360Srdivacky/// necessary.
1077201360Srdivackystatic Value *OptimizeAndOrXor(unsigned Opcode,
1078201360Srdivacky                               SmallVectorImpl<ValueEntry> &Ops) {
1079201360Srdivacky  // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
1080201360Srdivacky  // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
1081201360Srdivacky  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1082201360Srdivacky    // First, check for X and ~X in the operand list.
1083201360Srdivacky    assert(i < Ops.size());
1084201360Srdivacky    if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
1085201360Srdivacky      Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
1086201360Srdivacky      unsigned FoundX = FindInOperandList(Ops, i, X);
1087201360Srdivacky      if (FoundX != i) {
1088201360Srdivacky        if (Opcode == Instruction::And)   // ...&X&~X = 0
1089201360Srdivacky          return Constant::getNullValue(X->getType());
1090239462Sdim
1091201360Srdivacky        if (Opcode == Instruction::Or)    // ...|X|~X = -1
1092201360Srdivacky          return Constant::getAllOnesValue(X->getType());
1093201360Srdivacky      }
1094201360Srdivacky    }
1095239462Sdim
1096201360Srdivacky    // Next, check for duplicate pairs of values, which we assume are next to
1097201360Srdivacky    // each other, due to our sorting criteria.
1098201360Srdivacky    assert(i < Ops.size());
1099201360Srdivacky    if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
1100201360Srdivacky      if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1101201360Srdivacky        // Drop duplicate values for And and Or.
1102201360Srdivacky        Ops.erase(Ops.begin()+i);
1103201360Srdivacky        --i; --e;
1104201360Srdivacky        ++NumAnnihil;
1105201360Srdivacky        continue;
1106201360Srdivacky      }
1107239462Sdim
1108201360Srdivacky      // Drop pairs of values for Xor.
1109201360Srdivacky      assert(Opcode == Instruction::Xor);
1110201360Srdivacky      if (e == 2)
1111201360Srdivacky        return Constant::getNullValue(Ops[0].Op->getType());
1112239462Sdim
1113201360Srdivacky      // Y ^ X^X -> Y
1114201360Srdivacky      Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1115201360Srdivacky      i -= 1; e -= 2;
1116201360Srdivacky      ++NumAnnihil;
1117201360Srdivacky    }
1118201360Srdivacky  }
1119201360Srdivacky  return 0;
1120201360Srdivacky}
1121193323Sed
1122249423Sdim/// Helper funciton of CombineXorOpnd(). It creates a bitwise-and
1123249423Sdim/// instruction with the given two operands, and return the resulting
1124249423Sdim/// instruction. There are two special cases: 1) if the constant operand is 0,
1125249423Sdim/// it will return NULL. 2) if the constant is ~0, the symbolic operand will
1126249423Sdim/// be returned.
1127249423Sdimstatic Value *createAndInstr(Instruction *InsertBefore, Value *Opnd,
1128249423Sdim                             const APInt &ConstOpnd) {
1129249423Sdim  if (ConstOpnd != 0) {
1130249423Sdim    if (!ConstOpnd.isAllOnesValue()) {
1131249423Sdim      LLVMContext &Ctx = Opnd->getType()->getContext();
1132249423Sdim      Instruction *I;
1133249423Sdim      I = BinaryOperator::CreateAnd(Opnd, ConstantInt::get(Ctx, ConstOpnd),
1134249423Sdim                                    "and.ra", InsertBefore);
1135249423Sdim      I->setDebugLoc(InsertBefore->getDebugLoc());
1136249423Sdim      return I;
1137249423Sdim    }
1138249423Sdim    return Opnd;
1139249423Sdim  }
1140249423Sdim  return 0;
1141249423Sdim}
1142249423Sdim
1143249423Sdim// Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
1144249423Sdim// into "R ^ C", where C would be 0, and R is a symbolic value.
1145249423Sdim//
1146249423Sdim// If it was successful, true is returned, and the "R" and "C" is returned
1147249423Sdim// via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
1148249423Sdim// and both "Res" and "ConstOpnd" remain unchanged.
1149249423Sdim//
1150249423Sdimbool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
1151249423Sdim                                 APInt &ConstOpnd, Value *&Res) {
1152249423Sdim  // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2
1153249423Sdim  //                       = ((x | c1) ^ c1) ^ (c1 ^ c2)
1154249423Sdim  //                       = (x & ~c1) ^ (c1 ^ c2)
1155249423Sdim  // It is useful only when c1 == c2.
1156249423Sdim  if (Opnd1->isOrExpr() && Opnd1->getConstPart() != 0) {
1157249423Sdim    if (!Opnd1->getValue()->hasOneUse())
1158249423Sdim      return false;
1159249423Sdim
1160249423Sdim    const APInt &C1 = Opnd1->getConstPart();
1161249423Sdim    if (C1 != ConstOpnd)
1162249423Sdim      return false;
1163249423Sdim
1164249423Sdim    Value *X = Opnd1->getSymbolicPart();
1165249423Sdim    Res = createAndInstr(I, X, ~C1);
1166249423Sdim    // ConstOpnd was C2, now C1 ^ C2.
1167249423Sdim    ConstOpnd ^= C1;
1168249423Sdim
1169249423Sdim    if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
1170249423Sdim      RedoInsts.insert(T);
1171249423Sdim    return true;
1172249423Sdim  }
1173249423Sdim  return false;
1174249423Sdim}
1175249423Sdim
1176249423Sdim
1177249423Sdim// Helper function of OptimizeXor(). It tries to simplify
1178249423Sdim// "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
1179249423Sdim// symbolic value.
1180249423Sdim//
1181249423Sdim// If it was successful, true is returned, and the "R" and "C" is returned
1182249423Sdim// via "Res" and "ConstOpnd", respectively (If the entire expression is
1183249423Sdim// evaluated to a constant, the Res is set to NULL); otherwise, false is
1184249423Sdim// returned, and both "Res" and "ConstOpnd" remain unchanged.
1185249423Sdimbool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
1186249423Sdim                                 APInt &ConstOpnd, Value *&Res) {
1187249423Sdim  Value *X = Opnd1->getSymbolicPart();
1188249423Sdim  if (X != Opnd2->getSymbolicPart())
1189249423Sdim    return false;
1190249423Sdim
1191249423Sdim  // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
1192249423Sdim  int DeadInstNum = 1;
1193249423Sdim  if (Opnd1->getValue()->hasOneUse())
1194249423Sdim    DeadInstNum++;
1195249423Sdim  if (Opnd2->getValue()->hasOneUse())
1196249423Sdim    DeadInstNum++;
1197249423Sdim
1198249423Sdim  // Xor-Rule 2:
1199249423Sdim  //  (x | c1) ^ (x & c2)
1200249423Sdim  //   = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
1201249423Sdim  //   = (x & ~c1) ^ (x & c2) ^ c1               // Xor-Rule 1
1202249423Sdim  //   = (x & c3) ^ c1, where c3 = ~c1 ^ c2      // Xor-rule 3
1203249423Sdim  //
1204249423Sdim  if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
1205249423Sdim    if (Opnd2->isOrExpr())
1206249423Sdim      std::swap(Opnd1, Opnd2);
1207249423Sdim
1208251662Sdim    const APInt &C1 = Opnd1->getConstPart();
1209251662Sdim    const APInt &C2 = Opnd2->getConstPart();
1210249423Sdim    APInt C3((~C1) ^ C2);
1211249423Sdim
1212249423Sdim    // Do not increase code size!
1213249423Sdim    if (C3 != 0 && !C3.isAllOnesValue()) {
1214249423Sdim      int NewInstNum = ConstOpnd != 0 ? 1 : 2;
1215249423Sdim      if (NewInstNum > DeadInstNum)
1216249423Sdim        return false;
1217249423Sdim    }
1218249423Sdim
1219249423Sdim    Res = createAndInstr(I, X, C3);
1220249423Sdim    ConstOpnd ^= C1;
1221249423Sdim
1222249423Sdim  } else if (Opnd1->isOrExpr()) {
1223249423Sdim    // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
1224249423Sdim    //
1225251662Sdim    const APInt &C1 = Opnd1->getConstPart();
1226251662Sdim    const APInt &C2 = Opnd2->getConstPart();
1227249423Sdim    APInt C3 = C1 ^ C2;
1228249423Sdim
1229249423Sdim    // Do not increase code size
1230249423Sdim    if (C3 != 0 && !C3.isAllOnesValue()) {
1231249423Sdim      int NewInstNum = ConstOpnd != 0 ? 1 : 2;
1232249423Sdim      if (NewInstNum > DeadInstNum)
1233249423Sdim        return false;
1234249423Sdim    }
1235249423Sdim
1236249423Sdim    Res = createAndInstr(I, X, C3);
1237249423Sdim    ConstOpnd ^= C3;
1238249423Sdim  } else {
1239249423Sdim    // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
1240249423Sdim    //
1241251662Sdim    const APInt &C1 = Opnd1->getConstPart();
1242251662Sdim    const APInt &C2 = Opnd2->getConstPart();
1243249423Sdim    APInt C3 = C1 ^ C2;
1244249423Sdim    Res = createAndInstr(I, X, C3);
1245249423Sdim  }
1246249423Sdim
1247249423Sdim  // Put the original operands in the Redo list; hope they will be deleted
1248249423Sdim  // as dead code.
1249249423Sdim  if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
1250249423Sdim    RedoInsts.insert(T);
1251249423Sdim  if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
1252249423Sdim    RedoInsts.insert(T);
1253249423Sdim
1254249423Sdim  return true;
1255249423Sdim}
1256249423Sdim
1257249423Sdim/// Optimize a series of operands to an 'xor' instruction. If it can be reduced
1258249423Sdim/// to a single Value, it is returned, otherwise the Ops list is mutated as
1259249423Sdim/// necessary.
1260249423SdimValue *Reassociate::OptimizeXor(Instruction *I,
1261249423Sdim                                SmallVectorImpl<ValueEntry> &Ops) {
1262249423Sdim  if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
1263249423Sdim    return V;
1264249423Sdim
1265249423Sdim  if (Ops.size() == 1)
1266249423Sdim    return 0;
1267249423Sdim
1268249423Sdim  SmallVector<XorOpnd, 8> Opnds;
1269251662Sdim  SmallVector<XorOpnd*, 8> OpndPtrs;
1270249423Sdim  Type *Ty = Ops[0].Op->getType();
1271249423Sdim  APInt ConstOpnd(Ty->getIntegerBitWidth(), 0);
1272249423Sdim
1273249423Sdim  // Step 1: Convert ValueEntry to XorOpnd
1274249423Sdim  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1275249423Sdim    Value *V = Ops[i].Op;
1276249423Sdim    if (!isa<ConstantInt>(V)) {
1277249423Sdim      XorOpnd O(V);
1278249423Sdim      O.setSymbolicRank(getRank(O.getSymbolicPart()));
1279249423Sdim      Opnds.push_back(O);
1280249423Sdim    } else
1281249423Sdim      ConstOpnd ^= cast<ConstantInt>(V)->getValue();
1282249423Sdim  }
1283249423Sdim
1284251662Sdim  // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
1285251662Sdim  //  It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
1286251662Sdim  //  the "OpndPtrs" as well. For the similar reason, do not fuse this loop
1287251662Sdim  //  with the previous loop --- the iterator of the "Opnds" may be invalidated
1288251662Sdim  //  when new elements are added to the vector.
1289251662Sdim  for (unsigned i = 0, e = Opnds.size(); i != e; ++i)
1290251662Sdim    OpndPtrs.push_back(&Opnds[i]);
1291251662Sdim
1292249423Sdim  // Step 2: Sort the Xor-Operands in a way such that the operands containing
1293249423Sdim  //  the same symbolic value cluster together. For instance, the input operand
1294249423Sdim  //  sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
1295249423Sdim  //  ("x | 123", "x & 789", "y & 456").
1296251662Sdim  std::sort(OpndPtrs.begin(), OpndPtrs.end(), XorOpnd::PtrSortFunctor());
1297249423Sdim
1298249423Sdim  // Step 3: Combine adjacent operands
1299249423Sdim  XorOpnd *PrevOpnd = 0;
1300249423Sdim  bool Changed = false;
1301249423Sdim  for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
1302251662Sdim    XorOpnd *CurrOpnd = OpndPtrs[i];
1303249423Sdim    // The combined value
1304249423Sdim    Value *CV;
1305249423Sdim
1306249423Sdim    // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
1307249423Sdim    if (ConstOpnd != 0 && CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1308249423Sdim      Changed = true;
1309249423Sdim      if (CV)
1310249423Sdim        *CurrOpnd = XorOpnd(CV);
1311249423Sdim      else {
1312249423Sdim        CurrOpnd->Invalidate();
1313249423Sdim        continue;
1314249423Sdim      }
1315249423Sdim    }
1316249423Sdim
1317249423Sdim    if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1318249423Sdim      PrevOpnd = CurrOpnd;
1319249423Sdim      continue;
1320249423Sdim    }
1321249423Sdim
1322249423Sdim    // step 3.2: When previous and current operands share the same symbolic
1323249423Sdim    //  value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd"
1324249423Sdim    //
1325249423Sdim    if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1326249423Sdim      // Remove previous operand
1327249423Sdim      PrevOpnd->Invalidate();
1328249423Sdim      if (CV) {
1329249423Sdim        *CurrOpnd = XorOpnd(CV);
1330249423Sdim        PrevOpnd = CurrOpnd;
1331249423Sdim      } else {
1332249423Sdim        CurrOpnd->Invalidate();
1333249423Sdim        PrevOpnd = 0;
1334249423Sdim      }
1335249423Sdim      Changed = true;
1336249423Sdim    }
1337249423Sdim  }
1338249423Sdim
1339249423Sdim  // Step 4: Reassemble the Ops
1340249423Sdim  if (Changed) {
1341249423Sdim    Ops.clear();
1342249423Sdim    for (unsigned int i = 0, e = Opnds.size(); i < e; i++) {
1343249423Sdim      XorOpnd &O = Opnds[i];
1344249423Sdim      if (O.isInvalid())
1345249423Sdim        continue;
1346249423Sdim      ValueEntry VE(getRank(O.getValue()), O.getValue());
1347249423Sdim      Ops.push_back(VE);
1348249423Sdim    }
1349249423Sdim    if (ConstOpnd != 0) {
1350249423Sdim      Value *C = ConstantInt::get(Ty->getContext(), ConstOpnd);
1351249423Sdim      ValueEntry VE(getRank(C), C);
1352249423Sdim      Ops.push_back(VE);
1353249423Sdim    }
1354249423Sdim    int Sz = Ops.size();
1355249423Sdim    if (Sz == 1)
1356249423Sdim      return Ops.back().Op;
1357249423Sdim    else if (Sz == 0) {
1358249423Sdim      assert(ConstOpnd == 0);
1359249423Sdim      return ConstantInt::get(Ty->getContext(), ConstOpnd);
1360249423Sdim    }
1361249423Sdim  }
1362249423Sdim
1363249423Sdim  return 0;
1364249423Sdim}
1365249423Sdim
1366201360Srdivacky/// OptimizeAdd - Optimize a series of operands to an 'add' instruction.  This
1367201360Srdivacky/// optimizes based on identities.  If it can be reduced to a single Value, it
1368201360Srdivacky/// is returned, otherwise the Ops list is mutated as necessary.
1369201360SrdivackyValue *Reassociate::OptimizeAdd(Instruction *I,
1370201360Srdivacky                                SmallVectorImpl<ValueEntry> &Ops) {
1371201360Srdivacky  // Scan the operand lists looking for X and -X pairs.  If we find any, we
1372201360Srdivacky  // can simplify the expression. X+-X == 0.  While we're at it, scan for any
1373201360Srdivacky  // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
1374201360Srdivacky  //
1375201360Srdivacky  // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
1376201360Srdivacky  //
1377201360Srdivacky  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1378201360Srdivacky    Value *TheOp = Ops[i].Op;
1379201360Srdivacky    // Check to see if we've seen this operand before.  If so, we factor all
1380201360Srdivacky    // instances of the operand together.  Due to our sorting criteria, we know
1381201360Srdivacky    // that these need to be next to each other in the vector.
1382201360Srdivacky    if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
1383201360Srdivacky      // Rescan the list, remove all instances of this operand from the expr.
1384201360Srdivacky      unsigned NumFound = 0;
1385201360Srdivacky      do {
1386201360Srdivacky        Ops.erase(Ops.begin()+i);
1387201360Srdivacky        ++NumFound;
1388201360Srdivacky      } while (i != Ops.size() && Ops[i].Op == TheOp);
1389239462Sdim
1390201360Srdivacky      DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
1391201360Srdivacky      ++NumFactor;
1392239462Sdim
1393201360Srdivacky      // Insert a new multiply.
1394201360Srdivacky      Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
1395201360Srdivacky      Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
1396239462Sdim
1397201360Srdivacky      // Now that we have inserted a multiply, optimize it. This allows us to
1398201360Srdivacky      // handle cases that require multiple factoring steps, such as this:
1399201360Srdivacky      // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
1400239462Sdim      RedoInsts.insert(cast<Instruction>(Mul));
1401239462Sdim
1402201360Srdivacky      // If every add operand was a duplicate, return the multiply.
1403201360Srdivacky      if (Ops.empty())
1404201360Srdivacky        return Mul;
1405239462Sdim
1406201360Srdivacky      // Otherwise, we had some input that didn't have the dupe, such as
1407201360Srdivacky      // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
1408201360Srdivacky      // things being added by this operation.
1409201360Srdivacky      Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
1410239462Sdim
1411201360Srdivacky      --i;
1412201360Srdivacky      e = Ops.size();
1413201360Srdivacky      continue;
1414201360Srdivacky    }
1415239462Sdim
1416201360Srdivacky    // Check for X and -X in the operand list.
1417201360Srdivacky    if (!BinaryOperator::isNeg(TheOp))
1418201360Srdivacky      continue;
1419239462Sdim
1420201360Srdivacky    Value *X = BinaryOperator::getNegArgument(TheOp);
1421201360Srdivacky    unsigned FoundX = FindInOperandList(Ops, i, X);
1422201360Srdivacky    if (FoundX == i)
1423201360Srdivacky      continue;
1424239462Sdim
1425201360Srdivacky    // Remove X and -X from the operand list.
1426201360Srdivacky    if (Ops.size() == 2)
1427201360Srdivacky      return Constant::getNullValue(X->getType());
1428239462Sdim
1429201360Srdivacky    Ops.erase(Ops.begin()+i);
1430201360Srdivacky    if (i < FoundX)
1431201360Srdivacky      --FoundX;
1432201360Srdivacky    else
1433201360Srdivacky      --i;   // Need to back up an extra one.
1434201360Srdivacky    Ops.erase(Ops.begin()+FoundX);
1435201360Srdivacky    ++NumAnnihil;
1436201360Srdivacky    --i;     // Revisit element.
1437201360Srdivacky    e -= 2;  // Removed two elements.
1438201360Srdivacky  }
1439239462Sdim
1440201360Srdivacky  // Scan the operand list, checking to see if there are any common factors
1441201360Srdivacky  // between operands.  Consider something like A*A+A*B*C+D.  We would like to
1442201360Srdivacky  // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
1443201360Srdivacky  // To efficiently find this, we count the number of times a factor occurs
1444201360Srdivacky  // for any ADD operands that are MULs.
1445201360Srdivacky  DenseMap<Value*, unsigned> FactorOccurrences;
1446239462Sdim
1447201360Srdivacky  // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
1448201360Srdivacky  // where they are actually the same multiply.
1449201360Srdivacky  unsigned MaxOcc = 0;
1450201360Srdivacky  Value *MaxOccVal = 0;
1451201360Srdivacky  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1452239462Sdim    BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
1453239462Sdim    if (!BOp)
1454201360Srdivacky      continue;
1455239462Sdim
1456201360Srdivacky    // Compute all of the factors of this added value.
1457201360Srdivacky    SmallVector<Value*, 8> Factors;
1458239462Sdim    FindSingleUseMultiplyFactors(BOp, Factors, Ops);
1459201360Srdivacky    assert(Factors.size() > 1 && "Bad linearize!");
1460239462Sdim
1461201360Srdivacky    // Add one to FactorOccurrences for each unique factor in this op.
1462201360Srdivacky    SmallPtrSet<Value*, 8> Duplicates;
1463201360Srdivacky    for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1464201360Srdivacky      Value *Factor = Factors[i];
1465201360Srdivacky      if (!Duplicates.insert(Factor)) continue;
1466239462Sdim
1467201360Srdivacky      unsigned Occ = ++FactorOccurrences[Factor];
1468201360Srdivacky      if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
1469239462Sdim
1470201360Srdivacky      // If Factor is a negative constant, add the negated value as a factor
1471201360Srdivacky      // because we can percolate the negate out.  Watch for minint, which
1472201360Srdivacky      // cannot be positivified.
1473201360Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
1474224145Sdim        if (CI->isNegative() && !CI->isMinValue(true)) {
1475201360Srdivacky          Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
1476201360Srdivacky          assert(!Duplicates.count(Factor) &&
1477201360Srdivacky                 "Shouldn't have two constant factors, missed a canonicalize");
1478239462Sdim
1479201360Srdivacky          unsigned Occ = ++FactorOccurrences[Factor];
1480201360Srdivacky          if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
1481201360Srdivacky        }
1482201360Srdivacky    }
1483201360Srdivacky  }
1484239462Sdim
1485201360Srdivacky  // If any factor occurred more than one time, we can pull it out.
1486201360Srdivacky  if (MaxOcc > 1) {
1487201360Srdivacky    DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
1488201360Srdivacky    ++NumFactor;
1489193323Sed
1490201360Srdivacky    // Create a new instruction that uses the MaxOccVal twice.  If we don't do
1491201360Srdivacky    // this, we could otherwise run into situations where removing a factor
1492239462Sdim    // from an expression will drop a use of maxocc, and this can cause
1493201360Srdivacky    // RemoveFactorFromExpression on successive values to behave differently.
1494201360Srdivacky    Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
1495234982Sdim    SmallVector<WeakVH, 4> NewMulOps;
1496218893Sdim    for (unsigned i = 0; i != Ops.size(); ++i) {
1497202375Srdivacky      // Only try to remove factors from expressions we're allowed to.
1498239462Sdim      BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
1499239462Sdim      if (!BOp)
1500202375Srdivacky        continue;
1501239462Sdim
1502201360Srdivacky      if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1503218893Sdim        // The factorized operand may occur several times.  Convert them all in
1504218893Sdim        // one fell swoop.
1505218893Sdim        for (unsigned j = Ops.size(); j != i;) {
1506218893Sdim          --j;
1507218893Sdim          if (Ops[j].Op == Ops[i].Op) {
1508218893Sdim            NewMulOps.push_back(V);
1509218893Sdim            Ops.erase(Ops.begin()+j);
1510218893Sdim          }
1511218893Sdim        }
1512218893Sdim        --i;
1513201360Srdivacky      }
1514201360Srdivacky    }
1515239462Sdim
1516201360Srdivacky    // No need for extra uses anymore.
1517201360Srdivacky    delete DummyInst;
1518202375Srdivacky
1519201360Srdivacky    unsigned NumAddedValues = NewMulOps.size();
1520201360Srdivacky    Value *V = EmitAddTreeOfValues(I, NewMulOps);
1521202375Srdivacky
1522201360Srdivacky    // Now that we have inserted the add tree, optimize it. This allows us to
1523201360Srdivacky    // handle cases that require multiple factoring steps, such as this:
1524201360Srdivacky    // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
1525201360Srdivacky    assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
1526202375Srdivacky    (void)NumAddedValues;
1527239462Sdim    if (Instruction *VI = dyn_cast<Instruction>(V))
1528239462Sdim      RedoInsts.insert(VI);
1529201360Srdivacky
1530201360Srdivacky    // Create the multiply.
1531239462Sdim    Instruction *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
1532201360Srdivacky
1533201360Srdivacky    // Rerun associate on the multiply in case the inner expression turned into
1534201360Srdivacky    // a multiply.  We want to make sure that we keep things in canonical form.
1535239462Sdim    RedoInsts.insert(V2);
1536239462Sdim
1537201360Srdivacky    // If every add operand included the factor (e.g. "A*B + A*C"), then the
1538201360Srdivacky    // entire result expression is just the multiply "A*(B+C)".
1539201360Srdivacky    if (Ops.empty())
1540201360Srdivacky      return V2;
1541239462Sdim
1542201360Srdivacky    // Otherwise, we had some input that didn't have the factor, such as
1543201360Srdivacky    // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
1544201360Srdivacky    // things being added by this operation.
1545201360Srdivacky    Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
1546201360Srdivacky  }
1547239462Sdim
1548201360Srdivacky  return 0;
1549201360Srdivacky}
1550201360Srdivacky
1551239462Sdimnamespace {
1552239462Sdim  /// \brief Predicate tests whether a ValueEntry's op is in a map.
1553239462Sdim  struct IsValueInMap {
1554239462Sdim    const DenseMap<Value *, unsigned> &Map;
1555239462Sdim
1556239462Sdim    IsValueInMap(const DenseMap<Value *, unsigned> &Map) : Map(Map) {}
1557239462Sdim
1558239462Sdim    bool operator()(const ValueEntry &Entry) {
1559239462Sdim      return Map.find(Entry.Op) != Map.end();
1560239462Sdim    }
1561239462Sdim  };
1562239462Sdim}
1563239462Sdim
1564239462Sdim/// \brief Build up a vector of value/power pairs factoring a product.
1565239462Sdim///
1566239462Sdim/// Given a series of multiplication operands, build a vector of factors and
1567239462Sdim/// the powers each is raised to when forming the final product. Sort them in
1568239462Sdim/// the order of descending power.
1569239462Sdim///
1570239462Sdim///      (x*x)          -> [(x, 2)]
1571239462Sdim///     ((x*x)*x)       -> [(x, 3)]
1572239462Sdim///   ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
1573239462Sdim///
1574239462Sdim/// \returns Whether any factors have a power greater than one.
1575239462Sdimbool Reassociate::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
1576239462Sdim                                         SmallVectorImpl<Factor> &Factors) {
1577239462Sdim  // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
1578239462Sdim  // Compute the sum of powers of simplifiable factors.
1579239462Sdim  unsigned FactorPowerSum = 0;
1580239462Sdim  for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
1581239462Sdim    Value *Op = Ops[Idx-1].Op;
1582239462Sdim
1583239462Sdim    // Count the number of occurrences of this value.
1584239462Sdim    unsigned Count = 1;
1585239462Sdim    for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
1586239462Sdim      ++Count;
1587239462Sdim    // Track for simplification all factors which occur 2 or more times.
1588239462Sdim    if (Count > 1)
1589239462Sdim      FactorPowerSum += Count;
1590239462Sdim  }
1591239462Sdim
1592239462Sdim  // We can only simplify factors if the sum of the powers of our simplifiable
1593239462Sdim  // factors is 4 or higher. When that is the case, we will *always* have
1594239462Sdim  // a simplification. This is an important invariant to prevent cyclicly
1595239462Sdim  // trying to simplify already minimal formations.
1596239462Sdim  if (FactorPowerSum < 4)
1597239462Sdim    return false;
1598239462Sdim
1599239462Sdim  // Now gather the simplifiable factors, removing them from Ops.
1600239462Sdim  FactorPowerSum = 0;
1601239462Sdim  for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
1602239462Sdim    Value *Op = Ops[Idx-1].Op;
1603239462Sdim
1604239462Sdim    // Count the number of occurrences of this value.
1605239462Sdim    unsigned Count = 1;
1606239462Sdim    for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
1607239462Sdim      ++Count;
1608239462Sdim    if (Count == 1)
1609239462Sdim      continue;
1610239462Sdim    // Move an even number of occurrences to Factors.
1611239462Sdim    Count &= ~1U;
1612239462Sdim    Idx -= Count;
1613239462Sdim    FactorPowerSum += Count;
1614239462Sdim    Factors.push_back(Factor(Op, Count));
1615239462Sdim    Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
1616239462Sdim  }
1617239462Sdim
1618239462Sdim  // None of the adjustments above should have reduced the sum of factor powers
1619239462Sdim  // below our mininum of '4'.
1620239462Sdim  assert(FactorPowerSum >= 4);
1621239462Sdim
1622239462Sdim  std::sort(Factors.begin(), Factors.end(), Factor::PowerDescendingSorter());
1623239462Sdim  return true;
1624239462Sdim}
1625239462Sdim
1626239462Sdim/// \brief Build a tree of multiplies, computing the product of Ops.
1627239462Sdimstatic Value *buildMultiplyTree(IRBuilder<> &Builder,
1628239462Sdim                                SmallVectorImpl<Value*> &Ops) {
1629239462Sdim  if (Ops.size() == 1)
1630239462Sdim    return Ops.back();
1631239462Sdim
1632239462Sdim  Value *LHS = Ops.pop_back_val();
1633239462Sdim  do {
1634239462Sdim    LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
1635239462Sdim  } while (!Ops.empty());
1636239462Sdim
1637239462Sdim  return LHS;
1638239462Sdim}
1639239462Sdim
1640239462Sdim/// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
1641239462Sdim///
1642239462Sdim/// Given a vector of values raised to various powers, where no two values are
1643239462Sdim/// equal and the powers are sorted in decreasing order, compute the minimal
1644239462Sdim/// DAG of multiplies to compute the final product, and return that product
1645239462Sdim/// value.
1646239462SdimValue *Reassociate::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
1647239462Sdim                                            SmallVectorImpl<Factor> &Factors) {
1648239462Sdim  assert(Factors[0].Power);
1649239462Sdim  SmallVector<Value *, 4> OuterProduct;
1650239462Sdim  for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
1651239462Sdim       Idx < Size && Factors[Idx].Power > 0; ++Idx) {
1652239462Sdim    if (Factors[Idx].Power != Factors[LastIdx].Power) {
1653239462Sdim      LastIdx = Idx;
1654239462Sdim      continue;
1655239462Sdim    }
1656239462Sdim
1657239462Sdim    // We want to multiply across all the factors with the same power so that
1658239462Sdim    // we can raise them to that power as a single entity. Build a mini tree
1659239462Sdim    // for that.
1660239462Sdim    SmallVector<Value *, 4> InnerProduct;
1661239462Sdim    InnerProduct.push_back(Factors[LastIdx].Base);
1662239462Sdim    do {
1663239462Sdim      InnerProduct.push_back(Factors[Idx].Base);
1664239462Sdim      ++Idx;
1665239462Sdim    } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
1666239462Sdim
1667239462Sdim    // Reset the base value of the first factor to the new expression tree.
1668239462Sdim    // We'll remove all the factors with the same power in a second pass.
1669239462Sdim    Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
1670239462Sdim    if (Instruction *MI = dyn_cast<Instruction>(M))
1671239462Sdim      RedoInsts.insert(MI);
1672239462Sdim
1673239462Sdim    LastIdx = Idx;
1674239462Sdim  }
1675239462Sdim  // Unique factors with equal powers -- we've folded them into the first one's
1676239462Sdim  // base.
1677239462Sdim  Factors.erase(std::unique(Factors.begin(), Factors.end(),
1678239462Sdim                            Factor::PowerEqual()),
1679239462Sdim                Factors.end());
1680239462Sdim
1681239462Sdim  // Iteratively collect the base of each factor with an add power into the
1682239462Sdim  // outer product, and halve each power in preparation for squaring the
1683239462Sdim  // expression.
1684239462Sdim  for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
1685239462Sdim    if (Factors[Idx].Power & 1)
1686239462Sdim      OuterProduct.push_back(Factors[Idx].Base);
1687239462Sdim    Factors[Idx].Power >>= 1;
1688239462Sdim  }
1689239462Sdim  if (Factors[0].Power) {
1690239462Sdim    Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1691239462Sdim    OuterProduct.push_back(SquareRoot);
1692239462Sdim    OuterProduct.push_back(SquareRoot);
1693239462Sdim  }
1694239462Sdim  if (OuterProduct.size() == 1)
1695239462Sdim    return OuterProduct.front();
1696239462Sdim
1697239462Sdim  Value *V = buildMultiplyTree(Builder, OuterProduct);
1698239462Sdim  return V;
1699239462Sdim}
1700239462Sdim
1701239462SdimValue *Reassociate::OptimizeMul(BinaryOperator *I,
1702239462Sdim                                SmallVectorImpl<ValueEntry> &Ops) {
1703239462Sdim  // We can only optimize the multiplies when there is a chain of more than
1704239462Sdim  // three, such that a balanced tree might require fewer total multiplies.
1705239462Sdim  if (Ops.size() < 4)
1706239462Sdim    return 0;
1707239462Sdim
1708239462Sdim  // Try to turn linear trees of multiplies without other uses of the
1709239462Sdim  // intermediate stages into minimal multiply DAGs with perfect sub-expression
1710239462Sdim  // re-use.
1711239462Sdim  SmallVector<Factor, 4> Factors;
1712239462Sdim  if (!collectMultiplyFactors(Ops, Factors))
1713239462Sdim    return 0; // All distinct factors, so nothing left for us to do.
1714239462Sdim
1715239462Sdim  IRBuilder<> Builder(I);
1716239462Sdim  Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1717239462Sdim  if (Ops.empty())
1718239462Sdim    return V;
1719239462Sdim
1720239462Sdim  ValueEntry NewEntry = ValueEntry(getRank(V), V);
1721239462Sdim  Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
1722239462Sdim  return 0;
1723239462Sdim}
1724239462Sdim
1725193323SedValue *Reassociate::OptimizeExpression(BinaryOperator *I,
1726201360Srdivacky                                       SmallVectorImpl<ValueEntry> &Ops) {
1727193323Sed  // Now that we have the linearized expression tree, try to optimize it.
1728193323Sed  // Start by folding any constants that we found.
1729243830Sdim  Constant *Cst = 0;
1730243830Sdim  unsigned Opcode = I->getOpcode();
1731243830Sdim  while (!Ops.empty() && isa<Constant>(Ops.back().Op)) {
1732243830Sdim    Constant *C = cast<Constant>(Ops.pop_back_val().Op);
1733243830Sdim    Cst = Cst ? ConstantExpr::get(Opcode, C, Cst) : C;
1734243830Sdim  }
1735243830Sdim  // If there was nothing but constants then we are done.
1736243830Sdim  if (Ops.empty())
1737243830Sdim    return Cst;
1738243830Sdim
1739243830Sdim  // Put the combined constant back at the end of the operand list, except if
1740243830Sdim  // there is no point.  For example, an add of 0 gets dropped here, while a
1741243830Sdim  // multiplication by zero turns the whole expression into zero.
1742243830Sdim  if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
1743243830Sdim    if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
1744243830Sdim      return Cst;
1745243830Sdim    Ops.push_back(ValueEntry(0, Cst));
1746243830Sdim  }
1747243830Sdim
1748193323Sed  if (Ops.size() == 1) return Ops[0].Op;
1749193323Sed
1750201360Srdivacky  // Handle destructive annihilation due to identities between elements in the
1751193323Sed  // argument list here.
1752239462Sdim  unsigned NumOps = Ops.size();
1753193323Sed  switch (Opcode) {
1754193323Sed  default: break;
1755193323Sed  case Instruction::And:
1756193323Sed  case Instruction::Or:
1757201360Srdivacky    if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
1758201360Srdivacky      return Result;
1759193323Sed    break;
1760193323Sed
1761249423Sdim  case Instruction::Xor:
1762249423Sdim    if (Value *Result = OptimizeXor(I, Ops))
1763249423Sdim      return Result;
1764249423Sdim    break;
1765249423Sdim
1766239462Sdim  case Instruction::Add:
1767201360Srdivacky    if (Value *Result = OptimizeAdd(I, Ops))
1768201360Srdivacky      return Result;
1769239462Sdim    break;
1770193323Sed
1771239462Sdim  case Instruction::Mul:
1772239462Sdim    if (Value *Result = OptimizeMul(I, Ops))
1773239462Sdim      return Result;
1774193323Sed    break;
1775193323Sed  }
1776193323Sed
1777239462Sdim  if (Ops.size() != NumOps)
1778193323Sed    return OptimizeExpression(I, Ops);
1779193323Sed  return 0;
1780193323Sed}
1781193323Sed
1782239462Sdim/// EraseInst - Zap the given instruction, adding interesting operands to the
1783239462Sdim/// work list.
1784239462Sdimvoid Reassociate::EraseInst(Instruction *I) {
1785239462Sdim  assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1786239462Sdim  SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1787239462Sdim  // Erase the dead instruction.
1788239462Sdim  ValueRankMap.erase(I);
1789239462Sdim  RedoInsts.remove(I);
1790239462Sdim  I->eraseFromParent();
1791239462Sdim  // Optimize its operands.
1792239462Sdim  SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
1793239462Sdim  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1794239462Sdim    if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
1795239462Sdim      // If this is a node in an expression tree, climb to the expression root
1796239462Sdim      // and add that since that's where optimization actually happens.
1797239462Sdim      unsigned Opcode = Op->getOpcode();
1798239462Sdim      while (Op->hasOneUse() && Op->use_back()->getOpcode() == Opcode &&
1799239462Sdim             Visited.insert(Op))
1800239462Sdim        Op = Op->use_back();
1801239462Sdim      RedoInsts.insert(Op);
1802239462Sdim    }
1803239462Sdim}
1804193323Sed
1805239462Sdim/// OptimizeInst - Inspect and optimize the given instruction. Note that erasing
1806239462Sdim/// instructions is not allowed.
1807239462Sdimvoid Reassociate::OptimizeInst(Instruction *I) {
1808239462Sdim  // Only consider operations that we understand.
1809239462Sdim  if (!isa<BinaryOperator>(I))
1810239462Sdim    return;
1811239462Sdim
1812239462Sdim  if (I->getOpcode() == Instruction::Shl &&
1813239462Sdim      isa<ConstantInt>(I->getOperand(1)))
1814239462Sdim    // If an operand of this shift is a reassociable multiply, or if the shift
1815239462Sdim    // is used by a reassociable multiply or add, turn into a multiply.
1816239462Sdim    if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
1817239462Sdim        (I->hasOneUse() &&
1818239462Sdim         (isReassociableOp(I->use_back(), Instruction::Mul) ||
1819239462Sdim          isReassociableOp(I->use_back(), Instruction::Add)))) {
1820239462Sdim      Instruction *NI = ConvertShiftToMul(I);
1821239462Sdim      RedoInsts.insert(I);
1822221345Sdim      MadeChange = true;
1823239462Sdim      I = NI;
1824221345Sdim    }
1825193323Sed
1826239462Sdim  // Floating point binary operators are not associative, but we can still
1827239462Sdim  // commute (some) of them, to canonicalize the order of their operands.
1828239462Sdim  // This can potentially expose more CSE opportunities, and makes writing
1829239462Sdim  // other transformations simpler.
1830239462Sdim  if ((I->getType()->isFloatingPointTy() || I->getType()->isVectorTy())) {
1831239462Sdim    // FAdd and FMul can be commuted.
1832239462Sdim    if (I->getOpcode() != Instruction::FMul &&
1833239462Sdim        I->getOpcode() != Instruction::FAdd)
1834239462Sdim      return;
1835193323Sed
1836239462Sdim    Value *LHS = I->getOperand(0);
1837239462Sdim    Value *RHS = I->getOperand(1);
1838239462Sdim    unsigned LHSRank = getRank(LHS);
1839239462Sdim    unsigned RHSRank = getRank(RHS);
1840239462Sdim
1841239462Sdim    // Sort the operands by rank.
1842239462Sdim    if (RHSRank < LHSRank) {
1843239462Sdim      I->setOperand(0, RHS);
1844239462Sdim      I->setOperand(1, LHS);
1845239462Sdim    }
1846239462Sdim
1847239462Sdim    return;
1848239462Sdim  }
1849239462Sdim
1850221345Sdim  // Do not reassociate boolean (i1) expressions.  We want to preserve the
1851221345Sdim  // original order of evaluation for short-circuited comparisons that
1852221345Sdim  // SimplifyCFG has folded to AND/OR expressions.  If the expression
1853221345Sdim  // is not further optimized, it is likely to be transformed back to a
1854221345Sdim  // short-circuited form for code gen, and the source order may have been
1855221345Sdim  // optimized for the most likely conditions.
1856239462Sdim  if (I->getType()->isIntegerTy(1))
1857221345Sdim    return;
1858203954Srdivacky
1859221345Sdim  // If this is a subtract instruction which is not already in negate form,
1860221345Sdim  // see if we can convert it to X+-Y.
1861239462Sdim  if (I->getOpcode() == Instruction::Sub) {
1862239462Sdim    if (ShouldBreakUpSubtract(I)) {
1863239462Sdim      Instruction *NI = BreakUpSubtract(I);
1864239462Sdim      RedoInsts.insert(I);
1865221345Sdim      MadeChange = true;
1866239462Sdim      I = NI;
1867239462Sdim    } else if (BinaryOperator::isNeg(I)) {
1868221345Sdim      // Otherwise, this is a negation.  See if the operand is a multiply tree
1869221345Sdim      // and if this is not an inner node of a multiply tree.
1870239462Sdim      if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
1871239462Sdim          (!I->hasOneUse() ||
1872239462Sdim           !isReassociableOp(I->use_back(), Instruction::Mul))) {
1873239462Sdim        Instruction *NI = LowerNegateToMultiply(I);
1874239462Sdim        RedoInsts.insert(I);
1875193323Sed        MadeChange = true;
1876239462Sdim        I = NI;
1877193323Sed      }
1878193323Sed    }
1879221345Sdim  }
1880193323Sed
1881239462Sdim  // If this instruction is an associative binary operator, process it.
1882239462Sdim  if (!I->isAssociative()) return;
1883239462Sdim  BinaryOperator *BO = cast<BinaryOperator>(I);
1884193323Sed
1885221345Sdim  // If this is an interior node of a reassociable tree, ignore it until we
1886221345Sdim  // get to the root of the tree, to avoid N^2 analysis.
1887239462Sdim  unsigned Opcode = BO->getOpcode();
1888239462Sdim  if (BO->hasOneUse() && BO->use_back()->getOpcode() == Opcode)
1889221345Sdim    return;
1890193323Sed
1891239462Sdim  // If this is an add tree that is used by a sub instruction, ignore it
1892221345Sdim  // until we process the subtract.
1893239462Sdim  if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
1894239462Sdim      cast<Instruction>(BO->use_back())->getOpcode() == Instruction::Sub)
1895221345Sdim    return;
1896193323Sed
1897239462Sdim  ReassociateExpression(BO);
1898193323Sed}
1899193323Sed
1900239462Sdimvoid Reassociate::ReassociateExpression(BinaryOperator *I) {
1901239462Sdim
1902201360Srdivacky  // First, walk the expression tree, linearizing the tree, collecting the
1903201360Srdivacky  // operand information.
1904239462Sdim  SmallVector<RepeatedValue, 8> Tree;
1905239462Sdim  MadeChange |= LinearizeExprTree(I, Tree);
1906201360Srdivacky  SmallVector<ValueEntry, 8> Ops;
1907239462Sdim  Ops.reserve(Tree.size());
1908239462Sdim  for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
1909239462Sdim    RepeatedValue E = Tree[i];
1910239462Sdim    Ops.append(E.second.getZExtValue(),
1911239462Sdim               ValueEntry(getRank(E.first), E.first));
1912239462Sdim  }
1913239462Sdim
1914202375Srdivacky  DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
1915239462Sdim
1916193323Sed  // Now that we have linearized the tree to a list and have gathered all of
1917193323Sed  // the operands and their ranks, sort the operands by their rank.  Use a
1918193323Sed  // stable_sort so that values with equal ranks will have their relative
1919193323Sed  // positions maintained (and so the compiler is deterministic).  Note that
1920193323Sed  // this sorts so that the highest ranking values end up at the beginning of
1921193323Sed  // the vector.
1922193323Sed  std::stable_sort(Ops.begin(), Ops.end());
1923239462Sdim
1924193323Sed  // OptimizeExpression - Now that we have the expression tree in a convenient
1925193323Sed  // sorted form, optimize it globally if possible.
1926193323Sed  if (Value *V = OptimizeExpression(I, Ops)) {
1927239462Sdim    if (V == I)
1928239462Sdim      // Self-referential expression in unreachable code.
1929239462Sdim      return;
1930193323Sed    // This expression tree simplified to something that isn't a tree,
1931193323Sed    // eliminate it.
1932202375Srdivacky    DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
1933193323Sed    I->replaceAllUsesWith(V);
1934221345Sdim    if (Instruction *VI = dyn_cast<Instruction>(V))
1935221345Sdim      VI->setDebugLoc(I->getDebugLoc());
1936239462Sdim    RedoInsts.insert(I);
1937201360Srdivacky    ++NumAnnihil;
1938239462Sdim    return;
1939193323Sed  }
1940239462Sdim
1941193323Sed  // We want to sink immediates as deeply as possible except in the case where
1942193323Sed  // this is a multiply tree used only by an add, and the immediate is a -1.
1943193323Sed  // In this case we reassociate to put the negation on the outside so that we
1944193323Sed  // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
1945193323Sed  if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
1946193323Sed      cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
1947193323Sed      isa<ConstantInt>(Ops.back().Op) &&
1948193323Sed      cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
1949201360Srdivacky    ValueEntry Tmp = Ops.pop_back_val();
1950201360Srdivacky    Ops.insert(Ops.begin(), Tmp);
1951193323Sed  }
1952239462Sdim
1953202375Srdivacky  DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
1954239462Sdim
1955193323Sed  if (Ops.size() == 1) {
1956239462Sdim    if (Ops[0].Op == I)
1957239462Sdim      // Self-referential expression in unreachable code.
1958239462Sdim      return;
1959239462Sdim
1960193323Sed    // This expression tree simplified to something that isn't a tree,
1961193323Sed    // eliminate it.
1962193323Sed    I->replaceAllUsesWith(Ops[0].Op);
1963221345Sdim    if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
1964221345Sdim      OI->setDebugLoc(I->getDebugLoc());
1965239462Sdim    RedoInsts.insert(I);
1966239462Sdim    return;
1967193323Sed  }
1968239462Sdim
1969201360Srdivacky  // Now that we ordered and optimized the expressions, splat them back into
1970201360Srdivacky  // the expression tree, removing any unneeded nodes.
1971201360Srdivacky  RewriteExprTree(I, Ops);
1972193323Sed}
1973193323Sed
1974193323Sedbool Reassociate::runOnFunction(Function &F) {
1975239462Sdim  // Calculate the rank map for F
1976193323Sed  BuildRankMap(F);
1977193323Sed
1978193323Sed  MadeChange = false;
1979239462Sdim  for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1980239462Sdim    // Optimize every instruction in the basic block.
1981239462Sdim    for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
1982239462Sdim      if (isInstructionTriviallyDead(II)) {
1983239462Sdim        EraseInst(II++);
1984239462Sdim      } else {
1985239462Sdim        OptimizeInst(II);
1986239462Sdim        assert(II->getParent() == BI && "Moved to a different block!");
1987239462Sdim        ++II;
1988239462Sdim      }
1989193323Sed
1990239462Sdim    // If this produced extra instructions to optimize, handle them now.
1991239462Sdim    while (!RedoInsts.empty()) {
1992239462Sdim      Instruction *I = RedoInsts.pop_back_val();
1993239462Sdim      if (isInstructionTriviallyDead(I))
1994239462Sdim        EraseInst(I);
1995239462Sdim      else
1996239462Sdim        OptimizeInst(I);
1997221345Sdim    }
1998239462Sdim  }
1999221345Sdim
2000201360Srdivacky  // We are done with the rank map.
2001193323Sed  RankMap.clear();
2002193323Sed  ValueRankMap.clear();
2003239462Sdim
2004193323Sed  return MadeChange;
2005193323Sed}
2006