xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/Reassociate.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass reassociates commutative expressions in an order that is designed
11*9880d681SAndroid Build Coastguard Worker // to promote better constant propagation, GCSE, LICM, PRE, etc.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker // For example: 4 + (x + 5) -> x + (4 + 5)
14*9880d681SAndroid Build Coastguard Worker //
15*9880d681SAndroid Build Coastguard Worker // In the implementation of this algorithm, constants are assigned rank = 0,
16*9880d681SAndroid Build Coastguard Worker // function arguments are rank = 1, and other values are assigned ranks
17*9880d681SAndroid Build Coastguard Worker // corresponding to the reverse post order traversal of current function
18*9880d681SAndroid Build Coastguard Worker // (starting at 2), which effectively gives values in deep loops higher rank
19*9880d681SAndroid Build Coastguard Worker // than values not in loops.
20*9880d681SAndroid Build Coastguard Worker //
21*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
22*9880d681SAndroid Build Coastguard Worker 
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/Reassociate.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/PostOrderIterator.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueHandle.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
44*9880d681SAndroid Build Coastguard Worker #include <algorithm>
45*9880d681SAndroid Build Coastguard Worker using namespace llvm;
46*9880d681SAndroid Build Coastguard Worker using namespace reassociate;
47*9880d681SAndroid Build Coastguard Worker 
48*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "reassociate"
49*9880d681SAndroid Build Coastguard Worker 
50*9880d681SAndroid Build Coastguard Worker STATISTIC(NumChanged, "Number of insts reassociated");
51*9880d681SAndroid Build Coastguard Worker STATISTIC(NumAnnihil, "Number of expr tree annihilated");
52*9880d681SAndroid Build Coastguard Worker STATISTIC(NumFactor , "Number of multiplies factored");
53*9880d681SAndroid Build Coastguard Worker 
54*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
55*9880d681SAndroid Build Coastguard Worker /// Print out the expression identified in the Ops list.
56*9880d681SAndroid Build Coastguard Worker ///
PrintOps(Instruction * I,const SmallVectorImpl<ValueEntry> & Ops)57*9880d681SAndroid Build Coastguard Worker static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
58*9880d681SAndroid Build Coastguard Worker   Module *M = I->getModule();
59*9880d681SAndroid Build Coastguard Worker   dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
60*9880d681SAndroid Build Coastguard Worker        << *Ops[0].Op->getType() << '\t';
61*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
62*9880d681SAndroid Build Coastguard Worker     dbgs() << "[ ";
63*9880d681SAndroid Build Coastguard Worker     Ops[i].Op->printAsOperand(dbgs(), false, M);
64*9880d681SAndroid Build Coastguard Worker     dbgs() << ", #" << Ops[i].Rank << "] ";
65*9880d681SAndroid Build Coastguard Worker   }
66*9880d681SAndroid Build Coastguard Worker }
67*9880d681SAndroid Build Coastguard Worker #endif
68*9880d681SAndroid Build Coastguard Worker 
69*9880d681SAndroid Build Coastguard Worker /// Utility class representing a non-constant Xor-operand. We classify
70*9880d681SAndroid Build Coastguard Worker /// non-constant Xor-Operands into two categories:
71*9880d681SAndroid Build Coastguard Worker ///  C1) The operand is in the form "X & C", where C is a constant and C != ~0
72*9880d681SAndroid Build Coastguard Worker ///  C2)
73*9880d681SAndroid Build Coastguard Worker ///    C2.1) The operand is in the form of "X | C", where C is a non-zero
74*9880d681SAndroid Build Coastguard Worker ///          constant.
75*9880d681SAndroid Build Coastguard Worker ///    C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
76*9880d681SAndroid Build Coastguard Worker ///          operand as "E | 0"
77*9880d681SAndroid Build Coastguard Worker class llvm::reassociate::XorOpnd {
78*9880d681SAndroid Build Coastguard Worker public:
79*9880d681SAndroid Build Coastguard Worker   XorOpnd(Value *V);
80*9880d681SAndroid Build Coastguard Worker 
isInvalid() const81*9880d681SAndroid Build Coastguard Worker   bool isInvalid() const { return SymbolicPart == nullptr; }
isOrExpr() const82*9880d681SAndroid Build Coastguard Worker   bool isOrExpr() const { return isOr; }
getValue() const83*9880d681SAndroid Build Coastguard Worker   Value *getValue() const { return OrigVal; }
getSymbolicPart() const84*9880d681SAndroid Build Coastguard Worker   Value *getSymbolicPart() const { return SymbolicPart; }
getSymbolicRank() const85*9880d681SAndroid Build Coastguard Worker   unsigned getSymbolicRank() const { return SymbolicRank; }
getConstPart() const86*9880d681SAndroid Build Coastguard Worker   const APInt &getConstPart() const { return ConstPart; }
87*9880d681SAndroid Build Coastguard Worker 
Invalidate()88*9880d681SAndroid Build Coastguard Worker   void Invalidate() { SymbolicPart = OrigVal = nullptr; }
setSymbolicRank(unsigned R)89*9880d681SAndroid Build Coastguard Worker   void setSymbolicRank(unsigned R) { SymbolicRank = R; }
90*9880d681SAndroid Build Coastguard Worker 
91*9880d681SAndroid Build Coastguard Worker private:
92*9880d681SAndroid Build Coastguard Worker   Value *OrigVal;
93*9880d681SAndroid Build Coastguard Worker   Value *SymbolicPart;
94*9880d681SAndroid Build Coastguard Worker   APInt ConstPart;
95*9880d681SAndroid Build Coastguard Worker   unsigned SymbolicRank;
96*9880d681SAndroid Build Coastguard Worker   bool isOr;
97*9880d681SAndroid Build Coastguard Worker };
98*9880d681SAndroid Build Coastguard Worker 
XorOpnd(Value * V)99*9880d681SAndroid Build Coastguard Worker XorOpnd::XorOpnd(Value *V) {
100*9880d681SAndroid Build Coastguard Worker   assert(!isa<ConstantInt>(V) && "No ConstantInt");
101*9880d681SAndroid Build Coastguard Worker   OrigVal = V;
102*9880d681SAndroid Build Coastguard Worker   Instruction *I = dyn_cast<Instruction>(V);
103*9880d681SAndroid Build Coastguard Worker   SymbolicRank = 0;
104*9880d681SAndroid Build Coastguard Worker 
105*9880d681SAndroid Build Coastguard Worker   if (I && (I->getOpcode() == Instruction::Or ||
106*9880d681SAndroid Build Coastguard Worker             I->getOpcode() == Instruction::And)) {
107*9880d681SAndroid Build Coastguard Worker     Value *V0 = I->getOperand(0);
108*9880d681SAndroid Build Coastguard Worker     Value *V1 = I->getOperand(1);
109*9880d681SAndroid Build Coastguard Worker     if (isa<ConstantInt>(V0))
110*9880d681SAndroid Build Coastguard Worker       std::swap(V0, V1);
111*9880d681SAndroid Build Coastguard Worker 
112*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *C = dyn_cast<ConstantInt>(V1)) {
113*9880d681SAndroid Build Coastguard Worker       ConstPart = C->getValue();
114*9880d681SAndroid Build Coastguard Worker       SymbolicPart = V0;
115*9880d681SAndroid Build Coastguard Worker       isOr = (I->getOpcode() == Instruction::Or);
116*9880d681SAndroid Build Coastguard Worker       return;
117*9880d681SAndroid Build Coastguard Worker     }
118*9880d681SAndroid Build Coastguard Worker   }
119*9880d681SAndroid Build Coastguard Worker 
120*9880d681SAndroid Build Coastguard Worker   // view the operand as "V | 0"
121*9880d681SAndroid Build Coastguard Worker   SymbolicPart = V;
122*9880d681SAndroid Build Coastguard Worker   ConstPart = APInt::getNullValue(V->getType()->getIntegerBitWidth());
123*9880d681SAndroid Build Coastguard Worker   isOr = true;
124*9880d681SAndroid Build Coastguard Worker }
125*9880d681SAndroid Build Coastguard Worker 
126*9880d681SAndroid Build Coastguard Worker /// Return true if V is an instruction of the specified opcode and if it
127*9880d681SAndroid Build Coastguard Worker /// only has one use.
isReassociableOp(Value * V,unsigned Opcode)128*9880d681SAndroid Build Coastguard Worker static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
129*9880d681SAndroid Build Coastguard Worker   if (V->hasOneUse() && isa<Instruction>(V) &&
130*9880d681SAndroid Build Coastguard Worker       cast<Instruction>(V)->getOpcode() == Opcode &&
131*9880d681SAndroid Build Coastguard Worker       (!isa<FPMathOperator>(V) ||
132*9880d681SAndroid Build Coastguard Worker        cast<Instruction>(V)->hasUnsafeAlgebra()))
133*9880d681SAndroid Build Coastguard Worker     return cast<BinaryOperator>(V);
134*9880d681SAndroid Build Coastguard Worker   return nullptr;
135*9880d681SAndroid Build Coastguard Worker }
136*9880d681SAndroid Build Coastguard Worker 
isReassociableOp(Value * V,unsigned Opcode1,unsigned Opcode2)137*9880d681SAndroid Build Coastguard Worker static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode1,
138*9880d681SAndroid Build Coastguard Worker                                         unsigned Opcode2) {
139*9880d681SAndroid Build Coastguard Worker   if (V->hasOneUse() && isa<Instruction>(V) &&
140*9880d681SAndroid Build Coastguard Worker       (cast<Instruction>(V)->getOpcode() == Opcode1 ||
141*9880d681SAndroid Build Coastguard Worker        cast<Instruction>(V)->getOpcode() == Opcode2) &&
142*9880d681SAndroid Build Coastguard Worker       (!isa<FPMathOperator>(V) ||
143*9880d681SAndroid Build Coastguard Worker        cast<Instruction>(V)->hasUnsafeAlgebra()))
144*9880d681SAndroid Build Coastguard Worker     return cast<BinaryOperator>(V);
145*9880d681SAndroid Build Coastguard Worker   return nullptr;
146*9880d681SAndroid Build Coastguard Worker }
147*9880d681SAndroid Build Coastguard Worker 
BuildRankMap(Function & F,ReversePostOrderTraversal<Function * > & RPOT)148*9880d681SAndroid Build Coastguard Worker void ReassociatePass::BuildRankMap(
149*9880d681SAndroid Build Coastguard Worker     Function &F, ReversePostOrderTraversal<Function *> &RPOT) {
150*9880d681SAndroid Build Coastguard Worker   unsigned i = 2;
151*9880d681SAndroid Build Coastguard Worker 
152*9880d681SAndroid Build Coastguard Worker   // Assign distinct ranks to function arguments.
153*9880d681SAndroid Build Coastguard Worker   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
154*9880d681SAndroid Build Coastguard Worker     ValueRankMap[&*I] = ++i;
155*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Calculated Rank[" << I->getName() << "] = " << i << "\n");
156*9880d681SAndroid Build Coastguard Worker   }
157*9880d681SAndroid Build Coastguard Worker 
158*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *BB : RPOT) {
159*9880d681SAndroid Build Coastguard Worker     unsigned BBRank = RankMap[BB] = ++i << 16;
160*9880d681SAndroid Build Coastguard Worker 
161*9880d681SAndroid Build Coastguard Worker     // Walk the basic block, adding precomputed ranks for any instructions that
162*9880d681SAndroid Build Coastguard Worker     // we cannot move.  This ensures that the ranks for these instructions are
163*9880d681SAndroid Build Coastguard Worker     // all different in the block.
164*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *BB)
165*9880d681SAndroid Build Coastguard Worker       if (mayBeMemoryDependent(I))
166*9880d681SAndroid Build Coastguard Worker         ValueRankMap[&I] = ++BBRank;
167*9880d681SAndroid Build Coastguard Worker   }
168*9880d681SAndroid Build Coastguard Worker }
169*9880d681SAndroid Build Coastguard Worker 
getRank(Value * V)170*9880d681SAndroid Build Coastguard Worker unsigned ReassociatePass::getRank(Value *V) {
171*9880d681SAndroid Build Coastguard Worker   Instruction *I = dyn_cast<Instruction>(V);
172*9880d681SAndroid Build Coastguard Worker   if (!I) {
173*9880d681SAndroid Build Coastguard Worker     if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
174*9880d681SAndroid Build Coastguard Worker     return 0;  // Otherwise it's a global or constant, rank 0.
175*9880d681SAndroid Build Coastguard Worker   }
176*9880d681SAndroid Build Coastguard Worker 
177*9880d681SAndroid Build Coastguard Worker   if (unsigned Rank = ValueRankMap[I])
178*9880d681SAndroid Build Coastguard Worker     return Rank;    // Rank already known?
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
181*9880d681SAndroid Build Coastguard Worker   // we can reassociate expressions for code motion!  Since we do not recurse
182*9880d681SAndroid Build Coastguard Worker   // for PHI nodes, we cannot have infinite recursion here, because there
183*9880d681SAndroid Build Coastguard Worker   // cannot be loops in the value graph that do not go through PHI nodes.
184*9880d681SAndroid Build Coastguard Worker   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
185*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = I->getNumOperands();
186*9880d681SAndroid Build Coastguard Worker        i != e && Rank != MaxRank; ++i)
187*9880d681SAndroid Build Coastguard Worker     Rank = std::max(Rank, getRank(I->getOperand(i)));
188*9880d681SAndroid Build Coastguard Worker 
189*9880d681SAndroid Build Coastguard Worker   // If this is a not or neg instruction, do not count it for rank.  This
190*9880d681SAndroid Build Coastguard Worker   // assures us that X and ~X will have the same rank.
191*9880d681SAndroid Build Coastguard Worker   if  (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I) &&
192*9880d681SAndroid Build Coastguard Worker        !BinaryOperator::isFNeg(I))
193*9880d681SAndroid Build Coastguard Worker     ++Rank;
194*9880d681SAndroid Build Coastguard Worker 
195*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = " << Rank << "\n");
196*9880d681SAndroid Build Coastguard Worker 
197*9880d681SAndroid Build Coastguard Worker   return ValueRankMap[I] = Rank;
198*9880d681SAndroid Build Coastguard Worker }
199*9880d681SAndroid Build Coastguard Worker 
200*9880d681SAndroid Build Coastguard Worker // Canonicalize constants to RHS.  Otherwise, sort the operands by rank.
canonicalizeOperands(Instruction * I)201*9880d681SAndroid Build Coastguard Worker void ReassociatePass::canonicalizeOperands(Instruction *I) {
202*9880d681SAndroid Build Coastguard Worker   assert(isa<BinaryOperator>(I) && "Expected binary operator.");
203*9880d681SAndroid Build Coastguard Worker   assert(I->isCommutative() && "Expected commutative operator.");
204*9880d681SAndroid Build Coastguard Worker 
205*9880d681SAndroid Build Coastguard Worker   Value *LHS = I->getOperand(0);
206*9880d681SAndroid Build Coastguard Worker   Value *RHS = I->getOperand(1);
207*9880d681SAndroid Build Coastguard Worker   unsigned LHSRank = getRank(LHS);
208*9880d681SAndroid Build Coastguard Worker   unsigned RHSRank = getRank(RHS);
209*9880d681SAndroid Build Coastguard Worker 
210*9880d681SAndroid Build Coastguard Worker   if (isa<Constant>(RHS))
211*9880d681SAndroid Build Coastguard Worker     return;
212*9880d681SAndroid Build Coastguard Worker 
213*9880d681SAndroid Build Coastguard Worker   if (isa<Constant>(LHS) || RHSRank < LHSRank)
214*9880d681SAndroid Build Coastguard Worker     cast<BinaryOperator>(I)->swapOperands();
215*9880d681SAndroid Build Coastguard Worker }
216*9880d681SAndroid Build Coastguard Worker 
CreateAdd(Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore,Value * FlagsOp)217*9880d681SAndroid Build Coastguard Worker static BinaryOperator *CreateAdd(Value *S1, Value *S2, const Twine &Name,
218*9880d681SAndroid Build Coastguard Worker                                  Instruction *InsertBefore, Value *FlagsOp) {
219*9880d681SAndroid Build Coastguard Worker   if (S1->getType()->isIntOrIntVectorTy())
220*9880d681SAndroid Build Coastguard Worker     return BinaryOperator::CreateAdd(S1, S2, Name, InsertBefore);
221*9880d681SAndroid Build Coastguard Worker   else {
222*9880d681SAndroid Build Coastguard Worker     BinaryOperator *Res =
223*9880d681SAndroid Build Coastguard Worker         BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
224*9880d681SAndroid Build Coastguard Worker     Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
225*9880d681SAndroid Build Coastguard Worker     return Res;
226*9880d681SAndroid Build Coastguard Worker   }
227*9880d681SAndroid Build Coastguard Worker }
228*9880d681SAndroid Build Coastguard Worker 
CreateMul(Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore,Value * FlagsOp)229*9880d681SAndroid Build Coastguard Worker static BinaryOperator *CreateMul(Value *S1, Value *S2, const Twine &Name,
230*9880d681SAndroid Build Coastguard Worker                                  Instruction *InsertBefore, Value *FlagsOp) {
231*9880d681SAndroid Build Coastguard Worker   if (S1->getType()->isIntOrIntVectorTy())
232*9880d681SAndroid Build Coastguard Worker     return BinaryOperator::CreateMul(S1, S2, Name, InsertBefore);
233*9880d681SAndroid Build Coastguard Worker   else {
234*9880d681SAndroid Build Coastguard Worker     BinaryOperator *Res =
235*9880d681SAndroid Build Coastguard Worker       BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
236*9880d681SAndroid Build Coastguard Worker     Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
237*9880d681SAndroid Build Coastguard Worker     return Res;
238*9880d681SAndroid Build Coastguard Worker   }
239*9880d681SAndroid Build Coastguard Worker }
240*9880d681SAndroid Build Coastguard Worker 
CreateNeg(Value * S1,const Twine & Name,Instruction * InsertBefore,Value * FlagsOp)241*9880d681SAndroid Build Coastguard Worker static BinaryOperator *CreateNeg(Value *S1, const Twine &Name,
242*9880d681SAndroid Build Coastguard Worker                                  Instruction *InsertBefore, Value *FlagsOp) {
243*9880d681SAndroid Build Coastguard Worker   if (S1->getType()->isIntOrIntVectorTy())
244*9880d681SAndroid Build Coastguard Worker     return BinaryOperator::CreateNeg(S1, Name, InsertBefore);
245*9880d681SAndroid Build Coastguard Worker   else {
246*9880d681SAndroid Build Coastguard Worker     BinaryOperator *Res = BinaryOperator::CreateFNeg(S1, Name, InsertBefore);
247*9880d681SAndroid Build Coastguard Worker     Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
248*9880d681SAndroid Build Coastguard Worker     return Res;
249*9880d681SAndroid Build Coastguard Worker   }
250*9880d681SAndroid Build Coastguard Worker }
251*9880d681SAndroid Build Coastguard Worker 
252*9880d681SAndroid Build Coastguard Worker /// Replace 0-X with X*-1.
LowerNegateToMultiply(Instruction * Neg)253*9880d681SAndroid Build Coastguard Worker static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
254*9880d681SAndroid Build Coastguard Worker   Type *Ty = Neg->getType();
255*9880d681SAndroid Build Coastguard Worker   Constant *NegOne = Ty->isIntOrIntVectorTy() ?
256*9880d681SAndroid Build Coastguard Worker     ConstantInt::getAllOnesValue(Ty) : ConstantFP::get(Ty, -1.0);
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker   BinaryOperator *Res = CreateMul(Neg->getOperand(1), NegOne, "", Neg, Neg);
259*9880d681SAndroid Build Coastguard Worker   Neg->setOperand(1, Constant::getNullValue(Ty)); // Drop use of op.
260*9880d681SAndroid Build Coastguard Worker   Res->takeName(Neg);
261*9880d681SAndroid Build Coastguard Worker   Neg->replaceAllUsesWith(Res);
262*9880d681SAndroid Build Coastguard Worker   Res->setDebugLoc(Neg->getDebugLoc());
263*9880d681SAndroid Build Coastguard Worker   return Res;
264*9880d681SAndroid Build Coastguard Worker }
265*9880d681SAndroid Build Coastguard Worker 
266*9880d681SAndroid Build Coastguard Worker /// Returns k such that lambda(2^Bitwidth) = 2^k, where lambda is the Carmichael
267*9880d681SAndroid Build Coastguard Worker /// function. This means that x^(2^k) === 1 mod 2^Bitwidth for
268*9880d681SAndroid Build Coastguard Worker /// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
269*9880d681SAndroid Build Coastguard Worker /// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
270*9880d681SAndroid Build Coastguard Worker /// even x in Bitwidth-bit arithmetic.
CarmichaelShift(unsigned Bitwidth)271*9880d681SAndroid Build Coastguard Worker static unsigned CarmichaelShift(unsigned Bitwidth) {
272*9880d681SAndroid Build Coastguard Worker   if (Bitwidth < 3)
273*9880d681SAndroid Build Coastguard Worker     return Bitwidth - 1;
274*9880d681SAndroid Build Coastguard Worker   return Bitwidth - 2;
275*9880d681SAndroid Build Coastguard Worker }
276*9880d681SAndroid Build Coastguard Worker 
277*9880d681SAndroid Build Coastguard Worker /// Add the extra weight 'RHS' to the existing weight 'LHS',
278*9880d681SAndroid Build Coastguard Worker /// reducing the combined weight using any special properties of the operation.
279*9880d681SAndroid Build Coastguard Worker /// The existing weight LHS represents the computation X op X op ... op X where
280*9880d681SAndroid Build Coastguard Worker /// X occurs LHS times.  The combined weight represents  X op X op ... op X with
281*9880d681SAndroid Build Coastguard Worker /// X occurring LHS + RHS times.  If op is "Xor" for example then the combined
282*9880d681SAndroid Build Coastguard Worker /// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
283*9880d681SAndroid Build Coastguard Worker /// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
IncorporateWeight(APInt & LHS,const APInt & RHS,unsigned Opcode)284*9880d681SAndroid Build Coastguard Worker static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
285*9880d681SAndroid Build Coastguard Worker   // If we were working with infinite precision arithmetic then the combined
286*9880d681SAndroid Build Coastguard Worker   // weight would be LHS + RHS.  But we are using finite precision arithmetic,
287*9880d681SAndroid Build Coastguard Worker   // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
288*9880d681SAndroid Build Coastguard Worker   // for nilpotent operations and addition, but not for idempotent operations
289*9880d681SAndroid Build Coastguard Worker   // and multiplication), so it is important to correctly reduce the combined
290*9880d681SAndroid Build Coastguard Worker   // weight back into range if wrapping would be wrong.
291*9880d681SAndroid Build Coastguard Worker 
292*9880d681SAndroid Build Coastguard Worker   // If RHS is zero then the weight didn't change.
293*9880d681SAndroid Build Coastguard Worker   if (RHS.isMinValue())
294*9880d681SAndroid Build Coastguard Worker     return;
295*9880d681SAndroid Build Coastguard Worker   // If LHS is zero then the combined weight is RHS.
296*9880d681SAndroid Build Coastguard Worker   if (LHS.isMinValue()) {
297*9880d681SAndroid Build Coastguard Worker     LHS = RHS;
298*9880d681SAndroid Build Coastguard Worker     return;
299*9880d681SAndroid Build Coastguard Worker   }
300*9880d681SAndroid Build Coastguard Worker   // From this point on we know that neither LHS nor RHS is zero.
301*9880d681SAndroid Build Coastguard Worker 
302*9880d681SAndroid Build Coastguard Worker   if (Instruction::isIdempotent(Opcode)) {
303*9880d681SAndroid Build Coastguard Worker     // Idempotent means X op X === X, so any non-zero weight is equivalent to a
304*9880d681SAndroid Build Coastguard Worker     // weight of 1.  Keeping weights at zero or one also means that wrapping is
305*9880d681SAndroid Build Coastguard Worker     // not a problem.
306*9880d681SAndroid Build Coastguard Worker     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
307*9880d681SAndroid Build Coastguard Worker     return; // Return a weight of 1.
308*9880d681SAndroid Build Coastguard Worker   }
309*9880d681SAndroid Build Coastguard Worker   if (Instruction::isNilpotent(Opcode)) {
310*9880d681SAndroid Build Coastguard Worker     // Nilpotent means X op X === 0, so reduce weights modulo 2.
311*9880d681SAndroid Build Coastguard Worker     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
312*9880d681SAndroid Build Coastguard Worker     LHS = 0; // 1 + 1 === 0 modulo 2.
313*9880d681SAndroid Build Coastguard Worker     return;
314*9880d681SAndroid Build Coastguard Worker   }
315*9880d681SAndroid Build Coastguard Worker   if (Opcode == Instruction::Add || Opcode == Instruction::FAdd) {
316*9880d681SAndroid Build Coastguard Worker     // TODO: Reduce the weight by exploiting nsw/nuw?
317*9880d681SAndroid Build Coastguard Worker     LHS += RHS;
318*9880d681SAndroid Build Coastguard Worker     return;
319*9880d681SAndroid Build Coastguard Worker   }
320*9880d681SAndroid Build Coastguard Worker 
321*9880d681SAndroid Build Coastguard Worker   assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
322*9880d681SAndroid Build Coastguard Worker          "Unknown associative operation!");
323*9880d681SAndroid Build Coastguard Worker   unsigned Bitwidth = LHS.getBitWidth();
324*9880d681SAndroid Build Coastguard Worker   // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
325*9880d681SAndroid Build Coastguard Worker   // can be replaced with W-CM.  That's because x^W=x^(W-CM) for every Bitwidth
326*9880d681SAndroid Build Coastguard Worker   // bit number x, since either x is odd in which case x^CM = 1, or x is even in
327*9880d681SAndroid Build Coastguard Worker   // which case both x^W and x^(W - CM) are zero.  By subtracting off multiples
328*9880d681SAndroid Build Coastguard Worker   // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
329*9880d681SAndroid Build Coastguard Worker   // which by a happy accident means that they can always be represented using
330*9880d681SAndroid Build Coastguard Worker   // Bitwidth bits.
331*9880d681SAndroid Build Coastguard Worker   // TODO: Reduce the weight by exploiting nsw/nuw?  (Could do much better than
332*9880d681SAndroid Build Coastguard Worker   // the Carmichael number).
333*9880d681SAndroid Build Coastguard Worker   if (Bitwidth > 3) {
334*9880d681SAndroid Build Coastguard Worker     /// CM - The value of Carmichael's lambda function.
335*9880d681SAndroid Build Coastguard Worker     APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
336*9880d681SAndroid Build Coastguard Worker     // Any weight W >= Threshold can be replaced with W - CM.
337*9880d681SAndroid Build Coastguard Worker     APInt Threshold = CM + Bitwidth;
338*9880d681SAndroid Build Coastguard Worker     assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
339*9880d681SAndroid Build Coastguard Worker     // For Bitwidth 4 or more the following sum does not overflow.
340*9880d681SAndroid Build Coastguard Worker     LHS += RHS;
341*9880d681SAndroid Build Coastguard Worker     while (LHS.uge(Threshold))
342*9880d681SAndroid Build Coastguard Worker       LHS -= CM;
343*9880d681SAndroid Build Coastguard Worker   } else {
344*9880d681SAndroid Build Coastguard Worker     // To avoid problems with overflow do everything the same as above but using
345*9880d681SAndroid Build Coastguard Worker     // a larger type.
346*9880d681SAndroid Build Coastguard Worker     unsigned CM = 1U << CarmichaelShift(Bitwidth);
347*9880d681SAndroid Build Coastguard Worker     unsigned Threshold = CM + Bitwidth;
348*9880d681SAndroid Build Coastguard Worker     assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
349*9880d681SAndroid Build Coastguard Worker            "Weights not reduced!");
350*9880d681SAndroid Build Coastguard Worker     unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
351*9880d681SAndroid Build Coastguard Worker     while (Total >= Threshold)
352*9880d681SAndroid Build Coastguard Worker       Total -= CM;
353*9880d681SAndroid Build Coastguard Worker     LHS = Total;
354*9880d681SAndroid Build Coastguard Worker   }
355*9880d681SAndroid Build Coastguard Worker }
356*9880d681SAndroid Build Coastguard Worker 
357*9880d681SAndroid Build Coastguard Worker typedef std::pair<Value*, APInt> RepeatedValue;
358*9880d681SAndroid Build Coastguard Worker 
359*9880d681SAndroid Build Coastguard Worker /// Given an associative binary expression, return the leaf
360*9880d681SAndroid Build Coastguard Worker /// nodes in Ops along with their weights (how many times the leaf occurs).  The
361*9880d681SAndroid Build Coastguard Worker /// original expression is the same as
362*9880d681SAndroid Build Coastguard Worker ///   (Ops[0].first op Ops[0].first op ... Ops[0].first)  <- Ops[0].second times
363*9880d681SAndroid Build Coastguard Worker /// op
364*9880d681SAndroid Build Coastguard Worker ///   (Ops[1].first op Ops[1].first op ... Ops[1].first)  <- Ops[1].second times
365*9880d681SAndroid Build Coastguard Worker /// op
366*9880d681SAndroid Build Coastguard Worker ///   ...
367*9880d681SAndroid Build Coastguard Worker /// op
368*9880d681SAndroid Build Coastguard Worker ///   (Ops[N].first op Ops[N].first op ... Ops[N].first)  <- Ops[N].second times
369*9880d681SAndroid Build Coastguard Worker ///
370*9880d681SAndroid Build Coastguard Worker /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
371*9880d681SAndroid Build Coastguard Worker ///
372*9880d681SAndroid Build Coastguard Worker /// This routine may modify the function, in which case it returns 'true'.  The
373*9880d681SAndroid Build Coastguard Worker /// changes it makes may well be destructive, changing the value computed by 'I'
374*9880d681SAndroid Build Coastguard Worker /// to something completely different.  Thus if the routine returns 'true' then
375*9880d681SAndroid Build Coastguard Worker /// you MUST either replace I with a new expression computed from the Ops array,
376*9880d681SAndroid Build Coastguard Worker /// or use RewriteExprTree to put the values back in.
377*9880d681SAndroid Build Coastguard Worker ///
378*9880d681SAndroid Build Coastguard Worker /// A leaf node is either not a binary operation of the same kind as the root
379*9880d681SAndroid Build Coastguard Worker /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
380*9880d681SAndroid Build Coastguard Worker /// opcode), or is the same kind of binary operator but has a use which either
381*9880d681SAndroid Build Coastguard Worker /// does not belong to the expression, or does belong to the expression but is
382*9880d681SAndroid Build Coastguard Worker /// a leaf node.  Every leaf node has at least one use that is a non-leaf node
383*9880d681SAndroid Build Coastguard Worker /// of the expression, while for non-leaf nodes (except for the root 'I') every
384*9880d681SAndroid Build Coastguard Worker /// use is a non-leaf node of the expression.
385*9880d681SAndroid Build Coastguard Worker ///
386*9880d681SAndroid Build Coastguard Worker /// For example:
387*9880d681SAndroid Build Coastguard Worker ///           expression graph        node names
388*9880d681SAndroid Build Coastguard Worker ///
389*9880d681SAndroid Build Coastguard Worker ///                     +        |        I
390*9880d681SAndroid Build Coastguard Worker ///                    / \       |
391*9880d681SAndroid Build Coastguard Worker ///                   +   +      |      A,  B
392*9880d681SAndroid Build Coastguard Worker ///                  / \ / \     |
393*9880d681SAndroid Build Coastguard Worker ///                 *   +   *    |    C,  D,  E
394*9880d681SAndroid Build Coastguard Worker ///                / \ / \ / \   |
395*9880d681SAndroid Build Coastguard Worker ///                   +   *      |      F,  G
396*9880d681SAndroid Build Coastguard Worker ///
397*9880d681SAndroid Build Coastguard Worker /// The leaf nodes are C, E, F and G.  The Ops array will contain (maybe not in
398*9880d681SAndroid Build Coastguard Worker /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
399*9880d681SAndroid Build Coastguard Worker ///
400*9880d681SAndroid Build Coastguard Worker /// The expression is maximal: if some instruction is a binary operator of the
401*9880d681SAndroid Build Coastguard Worker /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
402*9880d681SAndroid Build Coastguard Worker /// then the instruction also belongs to the expression, is not a leaf node of
403*9880d681SAndroid Build Coastguard Worker /// it, and its operands also belong to the expression (but may be leaf nodes).
404*9880d681SAndroid Build Coastguard Worker ///
405*9880d681SAndroid Build Coastguard Worker /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
406*9880d681SAndroid Build Coastguard Worker /// order to ensure that every non-root node in the expression has *exactly one*
407*9880d681SAndroid Build Coastguard Worker /// use by a non-leaf node of the expression.  This destruction means that the
408*9880d681SAndroid Build Coastguard Worker /// caller MUST either replace 'I' with a new expression or use something like
409*9880d681SAndroid Build Coastguard Worker /// RewriteExprTree to put the values back in if the routine indicates that it
410*9880d681SAndroid Build Coastguard Worker /// made a change by returning 'true'.
411*9880d681SAndroid Build Coastguard Worker ///
412*9880d681SAndroid Build Coastguard Worker /// In the above example either the right operand of A or the left operand of B
413*9880d681SAndroid Build Coastguard Worker /// will be replaced by undef.  If it is B's operand then this gives:
414*9880d681SAndroid Build Coastguard Worker ///
415*9880d681SAndroid Build Coastguard Worker ///                     +        |        I
416*9880d681SAndroid Build Coastguard Worker ///                    / \       |
417*9880d681SAndroid Build Coastguard Worker ///                   +   +      |      A,  B - operand of B replaced with undef
418*9880d681SAndroid Build Coastguard Worker ///                  / \   \     |
419*9880d681SAndroid Build Coastguard Worker ///                 *   +   *    |    C,  D,  E
420*9880d681SAndroid Build Coastguard Worker ///                / \ / \ / \   |
421*9880d681SAndroid Build Coastguard Worker ///                   +   *      |      F,  G
422*9880d681SAndroid Build Coastguard Worker ///
423*9880d681SAndroid Build Coastguard Worker /// Note that such undef operands can only be reached by passing through 'I'.
424*9880d681SAndroid Build Coastguard Worker /// For example, if you visit operands recursively starting from a leaf node
425*9880d681SAndroid Build Coastguard Worker /// then you will never see such an undef operand unless you get back to 'I',
426*9880d681SAndroid Build Coastguard Worker /// which requires passing through a phi node.
427*9880d681SAndroid Build Coastguard Worker ///
428*9880d681SAndroid Build Coastguard Worker /// Note that this routine may also mutate binary operators of the wrong type
429*9880d681SAndroid Build Coastguard Worker /// that have all uses inside the expression (i.e. only used by non-leaf nodes
430*9880d681SAndroid Build Coastguard Worker /// of the expression) if it can turn them into binary operators of the right
431*9880d681SAndroid Build Coastguard Worker /// type and thus make the expression bigger.
432*9880d681SAndroid Build Coastguard Worker 
LinearizeExprTree(BinaryOperator * I,SmallVectorImpl<RepeatedValue> & Ops)433*9880d681SAndroid Build Coastguard Worker static bool LinearizeExprTree(BinaryOperator *I,
434*9880d681SAndroid Build Coastguard Worker                               SmallVectorImpl<RepeatedValue> &Ops) {
435*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
436*9880d681SAndroid Build Coastguard Worker   unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
437*9880d681SAndroid Build Coastguard Worker   unsigned Opcode = I->getOpcode();
438*9880d681SAndroid Build Coastguard Worker   assert(I->isAssociative() && I->isCommutative() &&
439*9880d681SAndroid Build Coastguard Worker          "Expected an associative and commutative operation!");
440*9880d681SAndroid Build Coastguard Worker 
441*9880d681SAndroid Build Coastguard Worker   // Visit all operands of the expression, keeping track of their weight (the
442*9880d681SAndroid Build Coastguard Worker   // number of paths from the expression root to the operand, or if you like
443*9880d681SAndroid Build Coastguard Worker   // the number of times that operand occurs in the linearized expression).
444*9880d681SAndroid Build Coastguard Worker   // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
445*9880d681SAndroid Build Coastguard Worker   // while A has weight two.
446*9880d681SAndroid Build Coastguard Worker 
447*9880d681SAndroid Build Coastguard Worker   // Worklist of non-leaf nodes (their operands are in the expression too) along
448*9880d681SAndroid Build Coastguard Worker   // with their weights, representing a certain number of paths to the operator.
449*9880d681SAndroid Build Coastguard Worker   // If an operator occurs in the worklist multiple times then we found multiple
450*9880d681SAndroid Build Coastguard Worker   // ways to get to it.
451*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<BinaryOperator*, APInt>, 8> Worklist; // (Op, Weight)
452*9880d681SAndroid Build Coastguard Worker   Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
453*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
454*9880d681SAndroid Build Coastguard Worker 
455*9880d681SAndroid Build Coastguard Worker   // Leaves of the expression are values that either aren't the right kind of
456*9880d681SAndroid Build Coastguard Worker   // operation (eg: a constant, or a multiply in an add tree), or are, but have
457*9880d681SAndroid Build Coastguard Worker   // some uses that are not inside the expression.  For example, in I = X + X,
458*9880d681SAndroid Build Coastguard Worker   // X = A + B, the value X has two uses (by I) that are in the expression.  If
459*9880d681SAndroid Build Coastguard Worker   // X has any other uses, for example in a return instruction, then we consider
460*9880d681SAndroid Build Coastguard Worker   // X to be a leaf, and won't analyze it further.  When we first visit a value,
461*9880d681SAndroid Build Coastguard Worker   // if it has more than one use then at first we conservatively consider it to
462*9880d681SAndroid Build Coastguard Worker   // be a leaf.  Later, as the expression is explored, we may discover some more
463*9880d681SAndroid Build Coastguard Worker   // uses of the value from inside the expression.  If all uses turn out to be
464*9880d681SAndroid Build Coastguard Worker   // from within the expression (and the value is a binary operator of the right
465*9880d681SAndroid Build Coastguard Worker   // kind) then the value is no longer considered to be a leaf, and its operands
466*9880d681SAndroid Build Coastguard Worker   // are explored.
467*9880d681SAndroid Build Coastguard Worker 
468*9880d681SAndroid Build Coastguard Worker   // Leaves - Keeps track of the set of putative leaves as well as the number of
469*9880d681SAndroid Build Coastguard Worker   // paths to each leaf seen so far.
470*9880d681SAndroid Build Coastguard Worker   typedef DenseMap<Value*, APInt> LeafMap;
471*9880d681SAndroid Build Coastguard Worker   LeafMap Leaves; // Leaf -> Total weight so far.
472*9880d681SAndroid Build Coastguard Worker   SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
473*9880d681SAndroid Build Coastguard Worker 
474*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
475*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
476*9880d681SAndroid Build Coastguard Worker #endif
477*9880d681SAndroid Build Coastguard Worker   while (!Worklist.empty()) {
478*9880d681SAndroid Build Coastguard Worker     std::pair<BinaryOperator*, APInt> P = Worklist.pop_back_val();
479*9880d681SAndroid Build Coastguard Worker     I = P.first; // We examine the operands of this binary operator.
480*9880d681SAndroid Build Coastguard Worker 
481*9880d681SAndroid Build Coastguard Worker     for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
482*9880d681SAndroid Build Coastguard Worker       Value *Op = I->getOperand(OpIdx);
483*9880d681SAndroid Build Coastguard Worker       APInt Weight = P.second; // Number of paths to this operand.
484*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
485*9880d681SAndroid Build Coastguard Worker       assert(!Op->use_empty() && "No uses, so how did we get to it?!");
486*9880d681SAndroid Build Coastguard Worker 
487*9880d681SAndroid Build Coastguard Worker       // If this is a binary operation of the right kind with only one use then
488*9880d681SAndroid Build Coastguard Worker       // add its operands to the expression.
489*9880d681SAndroid Build Coastguard Worker       if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
490*9880d681SAndroid Build Coastguard Worker         assert(Visited.insert(Op).second && "Not first visit!");
491*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
492*9880d681SAndroid Build Coastguard Worker         Worklist.push_back(std::make_pair(BO, Weight));
493*9880d681SAndroid Build Coastguard Worker         continue;
494*9880d681SAndroid Build Coastguard Worker       }
495*9880d681SAndroid Build Coastguard Worker 
496*9880d681SAndroid Build Coastguard Worker       // Appears to be a leaf.  Is the operand already in the set of leaves?
497*9880d681SAndroid Build Coastguard Worker       LeafMap::iterator It = Leaves.find(Op);
498*9880d681SAndroid Build Coastguard Worker       if (It == Leaves.end()) {
499*9880d681SAndroid Build Coastguard Worker         // Not in the leaf map.  Must be the first time we saw this operand.
500*9880d681SAndroid Build Coastguard Worker         assert(Visited.insert(Op).second && "Not first visit!");
501*9880d681SAndroid Build Coastguard Worker         if (!Op->hasOneUse()) {
502*9880d681SAndroid Build Coastguard Worker           // This value has uses not accounted for by the expression, so it is
503*9880d681SAndroid Build Coastguard Worker           // not safe to modify.  Mark it as being a leaf.
504*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
505*9880d681SAndroid Build Coastguard Worker           LeafOrder.push_back(Op);
506*9880d681SAndroid Build Coastguard Worker           Leaves[Op] = Weight;
507*9880d681SAndroid Build Coastguard Worker           continue;
508*9880d681SAndroid Build Coastguard Worker         }
509*9880d681SAndroid Build Coastguard Worker         // No uses outside the expression, try morphing it.
510*9880d681SAndroid Build Coastguard Worker       } else if (It != Leaves.end()) {
511*9880d681SAndroid Build Coastguard Worker         // Already in the leaf map.
512*9880d681SAndroid Build Coastguard Worker         assert(Visited.count(Op) && "In leaf map but not visited!");
513*9880d681SAndroid Build Coastguard Worker 
514*9880d681SAndroid Build Coastguard Worker         // Update the number of paths to the leaf.
515*9880d681SAndroid Build Coastguard Worker         IncorporateWeight(It->second, Weight, Opcode);
516*9880d681SAndroid Build Coastguard Worker 
517*9880d681SAndroid Build Coastguard Worker #if 0   // TODO: Re-enable once PR13021 is fixed.
518*9880d681SAndroid Build Coastguard Worker         // The leaf already has one use from inside the expression.  As we want
519*9880d681SAndroid Build Coastguard Worker         // exactly one such use, drop this new use of the leaf.
520*9880d681SAndroid Build Coastguard Worker         assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
521*9880d681SAndroid Build Coastguard Worker         I->setOperand(OpIdx, UndefValue::get(I->getType()));
522*9880d681SAndroid Build Coastguard Worker         Changed = true;
523*9880d681SAndroid Build Coastguard Worker 
524*9880d681SAndroid Build Coastguard Worker         // If the leaf is a binary operation of the right kind and we now see
525*9880d681SAndroid Build Coastguard Worker         // that its multiple original uses were in fact all by nodes belonging
526*9880d681SAndroid Build Coastguard Worker         // to the expression, then no longer consider it to be a leaf and add
527*9880d681SAndroid Build Coastguard Worker         // its operands to the expression.
528*9880d681SAndroid Build Coastguard Worker         if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
529*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
530*9880d681SAndroid Build Coastguard Worker           Worklist.push_back(std::make_pair(BO, It->second));
531*9880d681SAndroid Build Coastguard Worker           Leaves.erase(It);
532*9880d681SAndroid Build Coastguard Worker           continue;
533*9880d681SAndroid Build Coastguard Worker         }
534*9880d681SAndroid Build Coastguard Worker #endif
535*9880d681SAndroid Build Coastguard Worker 
536*9880d681SAndroid Build Coastguard Worker         // If we still have uses that are not accounted for by the expression
537*9880d681SAndroid Build Coastguard Worker         // then it is not safe to modify the value.
538*9880d681SAndroid Build Coastguard Worker         if (!Op->hasOneUse())
539*9880d681SAndroid Build Coastguard Worker           continue;
540*9880d681SAndroid Build Coastguard Worker 
541*9880d681SAndroid Build Coastguard Worker         // No uses outside the expression, try morphing it.
542*9880d681SAndroid Build Coastguard Worker         Weight = It->second;
543*9880d681SAndroid Build Coastguard Worker         Leaves.erase(It); // Since the value may be morphed below.
544*9880d681SAndroid Build Coastguard Worker       }
545*9880d681SAndroid Build Coastguard Worker 
546*9880d681SAndroid Build Coastguard Worker       // At this point we have a value which, first of all, is not a binary
547*9880d681SAndroid Build Coastguard Worker       // expression of the right kind, and secondly, is only used inside the
548*9880d681SAndroid Build Coastguard Worker       // expression.  This means that it can safely be modified.  See if we
549*9880d681SAndroid Build Coastguard Worker       // can usefully morph it into an expression of the right kind.
550*9880d681SAndroid Build Coastguard Worker       assert((!isa<Instruction>(Op) ||
551*9880d681SAndroid Build Coastguard Worker               cast<Instruction>(Op)->getOpcode() != Opcode
552*9880d681SAndroid Build Coastguard Worker               || (isa<FPMathOperator>(Op) &&
553*9880d681SAndroid Build Coastguard Worker                   !cast<Instruction>(Op)->hasUnsafeAlgebra())) &&
554*9880d681SAndroid Build Coastguard Worker              "Should have been handled above!");
555*9880d681SAndroid Build Coastguard Worker       assert(Op->hasOneUse() && "Has uses outside the expression tree!");
556*9880d681SAndroid Build Coastguard Worker 
557*9880d681SAndroid Build Coastguard Worker       // If this is a multiply expression, turn any internal negations into
558*9880d681SAndroid Build Coastguard Worker       // multiplies by -1 so they can be reassociated.
559*9880d681SAndroid Build Coastguard Worker       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op))
560*9880d681SAndroid Build Coastguard Worker         if ((Opcode == Instruction::Mul && BinaryOperator::isNeg(BO)) ||
561*9880d681SAndroid Build Coastguard Worker             (Opcode == Instruction::FMul && BinaryOperator::isFNeg(BO))) {
562*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
563*9880d681SAndroid Build Coastguard Worker           BO = LowerNegateToMultiply(BO);
564*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << *BO << '\n');
565*9880d681SAndroid Build Coastguard Worker           Worklist.push_back(std::make_pair(BO, Weight));
566*9880d681SAndroid Build Coastguard Worker           Changed = true;
567*9880d681SAndroid Build Coastguard Worker           continue;
568*9880d681SAndroid Build Coastguard Worker         }
569*9880d681SAndroid Build Coastguard Worker 
570*9880d681SAndroid Build Coastguard Worker       // Failed to morph into an expression of the right type.  This really is
571*9880d681SAndroid Build Coastguard Worker       // a leaf.
572*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
573*9880d681SAndroid Build Coastguard Worker       assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
574*9880d681SAndroid Build Coastguard Worker       LeafOrder.push_back(Op);
575*9880d681SAndroid Build Coastguard Worker       Leaves[Op] = Weight;
576*9880d681SAndroid Build Coastguard Worker     }
577*9880d681SAndroid Build Coastguard Worker   }
578*9880d681SAndroid Build Coastguard Worker 
579*9880d681SAndroid Build Coastguard Worker   // The leaves, repeated according to their weights, represent the linearized
580*9880d681SAndroid Build Coastguard Worker   // form of the expression.
581*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
582*9880d681SAndroid Build Coastguard Worker     Value *V = LeafOrder[i];
583*9880d681SAndroid Build Coastguard Worker     LeafMap::iterator It = Leaves.find(V);
584*9880d681SAndroid Build Coastguard Worker     if (It == Leaves.end())
585*9880d681SAndroid Build Coastguard Worker       // Node initially thought to be a leaf wasn't.
586*9880d681SAndroid Build Coastguard Worker       continue;
587*9880d681SAndroid Build Coastguard Worker     assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
588*9880d681SAndroid Build Coastguard Worker     APInt Weight = It->second;
589*9880d681SAndroid Build Coastguard Worker     if (Weight.isMinValue())
590*9880d681SAndroid Build Coastguard Worker       // Leaf already output or weight reduction eliminated it.
591*9880d681SAndroid Build Coastguard Worker       continue;
592*9880d681SAndroid Build Coastguard Worker     // Ensure the leaf is only output once.
593*9880d681SAndroid Build Coastguard Worker     It->second = 0;
594*9880d681SAndroid Build Coastguard Worker     Ops.push_back(std::make_pair(V, Weight));
595*9880d681SAndroid Build Coastguard Worker   }
596*9880d681SAndroid Build Coastguard Worker 
597*9880d681SAndroid Build Coastguard Worker   // For nilpotent operations or addition there may be no operands, for example
598*9880d681SAndroid Build Coastguard Worker   // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
599*9880d681SAndroid Build Coastguard Worker   // in both cases the weight reduces to 0 causing the value to be skipped.
600*9880d681SAndroid Build Coastguard Worker   if (Ops.empty()) {
601*9880d681SAndroid Build Coastguard Worker     Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
602*9880d681SAndroid Build Coastguard Worker     assert(Identity && "Associative operation without identity!");
603*9880d681SAndroid Build Coastguard Worker     Ops.emplace_back(Identity, APInt(Bitwidth, 1));
604*9880d681SAndroid Build Coastguard Worker   }
605*9880d681SAndroid Build Coastguard Worker 
606*9880d681SAndroid Build Coastguard Worker   return Changed;
607*9880d681SAndroid Build Coastguard Worker }
608*9880d681SAndroid Build Coastguard Worker 
609*9880d681SAndroid Build Coastguard Worker /// Now that the operands for this expression tree are
610*9880d681SAndroid Build Coastguard Worker /// linearized and optimized, emit them in-order.
RewriteExprTree(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)611*9880d681SAndroid Build Coastguard Worker void ReassociatePass::RewriteExprTree(BinaryOperator *I,
612*9880d681SAndroid Build Coastguard Worker                                       SmallVectorImpl<ValueEntry> &Ops) {
613*9880d681SAndroid Build Coastguard Worker   assert(Ops.size() > 1 && "Single values should be used directly!");
614*9880d681SAndroid Build Coastguard Worker 
615*9880d681SAndroid Build Coastguard Worker   // Since our optimizations should never increase the number of operations, the
616*9880d681SAndroid Build Coastguard Worker   // new expression can usually be written reusing the existing binary operators
617*9880d681SAndroid Build Coastguard Worker   // from the original expression tree, without creating any new instructions,
618*9880d681SAndroid Build Coastguard Worker   // though the rewritten expression may have a completely different topology.
619*9880d681SAndroid Build Coastguard Worker   // We take care to not change anything if the new expression will be the same
620*9880d681SAndroid Build Coastguard Worker   // as the original.  If more than trivial changes (like commuting operands)
621*9880d681SAndroid Build Coastguard Worker   // were made then we are obliged to clear out any optional subclass data like
622*9880d681SAndroid Build Coastguard Worker   // nsw flags.
623*9880d681SAndroid Build Coastguard Worker 
624*9880d681SAndroid Build Coastguard Worker   /// NodesToRewrite - Nodes from the original expression available for writing
625*9880d681SAndroid Build Coastguard Worker   /// the new expression into.
626*9880d681SAndroid Build Coastguard Worker   SmallVector<BinaryOperator*, 8> NodesToRewrite;
627*9880d681SAndroid Build Coastguard Worker   unsigned Opcode = I->getOpcode();
628*9880d681SAndroid Build Coastguard Worker   BinaryOperator *Op = I;
629*9880d681SAndroid Build Coastguard Worker 
630*9880d681SAndroid Build Coastguard Worker   /// NotRewritable - The operands being written will be the leaves of the new
631*9880d681SAndroid Build Coastguard Worker   /// expression and must not be used as inner nodes (via NodesToRewrite) by
632*9880d681SAndroid Build Coastguard Worker   /// mistake.  Inner nodes are always reassociable, and usually leaves are not
633*9880d681SAndroid Build Coastguard Worker   /// (if they were they would have been incorporated into the expression and so
634*9880d681SAndroid Build Coastguard Worker   /// would not be leaves), so most of the time there is no danger of this.  But
635*9880d681SAndroid Build Coastguard Worker   /// in rare cases a leaf may become reassociable if an optimization kills uses
636*9880d681SAndroid Build Coastguard Worker   /// of it, or it may momentarily become reassociable during rewriting (below)
637*9880d681SAndroid Build Coastguard Worker   /// due it being removed as an operand of one of its uses.  Ensure that misuse
638*9880d681SAndroid Build Coastguard Worker   /// of leaf nodes as inner nodes cannot occur by remembering all of the future
639*9880d681SAndroid Build Coastguard Worker   /// leaves and refusing to reuse any of them as inner nodes.
640*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Value*, 8> NotRewritable;
641*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
642*9880d681SAndroid Build Coastguard Worker     NotRewritable.insert(Ops[i].Op);
643*9880d681SAndroid Build Coastguard Worker 
644*9880d681SAndroid Build Coastguard Worker   // ExpressionChanged - Non-null if the rewritten expression differs from the
645*9880d681SAndroid Build Coastguard Worker   // original in some non-trivial way, requiring the clearing of optional flags.
646*9880d681SAndroid Build Coastguard Worker   // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
647*9880d681SAndroid Build Coastguard Worker   BinaryOperator *ExpressionChanged = nullptr;
648*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; ; ++i) {
649*9880d681SAndroid Build Coastguard Worker     // The last operation (which comes earliest in the IR) is special as both
650*9880d681SAndroid Build Coastguard Worker     // operands will come from Ops, rather than just one with the other being
651*9880d681SAndroid Build Coastguard Worker     // a subexpression.
652*9880d681SAndroid Build Coastguard Worker     if (i+2 == Ops.size()) {
653*9880d681SAndroid Build Coastguard Worker       Value *NewLHS = Ops[i].Op;
654*9880d681SAndroid Build Coastguard Worker       Value *NewRHS = Ops[i+1].Op;
655*9880d681SAndroid Build Coastguard Worker       Value *OldLHS = Op->getOperand(0);
656*9880d681SAndroid Build Coastguard Worker       Value *OldRHS = Op->getOperand(1);
657*9880d681SAndroid Build Coastguard Worker 
658*9880d681SAndroid Build Coastguard Worker       if (NewLHS == OldLHS && NewRHS == OldRHS)
659*9880d681SAndroid Build Coastguard Worker         // Nothing changed, leave it alone.
660*9880d681SAndroid Build Coastguard Worker         break;
661*9880d681SAndroid Build Coastguard Worker 
662*9880d681SAndroid Build Coastguard Worker       if (NewLHS == OldRHS && NewRHS == OldLHS) {
663*9880d681SAndroid Build Coastguard Worker         // The order of the operands was reversed.  Swap them.
664*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "RA: " << *Op << '\n');
665*9880d681SAndroid Build Coastguard Worker         Op->swapOperands();
666*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "TO: " << *Op << '\n');
667*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
668*9880d681SAndroid Build Coastguard Worker         ++NumChanged;
669*9880d681SAndroid Build Coastguard Worker         break;
670*9880d681SAndroid Build Coastguard Worker       }
671*9880d681SAndroid Build Coastguard Worker 
672*9880d681SAndroid Build Coastguard Worker       // The new operation differs non-trivially from the original. Overwrite
673*9880d681SAndroid Build Coastguard Worker       // the old operands with the new ones.
674*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "RA: " << *Op << '\n');
675*9880d681SAndroid Build Coastguard Worker       if (NewLHS != OldLHS) {
676*9880d681SAndroid Build Coastguard Worker         BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
677*9880d681SAndroid Build Coastguard Worker         if (BO && !NotRewritable.count(BO))
678*9880d681SAndroid Build Coastguard Worker           NodesToRewrite.push_back(BO);
679*9880d681SAndroid Build Coastguard Worker         Op->setOperand(0, NewLHS);
680*9880d681SAndroid Build Coastguard Worker       }
681*9880d681SAndroid Build Coastguard Worker       if (NewRHS != OldRHS) {
682*9880d681SAndroid Build Coastguard Worker         BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
683*9880d681SAndroid Build Coastguard Worker         if (BO && !NotRewritable.count(BO))
684*9880d681SAndroid Build Coastguard Worker           NodesToRewrite.push_back(BO);
685*9880d681SAndroid Build Coastguard Worker         Op->setOperand(1, NewRHS);
686*9880d681SAndroid Build Coastguard Worker       }
687*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "TO: " << *Op << '\n');
688*9880d681SAndroid Build Coastguard Worker 
689*9880d681SAndroid Build Coastguard Worker       ExpressionChanged = Op;
690*9880d681SAndroid Build Coastguard Worker       MadeChange = true;
691*9880d681SAndroid Build Coastguard Worker       ++NumChanged;
692*9880d681SAndroid Build Coastguard Worker 
693*9880d681SAndroid Build Coastguard Worker       break;
694*9880d681SAndroid Build Coastguard Worker     }
695*9880d681SAndroid Build Coastguard Worker 
696*9880d681SAndroid Build Coastguard Worker     // Not the last operation.  The left-hand side will be a sub-expression
697*9880d681SAndroid Build Coastguard Worker     // while the right-hand side will be the current element of Ops.
698*9880d681SAndroid Build Coastguard Worker     Value *NewRHS = Ops[i].Op;
699*9880d681SAndroid Build Coastguard Worker     if (NewRHS != Op->getOperand(1)) {
700*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "RA: " << *Op << '\n');
701*9880d681SAndroid Build Coastguard Worker       if (NewRHS == Op->getOperand(0)) {
702*9880d681SAndroid Build Coastguard Worker         // The new right-hand side was already present as the left operand.  If
703*9880d681SAndroid Build Coastguard Worker         // we are lucky then swapping the operands will sort out both of them.
704*9880d681SAndroid Build Coastguard Worker         Op->swapOperands();
705*9880d681SAndroid Build Coastguard Worker       } else {
706*9880d681SAndroid Build Coastguard Worker         // Overwrite with the new right-hand side.
707*9880d681SAndroid Build Coastguard Worker         BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
708*9880d681SAndroid Build Coastguard Worker         if (BO && !NotRewritable.count(BO))
709*9880d681SAndroid Build Coastguard Worker           NodesToRewrite.push_back(BO);
710*9880d681SAndroid Build Coastguard Worker         Op->setOperand(1, NewRHS);
711*9880d681SAndroid Build Coastguard Worker         ExpressionChanged = Op;
712*9880d681SAndroid Build Coastguard Worker       }
713*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "TO: " << *Op << '\n');
714*9880d681SAndroid Build Coastguard Worker       MadeChange = true;
715*9880d681SAndroid Build Coastguard Worker       ++NumChanged;
716*9880d681SAndroid Build Coastguard Worker     }
717*9880d681SAndroid Build Coastguard Worker 
718*9880d681SAndroid Build Coastguard Worker     // Now deal with the left-hand side.  If this is already an operation node
719*9880d681SAndroid Build Coastguard Worker     // from the original expression then just rewrite the rest of the expression
720*9880d681SAndroid Build Coastguard Worker     // into it.
721*9880d681SAndroid Build Coastguard Worker     BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
722*9880d681SAndroid Build Coastguard Worker     if (BO && !NotRewritable.count(BO)) {
723*9880d681SAndroid Build Coastguard Worker       Op = BO;
724*9880d681SAndroid Build Coastguard Worker       continue;
725*9880d681SAndroid Build Coastguard Worker     }
726*9880d681SAndroid Build Coastguard Worker 
727*9880d681SAndroid Build Coastguard Worker     // Otherwise, grab a spare node from the original expression and use that as
728*9880d681SAndroid Build Coastguard Worker     // the left-hand side.  If there are no nodes left then the optimizers made
729*9880d681SAndroid Build Coastguard Worker     // an expression with more nodes than the original!  This usually means that
730*9880d681SAndroid Build Coastguard Worker     // they did something stupid but it might mean that the problem was just too
731*9880d681SAndroid Build Coastguard Worker     // hard (finding the mimimal number of multiplications needed to realize a
732*9880d681SAndroid Build Coastguard Worker     // multiplication expression is NP-complete).  Whatever the reason, smart or
733*9880d681SAndroid Build Coastguard Worker     // stupid, create a new node if there are none left.
734*9880d681SAndroid Build Coastguard Worker     BinaryOperator *NewOp;
735*9880d681SAndroid Build Coastguard Worker     if (NodesToRewrite.empty()) {
736*9880d681SAndroid Build Coastguard Worker       Constant *Undef = UndefValue::get(I->getType());
737*9880d681SAndroid Build Coastguard Worker       NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
738*9880d681SAndroid Build Coastguard Worker                                      Undef, Undef, "", I);
739*9880d681SAndroid Build Coastguard Worker       if (NewOp->getType()->isFPOrFPVectorTy())
740*9880d681SAndroid Build Coastguard Worker         NewOp->setFastMathFlags(I->getFastMathFlags());
741*9880d681SAndroid Build Coastguard Worker     } else {
742*9880d681SAndroid Build Coastguard Worker       NewOp = NodesToRewrite.pop_back_val();
743*9880d681SAndroid Build Coastguard Worker     }
744*9880d681SAndroid Build Coastguard Worker 
745*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "RA: " << *Op << '\n');
746*9880d681SAndroid Build Coastguard Worker     Op->setOperand(0, NewOp);
747*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "TO: " << *Op << '\n');
748*9880d681SAndroid Build Coastguard Worker     ExpressionChanged = Op;
749*9880d681SAndroid Build Coastguard Worker     MadeChange = true;
750*9880d681SAndroid Build Coastguard Worker     ++NumChanged;
751*9880d681SAndroid Build Coastguard Worker     Op = NewOp;
752*9880d681SAndroid Build Coastguard Worker   }
753*9880d681SAndroid Build Coastguard Worker 
754*9880d681SAndroid Build Coastguard Worker   // If the expression changed non-trivially then clear out all subclass data
755*9880d681SAndroid Build Coastguard Worker   // starting from the operator specified in ExpressionChanged, and compactify
756*9880d681SAndroid Build Coastguard Worker   // the operators to just before the expression root to guarantee that the
757*9880d681SAndroid Build Coastguard Worker   // expression tree is dominated by all of Ops.
758*9880d681SAndroid Build Coastguard Worker   if (ExpressionChanged)
759*9880d681SAndroid Build Coastguard Worker     do {
760*9880d681SAndroid Build Coastguard Worker       // Preserve FastMathFlags.
761*9880d681SAndroid Build Coastguard Worker       if (isa<FPMathOperator>(I)) {
762*9880d681SAndroid Build Coastguard Worker         FastMathFlags Flags = I->getFastMathFlags();
763*9880d681SAndroid Build Coastguard Worker         ExpressionChanged->clearSubclassOptionalData();
764*9880d681SAndroid Build Coastguard Worker         ExpressionChanged->setFastMathFlags(Flags);
765*9880d681SAndroid Build Coastguard Worker       } else
766*9880d681SAndroid Build Coastguard Worker         ExpressionChanged->clearSubclassOptionalData();
767*9880d681SAndroid Build Coastguard Worker 
768*9880d681SAndroid Build Coastguard Worker       if (ExpressionChanged == I)
769*9880d681SAndroid Build Coastguard Worker         break;
770*9880d681SAndroid Build Coastguard Worker       ExpressionChanged->moveBefore(I);
771*9880d681SAndroid Build Coastguard Worker       ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->user_begin());
772*9880d681SAndroid Build Coastguard Worker     } while (1);
773*9880d681SAndroid Build Coastguard Worker 
774*9880d681SAndroid Build Coastguard Worker   // Throw away any left over nodes from the original expression.
775*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
776*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(NodesToRewrite[i]);
777*9880d681SAndroid Build Coastguard Worker }
778*9880d681SAndroid Build Coastguard Worker 
779*9880d681SAndroid Build Coastguard Worker /// Insert instructions before the instruction pointed to by BI,
780*9880d681SAndroid Build Coastguard Worker /// that computes the negative version of the value specified.  The negative
781*9880d681SAndroid Build Coastguard Worker /// version of the value is returned, and BI is left pointing at the instruction
782*9880d681SAndroid Build Coastguard Worker /// that should be processed next by the reassociation pass.
783*9880d681SAndroid Build Coastguard Worker /// Also add intermediate instructions to the redo list that are modified while
784*9880d681SAndroid Build Coastguard Worker /// pushing the negates through adds.  These will be revisited to see if
785*9880d681SAndroid Build Coastguard Worker /// additional opportunities have been exposed.
NegateValue(Value * V,Instruction * BI,SetVector<AssertingVH<Instruction>> & ToRedo)786*9880d681SAndroid Build Coastguard Worker static Value *NegateValue(Value *V, Instruction *BI,
787*9880d681SAndroid Build Coastguard Worker                           SetVector<AssertingVH<Instruction>> &ToRedo) {
788*9880d681SAndroid Build Coastguard Worker   if (Constant *C = dyn_cast<Constant>(V)) {
789*9880d681SAndroid Build Coastguard Worker     if (C->getType()->isFPOrFPVectorTy()) {
790*9880d681SAndroid Build Coastguard Worker       return ConstantExpr::getFNeg(C);
791*9880d681SAndroid Build Coastguard Worker     }
792*9880d681SAndroid Build Coastguard Worker     return ConstantExpr::getNeg(C);
793*9880d681SAndroid Build Coastguard Worker   }
794*9880d681SAndroid Build Coastguard Worker 
795*9880d681SAndroid Build Coastguard Worker 
796*9880d681SAndroid Build Coastguard Worker   // We are trying to expose opportunity for reassociation.  One of the things
797*9880d681SAndroid Build Coastguard Worker   // that we want to do to achieve this is to push a negation as deep into an
798*9880d681SAndroid Build Coastguard Worker   // expression chain as possible, to expose the add instructions.  In practice,
799*9880d681SAndroid Build Coastguard Worker   // this means that we turn this:
800*9880d681SAndroid Build Coastguard Worker   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
801*9880d681SAndroid Build Coastguard Worker   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
802*9880d681SAndroid Build Coastguard Worker   // the constants.  We assume that instcombine will clean up the mess later if
803*9880d681SAndroid Build Coastguard Worker   // we introduce tons of unnecessary negation instructions.
804*9880d681SAndroid Build Coastguard Worker   //
805*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator *I =
806*9880d681SAndroid Build Coastguard Worker           isReassociableOp(V, Instruction::Add, Instruction::FAdd)) {
807*9880d681SAndroid Build Coastguard Worker     // Push the negates through the add.
808*9880d681SAndroid Build Coastguard Worker     I->setOperand(0, NegateValue(I->getOperand(0), BI, ToRedo));
809*9880d681SAndroid Build Coastguard Worker     I->setOperand(1, NegateValue(I->getOperand(1), BI, ToRedo));
810*9880d681SAndroid Build Coastguard Worker     if (I->getOpcode() == Instruction::Add) {
811*9880d681SAndroid Build Coastguard Worker       I->setHasNoUnsignedWrap(false);
812*9880d681SAndroid Build Coastguard Worker       I->setHasNoSignedWrap(false);
813*9880d681SAndroid Build Coastguard Worker     }
814*9880d681SAndroid Build Coastguard Worker 
815*9880d681SAndroid Build Coastguard Worker     // We must move the add instruction here, because the neg instructions do
816*9880d681SAndroid Build Coastguard Worker     // not dominate the old add instruction in general.  By moving it, we are
817*9880d681SAndroid Build Coastguard Worker     // assured that the neg instructions we just inserted dominate the
818*9880d681SAndroid Build Coastguard Worker     // instruction we are about to insert after them.
819*9880d681SAndroid Build Coastguard Worker     //
820*9880d681SAndroid Build Coastguard Worker     I->moveBefore(BI);
821*9880d681SAndroid Build Coastguard Worker     I->setName(I->getName()+".neg");
822*9880d681SAndroid Build Coastguard Worker 
823*9880d681SAndroid Build Coastguard Worker     // Add the intermediate negates to the redo list as processing them later
824*9880d681SAndroid Build Coastguard Worker     // could expose more reassociating opportunities.
825*9880d681SAndroid Build Coastguard Worker     ToRedo.insert(I);
826*9880d681SAndroid Build Coastguard Worker     return I;
827*9880d681SAndroid Build Coastguard Worker   }
828*9880d681SAndroid Build Coastguard Worker 
829*9880d681SAndroid Build Coastguard Worker   // Okay, we need to materialize a negated version of V with an instruction.
830*9880d681SAndroid Build Coastguard Worker   // Scan the use lists of V to see if we have one already.
831*9880d681SAndroid Build Coastguard Worker   for (User *U : V->users()) {
832*9880d681SAndroid Build Coastguard Worker     if (!BinaryOperator::isNeg(U) && !BinaryOperator::isFNeg(U))
833*9880d681SAndroid Build Coastguard Worker       continue;
834*9880d681SAndroid Build Coastguard Worker 
835*9880d681SAndroid Build Coastguard Worker     // We found one!  Now we have to make sure that the definition dominates
836*9880d681SAndroid Build Coastguard Worker     // this use.  We do this by moving it to the entry block (if it is a
837*9880d681SAndroid Build Coastguard Worker     // non-instruction value) or right after the definition.  These negates will
838*9880d681SAndroid Build Coastguard Worker     // be zapped by reassociate later, so we don't need much finesse here.
839*9880d681SAndroid Build Coastguard Worker     BinaryOperator *TheNeg = cast<BinaryOperator>(U);
840*9880d681SAndroid Build Coastguard Worker 
841*9880d681SAndroid Build Coastguard Worker     // Verify that the negate is in this function, V might be a constant expr.
842*9880d681SAndroid Build Coastguard Worker     if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
843*9880d681SAndroid Build Coastguard Worker       continue;
844*9880d681SAndroid Build Coastguard Worker 
845*9880d681SAndroid Build Coastguard Worker     BasicBlock::iterator InsertPt;
846*9880d681SAndroid Build Coastguard Worker     if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
847*9880d681SAndroid Build Coastguard Worker       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
848*9880d681SAndroid Build Coastguard Worker         InsertPt = II->getNormalDest()->begin();
849*9880d681SAndroid Build Coastguard Worker       } else {
850*9880d681SAndroid Build Coastguard Worker         InsertPt = ++InstInput->getIterator();
851*9880d681SAndroid Build Coastguard Worker       }
852*9880d681SAndroid Build Coastguard Worker       while (isa<PHINode>(InsertPt)) ++InsertPt;
853*9880d681SAndroid Build Coastguard Worker     } else {
854*9880d681SAndroid Build Coastguard Worker       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
855*9880d681SAndroid Build Coastguard Worker     }
856*9880d681SAndroid Build Coastguard Worker     TheNeg->moveBefore(&*InsertPt);
857*9880d681SAndroid Build Coastguard Worker     if (TheNeg->getOpcode() == Instruction::Sub) {
858*9880d681SAndroid Build Coastguard Worker       TheNeg->setHasNoUnsignedWrap(false);
859*9880d681SAndroid Build Coastguard Worker       TheNeg->setHasNoSignedWrap(false);
860*9880d681SAndroid Build Coastguard Worker     } else {
861*9880d681SAndroid Build Coastguard Worker       TheNeg->andIRFlags(BI);
862*9880d681SAndroid Build Coastguard Worker     }
863*9880d681SAndroid Build Coastguard Worker     ToRedo.insert(TheNeg);
864*9880d681SAndroid Build Coastguard Worker     return TheNeg;
865*9880d681SAndroid Build Coastguard Worker   }
866*9880d681SAndroid Build Coastguard Worker 
867*9880d681SAndroid Build Coastguard Worker   // Insert a 'neg' instruction that subtracts the value from zero to get the
868*9880d681SAndroid Build Coastguard Worker   // negation.
869*9880d681SAndroid Build Coastguard Worker   BinaryOperator *NewNeg = CreateNeg(V, V->getName() + ".neg", BI, BI);
870*9880d681SAndroid Build Coastguard Worker   ToRedo.insert(NewNeg);
871*9880d681SAndroid Build Coastguard Worker   return NewNeg;
872*9880d681SAndroid Build Coastguard Worker }
873*9880d681SAndroid Build Coastguard Worker 
874*9880d681SAndroid Build Coastguard Worker /// Return true if we should break up this subtract of X-Y into (X + -Y).
ShouldBreakUpSubtract(Instruction * Sub)875*9880d681SAndroid Build Coastguard Worker static bool ShouldBreakUpSubtract(Instruction *Sub) {
876*9880d681SAndroid Build Coastguard Worker   // If this is a negation, we can't split it up!
877*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator::isNeg(Sub) || BinaryOperator::isFNeg(Sub))
878*9880d681SAndroid Build Coastguard Worker     return false;
879*9880d681SAndroid Build Coastguard Worker 
880*9880d681SAndroid Build Coastguard Worker   // Don't breakup X - undef.
881*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(Sub->getOperand(1)))
882*9880d681SAndroid Build Coastguard Worker     return false;
883*9880d681SAndroid Build Coastguard Worker 
884*9880d681SAndroid Build Coastguard Worker   // Don't bother to break this up unless either the LHS is an associable add or
885*9880d681SAndroid Build Coastguard Worker   // subtract or if this is only used by one.
886*9880d681SAndroid Build Coastguard Worker   Value *V0 = Sub->getOperand(0);
887*9880d681SAndroid Build Coastguard Worker   if (isReassociableOp(V0, Instruction::Add, Instruction::FAdd) ||
888*9880d681SAndroid Build Coastguard Worker       isReassociableOp(V0, Instruction::Sub, Instruction::FSub))
889*9880d681SAndroid Build Coastguard Worker     return true;
890*9880d681SAndroid Build Coastguard Worker   Value *V1 = Sub->getOperand(1);
891*9880d681SAndroid Build Coastguard Worker   if (isReassociableOp(V1, Instruction::Add, Instruction::FAdd) ||
892*9880d681SAndroid Build Coastguard Worker       isReassociableOp(V1, Instruction::Sub, Instruction::FSub))
893*9880d681SAndroid Build Coastguard Worker     return true;
894*9880d681SAndroid Build Coastguard Worker   Value *VB = Sub->user_back();
895*9880d681SAndroid Build Coastguard Worker   if (Sub->hasOneUse() &&
896*9880d681SAndroid Build Coastguard Worker       (isReassociableOp(VB, Instruction::Add, Instruction::FAdd) ||
897*9880d681SAndroid Build Coastguard Worker        isReassociableOp(VB, Instruction::Sub, Instruction::FSub)))
898*9880d681SAndroid Build Coastguard Worker     return true;
899*9880d681SAndroid Build Coastguard Worker 
900*9880d681SAndroid Build Coastguard Worker   return false;
901*9880d681SAndroid Build Coastguard Worker }
902*9880d681SAndroid Build Coastguard Worker 
903*9880d681SAndroid Build Coastguard Worker /// If we have (X-Y), and if either X is an add, or if this is only used by an
904*9880d681SAndroid Build Coastguard Worker /// add, transform this into (X+(0-Y)) to promote better reassociation.
905*9880d681SAndroid Build Coastguard Worker static BinaryOperator *
BreakUpSubtract(Instruction * Sub,SetVector<AssertingVH<Instruction>> & ToRedo)906*9880d681SAndroid Build Coastguard Worker BreakUpSubtract(Instruction *Sub, SetVector<AssertingVH<Instruction>> &ToRedo) {
907*9880d681SAndroid Build Coastguard Worker   // Convert a subtract into an add and a neg instruction. This allows sub
908*9880d681SAndroid Build Coastguard Worker   // instructions to be commuted with other add instructions.
909*9880d681SAndroid Build Coastguard Worker   //
910*9880d681SAndroid Build Coastguard Worker   // Calculate the negative value of Operand 1 of the sub instruction,
911*9880d681SAndroid Build Coastguard Worker   // and set it as the RHS of the add instruction we just made.
912*9880d681SAndroid Build Coastguard Worker   //
913*9880d681SAndroid Build Coastguard Worker   Value *NegVal = NegateValue(Sub->getOperand(1), Sub, ToRedo);
914*9880d681SAndroid Build Coastguard Worker   BinaryOperator *New = CreateAdd(Sub->getOperand(0), NegVal, "", Sub, Sub);
915*9880d681SAndroid Build Coastguard Worker   Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
916*9880d681SAndroid Build Coastguard Worker   Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
917*9880d681SAndroid Build Coastguard Worker   New->takeName(Sub);
918*9880d681SAndroid Build Coastguard Worker 
919*9880d681SAndroid Build Coastguard Worker   // Everyone now refers to the add instruction.
920*9880d681SAndroid Build Coastguard Worker   Sub->replaceAllUsesWith(New);
921*9880d681SAndroid Build Coastguard Worker   New->setDebugLoc(Sub->getDebugLoc());
922*9880d681SAndroid Build Coastguard Worker 
923*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Negated: " << *New << '\n');
924*9880d681SAndroid Build Coastguard Worker   return New;
925*9880d681SAndroid Build Coastguard Worker }
926*9880d681SAndroid Build Coastguard Worker 
927*9880d681SAndroid Build Coastguard Worker /// If this is a shift of a reassociable multiply or is used by one, change
928*9880d681SAndroid Build Coastguard Worker /// this into a multiply by a constant to assist with further reassociation.
ConvertShiftToMul(Instruction * Shl)929*9880d681SAndroid Build Coastguard Worker static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
930*9880d681SAndroid Build Coastguard Worker   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
931*9880d681SAndroid Build Coastguard Worker   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
932*9880d681SAndroid Build Coastguard Worker 
933*9880d681SAndroid Build Coastguard Worker   BinaryOperator *Mul =
934*9880d681SAndroid Build Coastguard Worker     BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
935*9880d681SAndroid Build Coastguard Worker   Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
936*9880d681SAndroid Build Coastguard Worker   Mul->takeName(Shl);
937*9880d681SAndroid Build Coastguard Worker 
938*9880d681SAndroid Build Coastguard Worker   // Everyone now refers to the mul instruction.
939*9880d681SAndroid Build Coastguard Worker   Shl->replaceAllUsesWith(Mul);
940*9880d681SAndroid Build Coastguard Worker   Mul->setDebugLoc(Shl->getDebugLoc());
941*9880d681SAndroid Build Coastguard Worker 
942*9880d681SAndroid Build Coastguard Worker   // We can safely preserve the nuw flag in all cases.  It's also safe to turn a
943*9880d681SAndroid Build Coastguard Worker   // nuw nsw shl into a nuw nsw mul.  However, nsw in isolation requires special
944*9880d681SAndroid Build Coastguard Worker   // handling.
945*9880d681SAndroid Build Coastguard Worker   bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
946*9880d681SAndroid Build Coastguard Worker   bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
947*9880d681SAndroid Build Coastguard Worker   if (NSW && NUW)
948*9880d681SAndroid Build Coastguard Worker     Mul->setHasNoSignedWrap(true);
949*9880d681SAndroid Build Coastguard Worker   Mul->setHasNoUnsignedWrap(NUW);
950*9880d681SAndroid Build Coastguard Worker   return Mul;
951*9880d681SAndroid Build Coastguard Worker }
952*9880d681SAndroid Build Coastguard Worker 
953*9880d681SAndroid Build Coastguard Worker /// Scan backwards and forwards among values with the same rank as element i
954*9880d681SAndroid Build Coastguard Worker /// to see if X exists.  If X does not exist, return i.  This is useful when
955*9880d681SAndroid Build Coastguard Worker /// scanning for 'x' when we see '-x' because they both get the same rank.
FindInOperandList(SmallVectorImpl<ValueEntry> & Ops,unsigned i,Value * X)956*9880d681SAndroid Build Coastguard Worker static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
957*9880d681SAndroid Build Coastguard Worker                                   Value *X) {
958*9880d681SAndroid Build Coastguard Worker   unsigned XRank = Ops[i].Rank;
959*9880d681SAndroid Build Coastguard Worker   unsigned e = Ops.size();
960*9880d681SAndroid Build Coastguard Worker   for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
961*9880d681SAndroid Build Coastguard Worker     if (Ops[j].Op == X)
962*9880d681SAndroid Build Coastguard Worker       return j;
963*9880d681SAndroid Build Coastguard Worker     if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
964*9880d681SAndroid Build Coastguard Worker       if (Instruction *I2 = dyn_cast<Instruction>(X))
965*9880d681SAndroid Build Coastguard Worker         if (I1->isIdenticalTo(I2))
966*9880d681SAndroid Build Coastguard Worker           return j;
967*9880d681SAndroid Build Coastguard Worker   }
968*9880d681SAndroid Build Coastguard Worker   // Scan backwards.
969*9880d681SAndroid Build Coastguard Worker   for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
970*9880d681SAndroid Build Coastguard Worker     if (Ops[j].Op == X)
971*9880d681SAndroid Build Coastguard Worker       return j;
972*9880d681SAndroid Build Coastguard Worker     if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
973*9880d681SAndroid Build Coastguard Worker       if (Instruction *I2 = dyn_cast<Instruction>(X))
974*9880d681SAndroid Build Coastguard Worker         if (I1->isIdenticalTo(I2))
975*9880d681SAndroid Build Coastguard Worker           return j;
976*9880d681SAndroid Build Coastguard Worker   }
977*9880d681SAndroid Build Coastguard Worker   return i;
978*9880d681SAndroid Build Coastguard Worker }
979*9880d681SAndroid Build Coastguard Worker 
980*9880d681SAndroid Build Coastguard Worker /// Emit a tree of add instructions, summing Ops together
981*9880d681SAndroid Build Coastguard Worker /// and returning the result.  Insert the tree before I.
EmitAddTreeOfValues(Instruction * I,SmallVectorImpl<WeakVH> & Ops)982*9880d681SAndroid Build Coastguard Worker static Value *EmitAddTreeOfValues(Instruction *I,
983*9880d681SAndroid Build Coastguard Worker                                   SmallVectorImpl<WeakVH> &Ops){
984*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 1) return Ops.back();
985*9880d681SAndroid Build Coastguard Worker 
986*9880d681SAndroid Build Coastguard Worker   Value *V1 = Ops.back();
987*9880d681SAndroid Build Coastguard Worker   Ops.pop_back();
988*9880d681SAndroid Build Coastguard Worker   Value *V2 = EmitAddTreeOfValues(I, Ops);
989*9880d681SAndroid Build Coastguard Worker   return CreateAdd(V2, V1, "tmp", I, I);
990*9880d681SAndroid Build Coastguard Worker }
991*9880d681SAndroid Build Coastguard Worker 
992*9880d681SAndroid Build Coastguard Worker /// If V is an expression tree that is a multiplication sequence,
993*9880d681SAndroid Build Coastguard Worker /// and if this sequence contains a multiply by Factor,
994*9880d681SAndroid Build Coastguard Worker /// remove Factor from the tree and return the new tree.
RemoveFactorFromExpression(Value * V,Value * Factor)995*9880d681SAndroid Build Coastguard Worker Value *ReassociatePass::RemoveFactorFromExpression(Value *V, Value *Factor) {
996*9880d681SAndroid Build Coastguard Worker   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
997*9880d681SAndroid Build Coastguard Worker   if (!BO)
998*9880d681SAndroid Build Coastguard Worker     return nullptr;
999*9880d681SAndroid Build Coastguard Worker 
1000*9880d681SAndroid Build Coastguard Worker   SmallVector<RepeatedValue, 8> Tree;
1001*9880d681SAndroid Build Coastguard Worker   MadeChange |= LinearizeExprTree(BO, Tree);
1002*9880d681SAndroid Build Coastguard Worker   SmallVector<ValueEntry, 8> Factors;
1003*9880d681SAndroid Build Coastguard Worker   Factors.reserve(Tree.size());
1004*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
1005*9880d681SAndroid Build Coastguard Worker     RepeatedValue E = Tree[i];
1006*9880d681SAndroid Build Coastguard Worker     Factors.append(E.second.getZExtValue(),
1007*9880d681SAndroid Build Coastguard Worker                    ValueEntry(getRank(E.first), E.first));
1008*9880d681SAndroid Build Coastguard Worker   }
1009*9880d681SAndroid Build Coastguard Worker 
1010*9880d681SAndroid Build Coastguard Worker   bool FoundFactor = false;
1011*9880d681SAndroid Build Coastguard Worker   bool NeedsNegate = false;
1012*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1013*9880d681SAndroid Build Coastguard Worker     if (Factors[i].Op == Factor) {
1014*9880d681SAndroid Build Coastguard Worker       FoundFactor = true;
1015*9880d681SAndroid Build Coastguard Worker       Factors.erase(Factors.begin()+i);
1016*9880d681SAndroid Build Coastguard Worker       break;
1017*9880d681SAndroid Build Coastguard Worker     }
1018*9880d681SAndroid Build Coastguard Worker 
1019*9880d681SAndroid Build Coastguard Worker     // If this is a negative version of this factor, remove it.
1020*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
1021*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
1022*9880d681SAndroid Build Coastguard Worker         if (FC1->getValue() == -FC2->getValue()) {
1023*9880d681SAndroid Build Coastguard Worker           FoundFactor = NeedsNegate = true;
1024*9880d681SAndroid Build Coastguard Worker           Factors.erase(Factors.begin()+i);
1025*9880d681SAndroid Build Coastguard Worker           break;
1026*9880d681SAndroid Build Coastguard Worker         }
1027*9880d681SAndroid Build Coastguard Worker     } else if (ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
1028*9880d681SAndroid Build Coastguard Worker       if (ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].Op)) {
1029*9880d681SAndroid Build Coastguard Worker         const APFloat &F1 = FC1->getValueAPF();
1030*9880d681SAndroid Build Coastguard Worker         APFloat F2(FC2->getValueAPF());
1031*9880d681SAndroid Build Coastguard Worker         F2.changeSign();
1032*9880d681SAndroid Build Coastguard Worker         if (F1.compare(F2) == APFloat::cmpEqual) {
1033*9880d681SAndroid Build Coastguard Worker           FoundFactor = NeedsNegate = true;
1034*9880d681SAndroid Build Coastguard Worker           Factors.erase(Factors.begin() + i);
1035*9880d681SAndroid Build Coastguard Worker           break;
1036*9880d681SAndroid Build Coastguard Worker         }
1037*9880d681SAndroid Build Coastguard Worker       }
1038*9880d681SAndroid Build Coastguard Worker     }
1039*9880d681SAndroid Build Coastguard Worker   }
1040*9880d681SAndroid Build Coastguard Worker 
1041*9880d681SAndroid Build Coastguard Worker   if (!FoundFactor) {
1042*9880d681SAndroid Build Coastguard Worker     // Make sure to restore the operands to the expression tree.
1043*9880d681SAndroid Build Coastguard Worker     RewriteExprTree(BO, Factors);
1044*9880d681SAndroid Build Coastguard Worker     return nullptr;
1045*9880d681SAndroid Build Coastguard Worker   }
1046*9880d681SAndroid Build Coastguard Worker 
1047*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator InsertPt = ++BO->getIterator();
1048*9880d681SAndroid Build Coastguard Worker 
1049*9880d681SAndroid Build Coastguard Worker   // If this was just a single multiply, remove the multiply and return the only
1050*9880d681SAndroid Build Coastguard Worker   // remaining operand.
1051*9880d681SAndroid Build Coastguard Worker   if (Factors.size() == 1) {
1052*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(BO);
1053*9880d681SAndroid Build Coastguard Worker     V = Factors[0].Op;
1054*9880d681SAndroid Build Coastguard Worker   } else {
1055*9880d681SAndroid Build Coastguard Worker     RewriteExprTree(BO, Factors);
1056*9880d681SAndroid Build Coastguard Worker     V = BO;
1057*9880d681SAndroid Build Coastguard Worker   }
1058*9880d681SAndroid Build Coastguard Worker 
1059*9880d681SAndroid Build Coastguard Worker   if (NeedsNegate)
1060*9880d681SAndroid Build Coastguard Worker     V = CreateNeg(V, "neg", &*InsertPt, BO);
1061*9880d681SAndroid Build Coastguard Worker 
1062*9880d681SAndroid Build Coastguard Worker   return V;
1063*9880d681SAndroid Build Coastguard Worker }
1064*9880d681SAndroid Build Coastguard Worker 
1065*9880d681SAndroid Build Coastguard Worker /// If V is a single-use multiply, recursively add its operands as factors,
1066*9880d681SAndroid Build Coastguard Worker /// otherwise add V to the list of factors.
1067*9880d681SAndroid Build Coastguard Worker ///
1068*9880d681SAndroid Build Coastguard Worker /// Ops is the top-level list of add operands we're trying to factor.
FindSingleUseMultiplyFactors(Value * V,SmallVectorImpl<Value * > & Factors,const SmallVectorImpl<ValueEntry> & Ops)1069*9880d681SAndroid Build Coastguard Worker static void FindSingleUseMultiplyFactors(Value *V,
1070*9880d681SAndroid Build Coastguard Worker                                          SmallVectorImpl<Value*> &Factors,
1071*9880d681SAndroid Build Coastguard Worker                                        const SmallVectorImpl<ValueEntry> &Ops) {
1072*9880d681SAndroid Build Coastguard Worker   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
1073*9880d681SAndroid Build Coastguard Worker   if (!BO) {
1074*9880d681SAndroid Build Coastguard Worker     Factors.push_back(V);
1075*9880d681SAndroid Build Coastguard Worker     return;
1076*9880d681SAndroid Build Coastguard Worker   }
1077*9880d681SAndroid Build Coastguard Worker 
1078*9880d681SAndroid Build Coastguard Worker   // Otherwise, add the LHS and RHS to the list of factors.
1079*9880d681SAndroid Build Coastguard Worker   FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
1080*9880d681SAndroid Build Coastguard Worker   FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
1081*9880d681SAndroid Build Coastguard Worker }
1082*9880d681SAndroid Build Coastguard Worker 
1083*9880d681SAndroid Build Coastguard Worker /// Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
1084*9880d681SAndroid Build Coastguard Worker /// This optimizes based on identities.  If it can be reduced to a single Value,
1085*9880d681SAndroid Build Coastguard Worker /// it is returned, otherwise the Ops list is mutated as necessary.
OptimizeAndOrXor(unsigned Opcode,SmallVectorImpl<ValueEntry> & Ops)1086*9880d681SAndroid Build Coastguard Worker static Value *OptimizeAndOrXor(unsigned Opcode,
1087*9880d681SAndroid Build Coastguard Worker                                SmallVectorImpl<ValueEntry> &Ops) {
1088*9880d681SAndroid Build Coastguard Worker   // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
1089*9880d681SAndroid Build Coastguard Worker   // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
1090*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1091*9880d681SAndroid Build Coastguard Worker     // First, check for X and ~X in the operand list.
1092*9880d681SAndroid Build Coastguard Worker     assert(i < Ops.size());
1093*9880d681SAndroid Build Coastguard Worker     if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
1094*9880d681SAndroid Build Coastguard Worker       Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
1095*9880d681SAndroid Build Coastguard Worker       unsigned FoundX = FindInOperandList(Ops, i, X);
1096*9880d681SAndroid Build Coastguard Worker       if (FoundX != i) {
1097*9880d681SAndroid Build Coastguard Worker         if (Opcode == Instruction::And)   // ...&X&~X = 0
1098*9880d681SAndroid Build Coastguard Worker           return Constant::getNullValue(X->getType());
1099*9880d681SAndroid Build Coastguard Worker 
1100*9880d681SAndroid Build Coastguard Worker         if (Opcode == Instruction::Or)    // ...|X|~X = -1
1101*9880d681SAndroid Build Coastguard Worker           return Constant::getAllOnesValue(X->getType());
1102*9880d681SAndroid Build Coastguard Worker       }
1103*9880d681SAndroid Build Coastguard Worker     }
1104*9880d681SAndroid Build Coastguard Worker 
1105*9880d681SAndroid Build Coastguard Worker     // Next, check for duplicate pairs of values, which we assume are next to
1106*9880d681SAndroid Build Coastguard Worker     // each other, due to our sorting criteria.
1107*9880d681SAndroid Build Coastguard Worker     assert(i < Ops.size());
1108*9880d681SAndroid Build Coastguard Worker     if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
1109*9880d681SAndroid Build Coastguard Worker       if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1110*9880d681SAndroid Build Coastguard Worker         // Drop duplicate values for And and Or.
1111*9880d681SAndroid Build Coastguard Worker         Ops.erase(Ops.begin()+i);
1112*9880d681SAndroid Build Coastguard Worker         --i; --e;
1113*9880d681SAndroid Build Coastguard Worker         ++NumAnnihil;
1114*9880d681SAndroid Build Coastguard Worker         continue;
1115*9880d681SAndroid Build Coastguard Worker       }
1116*9880d681SAndroid Build Coastguard Worker 
1117*9880d681SAndroid Build Coastguard Worker       // Drop pairs of values for Xor.
1118*9880d681SAndroid Build Coastguard Worker       assert(Opcode == Instruction::Xor);
1119*9880d681SAndroid Build Coastguard Worker       if (e == 2)
1120*9880d681SAndroid Build Coastguard Worker         return Constant::getNullValue(Ops[0].Op->getType());
1121*9880d681SAndroid Build Coastguard Worker 
1122*9880d681SAndroid Build Coastguard Worker       // Y ^ X^X -> Y
1123*9880d681SAndroid Build Coastguard Worker       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1124*9880d681SAndroid Build Coastguard Worker       i -= 1; e -= 2;
1125*9880d681SAndroid Build Coastguard Worker       ++NumAnnihil;
1126*9880d681SAndroid Build Coastguard Worker     }
1127*9880d681SAndroid Build Coastguard Worker   }
1128*9880d681SAndroid Build Coastguard Worker   return nullptr;
1129*9880d681SAndroid Build Coastguard Worker }
1130*9880d681SAndroid Build Coastguard Worker 
1131*9880d681SAndroid Build Coastguard Worker /// Helper function of CombineXorOpnd(). It creates a bitwise-and
1132*9880d681SAndroid Build Coastguard Worker /// instruction with the given two operands, and return the resulting
1133*9880d681SAndroid Build Coastguard Worker /// instruction. There are two special cases: 1) if the constant operand is 0,
1134*9880d681SAndroid Build Coastguard Worker /// it will return NULL. 2) if the constant is ~0, the symbolic operand will
1135*9880d681SAndroid Build Coastguard Worker /// be returned.
createAndInstr(Instruction * InsertBefore,Value * Opnd,const APInt & ConstOpnd)1136*9880d681SAndroid Build Coastguard Worker static Value *createAndInstr(Instruction *InsertBefore, Value *Opnd,
1137*9880d681SAndroid Build Coastguard Worker                              const APInt &ConstOpnd) {
1138*9880d681SAndroid Build Coastguard Worker   if (ConstOpnd != 0) {
1139*9880d681SAndroid Build Coastguard Worker     if (!ConstOpnd.isAllOnesValue()) {
1140*9880d681SAndroid Build Coastguard Worker       LLVMContext &Ctx = Opnd->getType()->getContext();
1141*9880d681SAndroid Build Coastguard Worker       Instruction *I;
1142*9880d681SAndroid Build Coastguard Worker       I = BinaryOperator::CreateAnd(Opnd, ConstantInt::get(Ctx, ConstOpnd),
1143*9880d681SAndroid Build Coastguard Worker                                     "and.ra", InsertBefore);
1144*9880d681SAndroid Build Coastguard Worker       I->setDebugLoc(InsertBefore->getDebugLoc());
1145*9880d681SAndroid Build Coastguard Worker       return I;
1146*9880d681SAndroid Build Coastguard Worker     }
1147*9880d681SAndroid Build Coastguard Worker     return Opnd;
1148*9880d681SAndroid Build Coastguard Worker   }
1149*9880d681SAndroid Build Coastguard Worker   return nullptr;
1150*9880d681SAndroid Build Coastguard Worker }
1151*9880d681SAndroid Build Coastguard Worker 
1152*9880d681SAndroid Build Coastguard Worker // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
1153*9880d681SAndroid Build Coastguard Worker // into "R ^ C", where C would be 0, and R is a symbolic value.
1154*9880d681SAndroid Build Coastguard Worker //
1155*9880d681SAndroid Build Coastguard Worker // If it was successful, true is returned, and the "R" and "C" is returned
1156*9880d681SAndroid Build Coastguard Worker // via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
1157*9880d681SAndroid Build Coastguard Worker // and both "Res" and "ConstOpnd" remain unchanged.
1158*9880d681SAndroid Build Coastguard Worker //
CombineXorOpnd(Instruction * I,XorOpnd * Opnd1,APInt & ConstOpnd,Value * & Res)1159*9880d681SAndroid Build Coastguard Worker bool ReassociatePass::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
1160*9880d681SAndroid Build Coastguard Worker                                      APInt &ConstOpnd, Value *&Res) {
1161*9880d681SAndroid Build Coastguard Worker   // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2
1162*9880d681SAndroid Build Coastguard Worker   //                       = ((x | c1) ^ c1) ^ (c1 ^ c2)
1163*9880d681SAndroid Build Coastguard Worker   //                       = (x & ~c1) ^ (c1 ^ c2)
1164*9880d681SAndroid Build Coastguard Worker   // It is useful only when c1 == c2.
1165*9880d681SAndroid Build Coastguard Worker   if (Opnd1->isOrExpr() && Opnd1->getConstPart() != 0) {
1166*9880d681SAndroid Build Coastguard Worker     if (!Opnd1->getValue()->hasOneUse())
1167*9880d681SAndroid Build Coastguard Worker       return false;
1168*9880d681SAndroid Build Coastguard Worker 
1169*9880d681SAndroid Build Coastguard Worker     const APInt &C1 = Opnd1->getConstPart();
1170*9880d681SAndroid Build Coastguard Worker     if (C1 != ConstOpnd)
1171*9880d681SAndroid Build Coastguard Worker       return false;
1172*9880d681SAndroid Build Coastguard Worker 
1173*9880d681SAndroid Build Coastguard Worker     Value *X = Opnd1->getSymbolicPart();
1174*9880d681SAndroid Build Coastguard Worker     Res = createAndInstr(I, X, ~C1);
1175*9880d681SAndroid Build Coastguard Worker     // ConstOpnd was C2, now C1 ^ C2.
1176*9880d681SAndroid Build Coastguard Worker     ConstOpnd ^= C1;
1177*9880d681SAndroid Build Coastguard Worker 
1178*9880d681SAndroid Build Coastguard Worker     if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
1179*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(T);
1180*9880d681SAndroid Build Coastguard Worker     return true;
1181*9880d681SAndroid Build Coastguard Worker   }
1182*9880d681SAndroid Build Coastguard Worker   return false;
1183*9880d681SAndroid Build Coastguard Worker }
1184*9880d681SAndroid Build Coastguard Worker 
1185*9880d681SAndroid Build Coastguard Worker 
1186*9880d681SAndroid Build Coastguard Worker // Helper function of OptimizeXor(). It tries to simplify
1187*9880d681SAndroid Build Coastguard Worker // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
1188*9880d681SAndroid Build Coastguard Worker // symbolic value.
1189*9880d681SAndroid Build Coastguard Worker //
1190*9880d681SAndroid Build Coastguard Worker // If it was successful, true is returned, and the "R" and "C" is returned
1191*9880d681SAndroid Build Coastguard Worker // via "Res" and "ConstOpnd", respectively (If the entire expression is
1192*9880d681SAndroid Build Coastguard Worker // evaluated to a constant, the Res is set to NULL); otherwise, false is
1193*9880d681SAndroid Build Coastguard Worker // returned, and both "Res" and "ConstOpnd" remain unchanged.
CombineXorOpnd(Instruction * I,XorOpnd * Opnd1,XorOpnd * Opnd2,APInt & ConstOpnd,Value * & Res)1194*9880d681SAndroid Build Coastguard Worker bool ReassociatePass::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
1195*9880d681SAndroid Build Coastguard Worker                                      XorOpnd *Opnd2, APInt &ConstOpnd,
1196*9880d681SAndroid Build Coastguard Worker                                      Value *&Res) {
1197*9880d681SAndroid Build Coastguard Worker   Value *X = Opnd1->getSymbolicPart();
1198*9880d681SAndroid Build Coastguard Worker   if (X != Opnd2->getSymbolicPart())
1199*9880d681SAndroid Build Coastguard Worker     return false;
1200*9880d681SAndroid Build Coastguard Worker 
1201*9880d681SAndroid Build Coastguard Worker   // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
1202*9880d681SAndroid Build Coastguard Worker   int DeadInstNum = 1;
1203*9880d681SAndroid Build Coastguard Worker   if (Opnd1->getValue()->hasOneUse())
1204*9880d681SAndroid Build Coastguard Worker     DeadInstNum++;
1205*9880d681SAndroid Build Coastguard Worker   if (Opnd2->getValue()->hasOneUse())
1206*9880d681SAndroid Build Coastguard Worker     DeadInstNum++;
1207*9880d681SAndroid Build Coastguard Worker 
1208*9880d681SAndroid Build Coastguard Worker   // Xor-Rule 2:
1209*9880d681SAndroid Build Coastguard Worker   //  (x | c1) ^ (x & c2)
1210*9880d681SAndroid Build Coastguard Worker   //   = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
1211*9880d681SAndroid Build Coastguard Worker   //   = (x & ~c1) ^ (x & c2) ^ c1               // Xor-Rule 1
1212*9880d681SAndroid Build Coastguard Worker   //   = (x & c3) ^ c1, where c3 = ~c1 ^ c2      // Xor-rule 3
1213*9880d681SAndroid Build Coastguard Worker   //
1214*9880d681SAndroid Build Coastguard Worker   if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
1215*9880d681SAndroid Build Coastguard Worker     if (Opnd2->isOrExpr())
1216*9880d681SAndroid Build Coastguard Worker       std::swap(Opnd1, Opnd2);
1217*9880d681SAndroid Build Coastguard Worker 
1218*9880d681SAndroid Build Coastguard Worker     const APInt &C1 = Opnd1->getConstPart();
1219*9880d681SAndroid Build Coastguard Worker     const APInt &C2 = Opnd2->getConstPart();
1220*9880d681SAndroid Build Coastguard Worker     APInt C3((~C1) ^ C2);
1221*9880d681SAndroid Build Coastguard Worker 
1222*9880d681SAndroid Build Coastguard Worker     // Do not increase code size!
1223*9880d681SAndroid Build Coastguard Worker     if (C3 != 0 && !C3.isAllOnesValue()) {
1224*9880d681SAndroid Build Coastguard Worker       int NewInstNum = ConstOpnd != 0 ? 1 : 2;
1225*9880d681SAndroid Build Coastguard Worker       if (NewInstNum > DeadInstNum)
1226*9880d681SAndroid Build Coastguard Worker         return false;
1227*9880d681SAndroid Build Coastguard Worker     }
1228*9880d681SAndroid Build Coastguard Worker 
1229*9880d681SAndroid Build Coastguard Worker     Res = createAndInstr(I, X, C3);
1230*9880d681SAndroid Build Coastguard Worker     ConstOpnd ^= C1;
1231*9880d681SAndroid Build Coastguard Worker 
1232*9880d681SAndroid Build Coastguard Worker   } else if (Opnd1->isOrExpr()) {
1233*9880d681SAndroid Build Coastguard Worker     // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
1234*9880d681SAndroid Build Coastguard Worker     //
1235*9880d681SAndroid Build Coastguard Worker     const APInt &C1 = Opnd1->getConstPart();
1236*9880d681SAndroid Build Coastguard Worker     const APInt &C2 = Opnd2->getConstPart();
1237*9880d681SAndroid Build Coastguard Worker     APInt C3 = C1 ^ C2;
1238*9880d681SAndroid Build Coastguard Worker 
1239*9880d681SAndroid Build Coastguard Worker     // Do not increase code size
1240*9880d681SAndroid Build Coastguard Worker     if (C3 != 0 && !C3.isAllOnesValue()) {
1241*9880d681SAndroid Build Coastguard Worker       int NewInstNum = ConstOpnd != 0 ? 1 : 2;
1242*9880d681SAndroid Build Coastguard Worker       if (NewInstNum > DeadInstNum)
1243*9880d681SAndroid Build Coastguard Worker         return false;
1244*9880d681SAndroid Build Coastguard Worker     }
1245*9880d681SAndroid Build Coastguard Worker 
1246*9880d681SAndroid Build Coastguard Worker     Res = createAndInstr(I, X, C3);
1247*9880d681SAndroid Build Coastguard Worker     ConstOpnd ^= C3;
1248*9880d681SAndroid Build Coastguard Worker   } else {
1249*9880d681SAndroid Build Coastguard Worker     // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
1250*9880d681SAndroid Build Coastguard Worker     //
1251*9880d681SAndroid Build Coastguard Worker     const APInt &C1 = Opnd1->getConstPart();
1252*9880d681SAndroid Build Coastguard Worker     const APInt &C2 = Opnd2->getConstPart();
1253*9880d681SAndroid Build Coastguard Worker     APInt C3 = C1 ^ C2;
1254*9880d681SAndroid Build Coastguard Worker     Res = createAndInstr(I, X, C3);
1255*9880d681SAndroid Build Coastguard Worker   }
1256*9880d681SAndroid Build Coastguard Worker 
1257*9880d681SAndroid Build Coastguard Worker   // Put the original operands in the Redo list; hope they will be deleted
1258*9880d681SAndroid Build Coastguard Worker   // as dead code.
1259*9880d681SAndroid Build Coastguard Worker   if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
1260*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(T);
1261*9880d681SAndroid Build Coastguard Worker   if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
1262*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(T);
1263*9880d681SAndroid Build Coastguard Worker 
1264*9880d681SAndroid Build Coastguard Worker   return true;
1265*9880d681SAndroid Build Coastguard Worker }
1266*9880d681SAndroid Build Coastguard Worker 
1267*9880d681SAndroid Build Coastguard Worker /// Optimize a series of operands to an 'xor' instruction. If it can be reduced
1268*9880d681SAndroid Build Coastguard Worker /// to a single Value, it is returned, otherwise the Ops list is mutated as
1269*9880d681SAndroid Build Coastguard Worker /// necessary.
OptimizeXor(Instruction * I,SmallVectorImpl<ValueEntry> & Ops)1270*9880d681SAndroid Build Coastguard Worker Value *ReassociatePass::OptimizeXor(Instruction *I,
1271*9880d681SAndroid Build Coastguard Worker                                     SmallVectorImpl<ValueEntry> &Ops) {
1272*9880d681SAndroid Build Coastguard Worker   if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
1273*9880d681SAndroid Build Coastguard Worker     return V;
1274*9880d681SAndroid Build Coastguard Worker 
1275*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 1)
1276*9880d681SAndroid Build Coastguard Worker     return nullptr;
1277*9880d681SAndroid Build Coastguard Worker 
1278*9880d681SAndroid Build Coastguard Worker   SmallVector<XorOpnd, 8> Opnds;
1279*9880d681SAndroid Build Coastguard Worker   SmallVector<XorOpnd*, 8> OpndPtrs;
1280*9880d681SAndroid Build Coastguard Worker   Type *Ty = Ops[0].Op->getType();
1281*9880d681SAndroid Build Coastguard Worker   APInt ConstOpnd(Ty->getIntegerBitWidth(), 0);
1282*9880d681SAndroid Build Coastguard Worker 
1283*9880d681SAndroid Build Coastguard Worker   // Step 1: Convert ValueEntry to XorOpnd
1284*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1285*9880d681SAndroid Build Coastguard Worker     Value *V = Ops[i].Op;
1286*9880d681SAndroid Build Coastguard Worker     if (!isa<ConstantInt>(V)) {
1287*9880d681SAndroid Build Coastguard Worker       XorOpnd O(V);
1288*9880d681SAndroid Build Coastguard Worker       O.setSymbolicRank(getRank(O.getSymbolicPart()));
1289*9880d681SAndroid Build Coastguard Worker       Opnds.push_back(O);
1290*9880d681SAndroid Build Coastguard Worker     } else
1291*9880d681SAndroid Build Coastguard Worker       ConstOpnd ^= cast<ConstantInt>(V)->getValue();
1292*9880d681SAndroid Build Coastguard Worker   }
1293*9880d681SAndroid Build Coastguard Worker 
1294*9880d681SAndroid Build Coastguard Worker   // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
1295*9880d681SAndroid Build Coastguard Worker   //  It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
1296*9880d681SAndroid Build Coastguard Worker   //  the "OpndPtrs" as well. For the similar reason, do not fuse this loop
1297*9880d681SAndroid Build Coastguard Worker   //  with the previous loop --- the iterator of the "Opnds" may be invalidated
1298*9880d681SAndroid Build Coastguard Worker   //  when new elements are added to the vector.
1299*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Opnds.size(); i != e; ++i)
1300*9880d681SAndroid Build Coastguard Worker     OpndPtrs.push_back(&Opnds[i]);
1301*9880d681SAndroid Build Coastguard Worker 
1302*9880d681SAndroid Build Coastguard Worker   // Step 2: Sort the Xor-Operands in a way such that the operands containing
1303*9880d681SAndroid Build Coastguard Worker   //  the same symbolic value cluster together. For instance, the input operand
1304*9880d681SAndroid Build Coastguard Worker   //  sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
1305*9880d681SAndroid Build Coastguard Worker   //  ("x | 123", "x & 789", "y & 456").
1306*9880d681SAndroid Build Coastguard Worker   //
1307*9880d681SAndroid Build Coastguard Worker   //  The purpose is twofold:
1308*9880d681SAndroid Build Coastguard Worker   //  1) Cluster together the operands sharing the same symbolic-value.
1309*9880d681SAndroid Build Coastguard Worker   //  2) Operand having smaller symbolic-value-rank is permuted earlier, which
1310*9880d681SAndroid Build Coastguard Worker   //     could potentially shorten crital path, and expose more loop-invariants.
1311*9880d681SAndroid Build Coastguard Worker   //     Note that values' rank are basically defined in RPO order (FIXME).
1312*9880d681SAndroid Build Coastguard Worker   //     So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier
1313*9880d681SAndroid Build Coastguard Worker   //     than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
1314*9880d681SAndroid Build Coastguard Worker   //     "z" in the order of X-Y-Z is better than any other orders.
1315*9880d681SAndroid Build Coastguard Worker   std::stable_sort(OpndPtrs.begin(), OpndPtrs.end(),
1316*9880d681SAndroid Build Coastguard Worker                    [](XorOpnd *LHS, XorOpnd *RHS) {
1317*9880d681SAndroid Build Coastguard Worker     return LHS->getSymbolicRank() < RHS->getSymbolicRank();
1318*9880d681SAndroid Build Coastguard Worker   });
1319*9880d681SAndroid Build Coastguard Worker 
1320*9880d681SAndroid Build Coastguard Worker   // Step 3: Combine adjacent operands
1321*9880d681SAndroid Build Coastguard Worker   XorOpnd *PrevOpnd = nullptr;
1322*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
1323*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
1324*9880d681SAndroid Build Coastguard Worker     XorOpnd *CurrOpnd = OpndPtrs[i];
1325*9880d681SAndroid Build Coastguard Worker     // The combined value
1326*9880d681SAndroid Build Coastguard Worker     Value *CV;
1327*9880d681SAndroid Build Coastguard Worker 
1328*9880d681SAndroid Build Coastguard Worker     // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
1329*9880d681SAndroid Build Coastguard Worker     if (ConstOpnd != 0 && CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1330*9880d681SAndroid Build Coastguard Worker       Changed = true;
1331*9880d681SAndroid Build Coastguard Worker       if (CV)
1332*9880d681SAndroid Build Coastguard Worker         *CurrOpnd = XorOpnd(CV);
1333*9880d681SAndroid Build Coastguard Worker       else {
1334*9880d681SAndroid Build Coastguard Worker         CurrOpnd->Invalidate();
1335*9880d681SAndroid Build Coastguard Worker         continue;
1336*9880d681SAndroid Build Coastguard Worker       }
1337*9880d681SAndroid Build Coastguard Worker     }
1338*9880d681SAndroid Build Coastguard Worker 
1339*9880d681SAndroid Build Coastguard Worker     if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1340*9880d681SAndroid Build Coastguard Worker       PrevOpnd = CurrOpnd;
1341*9880d681SAndroid Build Coastguard Worker       continue;
1342*9880d681SAndroid Build Coastguard Worker     }
1343*9880d681SAndroid Build Coastguard Worker 
1344*9880d681SAndroid Build Coastguard Worker     // step 3.2: When previous and current operands share the same symbolic
1345*9880d681SAndroid Build Coastguard Worker     //  value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd"
1346*9880d681SAndroid Build Coastguard Worker     //
1347*9880d681SAndroid Build Coastguard Worker     if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1348*9880d681SAndroid Build Coastguard Worker       // Remove previous operand
1349*9880d681SAndroid Build Coastguard Worker       PrevOpnd->Invalidate();
1350*9880d681SAndroid Build Coastguard Worker       if (CV) {
1351*9880d681SAndroid Build Coastguard Worker         *CurrOpnd = XorOpnd(CV);
1352*9880d681SAndroid Build Coastguard Worker         PrevOpnd = CurrOpnd;
1353*9880d681SAndroid Build Coastguard Worker       } else {
1354*9880d681SAndroid Build Coastguard Worker         CurrOpnd->Invalidate();
1355*9880d681SAndroid Build Coastguard Worker         PrevOpnd = nullptr;
1356*9880d681SAndroid Build Coastguard Worker       }
1357*9880d681SAndroid Build Coastguard Worker       Changed = true;
1358*9880d681SAndroid Build Coastguard Worker     }
1359*9880d681SAndroid Build Coastguard Worker   }
1360*9880d681SAndroid Build Coastguard Worker 
1361*9880d681SAndroid Build Coastguard Worker   // Step 4: Reassemble the Ops
1362*9880d681SAndroid Build Coastguard Worker   if (Changed) {
1363*9880d681SAndroid Build Coastguard Worker     Ops.clear();
1364*9880d681SAndroid Build Coastguard Worker     for (unsigned int i = 0, e = Opnds.size(); i < e; i++) {
1365*9880d681SAndroid Build Coastguard Worker       XorOpnd &O = Opnds[i];
1366*9880d681SAndroid Build Coastguard Worker       if (O.isInvalid())
1367*9880d681SAndroid Build Coastguard Worker         continue;
1368*9880d681SAndroid Build Coastguard Worker       ValueEntry VE(getRank(O.getValue()), O.getValue());
1369*9880d681SAndroid Build Coastguard Worker       Ops.push_back(VE);
1370*9880d681SAndroid Build Coastguard Worker     }
1371*9880d681SAndroid Build Coastguard Worker     if (ConstOpnd != 0) {
1372*9880d681SAndroid Build Coastguard Worker       Value *C = ConstantInt::get(Ty->getContext(), ConstOpnd);
1373*9880d681SAndroid Build Coastguard Worker       ValueEntry VE(getRank(C), C);
1374*9880d681SAndroid Build Coastguard Worker       Ops.push_back(VE);
1375*9880d681SAndroid Build Coastguard Worker     }
1376*9880d681SAndroid Build Coastguard Worker     int Sz = Ops.size();
1377*9880d681SAndroid Build Coastguard Worker     if (Sz == 1)
1378*9880d681SAndroid Build Coastguard Worker       return Ops.back().Op;
1379*9880d681SAndroid Build Coastguard Worker     else if (Sz == 0) {
1380*9880d681SAndroid Build Coastguard Worker       assert(ConstOpnd == 0);
1381*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(Ty->getContext(), ConstOpnd);
1382*9880d681SAndroid Build Coastguard Worker     }
1383*9880d681SAndroid Build Coastguard Worker   }
1384*9880d681SAndroid Build Coastguard Worker 
1385*9880d681SAndroid Build Coastguard Worker   return nullptr;
1386*9880d681SAndroid Build Coastguard Worker }
1387*9880d681SAndroid Build Coastguard Worker 
1388*9880d681SAndroid Build Coastguard Worker /// Optimize a series of operands to an 'add' instruction.  This
1389*9880d681SAndroid Build Coastguard Worker /// optimizes based on identities.  If it can be reduced to a single Value, it
1390*9880d681SAndroid Build Coastguard Worker /// is returned, otherwise the Ops list is mutated as necessary.
OptimizeAdd(Instruction * I,SmallVectorImpl<ValueEntry> & Ops)1391*9880d681SAndroid Build Coastguard Worker Value *ReassociatePass::OptimizeAdd(Instruction *I,
1392*9880d681SAndroid Build Coastguard Worker                                     SmallVectorImpl<ValueEntry> &Ops) {
1393*9880d681SAndroid Build Coastguard Worker   // Scan the operand lists looking for X and -X pairs.  If we find any, we
1394*9880d681SAndroid Build Coastguard Worker   // can simplify expressions like X+-X == 0 and X+~X ==-1.  While we're at it,
1395*9880d681SAndroid Build Coastguard Worker   // scan for any
1396*9880d681SAndroid Build Coastguard Worker   // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
1397*9880d681SAndroid Build Coastguard Worker 
1398*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1399*9880d681SAndroid Build Coastguard Worker     Value *TheOp = Ops[i].Op;
1400*9880d681SAndroid Build Coastguard Worker     // Check to see if we've seen this operand before.  If so, we factor all
1401*9880d681SAndroid Build Coastguard Worker     // instances of the operand together.  Due to our sorting criteria, we know
1402*9880d681SAndroid Build Coastguard Worker     // that these need to be next to each other in the vector.
1403*9880d681SAndroid Build Coastguard Worker     if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
1404*9880d681SAndroid Build Coastguard Worker       // Rescan the list, remove all instances of this operand from the expr.
1405*9880d681SAndroid Build Coastguard Worker       unsigned NumFound = 0;
1406*9880d681SAndroid Build Coastguard Worker       do {
1407*9880d681SAndroid Build Coastguard Worker         Ops.erase(Ops.begin()+i);
1408*9880d681SAndroid Build Coastguard Worker         ++NumFound;
1409*9880d681SAndroid Build Coastguard Worker       } while (i != Ops.size() && Ops[i].Op == TheOp);
1410*9880d681SAndroid Build Coastguard Worker 
1411*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
1412*9880d681SAndroid Build Coastguard Worker       ++NumFactor;
1413*9880d681SAndroid Build Coastguard Worker 
1414*9880d681SAndroid Build Coastguard Worker       // Insert a new multiply.
1415*9880d681SAndroid Build Coastguard Worker       Type *Ty = TheOp->getType();
1416*9880d681SAndroid Build Coastguard Worker       Constant *C = Ty->isIntOrIntVectorTy() ?
1417*9880d681SAndroid Build Coastguard Worker         ConstantInt::get(Ty, NumFound) : ConstantFP::get(Ty, NumFound);
1418*9880d681SAndroid Build Coastguard Worker       Instruction *Mul = CreateMul(TheOp, C, "factor", I, I);
1419*9880d681SAndroid Build Coastguard Worker 
1420*9880d681SAndroid Build Coastguard Worker       // Now that we have inserted a multiply, optimize it. This allows us to
1421*9880d681SAndroid Build Coastguard Worker       // handle cases that require multiple factoring steps, such as this:
1422*9880d681SAndroid Build Coastguard Worker       // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
1423*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(Mul);
1424*9880d681SAndroid Build Coastguard Worker 
1425*9880d681SAndroid Build Coastguard Worker       // If every add operand was a duplicate, return the multiply.
1426*9880d681SAndroid Build Coastguard Worker       if (Ops.empty())
1427*9880d681SAndroid Build Coastguard Worker         return Mul;
1428*9880d681SAndroid Build Coastguard Worker 
1429*9880d681SAndroid Build Coastguard Worker       // Otherwise, we had some input that didn't have the dupe, such as
1430*9880d681SAndroid Build Coastguard Worker       // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
1431*9880d681SAndroid Build Coastguard Worker       // things being added by this operation.
1432*9880d681SAndroid Build Coastguard Worker       Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
1433*9880d681SAndroid Build Coastguard Worker 
1434*9880d681SAndroid Build Coastguard Worker       --i;
1435*9880d681SAndroid Build Coastguard Worker       e = Ops.size();
1436*9880d681SAndroid Build Coastguard Worker       continue;
1437*9880d681SAndroid Build Coastguard Worker     }
1438*9880d681SAndroid Build Coastguard Worker 
1439*9880d681SAndroid Build Coastguard Worker     // Check for X and -X or X and ~X in the operand list.
1440*9880d681SAndroid Build Coastguard Worker     if (!BinaryOperator::isNeg(TheOp) && !BinaryOperator::isFNeg(TheOp) &&
1441*9880d681SAndroid Build Coastguard Worker         !BinaryOperator::isNot(TheOp))
1442*9880d681SAndroid Build Coastguard Worker       continue;
1443*9880d681SAndroid Build Coastguard Worker 
1444*9880d681SAndroid Build Coastguard Worker     Value *X = nullptr;
1445*9880d681SAndroid Build Coastguard Worker     if (BinaryOperator::isNeg(TheOp) || BinaryOperator::isFNeg(TheOp))
1446*9880d681SAndroid Build Coastguard Worker       X = BinaryOperator::getNegArgument(TheOp);
1447*9880d681SAndroid Build Coastguard Worker     else if (BinaryOperator::isNot(TheOp))
1448*9880d681SAndroid Build Coastguard Worker       X = BinaryOperator::getNotArgument(TheOp);
1449*9880d681SAndroid Build Coastguard Worker 
1450*9880d681SAndroid Build Coastguard Worker     unsigned FoundX = FindInOperandList(Ops, i, X);
1451*9880d681SAndroid Build Coastguard Worker     if (FoundX == i)
1452*9880d681SAndroid Build Coastguard Worker       continue;
1453*9880d681SAndroid Build Coastguard Worker 
1454*9880d681SAndroid Build Coastguard Worker     // Remove X and -X from the operand list.
1455*9880d681SAndroid Build Coastguard Worker     if (Ops.size() == 2 &&
1456*9880d681SAndroid Build Coastguard Worker         (BinaryOperator::isNeg(TheOp) || BinaryOperator::isFNeg(TheOp)))
1457*9880d681SAndroid Build Coastguard Worker       return Constant::getNullValue(X->getType());
1458*9880d681SAndroid Build Coastguard Worker 
1459*9880d681SAndroid Build Coastguard Worker     // Remove X and ~X from the operand list.
1460*9880d681SAndroid Build Coastguard Worker     if (Ops.size() == 2 && BinaryOperator::isNot(TheOp))
1461*9880d681SAndroid Build Coastguard Worker       return Constant::getAllOnesValue(X->getType());
1462*9880d681SAndroid Build Coastguard Worker 
1463*9880d681SAndroid Build Coastguard Worker     Ops.erase(Ops.begin()+i);
1464*9880d681SAndroid Build Coastguard Worker     if (i < FoundX)
1465*9880d681SAndroid Build Coastguard Worker       --FoundX;
1466*9880d681SAndroid Build Coastguard Worker     else
1467*9880d681SAndroid Build Coastguard Worker       --i;   // Need to back up an extra one.
1468*9880d681SAndroid Build Coastguard Worker     Ops.erase(Ops.begin()+FoundX);
1469*9880d681SAndroid Build Coastguard Worker     ++NumAnnihil;
1470*9880d681SAndroid Build Coastguard Worker     --i;     // Revisit element.
1471*9880d681SAndroid Build Coastguard Worker     e -= 2;  // Removed two elements.
1472*9880d681SAndroid Build Coastguard Worker 
1473*9880d681SAndroid Build Coastguard Worker     // if X and ~X we append -1 to the operand list.
1474*9880d681SAndroid Build Coastguard Worker     if (BinaryOperator::isNot(TheOp)) {
1475*9880d681SAndroid Build Coastguard Worker       Value *V = Constant::getAllOnesValue(X->getType());
1476*9880d681SAndroid Build Coastguard Worker       Ops.insert(Ops.end(), ValueEntry(getRank(V), V));
1477*9880d681SAndroid Build Coastguard Worker       e += 1;
1478*9880d681SAndroid Build Coastguard Worker     }
1479*9880d681SAndroid Build Coastguard Worker   }
1480*9880d681SAndroid Build Coastguard Worker 
1481*9880d681SAndroid Build Coastguard Worker   // Scan the operand list, checking to see if there are any common factors
1482*9880d681SAndroid Build Coastguard Worker   // between operands.  Consider something like A*A+A*B*C+D.  We would like to
1483*9880d681SAndroid Build Coastguard Worker   // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
1484*9880d681SAndroid Build Coastguard Worker   // To efficiently find this, we count the number of times a factor occurs
1485*9880d681SAndroid Build Coastguard Worker   // for any ADD operands that are MULs.
1486*9880d681SAndroid Build Coastguard Worker   DenseMap<Value*, unsigned> FactorOccurrences;
1487*9880d681SAndroid Build Coastguard Worker 
1488*9880d681SAndroid Build Coastguard Worker   // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
1489*9880d681SAndroid Build Coastguard Worker   // where they are actually the same multiply.
1490*9880d681SAndroid Build Coastguard Worker   unsigned MaxOcc = 0;
1491*9880d681SAndroid Build Coastguard Worker   Value *MaxOccVal = nullptr;
1492*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1493*9880d681SAndroid Build Coastguard Worker     BinaryOperator *BOp =
1494*9880d681SAndroid Build Coastguard Worker         isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
1495*9880d681SAndroid Build Coastguard Worker     if (!BOp)
1496*9880d681SAndroid Build Coastguard Worker       continue;
1497*9880d681SAndroid Build Coastguard Worker 
1498*9880d681SAndroid Build Coastguard Worker     // Compute all of the factors of this added value.
1499*9880d681SAndroid Build Coastguard Worker     SmallVector<Value*, 8> Factors;
1500*9880d681SAndroid Build Coastguard Worker     FindSingleUseMultiplyFactors(BOp, Factors, Ops);
1501*9880d681SAndroid Build Coastguard Worker     assert(Factors.size() > 1 && "Bad linearize!");
1502*9880d681SAndroid Build Coastguard Worker 
1503*9880d681SAndroid Build Coastguard Worker     // Add one to FactorOccurrences for each unique factor in this op.
1504*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<Value*, 8> Duplicates;
1505*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1506*9880d681SAndroid Build Coastguard Worker       Value *Factor = Factors[i];
1507*9880d681SAndroid Build Coastguard Worker       if (!Duplicates.insert(Factor).second)
1508*9880d681SAndroid Build Coastguard Worker         continue;
1509*9880d681SAndroid Build Coastguard Worker 
1510*9880d681SAndroid Build Coastguard Worker       unsigned Occ = ++FactorOccurrences[Factor];
1511*9880d681SAndroid Build Coastguard Worker       if (Occ > MaxOcc) {
1512*9880d681SAndroid Build Coastguard Worker         MaxOcc = Occ;
1513*9880d681SAndroid Build Coastguard Worker         MaxOccVal = Factor;
1514*9880d681SAndroid Build Coastguard Worker       }
1515*9880d681SAndroid Build Coastguard Worker 
1516*9880d681SAndroid Build Coastguard Worker       // If Factor is a negative constant, add the negated value as a factor
1517*9880d681SAndroid Build Coastguard Worker       // because we can percolate the negate out.  Watch for minint, which
1518*9880d681SAndroid Build Coastguard Worker       // cannot be positivified.
1519*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
1520*9880d681SAndroid Build Coastguard Worker         if (CI->isNegative() && !CI->isMinValue(true)) {
1521*9880d681SAndroid Build Coastguard Worker           Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
1522*9880d681SAndroid Build Coastguard Worker           assert(!Duplicates.count(Factor) &&
1523*9880d681SAndroid Build Coastguard Worker                  "Shouldn't have two constant factors, missed a canonicalize");
1524*9880d681SAndroid Build Coastguard Worker           unsigned Occ = ++FactorOccurrences[Factor];
1525*9880d681SAndroid Build Coastguard Worker           if (Occ > MaxOcc) {
1526*9880d681SAndroid Build Coastguard Worker             MaxOcc = Occ;
1527*9880d681SAndroid Build Coastguard Worker             MaxOccVal = Factor;
1528*9880d681SAndroid Build Coastguard Worker           }
1529*9880d681SAndroid Build Coastguard Worker         }
1530*9880d681SAndroid Build Coastguard Worker       } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
1531*9880d681SAndroid Build Coastguard Worker         if (CF->isNegative()) {
1532*9880d681SAndroid Build Coastguard Worker           APFloat F(CF->getValueAPF());
1533*9880d681SAndroid Build Coastguard Worker           F.changeSign();
1534*9880d681SAndroid Build Coastguard Worker           Factor = ConstantFP::get(CF->getContext(), F);
1535*9880d681SAndroid Build Coastguard Worker           assert(!Duplicates.count(Factor) &&
1536*9880d681SAndroid Build Coastguard Worker                  "Shouldn't have two constant factors, missed a canonicalize");
1537*9880d681SAndroid Build Coastguard Worker           unsigned Occ = ++FactorOccurrences[Factor];
1538*9880d681SAndroid Build Coastguard Worker           if (Occ > MaxOcc) {
1539*9880d681SAndroid Build Coastguard Worker             MaxOcc = Occ;
1540*9880d681SAndroid Build Coastguard Worker             MaxOccVal = Factor;
1541*9880d681SAndroid Build Coastguard Worker           }
1542*9880d681SAndroid Build Coastguard Worker         }
1543*9880d681SAndroid Build Coastguard Worker       }
1544*9880d681SAndroid Build Coastguard Worker     }
1545*9880d681SAndroid Build Coastguard Worker   }
1546*9880d681SAndroid Build Coastguard Worker 
1547*9880d681SAndroid Build Coastguard Worker   // If any factor occurred more than one time, we can pull it out.
1548*9880d681SAndroid Build Coastguard Worker   if (MaxOcc > 1) {
1549*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
1550*9880d681SAndroid Build Coastguard Worker     ++NumFactor;
1551*9880d681SAndroid Build Coastguard Worker 
1552*9880d681SAndroid Build Coastguard Worker     // Create a new instruction that uses the MaxOccVal twice.  If we don't do
1553*9880d681SAndroid Build Coastguard Worker     // this, we could otherwise run into situations where removing a factor
1554*9880d681SAndroid Build Coastguard Worker     // from an expression will drop a use of maxocc, and this can cause
1555*9880d681SAndroid Build Coastguard Worker     // RemoveFactorFromExpression on successive values to behave differently.
1556*9880d681SAndroid Build Coastguard Worker     Instruction *DummyInst =
1557*9880d681SAndroid Build Coastguard Worker         I->getType()->isIntOrIntVectorTy()
1558*9880d681SAndroid Build Coastguard Worker             ? BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal)
1559*9880d681SAndroid Build Coastguard Worker             : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
1560*9880d681SAndroid Build Coastguard Worker 
1561*9880d681SAndroid Build Coastguard Worker     SmallVector<WeakVH, 4> NewMulOps;
1562*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0; i != Ops.size(); ++i) {
1563*9880d681SAndroid Build Coastguard Worker       // Only try to remove factors from expressions we're allowed to.
1564*9880d681SAndroid Build Coastguard Worker       BinaryOperator *BOp =
1565*9880d681SAndroid Build Coastguard Worker           isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
1566*9880d681SAndroid Build Coastguard Worker       if (!BOp)
1567*9880d681SAndroid Build Coastguard Worker         continue;
1568*9880d681SAndroid Build Coastguard Worker 
1569*9880d681SAndroid Build Coastguard Worker       if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1570*9880d681SAndroid Build Coastguard Worker         // The factorized operand may occur several times.  Convert them all in
1571*9880d681SAndroid Build Coastguard Worker         // one fell swoop.
1572*9880d681SAndroid Build Coastguard Worker         for (unsigned j = Ops.size(); j != i;) {
1573*9880d681SAndroid Build Coastguard Worker           --j;
1574*9880d681SAndroid Build Coastguard Worker           if (Ops[j].Op == Ops[i].Op) {
1575*9880d681SAndroid Build Coastguard Worker             NewMulOps.push_back(V);
1576*9880d681SAndroid Build Coastguard Worker             Ops.erase(Ops.begin()+j);
1577*9880d681SAndroid Build Coastguard Worker           }
1578*9880d681SAndroid Build Coastguard Worker         }
1579*9880d681SAndroid Build Coastguard Worker         --i;
1580*9880d681SAndroid Build Coastguard Worker       }
1581*9880d681SAndroid Build Coastguard Worker     }
1582*9880d681SAndroid Build Coastguard Worker 
1583*9880d681SAndroid Build Coastguard Worker     // No need for extra uses anymore.
1584*9880d681SAndroid Build Coastguard Worker     delete DummyInst;
1585*9880d681SAndroid Build Coastguard Worker 
1586*9880d681SAndroid Build Coastguard Worker     unsigned NumAddedValues = NewMulOps.size();
1587*9880d681SAndroid Build Coastguard Worker     Value *V = EmitAddTreeOfValues(I, NewMulOps);
1588*9880d681SAndroid Build Coastguard Worker 
1589*9880d681SAndroid Build Coastguard Worker     // Now that we have inserted the add tree, optimize it. This allows us to
1590*9880d681SAndroid Build Coastguard Worker     // handle cases that require multiple factoring steps, such as this:
1591*9880d681SAndroid Build Coastguard Worker     // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
1592*9880d681SAndroid Build Coastguard Worker     assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
1593*9880d681SAndroid Build Coastguard Worker     (void)NumAddedValues;
1594*9880d681SAndroid Build Coastguard Worker     if (Instruction *VI = dyn_cast<Instruction>(V))
1595*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(VI);
1596*9880d681SAndroid Build Coastguard Worker 
1597*9880d681SAndroid Build Coastguard Worker     // Create the multiply.
1598*9880d681SAndroid Build Coastguard Worker     Instruction *V2 = CreateMul(V, MaxOccVal, "tmp", I, I);
1599*9880d681SAndroid Build Coastguard Worker 
1600*9880d681SAndroid Build Coastguard Worker     // Rerun associate on the multiply in case the inner expression turned into
1601*9880d681SAndroid Build Coastguard Worker     // a multiply.  We want to make sure that we keep things in canonical form.
1602*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(V2);
1603*9880d681SAndroid Build Coastguard Worker 
1604*9880d681SAndroid Build Coastguard Worker     // If every add operand included the factor (e.g. "A*B + A*C"), then the
1605*9880d681SAndroid Build Coastguard Worker     // entire result expression is just the multiply "A*(B+C)".
1606*9880d681SAndroid Build Coastguard Worker     if (Ops.empty())
1607*9880d681SAndroid Build Coastguard Worker       return V2;
1608*9880d681SAndroid Build Coastguard Worker 
1609*9880d681SAndroid Build Coastguard Worker     // Otherwise, we had some input that didn't have the factor, such as
1610*9880d681SAndroid Build Coastguard Worker     // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
1611*9880d681SAndroid Build Coastguard Worker     // things being added by this operation.
1612*9880d681SAndroid Build Coastguard Worker     Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
1613*9880d681SAndroid Build Coastguard Worker   }
1614*9880d681SAndroid Build Coastguard Worker 
1615*9880d681SAndroid Build Coastguard Worker   return nullptr;
1616*9880d681SAndroid Build Coastguard Worker }
1617*9880d681SAndroid Build Coastguard Worker 
1618*9880d681SAndroid Build Coastguard Worker /// \brief Build up a vector of value/power pairs factoring a product.
1619*9880d681SAndroid Build Coastguard Worker ///
1620*9880d681SAndroid Build Coastguard Worker /// Given a series of multiplication operands, build a vector of factors and
1621*9880d681SAndroid Build Coastguard Worker /// the powers each is raised to when forming the final product. Sort them in
1622*9880d681SAndroid Build Coastguard Worker /// the order of descending power.
1623*9880d681SAndroid Build Coastguard Worker ///
1624*9880d681SAndroid Build Coastguard Worker ///      (x*x)          -> [(x, 2)]
1625*9880d681SAndroid Build Coastguard Worker ///     ((x*x)*x)       -> [(x, 3)]
1626*9880d681SAndroid Build Coastguard Worker ///   ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
1627*9880d681SAndroid Build Coastguard Worker ///
1628*9880d681SAndroid Build Coastguard Worker /// \returns Whether any factors have a power greater than one.
collectMultiplyFactors(SmallVectorImpl<ValueEntry> & Ops,SmallVectorImpl<Factor> & Factors)1629*9880d681SAndroid Build Coastguard Worker bool ReassociatePass::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
1630*9880d681SAndroid Build Coastguard Worker                                              SmallVectorImpl<Factor> &Factors) {
1631*9880d681SAndroid Build Coastguard Worker   // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
1632*9880d681SAndroid Build Coastguard Worker   // Compute the sum of powers of simplifiable factors.
1633*9880d681SAndroid Build Coastguard Worker   unsigned FactorPowerSum = 0;
1634*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
1635*9880d681SAndroid Build Coastguard Worker     Value *Op = Ops[Idx-1].Op;
1636*9880d681SAndroid Build Coastguard Worker 
1637*9880d681SAndroid Build Coastguard Worker     // Count the number of occurrences of this value.
1638*9880d681SAndroid Build Coastguard Worker     unsigned Count = 1;
1639*9880d681SAndroid Build Coastguard Worker     for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
1640*9880d681SAndroid Build Coastguard Worker       ++Count;
1641*9880d681SAndroid Build Coastguard Worker     // Track for simplification all factors which occur 2 or more times.
1642*9880d681SAndroid Build Coastguard Worker     if (Count > 1)
1643*9880d681SAndroid Build Coastguard Worker       FactorPowerSum += Count;
1644*9880d681SAndroid Build Coastguard Worker   }
1645*9880d681SAndroid Build Coastguard Worker 
1646*9880d681SAndroid Build Coastguard Worker   // We can only simplify factors if the sum of the powers of our simplifiable
1647*9880d681SAndroid Build Coastguard Worker   // factors is 4 or higher. When that is the case, we will *always* have
1648*9880d681SAndroid Build Coastguard Worker   // a simplification. This is an important invariant to prevent cyclicly
1649*9880d681SAndroid Build Coastguard Worker   // trying to simplify already minimal formations.
1650*9880d681SAndroid Build Coastguard Worker   if (FactorPowerSum < 4)
1651*9880d681SAndroid Build Coastguard Worker     return false;
1652*9880d681SAndroid Build Coastguard Worker 
1653*9880d681SAndroid Build Coastguard Worker   // Now gather the simplifiable factors, removing them from Ops.
1654*9880d681SAndroid Build Coastguard Worker   FactorPowerSum = 0;
1655*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
1656*9880d681SAndroid Build Coastguard Worker     Value *Op = Ops[Idx-1].Op;
1657*9880d681SAndroid Build Coastguard Worker 
1658*9880d681SAndroid Build Coastguard Worker     // Count the number of occurrences of this value.
1659*9880d681SAndroid Build Coastguard Worker     unsigned Count = 1;
1660*9880d681SAndroid Build Coastguard Worker     for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
1661*9880d681SAndroid Build Coastguard Worker       ++Count;
1662*9880d681SAndroid Build Coastguard Worker     if (Count == 1)
1663*9880d681SAndroid Build Coastguard Worker       continue;
1664*9880d681SAndroid Build Coastguard Worker     // Move an even number of occurrences to Factors.
1665*9880d681SAndroid Build Coastguard Worker     Count &= ~1U;
1666*9880d681SAndroid Build Coastguard Worker     Idx -= Count;
1667*9880d681SAndroid Build Coastguard Worker     FactorPowerSum += Count;
1668*9880d681SAndroid Build Coastguard Worker     Factors.push_back(Factor(Op, Count));
1669*9880d681SAndroid Build Coastguard Worker     Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
1670*9880d681SAndroid Build Coastguard Worker   }
1671*9880d681SAndroid Build Coastguard Worker 
1672*9880d681SAndroid Build Coastguard Worker   // None of the adjustments above should have reduced the sum of factor powers
1673*9880d681SAndroid Build Coastguard Worker   // below our mininum of '4'.
1674*9880d681SAndroid Build Coastguard Worker   assert(FactorPowerSum >= 4);
1675*9880d681SAndroid Build Coastguard Worker 
1676*9880d681SAndroid Build Coastguard Worker   std::stable_sort(Factors.begin(), Factors.end(),
1677*9880d681SAndroid Build Coastguard Worker                    [](const Factor &LHS, const Factor &RHS) {
1678*9880d681SAndroid Build Coastguard Worker     return LHS.Power > RHS.Power;
1679*9880d681SAndroid Build Coastguard Worker   });
1680*9880d681SAndroid Build Coastguard Worker   return true;
1681*9880d681SAndroid Build Coastguard Worker }
1682*9880d681SAndroid Build Coastguard Worker 
1683*9880d681SAndroid Build Coastguard Worker /// \brief Build a tree of multiplies, computing the product of Ops.
buildMultiplyTree(IRBuilder<> & Builder,SmallVectorImpl<Value * > & Ops)1684*9880d681SAndroid Build Coastguard Worker static Value *buildMultiplyTree(IRBuilder<> &Builder,
1685*9880d681SAndroid Build Coastguard Worker                                 SmallVectorImpl<Value*> &Ops) {
1686*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 1)
1687*9880d681SAndroid Build Coastguard Worker     return Ops.back();
1688*9880d681SAndroid Build Coastguard Worker 
1689*9880d681SAndroid Build Coastguard Worker   Value *LHS = Ops.pop_back_val();
1690*9880d681SAndroid Build Coastguard Worker   do {
1691*9880d681SAndroid Build Coastguard Worker     if (LHS->getType()->isIntOrIntVectorTy())
1692*9880d681SAndroid Build Coastguard Worker       LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
1693*9880d681SAndroid Build Coastguard Worker     else
1694*9880d681SAndroid Build Coastguard Worker       LHS = Builder.CreateFMul(LHS, Ops.pop_back_val());
1695*9880d681SAndroid Build Coastguard Worker   } while (!Ops.empty());
1696*9880d681SAndroid Build Coastguard Worker 
1697*9880d681SAndroid Build Coastguard Worker   return LHS;
1698*9880d681SAndroid Build Coastguard Worker }
1699*9880d681SAndroid Build Coastguard Worker 
1700*9880d681SAndroid Build Coastguard Worker /// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
1701*9880d681SAndroid Build Coastguard Worker ///
1702*9880d681SAndroid Build Coastguard Worker /// Given a vector of values raised to various powers, where no two values are
1703*9880d681SAndroid Build Coastguard Worker /// equal and the powers are sorted in decreasing order, compute the minimal
1704*9880d681SAndroid Build Coastguard Worker /// DAG of multiplies to compute the final product, and return that product
1705*9880d681SAndroid Build Coastguard Worker /// value.
1706*9880d681SAndroid Build Coastguard Worker Value *
buildMinimalMultiplyDAG(IRBuilder<> & Builder,SmallVectorImpl<Factor> & Factors)1707*9880d681SAndroid Build Coastguard Worker ReassociatePass::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
1708*9880d681SAndroid Build Coastguard Worker                                          SmallVectorImpl<Factor> &Factors) {
1709*9880d681SAndroid Build Coastguard Worker   assert(Factors[0].Power);
1710*9880d681SAndroid Build Coastguard Worker   SmallVector<Value *, 4> OuterProduct;
1711*9880d681SAndroid Build Coastguard Worker   for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
1712*9880d681SAndroid Build Coastguard Worker        Idx < Size && Factors[Idx].Power > 0; ++Idx) {
1713*9880d681SAndroid Build Coastguard Worker     if (Factors[Idx].Power != Factors[LastIdx].Power) {
1714*9880d681SAndroid Build Coastguard Worker       LastIdx = Idx;
1715*9880d681SAndroid Build Coastguard Worker       continue;
1716*9880d681SAndroid Build Coastguard Worker     }
1717*9880d681SAndroid Build Coastguard Worker 
1718*9880d681SAndroid Build Coastguard Worker     // We want to multiply across all the factors with the same power so that
1719*9880d681SAndroid Build Coastguard Worker     // we can raise them to that power as a single entity. Build a mini tree
1720*9880d681SAndroid Build Coastguard Worker     // for that.
1721*9880d681SAndroid Build Coastguard Worker     SmallVector<Value *, 4> InnerProduct;
1722*9880d681SAndroid Build Coastguard Worker     InnerProduct.push_back(Factors[LastIdx].Base);
1723*9880d681SAndroid Build Coastguard Worker     do {
1724*9880d681SAndroid Build Coastguard Worker       InnerProduct.push_back(Factors[Idx].Base);
1725*9880d681SAndroid Build Coastguard Worker       ++Idx;
1726*9880d681SAndroid Build Coastguard Worker     } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
1727*9880d681SAndroid Build Coastguard Worker 
1728*9880d681SAndroid Build Coastguard Worker     // Reset the base value of the first factor to the new expression tree.
1729*9880d681SAndroid Build Coastguard Worker     // We'll remove all the factors with the same power in a second pass.
1730*9880d681SAndroid Build Coastguard Worker     Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
1731*9880d681SAndroid Build Coastguard Worker     if (Instruction *MI = dyn_cast<Instruction>(M))
1732*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(MI);
1733*9880d681SAndroid Build Coastguard Worker 
1734*9880d681SAndroid Build Coastguard Worker     LastIdx = Idx;
1735*9880d681SAndroid Build Coastguard Worker   }
1736*9880d681SAndroid Build Coastguard Worker   // Unique factors with equal powers -- we've folded them into the first one's
1737*9880d681SAndroid Build Coastguard Worker   // base.
1738*9880d681SAndroid Build Coastguard Worker   Factors.erase(std::unique(Factors.begin(), Factors.end(),
1739*9880d681SAndroid Build Coastguard Worker                             [](const Factor &LHS, const Factor &RHS) {
1740*9880d681SAndroid Build Coastguard Worker                               return LHS.Power == RHS.Power;
1741*9880d681SAndroid Build Coastguard Worker                             }),
1742*9880d681SAndroid Build Coastguard Worker                 Factors.end());
1743*9880d681SAndroid Build Coastguard Worker 
1744*9880d681SAndroid Build Coastguard Worker   // Iteratively collect the base of each factor with an add power into the
1745*9880d681SAndroid Build Coastguard Worker   // outer product, and halve each power in preparation for squaring the
1746*9880d681SAndroid Build Coastguard Worker   // expression.
1747*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
1748*9880d681SAndroid Build Coastguard Worker     if (Factors[Idx].Power & 1)
1749*9880d681SAndroid Build Coastguard Worker       OuterProduct.push_back(Factors[Idx].Base);
1750*9880d681SAndroid Build Coastguard Worker     Factors[Idx].Power >>= 1;
1751*9880d681SAndroid Build Coastguard Worker   }
1752*9880d681SAndroid Build Coastguard Worker   if (Factors[0].Power) {
1753*9880d681SAndroid Build Coastguard Worker     Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1754*9880d681SAndroid Build Coastguard Worker     OuterProduct.push_back(SquareRoot);
1755*9880d681SAndroid Build Coastguard Worker     OuterProduct.push_back(SquareRoot);
1756*9880d681SAndroid Build Coastguard Worker   }
1757*9880d681SAndroid Build Coastguard Worker   if (OuterProduct.size() == 1)
1758*9880d681SAndroid Build Coastguard Worker     return OuterProduct.front();
1759*9880d681SAndroid Build Coastguard Worker 
1760*9880d681SAndroid Build Coastguard Worker   Value *V = buildMultiplyTree(Builder, OuterProduct);
1761*9880d681SAndroid Build Coastguard Worker   return V;
1762*9880d681SAndroid Build Coastguard Worker }
1763*9880d681SAndroid Build Coastguard Worker 
OptimizeMul(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)1764*9880d681SAndroid Build Coastguard Worker Value *ReassociatePass::OptimizeMul(BinaryOperator *I,
1765*9880d681SAndroid Build Coastguard Worker                                     SmallVectorImpl<ValueEntry> &Ops) {
1766*9880d681SAndroid Build Coastguard Worker   // We can only optimize the multiplies when there is a chain of more than
1767*9880d681SAndroid Build Coastguard Worker   // three, such that a balanced tree might require fewer total multiplies.
1768*9880d681SAndroid Build Coastguard Worker   if (Ops.size() < 4)
1769*9880d681SAndroid Build Coastguard Worker     return nullptr;
1770*9880d681SAndroid Build Coastguard Worker 
1771*9880d681SAndroid Build Coastguard Worker   // Try to turn linear trees of multiplies without other uses of the
1772*9880d681SAndroid Build Coastguard Worker   // intermediate stages into minimal multiply DAGs with perfect sub-expression
1773*9880d681SAndroid Build Coastguard Worker   // re-use.
1774*9880d681SAndroid Build Coastguard Worker   SmallVector<Factor, 4> Factors;
1775*9880d681SAndroid Build Coastguard Worker   if (!collectMultiplyFactors(Ops, Factors))
1776*9880d681SAndroid Build Coastguard Worker     return nullptr; // All distinct factors, so nothing left for us to do.
1777*9880d681SAndroid Build Coastguard Worker 
1778*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(I);
1779*9880d681SAndroid Build Coastguard Worker   Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1780*9880d681SAndroid Build Coastguard Worker   if (Ops.empty())
1781*9880d681SAndroid Build Coastguard Worker     return V;
1782*9880d681SAndroid Build Coastguard Worker 
1783*9880d681SAndroid Build Coastguard Worker   ValueEntry NewEntry = ValueEntry(getRank(V), V);
1784*9880d681SAndroid Build Coastguard Worker   Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
1785*9880d681SAndroid Build Coastguard Worker   return nullptr;
1786*9880d681SAndroid Build Coastguard Worker }
1787*9880d681SAndroid Build Coastguard Worker 
OptimizeExpression(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)1788*9880d681SAndroid Build Coastguard Worker Value *ReassociatePass::OptimizeExpression(BinaryOperator *I,
1789*9880d681SAndroid Build Coastguard Worker                                            SmallVectorImpl<ValueEntry> &Ops) {
1790*9880d681SAndroid Build Coastguard Worker   // Now that we have the linearized expression tree, try to optimize it.
1791*9880d681SAndroid Build Coastguard Worker   // Start by folding any constants that we found.
1792*9880d681SAndroid Build Coastguard Worker   Constant *Cst = nullptr;
1793*9880d681SAndroid Build Coastguard Worker   unsigned Opcode = I->getOpcode();
1794*9880d681SAndroid Build Coastguard Worker   while (!Ops.empty() && isa<Constant>(Ops.back().Op)) {
1795*9880d681SAndroid Build Coastguard Worker     Constant *C = cast<Constant>(Ops.pop_back_val().Op);
1796*9880d681SAndroid Build Coastguard Worker     Cst = Cst ? ConstantExpr::get(Opcode, C, Cst) : C;
1797*9880d681SAndroid Build Coastguard Worker   }
1798*9880d681SAndroid Build Coastguard Worker   // If there was nothing but constants then we are done.
1799*9880d681SAndroid Build Coastguard Worker   if (Ops.empty())
1800*9880d681SAndroid Build Coastguard Worker     return Cst;
1801*9880d681SAndroid Build Coastguard Worker 
1802*9880d681SAndroid Build Coastguard Worker   // Put the combined constant back at the end of the operand list, except if
1803*9880d681SAndroid Build Coastguard Worker   // there is no point.  For example, an add of 0 gets dropped here, while a
1804*9880d681SAndroid Build Coastguard Worker   // multiplication by zero turns the whole expression into zero.
1805*9880d681SAndroid Build Coastguard Worker   if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
1806*9880d681SAndroid Build Coastguard Worker     if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
1807*9880d681SAndroid Build Coastguard Worker       return Cst;
1808*9880d681SAndroid Build Coastguard Worker     Ops.push_back(ValueEntry(0, Cst));
1809*9880d681SAndroid Build Coastguard Worker   }
1810*9880d681SAndroid Build Coastguard Worker 
1811*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 1) return Ops[0].Op;
1812*9880d681SAndroid Build Coastguard Worker 
1813*9880d681SAndroid Build Coastguard Worker   // Handle destructive annihilation due to identities between elements in the
1814*9880d681SAndroid Build Coastguard Worker   // argument list here.
1815*9880d681SAndroid Build Coastguard Worker   unsigned NumOps = Ops.size();
1816*9880d681SAndroid Build Coastguard Worker   switch (Opcode) {
1817*9880d681SAndroid Build Coastguard Worker   default: break;
1818*9880d681SAndroid Build Coastguard Worker   case Instruction::And:
1819*9880d681SAndroid Build Coastguard Worker   case Instruction::Or:
1820*9880d681SAndroid Build Coastguard Worker     if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
1821*9880d681SAndroid Build Coastguard Worker       return Result;
1822*9880d681SAndroid Build Coastguard Worker     break;
1823*9880d681SAndroid Build Coastguard Worker 
1824*9880d681SAndroid Build Coastguard Worker   case Instruction::Xor:
1825*9880d681SAndroid Build Coastguard Worker     if (Value *Result = OptimizeXor(I, Ops))
1826*9880d681SAndroid Build Coastguard Worker       return Result;
1827*9880d681SAndroid Build Coastguard Worker     break;
1828*9880d681SAndroid Build Coastguard Worker 
1829*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
1830*9880d681SAndroid Build Coastguard Worker   case Instruction::FAdd:
1831*9880d681SAndroid Build Coastguard Worker     if (Value *Result = OptimizeAdd(I, Ops))
1832*9880d681SAndroid Build Coastguard Worker       return Result;
1833*9880d681SAndroid Build Coastguard Worker     break;
1834*9880d681SAndroid Build Coastguard Worker 
1835*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
1836*9880d681SAndroid Build Coastguard Worker   case Instruction::FMul:
1837*9880d681SAndroid Build Coastguard Worker     if (Value *Result = OptimizeMul(I, Ops))
1838*9880d681SAndroid Build Coastguard Worker       return Result;
1839*9880d681SAndroid Build Coastguard Worker     break;
1840*9880d681SAndroid Build Coastguard Worker   }
1841*9880d681SAndroid Build Coastguard Worker 
1842*9880d681SAndroid Build Coastguard Worker   if (Ops.size() != NumOps)
1843*9880d681SAndroid Build Coastguard Worker     return OptimizeExpression(I, Ops);
1844*9880d681SAndroid Build Coastguard Worker   return nullptr;
1845*9880d681SAndroid Build Coastguard Worker }
1846*9880d681SAndroid Build Coastguard Worker 
1847*9880d681SAndroid Build Coastguard Worker // Remove dead instructions and if any operands are trivially dead add them to
1848*9880d681SAndroid Build Coastguard Worker // Insts so they will be removed as well.
RecursivelyEraseDeadInsts(Instruction * I,SetVector<AssertingVH<Instruction>> & Insts)1849*9880d681SAndroid Build Coastguard Worker void ReassociatePass::RecursivelyEraseDeadInsts(
1850*9880d681SAndroid Build Coastguard Worker     Instruction *I, SetVector<AssertingVH<Instruction>> &Insts) {
1851*9880d681SAndroid Build Coastguard Worker   assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1852*9880d681SAndroid Build Coastguard Worker   SmallVector<Value *, 4> Ops(I->op_begin(), I->op_end());
1853*9880d681SAndroid Build Coastguard Worker   ValueRankMap.erase(I);
1854*9880d681SAndroid Build Coastguard Worker   Insts.remove(I);
1855*9880d681SAndroid Build Coastguard Worker   RedoInsts.remove(I);
1856*9880d681SAndroid Build Coastguard Worker   I->eraseFromParent();
1857*9880d681SAndroid Build Coastguard Worker   for (auto Op : Ops)
1858*9880d681SAndroid Build Coastguard Worker     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1859*9880d681SAndroid Build Coastguard Worker       if (OpInst->use_empty())
1860*9880d681SAndroid Build Coastguard Worker         Insts.insert(OpInst);
1861*9880d681SAndroid Build Coastguard Worker }
1862*9880d681SAndroid Build Coastguard Worker 
1863*9880d681SAndroid Build Coastguard Worker /// Zap the given instruction, adding interesting operands to the work list.
EraseInst(Instruction * I)1864*9880d681SAndroid Build Coastguard Worker void ReassociatePass::EraseInst(Instruction *I) {
1865*9880d681SAndroid Build Coastguard Worker   assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1866*9880d681SAndroid Build Coastguard Worker   SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1867*9880d681SAndroid Build Coastguard Worker   // Erase the dead instruction.
1868*9880d681SAndroid Build Coastguard Worker   ValueRankMap.erase(I);
1869*9880d681SAndroid Build Coastguard Worker   RedoInsts.remove(I);
1870*9880d681SAndroid Build Coastguard Worker   I->eraseFromParent();
1871*9880d681SAndroid Build Coastguard Worker   // Optimize its operands.
1872*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
1873*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1874*9880d681SAndroid Build Coastguard Worker     if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
1875*9880d681SAndroid Build Coastguard Worker       // If this is a node in an expression tree, climb to the expression root
1876*9880d681SAndroid Build Coastguard Worker       // and add that since that's where optimization actually happens.
1877*9880d681SAndroid Build Coastguard Worker       unsigned Opcode = Op->getOpcode();
1878*9880d681SAndroid Build Coastguard Worker       while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
1879*9880d681SAndroid Build Coastguard Worker              Visited.insert(Op).second)
1880*9880d681SAndroid Build Coastguard Worker         Op = Op->user_back();
1881*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(Op);
1882*9880d681SAndroid Build Coastguard Worker     }
1883*9880d681SAndroid Build Coastguard Worker }
1884*9880d681SAndroid Build Coastguard Worker 
1885*9880d681SAndroid Build Coastguard Worker // Canonicalize expressions of the following form:
1886*9880d681SAndroid Build Coastguard Worker //  x + (-Constant * y) -> x - (Constant * y)
1887*9880d681SAndroid Build Coastguard Worker //  x - (-Constant * y) -> x + (Constant * y)
canonicalizeNegConstExpr(Instruction * I)1888*9880d681SAndroid Build Coastguard Worker Instruction *ReassociatePass::canonicalizeNegConstExpr(Instruction *I) {
1889*9880d681SAndroid Build Coastguard Worker   if (!I->hasOneUse() || I->getType()->isVectorTy())
1890*9880d681SAndroid Build Coastguard Worker     return nullptr;
1891*9880d681SAndroid Build Coastguard Worker 
1892*9880d681SAndroid Build Coastguard Worker   // Must be a fmul or fdiv instruction.
1893*9880d681SAndroid Build Coastguard Worker   unsigned Opcode = I->getOpcode();
1894*9880d681SAndroid Build Coastguard Worker   if (Opcode != Instruction::FMul && Opcode != Instruction::FDiv)
1895*9880d681SAndroid Build Coastguard Worker     return nullptr;
1896*9880d681SAndroid Build Coastguard Worker 
1897*9880d681SAndroid Build Coastguard Worker   auto *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
1898*9880d681SAndroid Build Coastguard Worker   auto *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
1899*9880d681SAndroid Build Coastguard Worker 
1900*9880d681SAndroid Build Coastguard Worker   // Both operands are constant, let it get constant folded away.
1901*9880d681SAndroid Build Coastguard Worker   if (C0 && C1)
1902*9880d681SAndroid Build Coastguard Worker     return nullptr;
1903*9880d681SAndroid Build Coastguard Worker 
1904*9880d681SAndroid Build Coastguard Worker   ConstantFP *CF = C0 ? C0 : C1;
1905*9880d681SAndroid Build Coastguard Worker 
1906*9880d681SAndroid Build Coastguard Worker   // Must have one constant operand.
1907*9880d681SAndroid Build Coastguard Worker   if (!CF)
1908*9880d681SAndroid Build Coastguard Worker     return nullptr;
1909*9880d681SAndroid Build Coastguard Worker 
1910*9880d681SAndroid Build Coastguard Worker   // Must be a negative ConstantFP.
1911*9880d681SAndroid Build Coastguard Worker   if (!CF->isNegative())
1912*9880d681SAndroid Build Coastguard Worker     return nullptr;
1913*9880d681SAndroid Build Coastguard Worker 
1914*9880d681SAndroid Build Coastguard Worker   // User must be a binary operator with one or more uses.
1915*9880d681SAndroid Build Coastguard Worker   Instruction *User = I->user_back();
1916*9880d681SAndroid Build Coastguard Worker   if (!isa<BinaryOperator>(User) || !User->hasNUsesOrMore(1))
1917*9880d681SAndroid Build Coastguard Worker     return nullptr;
1918*9880d681SAndroid Build Coastguard Worker 
1919*9880d681SAndroid Build Coastguard Worker   unsigned UserOpcode = User->getOpcode();
1920*9880d681SAndroid Build Coastguard Worker   if (UserOpcode != Instruction::FAdd && UserOpcode != Instruction::FSub)
1921*9880d681SAndroid Build Coastguard Worker     return nullptr;
1922*9880d681SAndroid Build Coastguard Worker 
1923*9880d681SAndroid Build Coastguard Worker   // Subtraction is not commutative. Explicitly, the following transform is
1924*9880d681SAndroid Build Coastguard Worker   // not valid: (-Constant * y) - x  -> x + (Constant * y)
1925*9880d681SAndroid Build Coastguard Worker   if (!User->isCommutative() && User->getOperand(1) != I)
1926*9880d681SAndroid Build Coastguard Worker     return nullptr;
1927*9880d681SAndroid Build Coastguard Worker 
1928*9880d681SAndroid Build Coastguard Worker   // Change the sign of the constant.
1929*9880d681SAndroid Build Coastguard Worker   APFloat Val = CF->getValueAPF();
1930*9880d681SAndroid Build Coastguard Worker   Val.changeSign();
1931*9880d681SAndroid Build Coastguard Worker   I->setOperand(C0 ? 0 : 1, ConstantFP::get(CF->getContext(), Val));
1932*9880d681SAndroid Build Coastguard Worker 
1933*9880d681SAndroid Build Coastguard Worker   // Canonicalize I to RHS to simplify the next bit of logic. E.g.,
1934*9880d681SAndroid Build Coastguard Worker   // ((-Const*y) + x) -> (x + (-Const*y)).
1935*9880d681SAndroid Build Coastguard Worker   if (User->getOperand(0) == I && User->isCommutative())
1936*9880d681SAndroid Build Coastguard Worker     cast<BinaryOperator>(User)->swapOperands();
1937*9880d681SAndroid Build Coastguard Worker 
1938*9880d681SAndroid Build Coastguard Worker   Value *Op0 = User->getOperand(0);
1939*9880d681SAndroid Build Coastguard Worker   Value *Op1 = User->getOperand(1);
1940*9880d681SAndroid Build Coastguard Worker   BinaryOperator *NI;
1941*9880d681SAndroid Build Coastguard Worker   switch (UserOpcode) {
1942*9880d681SAndroid Build Coastguard Worker   default:
1943*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unexpected Opcode!");
1944*9880d681SAndroid Build Coastguard Worker   case Instruction::FAdd:
1945*9880d681SAndroid Build Coastguard Worker     NI = BinaryOperator::CreateFSub(Op0, Op1);
1946*9880d681SAndroid Build Coastguard Worker     NI->setFastMathFlags(cast<FPMathOperator>(User)->getFastMathFlags());
1947*9880d681SAndroid Build Coastguard Worker     break;
1948*9880d681SAndroid Build Coastguard Worker   case Instruction::FSub:
1949*9880d681SAndroid Build Coastguard Worker     NI = BinaryOperator::CreateFAdd(Op0, Op1);
1950*9880d681SAndroid Build Coastguard Worker     NI->setFastMathFlags(cast<FPMathOperator>(User)->getFastMathFlags());
1951*9880d681SAndroid Build Coastguard Worker     break;
1952*9880d681SAndroid Build Coastguard Worker   }
1953*9880d681SAndroid Build Coastguard Worker 
1954*9880d681SAndroid Build Coastguard Worker   NI->insertBefore(User);
1955*9880d681SAndroid Build Coastguard Worker   NI->setName(User->getName());
1956*9880d681SAndroid Build Coastguard Worker   User->replaceAllUsesWith(NI);
1957*9880d681SAndroid Build Coastguard Worker   NI->setDebugLoc(I->getDebugLoc());
1958*9880d681SAndroid Build Coastguard Worker   RedoInsts.insert(I);
1959*9880d681SAndroid Build Coastguard Worker   MadeChange = true;
1960*9880d681SAndroid Build Coastguard Worker   return NI;
1961*9880d681SAndroid Build Coastguard Worker }
1962*9880d681SAndroid Build Coastguard Worker 
1963*9880d681SAndroid Build Coastguard Worker /// Inspect and optimize the given instruction. Note that erasing
1964*9880d681SAndroid Build Coastguard Worker /// instructions is not allowed.
OptimizeInst(Instruction * I)1965*9880d681SAndroid Build Coastguard Worker void ReassociatePass::OptimizeInst(Instruction *I) {
1966*9880d681SAndroid Build Coastguard Worker   // Only consider operations that we understand.
1967*9880d681SAndroid Build Coastguard Worker   if (!isa<BinaryOperator>(I))
1968*9880d681SAndroid Build Coastguard Worker     return;
1969*9880d681SAndroid Build Coastguard Worker 
1970*9880d681SAndroid Build Coastguard Worker   if (I->getOpcode() == Instruction::Shl && isa<ConstantInt>(I->getOperand(1)))
1971*9880d681SAndroid Build Coastguard Worker     // If an operand of this shift is a reassociable multiply, or if the shift
1972*9880d681SAndroid Build Coastguard Worker     // is used by a reassociable multiply or add, turn into a multiply.
1973*9880d681SAndroid Build Coastguard Worker     if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
1974*9880d681SAndroid Build Coastguard Worker         (I->hasOneUse() &&
1975*9880d681SAndroid Build Coastguard Worker          (isReassociableOp(I->user_back(), Instruction::Mul) ||
1976*9880d681SAndroid Build Coastguard Worker           isReassociableOp(I->user_back(), Instruction::Add)))) {
1977*9880d681SAndroid Build Coastguard Worker       Instruction *NI = ConvertShiftToMul(I);
1978*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(I);
1979*9880d681SAndroid Build Coastguard Worker       MadeChange = true;
1980*9880d681SAndroid Build Coastguard Worker       I = NI;
1981*9880d681SAndroid Build Coastguard Worker     }
1982*9880d681SAndroid Build Coastguard Worker 
1983*9880d681SAndroid Build Coastguard Worker   // Canonicalize negative constants out of expressions.
1984*9880d681SAndroid Build Coastguard Worker   if (Instruction *Res = canonicalizeNegConstExpr(I))
1985*9880d681SAndroid Build Coastguard Worker     I = Res;
1986*9880d681SAndroid Build Coastguard Worker 
1987*9880d681SAndroid Build Coastguard Worker   // Commute binary operators, to canonicalize the order of their operands.
1988*9880d681SAndroid Build Coastguard Worker   // This can potentially expose more CSE opportunities, and makes writing other
1989*9880d681SAndroid Build Coastguard Worker   // transformations simpler.
1990*9880d681SAndroid Build Coastguard Worker   if (I->isCommutative())
1991*9880d681SAndroid Build Coastguard Worker     canonicalizeOperands(I);
1992*9880d681SAndroid Build Coastguard Worker 
1993*9880d681SAndroid Build Coastguard Worker   // TODO: We should optimize vector Xor instructions, but they are
1994*9880d681SAndroid Build Coastguard Worker   // currently unsupported.
1995*9880d681SAndroid Build Coastguard Worker   if (I->getType()->isVectorTy() && I->getOpcode() == Instruction::Xor)
1996*9880d681SAndroid Build Coastguard Worker     return;
1997*9880d681SAndroid Build Coastguard Worker 
1998*9880d681SAndroid Build Coastguard Worker   // Don't optimize floating point instructions that don't have unsafe algebra.
1999*9880d681SAndroid Build Coastguard Worker   if (I->getType()->isFPOrFPVectorTy() && !I->hasUnsafeAlgebra())
2000*9880d681SAndroid Build Coastguard Worker     return;
2001*9880d681SAndroid Build Coastguard Worker 
2002*9880d681SAndroid Build Coastguard Worker   // Do not reassociate boolean (i1) expressions.  We want to preserve the
2003*9880d681SAndroid Build Coastguard Worker   // original order of evaluation for short-circuited comparisons that
2004*9880d681SAndroid Build Coastguard Worker   // SimplifyCFG has folded to AND/OR expressions.  If the expression
2005*9880d681SAndroid Build Coastguard Worker   // is not further optimized, it is likely to be transformed back to a
2006*9880d681SAndroid Build Coastguard Worker   // short-circuited form for code gen, and the source order may have been
2007*9880d681SAndroid Build Coastguard Worker   // optimized for the most likely conditions.
2008*9880d681SAndroid Build Coastguard Worker   if (I->getType()->isIntegerTy(1))
2009*9880d681SAndroid Build Coastguard Worker     return;
2010*9880d681SAndroid Build Coastguard Worker 
2011*9880d681SAndroid Build Coastguard Worker   // If this is a subtract instruction which is not already in negate form,
2012*9880d681SAndroid Build Coastguard Worker   // see if we can convert it to X+-Y.
2013*9880d681SAndroid Build Coastguard Worker   if (I->getOpcode() == Instruction::Sub) {
2014*9880d681SAndroid Build Coastguard Worker     if (ShouldBreakUpSubtract(I)) {
2015*9880d681SAndroid Build Coastguard Worker       Instruction *NI = BreakUpSubtract(I, RedoInsts);
2016*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(I);
2017*9880d681SAndroid Build Coastguard Worker       MadeChange = true;
2018*9880d681SAndroid Build Coastguard Worker       I = NI;
2019*9880d681SAndroid Build Coastguard Worker     } else if (BinaryOperator::isNeg(I)) {
2020*9880d681SAndroid Build Coastguard Worker       // Otherwise, this is a negation.  See if the operand is a multiply tree
2021*9880d681SAndroid Build Coastguard Worker       // and if this is not an inner node of a multiply tree.
2022*9880d681SAndroid Build Coastguard Worker       if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
2023*9880d681SAndroid Build Coastguard Worker           (!I->hasOneUse() ||
2024*9880d681SAndroid Build Coastguard Worker            !isReassociableOp(I->user_back(), Instruction::Mul))) {
2025*9880d681SAndroid Build Coastguard Worker         Instruction *NI = LowerNegateToMultiply(I);
2026*9880d681SAndroid Build Coastguard Worker         // If the negate was simplified, revisit the users to see if we can
2027*9880d681SAndroid Build Coastguard Worker         // reassociate further.
2028*9880d681SAndroid Build Coastguard Worker         for (User *U : NI->users()) {
2029*9880d681SAndroid Build Coastguard Worker           if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U))
2030*9880d681SAndroid Build Coastguard Worker             RedoInsts.insert(Tmp);
2031*9880d681SAndroid Build Coastguard Worker         }
2032*9880d681SAndroid Build Coastguard Worker         RedoInsts.insert(I);
2033*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
2034*9880d681SAndroid Build Coastguard Worker         I = NI;
2035*9880d681SAndroid Build Coastguard Worker       }
2036*9880d681SAndroid Build Coastguard Worker     }
2037*9880d681SAndroid Build Coastguard Worker   } else if (I->getOpcode() == Instruction::FSub) {
2038*9880d681SAndroid Build Coastguard Worker     if (ShouldBreakUpSubtract(I)) {
2039*9880d681SAndroid Build Coastguard Worker       Instruction *NI = BreakUpSubtract(I, RedoInsts);
2040*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(I);
2041*9880d681SAndroid Build Coastguard Worker       MadeChange = true;
2042*9880d681SAndroid Build Coastguard Worker       I = NI;
2043*9880d681SAndroid Build Coastguard Worker     } else if (BinaryOperator::isFNeg(I)) {
2044*9880d681SAndroid Build Coastguard Worker       // Otherwise, this is a negation.  See if the operand is a multiply tree
2045*9880d681SAndroid Build Coastguard Worker       // and if this is not an inner node of a multiply tree.
2046*9880d681SAndroid Build Coastguard Worker       if (isReassociableOp(I->getOperand(1), Instruction::FMul) &&
2047*9880d681SAndroid Build Coastguard Worker           (!I->hasOneUse() ||
2048*9880d681SAndroid Build Coastguard Worker            !isReassociableOp(I->user_back(), Instruction::FMul))) {
2049*9880d681SAndroid Build Coastguard Worker         // If the negate was simplified, revisit the users to see if we can
2050*9880d681SAndroid Build Coastguard Worker         // reassociate further.
2051*9880d681SAndroid Build Coastguard Worker         Instruction *NI = LowerNegateToMultiply(I);
2052*9880d681SAndroid Build Coastguard Worker         for (User *U : NI->users()) {
2053*9880d681SAndroid Build Coastguard Worker           if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U))
2054*9880d681SAndroid Build Coastguard Worker             RedoInsts.insert(Tmp);
2055*9880d681SAndroid Build Coastguard Worker         }
2056*9880d681SAndroid Build Coastguard Worker         RedoInsts.insert(I);
2057*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
2058*9880d681SAndroid Build Coastguard Worker         I = NI;
2059*9880d681SAndroid Build Coastguard Worker       }
2060*9880d681SAndroid Build Coastguard Worker     }
2061*9880d681SAndroid Build Coastguard Worker   }
2062*9880d681SAndroid Build Coastguard Worker 
2063*9880d681SAndroid Build Coastguard Worker   // If this instruction is an associative binary operator, process it.
2064*9880d681SAndroid Build Coastguard Worker   if (!I->isAssociative()) return;
2065*9880d681SAndroid Build Coastguard Worker   BinaryOperator *BO = cast<BinaryOperator>(I);
2066*9880d681SAndroid Build Coastguard Worker 
2067*9880d681SAndroid Build Coastguard Worker   // If this is an interior node of a reassociable tree, ignore it until we
2068*9880d681SAndroid Build Coastguard Worker   // get to the root of the tree, to avoid N^2 analysis.
2069*9880d681SAndroid Build Coastguard Worker   unsigned Opcode = BO->getOpcode();
2070*9880d681SAndroid Build Coastguard Worker   if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode) {
2071*9880d681SAndroid Build Coastguard Worker     // During the initial run we will get to the root of the tree.
2072*9880d681SAndroid Build Coastguard Worker     // But if we get here while we are redoing instructions, there is no
2073*9880d681SAndroid Build Coastguard Worker     // guarantee that the root will be visited. So Redo later
2074*9880d681SAndroid Build Coastguard Worker     if (BO->user_back() != BO &&
2075*9880d681SAndroid Build Coastguard Worker         BO->getParent() == BO->user_back()->getParent())
2076*9880d681SAndroid Build Coastguard Worker       RedoInsts.insert(BO->user_back());
2077*9880d681SAndroid Build Coastguard Worker     return;
2078*9880d681SAndroid Build Coastguard Worker   }
2079*9880d681SAndroid Build Coastguard Worker 
2080*9880d681SAndroid Build Coastguard Worker   // If this is an add tree that is used by a sub instruction, ignore it
2081*9880d681SAndroid Build Coastguard Worker   // until we process the subtract.
2082*9880d681SAndroid Build Coastguard Worker   if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
2083*9880d681SAndroid Build Coastguard Worker       cast<Instruction>(BO->user_back())->getOpcode() == Instruction::Sub)
2084*9880d681SAndroid Build Coastguard Worker     return;
2085*9880d681SAndroid Build Coastguard Worker   if (BO->hasOneUse() && BO->getOpcode() == Instruction::FAdd &&
2086*9880d681SAndroid Build Coastguard Worker       cast<Instruction>(BO->user_back())->getOpcode() == Instruction::FSub)
2087*9880d681SAndroid Build Coastguard Worker     return;
2088*9880d681SAndroid Build Coastguard Worker 
2089*9880d681SAndroid Build Coastguard Worker   ReassociateExpression(BO);
2090*9880d681SAndroid Build Coastguard Worker }
2091*9880d681SAndroid Build Coastguard Worker 
ReassociateExpression(BinaryOperator * I)2092*9880d681SAndroid Build Coastguard Worker void ReassociatePass::ReassociateExpression(BinaryOperator *I) {
2093*9880d681SAndroid Build Coastguard Worker   // First, walk the expression tree, linearizing the tree, collecting the
2094*9880d681SAndroid Build Coastguard Worker   // operand information.
2095*9880d681SAndroid Build Coastguard Worker   SmallVector<RepeatedValue, 8> Tree;
2096*9880d681SAndroid Build Coastguard Worker   MadeChange |= LinearizeExprTree(I, Tree);
2097*9880d681SAndroid Build Coastguard Worker   SmallVector<ValueEntry, 8> Ops;
2098*9880d681SAndroid Build Coastguard Worker   Ops.reserve(Tree.size());
2099*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
2100*9880d681SAndroid Build Coastguard Worker     RepeatedValue E = Tree[i];
2101*9880d681SAndroid Build Coastguard Worker     Ops.append(E.second.getZExtValue(),
2102*9880d681SAndroid Build Coastguard Worker                ValueEntry(getRank(E.first), E.first));
2103*9880d681SAndroid Build Coastguard Worker   }
2104*9880d681SAndroid Build Coastguard Worker 
2105*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
2106*9880d681SAndroid Build Coastguard Worker 
2107*9880d681SAndroid Build Coastguard Worker   // Now that we have linearized the tree to a list and have gathered all of
2108*9880d681SAndroid Build Coastguard Worker   // the operands and their ranks, sort the operands by their rank.  Use a
2109*9880d681SAndroid Build Coastguard Worker   // stable_sort so that values with equal ranks will have their relative
2110*9880d681SAndroid Build Coastguard Worker   // positions maintained (and so the compiler is deterministic).  Note that
2111*9880d681SAndroid Build Coastguard Worker   // this sorts so that the highest ranking values end up at the beginning of
2112*9880d681SAndroid Build Coastguard Worker   // the vector.
2113*9880d681SAndroid Build Coastguard Worker   std::stable_sort(Ops.begin(), Ops.end());
2114*9880d681SAndroid Build Coastguard Worker 
2115*9880d681SAndroid Build Coastguard Worker   // Now that we have the expression tree in a convenient
2116*9880d681SAndroid Build Coastguard Worker   // sorted form, optimize it globally if possible.
2117*9880d681SAndroid Build Coastguard Worker   if (Value *V = OptimizeExpression(I, Ops)) {
2118*9880d681SAndroid Build Coastguard Worker     if (V == I)
2119*9880d681SAndroid Build Coastguard Worker       // Self-referential expression in unreachable code.
2120*9880d681SAndroid Build Coastguard Worker       return;
2121*9880d681SAndroid Build Coastguard Worker     // This expression tree simplified to something that isn't a tree,
2122*9880d681SAndroid Build Coastguard Worker     // eliminate it.
2123*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
2124*9880d681SAndroid Build Coastguard Worker     I->replaceAllUsesWith(V);
2125*9880d681SAndroid Build Coastguard Worker     if (Instruction *VI = dyn_cast<Instruction>(V))
2126*9880d681SAndroid Build Coastguard Worker       VI->setDebugLoc(I->getDebugLoc());
2127*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(I);
2128*9880d681SAndroid Build Coastguard Worker     ++NumAnnihil;
2129*9880d681SAndroid Build Coastguard Worker     return;
2130*9880d681SAndroid Build Coastguard Worker   }
2131*9880d681SAndroid Build Coastguard Worker 
2132*9880d681SAndroid Build Coastguard Worker   // We want to sink immediates as deeply as possible except in the case where
2133*9880d681SAndroid Build Coastguard Worker   // this is a multiply tree used only by an add, and the immediate is a -1.
2134*9880d681SAndroid Build Coastguard Worker   // In this case we reassociate to put the negation on the outside so that we
2135*9880d681SAndroid Build Coastguard Worker   // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
2136*9880d681SAndroid Build Coastguard Worker   if (I->hasOneUse()) {
2137*9880d681SAndroid Build Coastguard Worker     if (I->getOpcode() == Instruction::Mul &&
2138*9880d681SAndroid Build Coastguard Worker         cast<Instruction>(I->user_back())->getOpcode() == Instruction::Add &&
2139*9880d681SAndroid Build Coastguard Worker         isa<ConstantInt>(Ops.back().Op) &&
2140*9880d681SAndroid Build Coastguard Worker         cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
2141*9880d681SAndroid Build Coastguard Worker       ValueEntry Tmp = Ops.pop_back_val();
2142*9880d681SAndroid Build Coastguard Worker       Ops.insert(Ops.begin(), Tmp);
2143*9880d681SAndroid Build Coastguard Worker     } else if (I->getOpcode() == Instruction::FMul &&
2144*9880d681SAndroid Build Coastguard Worker                cast<Instruction>(I->user_back())->getOpcode() ==
2145*9880d681SAndroid Build Coastguard Worker                    Instruction::FAdd &&
2146*9880d681SAndroid Build Coastguard Worker                isa<ConstantFP>(Ops.back().Op) &&
2147*9880d681SAndroid Build Coastguard Worker                cast<ConstantFP>(Ops.back().Op)->isExactlyValue(-1.0)) {
2148*9880d681SAndroid Build Coastguard Worker       ValueEntry Tmp = Ops.pop_back_val();
2149*9880d681SAndroid Build Coastguard Worker       Ops.insert(Ops.begin(), Tmp);
2150*9880d681SAndroid Build Coastguard Worker     }
2151*9880d681SAndroid Build Coastguard Worker   }
2152*9880d681SAndroid Build Coastguard Worker 
2153*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
2154*9880d681SAndroid Build Coastguard Worker 
2155*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 1) {
2156*9880d681SAndroid Build Coastguard Worker     if (Ops[0].Op == I)
2157*9880d681SAndroid Build Coastguard Worker       // Self-referential expression in unreachable code.
2158*9880d681SAndroid Build Coastguard Worker       return;
2159*9880d681SAndroid Build Coastguard Worker 
2160*9880d681SAndroid Build Coastguard Worker     // This expression tree simplified to something that isn't a tree,
2161*9880d681SAndroid Build Coastguard Worker     // eliminate it.
2162*9880d681SAndroid Build Coastguard Worker     I->replaceAllUsesWith(Ops[0].Op);
2163*9880d681SAndroid Build Coastguard Worker     if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
2164*9880d681SAndroid Build Coastguard Worker       OI->setDebugLoc(I->getDebugLoc());
2165*9880d681SAndroid Build Coastguard Worker     RedoInsts.insert(I);
2166*9880d681SAndroid Build Coastguard Worker     return;
2167*9880d681SAndroid Build Coastguard Worker   }
2168*9880d681SAndroid Build Coastguard Worker 
2169*9880d681SAndroid Build Coastguard Worker   // Now that we ordered and optimized the expressions, splat them back into
2170*9880d681SAndroid Build Coastguard Worker   // the expression tree, removing any unneeded nodes.
2171*9880d681SAndroid Build Coastguard Worker   RewriteExprTree(I, Ops);
2172*9880d681SAndroid Build Coastguard Worker }
2173*9880d681SAndroid Build Coastguard Worker 
run(Function & F,FunctionAnalysisManager &)2174*9880d681SAndroid Build Coastguard Worker PreservedAnalyses ReassociatePass::run(Function &F, FunctionAnalysisManager &) {
2175*9880d681SAndroid Build Coastguard Worker   // Reassociate needs for each instruction to have its operands already
2176*9880d681SAndroid Build Coastguard Worker   // processed, so we first perform a RPOT of the basic blocks so that
2177*9880d681SAndroid Build Coastguard Worker   // when we process a basic block, all its dominators have been processed
2178*9880d681SAndroid Build Coastguard Worker   // before.
2179*9880d681SAndroid Build Coastguard Worker   ReversePostOrderTraversal<Function *> RPOT(&F);
2180*9880d681SAndroid Build Coastguard Worker   BuildRankMap(F, RPOT);
2181*9880d681SAndroid Build Coastguard Worker 
2182*9880d681SAndroid Build Coastguard Worker   MadeChange = false;
2183*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *BI : RPOT) {
2184*9880d681SAndroid Build Coastguard Worker     // Use a worklist to keep track of which instructions have been processed
2185*9880d681SAndroid Build Coastguard Worker     // (and which insts won't be optimized again) so when redoing insts,
2186*9880d681SAndroid Build Coastguard Worker     // optimize insts rightaway which won't be processed later.
2187*9880d681SAndroid Build Coastguard Worker     SmallSet<Instruction *, 8> Worklist;
2188*9880d681SAndroid Build Coastguard Worker 
2189*9880d681SAndroid Build Coastguard Worker     // Insert all instructions in the BB
2190*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *BI)
2191*9880d681SAndroid Build Coastguard Worker       Worklist.insert(&I);
2192*9880d681SAndroid Build Coastguard Worker 
2193*9880d681SAndroid Build Coastguard Worker     // Optimize every instruction in the basic block.
2194*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;) {
2195*9880d681SAndroid Build Coastguard Worker       // This instruction has been processed.
2196*9880d681SAndroid Build Coastguard Worker       Worklist.erase(&*II);
2197*9880d681SAndroid Build Coastguard Worker       if (isInstructionTriviallyDead(&*II)) {
2198*9880d681SAndroid Build Coastguard Worker         EraseInst(&*II++);
2199*9880d681SAndroid Build Coastguard Worker       } else {
2200*9880d681SAndroid Build Coastguard Worker         OptimizeInst(&*II);
2201*9880d681SAndroid Build Coastguard Worker         assert(II->getParent() == &*BI && "Moved to a different block!");
2202*9880d681SAndroid Build Coastguard Worker         ++II;
2203*9880d681SAndroid Build Coastguard Worker       }
2204*9880d681SAndroid Build Coastguard Worker 
2205*9880d681SAndroid Build Coastguard Worker       // If the above optimizations produced new instructions to optimize or
2206*9880d681SAndroid Build Coastguard Worker       // made modifications which need to be redone, do them now if they won't
2207*9880d681SAndroid Build Coastguard Worker       // be handled later.
2208*9880d681SAndroid Build Coastguard Worker       while (!RedoInsts.empty()) {
2209*9880d681SAndroid Build Coastguard Worker         Instruction *I = RedoInsts.pop_back_val();
2210*9880d681SAndroid Build Coastguard Worker         // Process instructions that won't be processed later, either
2211*9880d681SAndroid Build Coastguard Worker         // inside the block itself or in another basic block (based on rank),
2212*9880d681SAndroid Build Coastguard Worker         // since these will be processed later.
2213*9880d681SAndroid Build Coastguard Worker         if ((I->getParent() != BI || !Worklist.count(I)) &&
2214*9880d681SAndroid Build Coastguard Worker             RankMap[I->getParent()] <= RankMap[BI]) {
2215*9880d681SAndroid Build Coastguard Worker           if (isInstructionTriviallyDead(I))
2216*9880d681SAndroid Build Coastguard Worker             EraseInst(I);
2217*9880d681SAndroid Build Coastguard Worker           else
2218*9880d681SAndroid Build Coastguard Worker             OptimizeInst(I);
2219*9880d681SAndroid Build Coastguard Worker         }
2220*9880d681SAndroid Build Coastguard Worker       }
2221*9880d681SAndroid Build Coastguard Worker     }
2222*9880d681SAndroid Build Coastguard Worker   }
2223*9880d681SAndroid Build Coastguard Worker 
2224*9880d681SAndroid Build Coastguard Worker   // We are done with the rank map.
2225*9880d681SAndroid Build Coastguard Worker   RankMap.clear();
2226*9880d681SAndroid Build Coastguard Worker   ValueRankMap.clear();
2227*9880d681SAndroid Build Coastguard Worker 
2228*9880d681SAndroid Build Coastguard Worker   if (MadeChange) {
2229*9880d681SAndroid Build Coastguard Worker     // FIXME: This should also 'preserve the CFG'.
2230*9880d681SAndroid Build Coastguard Worker     auto PA = PreservedAnalyses();
2231*9880d681SAndroid Build Coastguard Worker     PA.preserve<GlobalsAA>();
2232*9880d681SAndroid Build Coastguard Worker     return PA;
2233*9880d681SAndroid Build Coastguard Worker   }
2234*9880d681SAndroid Build Coastguard Worker 
2235*9880d681SAndroid Build Coastguard Worker   return PreservedAnalyses::all();
2236*9880d681SAndroid Build Coastguard Worker }
2237*9880d681SAndroid Build Coastguard Worker 
2238*9880d681SAndroid Build Coastguard Worker namespace {
2239*9880d681SAndroid Build Coastguard Worker   class ReassociateLegacyPass : public FunctionPass {
2240*9880d681SAndroid Build Coastguard Worker     ReassociatePass Impl;
2241*9880d681SAndroid Build Coastguard Worker   public:
2242*9880d681SAndroid Build Coastguard Worker     static char ID; // Pass identification, replacement for typeid
ReassociateLegacyPass()2243*9880d681SAndroid Build Coastguard Worker     ReassociateLegacyPass() : FunctionPass(ID) {
2244*9880d681SAndroid Build Coastguard Worker       initializeReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
2245*9880d681SAndroid Build Coastguard Worker     }
2246*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)2247*9880d681SAndroid Build Coastguard Worker     bool runOnFunction(Function &F) override {
2248*9880d681SAndroid Build Coastguard Worker       if (skipFunction(F))
2249*9880d681SAndroid Build Coastguard Worker         return false;
2250*9880d681SAndroid Build Coastguard Worker 
2251*9880d681SAndroid Build Coastguard Worker       FunctionAnalysisManager DummyFAM;
2252*9880d681SAndroid Build Coastguard Worker       auto PA = Impl.run(F, DummyFAM);
2253*9880d681SAndroid Build Coastguard Worker       return !PA.areAllPreserved();
2254*9880d681SAndroid Build Coastguard Worker     }
2255*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const2256*9880d681SAndroid Build Coastguard Worker     void getAnalysisUsage(AnalysisUsage &AU) const override {
2257*9880d681SAndroid Build Coastguard Worker       AU.setPreservesCFG();
2258*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<GlobalsAAWrapperPass>();
2259*9880d681SAndroid Build Coastguard Worker     }
2260*9880d681SAndroid Build Coastguard Worker   };
2261*9880d681SAndroid Build Coastguard Worker }
2262*9880d681SAndroid Build Coastguard Worker 
2263*9880d681SAndroid Build Coastguard Worker char ReassociateLegacyPass::ID = 0;
2264*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS(ReassociateLegacyPass, "reassociate",
2265*9880d681SAndroid Build Coastguard Worker                 "Reassociate expressions", false, false)
2266*9880d681SAndroid Build Coastguard Worker 
2267*9880d681SAndroid Build Coastguard Worker // Public interface to the Reassociate pass
createReassociatePass()2268*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createReassociatePass() {
2269*9880d681SAndroid Build Coastguard Worker   return new ReassociateLegacyPass();
2270*9880d681SAndroid Build Coastguard Worker }
2271