1
//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This pass reassociates commutative expressions in an order that is designed
11
// to promote better constant propagation, GCSE, LICM, PRE, etc.
13
// For example: 4 + (x + 5) -> x + (4 + 5)
15
// In the implementation of this algorithm, constants are assigned rank = 0,
16
// function arguments are rank = 1, and other values are assigned ranks
17
// corresponding to the reverse post order traversal of current function
18
// (starting at 2), which effectively gives values in deep loops higher rank
19
// than values not in loops.
21
//===----------------------------------------------------------------------===//
23
#define DEBUG_TYPE "reassociate"
24
#include "llvm/Transforms/Scalar.h"
25
#include "llvm/Constants.h"
26
#include "llvm/DerivedTypes.h"
27
#include "llvm/Function.h"
28
#include "llvm/Instructions.h"
29
#include "llvm/IntrinsicInst.h"
30
#include "llvm/Pass.h"
31
#include "llvm/Assembly/Writer.h"
32
#include "llvm/Support/CFG.h"
33
#include "llvm/Support/Debug.h"
34
#include "llvm/Support/ValueHandle.h"
35
#include "llvm/Support/raw_ostream.h"
36
#include "llvm/ADT/PostOrderIterator.h"
37
#include "llvm/ADT/Statistic.h"
38
#include "llvm/ADT/DenseMap.h"
42
STATISTIC(NumLinear , "Number of insts linearized");
43
STATISTIC(NumChanged, "Number of insts reassociated");
44
STATISTIC(NumAnnihil, "Number of expr tree annihilated");
45
STATISTIC(NumFactor , "Number of multiplies factored");
51
ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
53
inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
54
return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
59
/// PrintOps - Print out the expression identified in the Ops list.
61
static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
62
Module *M = I->getParent()->getParent()->getParent();
63
dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
64
<< *Ops[0].Op->getType() << '\t';
65
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
67
WriteAsOperand(dbgs(), Ops[i].Op, false, M);
68
dbgs() << ", #" << Ops[i].Rank << "] ";
74
class Reassociate : public FunctionPass {
75
DenseMap<BasicBlock*, unsigned> RankMap;
76
DenseMap<AssertingVH<>, unsigned> ValueRankMap;
79
static char ID; // Pass identification, replacement for typeid
80
Reassociate() : FunctionPass(ID) {}
82
bool runOnFunction(Function &F);
84
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88
void BuildRankMap(Function &F);
89
unsigned getRank(Value *V);
90
Value *ReassociateExpression(BinaryOperator *I);
91
void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops,
93
Value *OptimizeExpression(BinaryOperator *I,
94
SmallVectorImpl<ValueEntry> &Ops);
95
Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
96
void LinearizeExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
97
void LinearizeExpr(BinaryOperator *I);
98
Value *RemoveFactorFromExpression(Value *V, Value *Factor);
99
void ReassociateBB(BasicBlock *BB);
101
void RemoveDeadBinaryOp(Value *V);
105
char Reassociate::ID = 0;
106
INITIALIZE_PASS(Reassociate, "reassociate",
107
"Reassociate expressions", false, false);
109
// Public interface to the Reassociate pass
110
FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
112
void Reassociate::RemoveDeadBinaryOp(Value *V) {
113
Instruction *Op = dyn_cast<Instruction>(V);
114
if (!Op || !isa<BinaryOperator>(Op) || !Op->use_empty())
117
Value *LHS = Op->getOperand(0), *RHS = Op->getOperand(1);
119
ValueRankMap.erase(Op);
120
Op->eraseFromParent();
121
RemoveDeadBinaryOp(LHS);
122
RemoveDeadBinaryOp(RHS);
126
static bool isUnmovableInstruction(Instruction *I) {
127
if (I->getOpcode() == Instruction::PHI ||
128
I->getOpcode() == Instruction::Alloca ||
129
I->getOpcode() == Instruction::Load ||
130
I->getOpcode() == Instruction::Invoke ||
131
(I->getOpcode() == Instruction::Call &&
132
!isa<DbgInfoIntrinsic>(I)) ||
133
I->getOpcode() == Instruction::UDiv ||
134
I->getOpcode() == Instruction::SDiv ||
135
I->getOpcode() == Instruction::FDiv ||
136
I->getOpcode() == Instruction::URem ||
137
I->getOpcode() == Instruction::SRem ||
138
I->getOpcode() == Instruction::FRem)
143
void Reassociate::BuildRankMap(Function &F) {
146
// Assign distinct ranks to function arguments
147
for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
148
ValueRankMap[&*I] = ++i;
150
ReversePostOrderTraversal<Function*> RPOT(&F);
151
for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
152
E = RPOT.end(); I != E; ++I) {
154
unsigned BBRank = RankMap[BB] = ++i << 16;
156
// Walk the basic block, adding precomputed ranks for any instructions that
157
// we cannot move. This ensures that the ranks for these instructions are
158
// all different in the block.
159
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
160
if (isUnmovableInstruction(I))
161
ValueRankMap[&*I] = ++BBRank;
165
unsigned Reassociate::getRank(Value *V) {
166
Instruction *I = dyn_cast<Instruction>(V);
168
if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument.
169
return 0; // Otherwise it's a global or constant, rank 0.
172
if (unsigned Rank = ValueRankMap[I])
173
return Rank; // Rank already known?
175
// If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
176
// we can reassociate expressions for code motion! Since we do not recurse
177
// for PHI nodes, we cannot have infinite recursion here, because there
178
// cannot be loops in the value graph that do not go through PHI nodes.
179
unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
180
for (unsigned i = 0, e = I->getNumOperands();
181
i != e && Rank != MaxRank; ++i)
182
Rank = std::max(Rank, getRank(I->getOperand(i)));
184
// If this is a not or neg instruction, do not count it for rank. This
185
// assures us that X and ~X will have the same rank.
186
if (!I->getType()->isIntegerTy() ||
187
(!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
190
//DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
193
return ValueRankMap[I] = Rank;
196
/// isReassociableOp - Return true if V is an instruction of the specified
197
/// opcode and if it only has one use.
198
static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
199
if ((V->hasOneUse() || V->use_empty()) && isa<Instruction>(V) &&
200
cast<Instruction>(V)->getOpcode() == Opcode)
201
return cast<BinaryOperator>(V);
205
/// LowerNegateToMultiply - Replace 0-X with X*-1.
207
static Instruction *LowerNegateToMultiply(Instruction *Neg,
208
DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
209
Constant *Cst = Constant::getAllOnesValue(Neg->getType());
211
Instruction *Res = BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
212
ValueRankMap.erase(Neg);
214
Neg->replaceAllUsesWith(Res);
215
Neg->eraseFromParent();
219
// Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
220
// Note that if D is also part of the expression tree that we recurse to
221
// linearize it as well. Besides that case, this does not recurse into A,B, or
223
void Reassociate::LinearizeExpr(BinaryOperator *I) {
224
BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
225
BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
226
assert(isReassociableOp(LHS, I->getOpcode()) &&
227
isReassociableOp(RHS, I->getOpcode()) &&
228
"Not an expression that needs linearization?");
230
DEBUG(dbgs() << "Linear" << *LHS << '\n' << *RHS << '\n' << *I << '\n');
232
// Move the RHS instruction to live immediately before I, avoiding breaking
233
// dominator properties.
236
// Move operands around to do the linearization.
237
I->setOperand(1, RHS->getOperand(0));
238
RHS->setOperand(0, LHS);
239
I->setOperand(0, RHS);
243
DEBUG(dbgs() << "Linearized: " << *I << '\n');
245
// If D is part of this expression tree, tail recurse.
246
if (isReassociableOp(I->getOperand(1), I->getOpcode()))
251
/// LinearizeExprTree - Given an associative binary expression tree, traverse
252
/// all of the uses putting it into canonical form. This forces a left-linear
253
/// form of the expression (((a+b)+c)+d), and collects information about the
254
/// rank of the non-tree operands.
256
/// NOTE: These intentionally destroys the expression tree operands (turning
257
/// them into undef values) to reduce #uses of the values. This means that the
258
/// caller MUST use something like RewriteExprTree to put the values back in.
260
void Reassociate::LinearizeExprTree(BinaryOperator *I,
261
SmallVectorImpl<ValueEntry> &Ops) {
262
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
263
unsigned Opcode = I->getOpcode();
265
// First step, linearize the expression if it is in ((A+B)+(C+D)) form.
266
BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
267
BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
269
// If this is a multiply expression tree and it contains internal negations,
270
// transform them into multiplies by -1 so they can be reassociated.
271
if (I->getOpcode() == Instruction::Mul) {
272
if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
273
LHS = LowerNegateToMultiply(cast<Instruction>(LHS), ValueRankMap);
274
LHSBO = isReassociableOp(LHS, Opcode);
276
if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
277
RHS = LowerNegateToMultiply(cast<Instruction>(RHS), ValueRankMap);
278
RHSBO = isReassociableOp(RHS, Opcode);
284
// Neither the LHS or RHS as part of the tree, thus this is a leaf. As
285
// such, just remember these operands and their rank.
286
Ops.push_back(ValueEntry(getRank(LHS), LHS));
287
Ops.push_back(ValueEntry(getRank(RHS), RHS));
289
// Clear the leaves out.
290
I->setOperand(0, UndefValue::get(I->getType()));
291
I->setOperand(1, UndefValue::get(I->getType()));
295
// Turn X+(Y+Z) -> (Y+Z)+X
296
std::swap(LHSBO, RHSBO);
298
bool Success = !I->swapOperands();
299
assert(Success && "swapOperands failed");
303
// Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the RHS is not
304
// part of the expression tree.
306
LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
307
RHS = I->getOperand(1);
311
// Okay, now we know that the LHS is a nested expression and that the RHS is
312
// not. Perform reassociation.
313
assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
315
// Move LHS right before I to make sure that the tree expression dominates all
317
LHSBO->moveBefore(I);
319
// Linearize the expression tree on the LHS.
320
LinearizeExprTree(LHSBO, Ops);
322
// Remember the RHS operand and its rank.
323
Ops.push_back(ValueEntry(getRank(RHS), RHS));
325
// Clear the RHS leaf out.
326
I->setOperand(1, UndefValue::get(I->getType()));
329
// RewriteExprTree - Now that the operands for this expression tree are
330
// linearized and optimized, emit them in-order. This function is written to be
332
void Reassociate::RewriteExprTree(BinaryOperator *I,
333
SmallVectorImpl<ValueEntry> &Ops,
335
if (i+2 == Ops.size()) {
336
if (I->getOperand(0) != Ops[i].Op ||
337
I->getOperand(1) != Ops[i+1].Op) {
338
Value *OldLHS = I->getOperand(0);
339
DEBUG(dbgs() << "RA: " << *I << '\n');
340
I->setOperand(0, Ops[i].Op);
341
I->setOperand(1, Ops[i+1].Op);
342
DEBUG(dbgs() << "TO: " << *I << '\n');
346
// If we reassociated a tree to fewer operands (e.g. (1+a+2) -> (a+3)
347
// delete the extra, now dead, nodes.
348
RemoveDeadBinaryOp(OldLHS);
352
assert(i+2 < Ops.size() && "Ops index out of range!");
354
if (I->getOperand(1) != Ops[i].Op) {
355
DEBUG(dbgs() << "RA: " << *I << '\n');
356
I->setOperand(1, Ops[i].Op);
357
DEBUG(dbgs() << "TO: " << *I << '\n');
362
BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
363
assert(LHS->getOpcode() == I->getOpcode() &&
364
"Improper expression tree!");
366
// Compactify the tree instructions together with each other to guarantee
367
// that the expression tree is dominated by all of Ops.
369
RewriteExprTree(LHS, Ops, i+1);
374
// NegateValue - Insert instructions before the instruction pointed to by BI,
375
// that computes the negative version of the value specified. The negative
376
// version of the value is returned, and BI is left pointing at the instruction
377
// that should be processed next by the reassociation pass.
379
static Value *NegateValue(Value *V, Instruction *BI) {
380
if (Constant *C = dyn_cast<Constant>(V))
381
return ConstantExpr::getNeg(C);
383
// We are trying to expose opportunity for reassociation. One of the things
384
// that we want to do to achieve this is to push a negation as deep into an
385
// expression chain as possible, to expose the add instructions. In practice,
386
// this means that we turn this:
387
// X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
388
// so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
389
// the constants. We assume that instcombine will clean up the mess later if
390
// we introduce tons of unnecessary negation instructions.
392
if (Instruction *I = dyn_cast<Instruction>(V))
393
if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
394
// Push the negates through the add.
395
I->setOperand(0, NegateValue(I->getOperand(0), BI));
396
I->setOperand(1, NegateValue(I->getOperand(1), BI));
398
// We must move the add instruction here, because the neg instructions do
399
// not dominate the old add instruction in general. By moving it, we are
400
// assured that the neg instructions we just inserted dominate the
401
// instruction we are about to insert after them.
404
I->setName(I->getName()+".neg");
408
// Okay, we need to materialize a negated version of V with an instruction.
409
// Scan the use lists of V to see if we have one already.
410
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
412
if (!BinaryOperator::isNeg(U)) continue;
414
// We found one! Now we have to make sure that the definition dominates
415
// this use. We do this by moving it to the entry block (if it is a
416
// non-instruction value) or right after the definition. These negates will
417
// be zapped by reassociate later, so we don't need much finesse here.
418
BinaryOperator *TheNeg = cast<BinaryOperator>(U);
420
// Verify that the negate is in this function, V might be a constant expr.
421
if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
424
BasicBlock::iterator InsertPt;
425
if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
426
if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
427
InsertPt = II->getNormalDest()->begin();
429
InsertPt = InstInput;
432
while (isa<PHINode>(InsertPt)) ++InsertPt;
434
InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
436
TheNeg->moveBefore(InsertPt);
440
// Insert a 'neg' instruction that subtracts the value from zero to get the
442
return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
445
/// ShouldBreakUpSubtract - Return true if we should break up this subtract of
446
/// X-Y into (X + -Y).
447
static bool ShouldBreakUpSubtract(Instruction *Sub) {
448
// If this is a negation, we can't split it up!
449
if (BinaryOperator::isNeg(Sub))
452
// Don't bother to break this up unless either the LHS is an associable add or
453
// subtract or if this is only used by one.
454
if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
455
isReassociableOp(Sub->getOperand(0), Instruction::Sub))
457
if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
458
isReassociableOp(Sub->getOperand(1), Instruction::Sub))
460
if (Sub->hasOneUse() &&
461
(isReassociableOp(Sub->use_back(), Instruction::Add) ||
462
isReassociableOp(Sub->use_back(), Instruction::Sub)))
468
/// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
469
/// only used by an add, transform this into (X+(0-Y)) to promote better
471
static Instruction *BreakUpSubtract(Instruction *Sub,
472
DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
473
// Convert a subtract into an add and a neg instruction. This allows sub
474
// instructions to be commuted with other add instructions.
476
// Calculate the negative value of Operand 1 of the sub instruction,
477
// and set it as the RHS of the add instruction we just made.
479
Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
481
BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
484
// Everyone now refers to the add instruction.
485
ValueRankMap.erase(Sub);
486
Sub->replaceAllUsesWith(New);
487
Sub->eraseFromParent();
489
DEBUG(dbgs() << "Negated: " << *New << '\n');
493
/// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
494
/// by one, change this into a multiply by a constant to assist with further
496
static Instruction *ConvertShiftToMul(Instruction *Shl,
497
DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
498
// If an operand of this shift is a reassociable multiply, or if the shift
499
// is used by a reassociable multiply or add, turn into a multiply.
500
if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) ||
502
(isReassociableOp(Shl->use_back(), Instruction::Mul) ||
503
isReassociableOp(Shl->use_back(), Instruction::Add)))) {
504
Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
505
MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
508
BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
509
ValueRankMap.erase(Shl);
511
Shl->replaceAllUsesWith(Mul);
512
Shl->eraseFromParent();
518
// Scan backwards and forwards among values with the same rank as element i to
519
// see if X exists. If X does not exist, return i. This is useful when
520
// scanning for 'x' when we see '-x' because they both get the same rank.
521
static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
523
unsigned XRank = Ops[i].Rank;
524
unsigned e = Ops.size();
525
for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
529
for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
535
/// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
536
/// and returning the result. Insert the tree before I.
537
static Value *EmitAddTreeOfValues(Instruction *I, SmallVectorImpl<Value*> &Ops){
538
if (Ops.size() == 1) return Ops.back();
540
Value *V1 = Ops.back();
542
Value *V2 = EmitAddTreeOfValues(I, Ops);
543
return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
546
/// RemoveFactorFromExpression - If V is an expression tree that is a
547
/// multiplication sequence, and if this sequence contains a multiply by Factor,
548
/// remove Factor from the tree and return the new tree.
549
Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
550
BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
553
SmallVector<ValueEntry, 8> Factors;
554
LinearizeExprTree(BO, Factors);
556
bool FoundFactor = false;
557
bool NeedsNegate = false;
558
for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
559
if (Factors[i].Op == Factor) {
561
Factors.erase(Factors.begin()+i);
565
// If this is a negative version of this factor, remove it.
566
if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
567
if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
568
if (FC1->getValue() == -FC2->getValue()) {
569
FoundFactor = NeedsNegate = true;
570
Factors.erase(Factors.begin()+i);
576
// Make sure to restore the operands to the expression tree.
577
RewriteExprTree(BO, Factors);
581
BasicBlock::iterator InsertPt = BO; ++InsertPt;
583
// If this was just a single multiply, remove the multiply and return the only
584
// remaining operand.
585
if (Factors.size() == 1) {
586
ValueRankMap.erase(BO);
587
BO->eraseFromParent();
590
RewriteExprTree(BO, Factors);
595
V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
600
/// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
601
/// add its operands as factors, otherwise add V to the list of factors.
603
/// Ops is the top-level list of add operands we're trying to factor.
604
static void FindSingleUseMultiplyFactors(Value *V,
605
SmallVectorImpl<Value*> &Factors,
606
const SmallVectorImpl<ValueEntry> &Ops,
609
if (!(V->hasOneUse() || V->use_empty()) || // More than one use.
610
!(BO = dyn_cast<BinaryOperator>(V)) ||
611
BO->getOpcode() != Instruction::Mul) {
612
Factors.push_back(V);
616
// If this value has a single use because it is another input to the add
617
// tree we're reassociating and we dropped its use, it actually has two
618
// uses and we can't factor it.
620
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
621
if (Ops[i].Op == V) {
622
Factors.push_back(V);
628
// Otherwise, add the LHS and RHS to the list of factors.
629
FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops, false);
630
FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops, false);
633
/// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
634
/// instruction. This optimizes based on identities. If it can be reduced to
635
/// a single Value, it is returned, otherwise the Ops list is mutated as
637
static Value *OptimizeAndOrXor(unsigned Opcode,
638
SmallVectorImpl<ValueEntry> &Ops) {
639
// Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
640
// If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
641
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
642
// First, check for X and ~X in the operand list.
643
assert(i < Ops.size());
644
if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^.
645
Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
646
unsigned FoundX = FindInOperandList(Ops, i, X);
648
if (Opcode == Instruction::And) // ...&X&~X = 0
649
return Constant::getNullValue(X->getType());
651
if (Opcode == Instruction::Or) // ...|X|~X = -1
652
return Constant::getAllOnesValue(X->getType());
656
// Next, check for duplicate pairs of values, which we assume are next to
657
// each other, due to our sorting criteria.
658
assert(i < Ops.size());
659
if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
660
if (Opcode == Instruction::And || Opcode == Instruction::Or) {
661
// Drop duplicate values for And and Or.
662
Ops.erase(Ops.begin()+i);
668
// Drop pairs of values for Xor.
669
assert(Opcode == Instruction::Xor);
671
return Constant::getNullValue(Ops[0].Op->getType());
674
Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
682
/// OptimizeAdd - Optimize a series of operands to an 'add' instruction. This
683
/// optimizes based on identities. If it can be reduced to a single Value, it
684
/// is returned, otherwise the Ops list is mutated as necessary.
685
Value *Reassociate::OptimizeAdd(Instruction *I,
686
SmallVectorImpl<ValueEntry> &Ops) {
687
// Scan the operand lists looking for X and -X pairs. If we find any, we
688
// can simplify the expression. X+-X == 0. While we're at it, scan for any
689
// duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
691
// TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
693
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
694
Value *TheOp = Ops[i].Op;
695
// Check to see if we've seen this operand before. If so, we factor all
696
// instances of the operand together. Due to our sorting criteria, we know
697
// that these need to be next to each other in the vector.
698
if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
699
// Rescan the list, remove all instances of this operand from the expr.
700
unsigned NumFound = 0;
702
Ops.erase(Ops.begin()+i);
704
} while (i != Ops.size() && Ops[i].Op == TheOp);
706
DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
709
// Insert a new multiply.
710
Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
711
Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
713
// Now that we have inserted a multiply, optimize it. This allows us to
714
// handle cases that require multiple factoring steps, such as this:
715
// (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
716
Mul = ReassociateExpression(cast<BinaryOperator>(Mul));
718
// If every add operand was a duplicate, return the multiply.
722
// Otherwise, we had some input that didn't have the dupe, such as
723
// "A + A + B" -> "A*2 + B". Add the new multiply to the list of
724
// things being added by this operation.
725
Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
732
// Check for X and -X in the operand list.
733
if (!BinaryOperator::isNeg(TheOp))
736
Value *X = BinaryOperator::getNegArgument(TheOp);
737
unsigned FoundX = FindInOperandList(Ops, i, X);
741
// Remove X and -X from the operand list.
743
return Constant::getNullValue(X->getType());
745
Ops.erase(Ops.begin()+i);
749
--i; // Need to back up an extra one.
750
Ops.erase(Ops.begin()+FoundX);
752
--i; // Revisit element.
753
e -= 2; // Removed two elements.
756
// Scan the operand list, checking to see if there are any common factors
757
// between operands. Consider something like A*A+A*B*C+D. We would like to
758
// reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
759
// To efficiently find this, we count the number of times a factor occurs
760
// for any ADD operands that are MULs.
761
DenseMap<Value*, unsigned> FactorOccurrences;
763
// Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
764
// where they are actually the same multiply.
766
Value *MaxOccVal = 0;
767
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
768
BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op);
769
if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty())
772
// Compute all of the factors of this added value.
773
SmallVector<Value*, 8> Factors;
774
FindSingleUseMultiplyFactors(BOp, Factors, Ops, true);
775
assert(Factors.size() > 1 && "Bad linearize!");
777
// Add one to FactorOccurrences for each unique factor in this op.
778
SmallPtrSet<Value*, 8> Duplicates;
779
for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
780
Value *Factor = Factors[i];
781
if (!Duplicates.insert(Factor)) continue;
783
unsigned Occ = ++FactorOccurrences[Factor];
784
if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
786
// If Factor is a negative constant, add the negated value as a factor
787
// because we can percolate the negate out. Watch for minint, which
788
// cannot be positivified.
789
if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
790
if (CI->getValue().isNegative() && !CI->getValue().isMinSignedValue()) {
791
Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
792
assert(!Duplicates.count(Factor) &&
793
"Shouldn't have two constant factors, missed a canonicalize");
795
unsigned Occ = ++FactorOccurrences[Factor];
796
if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
801
// If any factor occurred more than one time, we can pull it out.
803
DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
806
// Create a new instruction that uses the MaxOccVal twice. If we don't do
807
// this, we could otherwise run into situations where removing a factor
808
// from an expression will drop a use of maxocc, and this can cause
809
// RemoveFactorFromExpression on successive values to behave differently.
810
Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
811
SmallVector<Value*, 4> NewMulOps;
812
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
813
// Only try to remove factors from expressions we're allowed to.
814
BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op);
815
if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty())
818
if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
819
NewMulOps.push_back(V);
820
Ops.erase(Ops.begin()+i);
825
// No need for extra uses anymore.
828
unsigned NumAddedValues = NewMulOps.size();
829
Value *V = EmitAddTreeOfValues(I, NewMulOps);
831
// Now that we have inserted the add tree, optimize it. This allows us to
832
// handle cases that require multiple factoring steps, such as this:
833
// A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C))
834
assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
835
(void)NumAddedValues;
836
V = ReassociateExpression(cast<BinaryOperator>(V));
838
// Create the multiply.
839
Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
841
// Rerun associate on the multiply in case the inner expression turned into
842
// a multiply. We want to make sure that we keep things in canonical form.
843
V2 = ReassociateExpression(cast<BinaryOperator>(V2));
845
// If every add operand included the factor (e.g. "A*B + A*C"), then the
846
// entire result expression is just the multiply "A*(B+C)".
850
// Otherwise, we had some input that didn't have the factor, such as
851
// "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of
852
// things being added by this operation.
853
Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
859
Value *Reassociate::OptimizeExpression(BinaryOperator *I,
860
SmallVectorImpl<ValueEntry> &Ops) {
861
// Now that we have the linearized expression tree, try to optimize it.
862
// Start by folding any constants that we found.
863
bool IterateOptimization = false;
864
if (Ops.size() == 1) return Ops[0].Op;
866
unsigned Opcode = I->getOpcode();
868
if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
869
if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
871
Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
872
return OptimizeExpression(I, Ops);
875
// Check for destructive annihilation due to a constant being used.
876
if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Ops.back().Op))
879
case Instruction::And:
880
if (CstVal->isZero()) // X & 0 -> 0
882
if (CstVal->isAllOnesValue()) // X & -1 -> X
885
case Instruction::Mul:
886
if (CstVal->isZero()) { // X * 0 -> 0
891
if (cast<ConstantInt>(CstVal)->isOne())
892
Ops.pop_back(); // X * 1 -> X
894
case Instruction::Or:
895
if (CstVal->isAllOnesValue()) // X | -1 -> -1
898
case Instruction::Add:
899
case Instruction::Xor:
900
if (CstVal->isZero()) // X [|^+] 0 -> X
904
if (Ops.size() == 1) return Ops[0].Op;
906
// Handle destructive annihilation due to identities between elements in the
907
// argument list here.
910
case Instruction::And:
911
case Instruction::Or:
912
case Instruction::Xor: {
913
unsigned NumOps = Ops.size();
914
if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
916
IterateOptimization |= Ops.size() != NumOps;
920
case Instruction::Add: {
921
unsigned NumOps = Ops.size();
922
if (Value *Result = OptimizeAdd(I, Ops))
924
IterateOptimization |= Ops.size() != NumOps;
928
//case Instruction::Mul:
931
if (IterateOptimization)
932
return OptimizeExpression(I, Ops);
937
/// ReassociateBB - Inspect all of the instructions in this basic block,
938
/// reassociating them as we go.
939
void Reassociate::ReassociateBB(BasicBlock *BB) {
940
for (BasicBlock::iterator BBI = BB->begin(); BBI != BB->end(); ) {
941
Instruction *BI = BBI++;
942
if (BI->getOpcode() == Instruction::Shl &&
943
isa<ConstantInt>(BI->getOperand(1)))
944
if (Instruction *NI = ConvertShiftToMul(BI, ValueRankMap)) {
949
// Reject cases where it is pointless to do this.
950
if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPointTy() ||
951
BI->getType()->isVectorTy())
952
continue; // Floating point ops are not associative.
954
// Do not reassociate boolean (i1) expressions. We want to preserve the
955
// original order of evaluation for short-circuited comparisons that
956
// SimplifyCFG has folded to AND/OR expressions. If the expression
957
// is not further optimized, it is likely to be transformed back to a
958
// short-circuited form for code gen, and the source order may have been
959
// optimized for the most likely conditions.
960
if (BI->getType()->isIntegerTy(1))
963
// If this is a subtract instruction which is not already in negate form,
964
// see if we can convert it to X+-Y.
965
if (BI->getOpcode() == Instruction::Sub) {
966
if (ShouldBreakUpSubtract(BI)) {
967
BI = BreakUpSubtract(BI, ValueRankMap);
968
// Reset the BBI iterator in case BreakUpSubtract changed the
969
// instruction it points to.
973
} else if (BinaryOperator::isNeg(BI)) {
974
// Otherwise, this is a negation. See if the operand is a multiply tree
975
// and if this is not an inner node of a multiply tree.
976
if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
978
!isReassociableOp(BI->use_back(), Instruction::Mul))) {
979
BI = LowerNegateToMultiply(BI, ValueRankMap);
985
// If this instruction is a commutative binary operator, process it.
986
if (!BI->isAssociative()) continue;
987
BinaryOperator *I = cast<BinaryOperator>(BI);
989
// If this is an interior node of a reassociable tree, ignore it until we
990
// get to the root of the tree, to avoid N^2 analysis.
991
if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
994
// If this is an add tree that is used by a sub instruction, ignore it
995
// until we process the subtract.
996
if (I->hasOneUse() && I->getOpcode() == Instruction::Add &&
997
cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub)
1000
ReassociateExpression(I);
1004
Value *Reassociate::ReassociateExpression(BinaryOperator *I) {
1006
// First, walk the expression tree, linearizing the tree, collecting the
1007
// operand information.
1008
SmallVector<ValueEntry, 8> Ops;
1009
LinearizeExprTree(I, Ops);
1011
DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
1013
// Now that we have linearized the tree to a list and have gathered all of
1014
// the operands and their ranks, sort the operands by their rank. Use a
1015
// stable_sort so that values with equal ranks will have their relative
1016
// positions maintained (and so the compiler is deterministic). Note that
1017
// this sorts so that the highest ranking values end up at the beginning of
1019
std::stable_sort(Ops.begin(), Ops.end());
1021
// OptimizeExpression - Now that we have the expression tree in a convenient
1022
// sorted form, optimize it globally if possible.
1023
if (Value *V = OptimizeExpression(I, Ops)) {
1024
// This expression tree simplified to something that isn't a tree,
1026
DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
1027
I->replaceAllUsesWith(V);
1028
RemoveDeadBinaryOp(I);
1033
// We want to sink immediates as deeply as possible except in the case where
1034
// this is a multiply tree used only by an add, and the immediate is a -1.
1035
// In this case we reassociate to put the negation on the outside so that we
1036
// can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
1037
if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
1038
cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
1039
isa<ConstantInt>(Ops.back().Op) &&
1040
cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
1041
ValueEntry Tmp = Ops.pop_back_val();
1042
Ops.insert(Ops.begin(), Tmp);
1045
DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
1047
if (Ops.size() == 1) {
1048
// This expression tree simplified to something that isn't a tree,
1050
I->replaceAllUsesWith(Ops[0].Op);
1051
RemoveDeadBinaryOp(I);
1055
// Now that we ordered and optimized the expressions, splat them back into
1056
// the expression tree, removing any unneeded nodes.
1057
RewriteExprTree(I, Ops);
1062
bool Reassociate::runOnFunction(Function &F) {
1063
// Recalculate the rank map for F
1067
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1070
// We are done with the rank map.
1072
ValueRankMap.clear();