1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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...
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/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Type.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/Statistic.h"
38 Statistic<> NumLinear ("reassociate","Number of insts linearized");
39 Statistic<> NumChanged("reassociate","Number of insts reassociated");
40 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
45 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
47 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
48 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
51 class Reassociate : public FunctionPass {
52 std::map<BasicBlock*, unsigned> RankMap;
53 std::map<Value*, unsigned> ValueRankMap;
56 bool runOnFunction(Function &F);
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 void BuildRankMap(Function &F);
63 unsigned getRank(Value *V);
64 void RewriteExprTree(BinaryOperator *I, unsigned Idx,
65 std::vector<ValueEntry> &Ops);
66 void OptimizeExpression(unsigned Opcode, std::vector<ValueEntry> &Ops);
67 void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
68 void LinearizeExpr(BinaryOperator *I);
69 void ReassociateBB(BasicBlock *BB);
72 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
75 // Public interface to the Reassociate pass
76 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
78 void Reassociate::BuildRankMap(Function &F) {
81 // Assign distinct ranks to function arguments
82 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
83 ValueRankMap[I] = ++i;
85 ReversePostOrderTraversal<Function*> RPOT(&F);
86 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
87 E = RPOT.end(); I != E; ++I)
88 RankMap[*I] = ++i << 16;
91 unsigned Reassociate::getRank(Value *V) {
92 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
94 Instruction *I = dyn_cast<Instruction>(V);
95 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
97 unsigned &CachedRank = ValueRankMap[I];
98 if (CachedRank) return CachedRank; // Rank already known?
100 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
101 // we can reassociate expressions for code motion! Since we do not recurse
102 // for PHI nodes, we cannot have infinite recursion here, because there
103 // cannot be loops in the value graph that do not go through PHI nodes.
105 if (I->getOpcode() == Instruction::PHI ||
106 I->getOpcode() == Instruction::Alloca ||
107 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
108 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
109 return RankMap[I->getParent()];
111 // If not, compute it!
112 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
113 for (unsigned i = 0, e = I->getNumOperands();
114 i != e && Rank != MaxRank; ++i)
115 Rank = std::max(Rank, getRank(I->getOperand(i)));
117 // If this is a not or neg instruction, do not count it for rank. This
118 // assures us that X and ~X will have the same rank.
119 if (!I->getType()->isIntegral() ||
120 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
123 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
126 return CachedRank = Rank;
129 /// isReassociableOp - Return true if V is an instruction of the specified
130 /// opcode and if it only has one use.
131 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
132 if (V->hasOneUse() && isa<Instruction>(V) &&
133 cast<Instruction>(V)->getOpcode() == Opcode)
134 return cast<BinaryOperator>(V);
138 // Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
139 // Note that if D is also part of the expression tree that we recurse to
140 // linearize it as well. Besides that case, this does not recurse into A,B, or
142 void Reassociate::LinearizeExpr(BinaryOperator *I) {
143 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
144 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
145 assert(isReassociableOp(LHS, I->getOpcode()) &&
146 isReassociableOp(RHS, I->getOpcode()) &&
147 "Not an expression that needs linearization?");
149 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
151 // Move the RHS instruction to live immediately before I, avoiding breaking
152 // dominator properties.
153 I->getParent()->getInstList().splice(I, RHS->getParent()->getInstList(), RHS);
155 // Move operands around to do the linearization.
156 I->setOperand(1, RHS->getOperand(0));
157 RHS->setOperand(0, LHS);
158 I->setOperand(0, RHS);
162 DEBUG(std::cerr << "Linearized: " << *I);
164 // If D is part of this expression tree, tail recurse.
165 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
170 /// LinearizeExprTree - Given an associative binary expression tree, traverse
171 /// all of the uses putting it into canonical form. This forces a left-linear
172 /// form of the the expression (((a+b)+c)+d), and collects information about the
173 /// rank of the non-tree operands.
175 /// This returns the rank of the RHS operand, which is known to be the highest
176 /// rank value in the expression tree.
178 void Reassociate::LinearizeExprTree(BinaryOperator *I,
179 std::vector<ValueEntry> &Ops) {
180 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
181 unsigned Opcode = I->getOpcode();
183 // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
184 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
185 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
189 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As
190 // such, just remember these operands and their rank.
191 Ops.push_back(ValueEntry(getRank(LHS), LHS));
192 Ops.push_back(ValueEntry(getRank(RHS), RHS));
195 // Turn X+(Y+Z) -> (Y+Z)+X
196 std::swap(LHSBO, RHSBO);
198 bool Success = !I->swapOperands();
199 assert(Success && "swapOperands failed");
203 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
204 // part of the expression tree.
206 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
207 RHS = I->getOperand(1);
211 // Okay, now we know that the LHS is a nested expression and that the RHS is
212 // not. Perform reassociation.
213 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
215 // Move LHS right before I to make sure that the tree expression dominates all
217 I->getParent()->getInstList().splice(I,
218 LHSBO->getParent()->getInstList(), LHSBO);
220 // Linearize the expression tree on the LHS.
221 LinearizeExprTree(LHSBO, Ops);
223 // Remember the RHS operand and its rank.
224 Ops.push_back(ValueEntry(getRank(RHS), RHS));
227 // RewriteExprTree - Now that the operands for this expression tree are
228 // linearized and optimized, emit them in-order. This function is written to be
230 void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
231 std::vector<ValueEntry> &Ops) {
232 if (i+2 == Ops.size()) {
233 if (I->getOperand(0) != Ops[i].Op ||
234 I->getOperand(1) != Ops[i+1].Op) {
235 DEBUG(std::cerr << "RA: " << *I);
236 I->setOperand(0, Ops[i].Op);
237 I->setOperand(1, Ops[i+1].Op);
238 DEBUG(std::cerr << "TO: " << *I);
244 assert(i+2 < Ops.size() && "Ops index out of range!");
246 if (I->getOperand(1) != Ops[i].Op) {
247 DEBUG(std::cerr << "RA: " << *I);
248 I->setOperand(1, Ops[i].Op);
249 DEBUG(std::cerr << "TO: " << *I);
253 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
258 // NegateValue - Insert instructions before the instruction pointed to by BI,
259 // that computes the negative version of the value specified. The negative
260 // version of the value is returned, and BI is left pointing at the instruction
261 // that should be processed next by the reassociation pass.
263 static Value *NegateValue(Value *V, Instruction *BI) {
264 // We are trying to expose opportunity for reassociation. One of the things
265 // that we want to do to achieve this is to push a negation as deep into an
266 // expression chain as possible, to expose the add instructions. In practice,
267 // this means that we turn this:
268 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
269 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
270 // the constants. We assume that instcombine will clean up the mess later if
271 // we introduce tons of unnecessary negation instructions...
273 if (Instruction *I = dyn_cast<Instruction>(V))
274 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
275 Value *RHS = NegateValue(I->getOperand(1), BI);
276 Value *LHS = NegateValue(I->getOperand(0), BI);
278 // We must actually insert a new add instruction here, because the neg
279 // instructions do not dominate the old add instruction in general. By
280 // adding it now, we are assured that the neg instructions we just
281 // inserted dominate the instruction we are about to insert after them.
283 return BinaryOperator::create(Instruction::Add, LHS, RHS,
284 I->getName()+".neg", BI);
287 // Insert a 'neg' instruction that subtracts the value from zero to get the
290 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
293 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
294 /// only used by an add, transform this into (X+(0-Y)) to promote better
296 static Instruction *BreakUpSubtract(Instruction *Sub) {
297 // Reject cases where it is pointless to do this.
298 if (Sub->getType()->isFloatingPoint())
299 return 0; // Floating point adds are not associative.
301 // Don't bother to break this up unless either the LHS is an associable add or
302 // if this is only used by one.
303 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
304 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
305 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
308 // Convert a subtract into an add and a neg instruction... so that sub
309 // instructions can be commuted with other add instructions...
311 // Calculate the negative value of Operand 1 of the sub instruction...
312 // and set it as the RHS of the add instruction we just made...
314 std::string Name = Sub->getName();
316 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
318 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
320 // Everyone now refers to the add instruction.
321 Sub->replaceAllUsesWith(New);
322 Sub->eraseFromParent();
324 DEBUG(std::cerr << "Negated: " << *New);
328 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
329 /// by one, change this into a multiply by a constant to assist with further
331 static Instruction *ConvertShiftToMul(Instruction *Shl) {
332 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
333 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
336 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
337 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
339 std::string Name = Shl->getName(); Shl->setName("");
340 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
342 Shl->replaceAllUsesWith(Mul);
343 Shl->eraseFromParent();
347 void Reassociate::OptimizeExpression(unsigned Opcode,
348 std::vector<ValueEntry> &Ops) {
349 // Now that we have the linearized expression tree, try to optimize it.
350 // Start by folding any constants that we found.
352 if (Ops.size() == 1) return;
354 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
355 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
357 Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
361 // Check for destructive annihilation due to a constant being used.
362 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
365 case Instruction::And:
366 if (CstVal->isNullValue()) { // ... & 0 -> 0
368 Ops.erase(Ops.begin()+1, Ops.end());
369 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
373 case Instruction::Mul:
374 if (CstVal->isNullValue()) { // ... * 0 -> 0
376 Ops.erase(Ops.begin()+1, Ops.end());
377 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
378 Ops.pop_back(); // ... * 1 -> ...
381 case Instruction::Or:
382 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
384 Ops.erase(Ops.begin()+1, Ops.end());
387 case Instruction::Add:
388 case Instruction::Xor:
389 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
394 // Handle destructive annihilation do to identities between elements in the
395 // argument list here.
399 /// ReassociateBB - Inspect all of the instructions in this basic block,
400 /// reassociating them as we go.
401 void Reassociate::ReassociateBB(BasicBlock *BB) {
402 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
403 // If this is a subtract instruction which is not already in negate form,
404 // see if we can convert it to X+-Y.
405 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
406 if (Instruction *NI = BreakUpSubtract(BI)) {
410 if (BI->getOpcode() == Instruction::Shl &&
411 isa<ConstantInt>(BI->getOperand(1)))
412 if (Instruction *NI = ConvertShiftToMul(BI)) {
417 // If this instruction is a commutative binary operator, process it.
418 if (!BI->isAssociative()) continue;
419 BinaryOperator *I = cast<BinaryOperator>(BI);
421 // If this is an interior node of a reassociable tree, ignore it until we
422 // get to the root of the tree, to avoid N^2 analysis.
423 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
426 // First, walk the expression tree, linearizing the tree, collecting
427 std::vector<ValueEntry> Ops;
428 LinearizeExprTree(I, Ops);
430 // Now that we have linearized the tree to a list and have gathered all of
431 // the operands and their ranks, sort the operands by their rank. Use a
432 // stable_sort so that values with equal ranks will have their relative
433 // positions maintained (and so the compiler is deterministic). Note that
434 // this sorts so that the highest ranking values end up at the beginning of
436 std::stable_sort(Ops.begin(), Ops.end());
438 // OptimizeExpression - Now that we have the expression tree in a convenient
439 // sorted form, optimize it globally if possible.
440 OptimizeExpression(I->getOpcode(), Ops);
442 if (Ops.size() == 1) {
443 // This expression tree simplified to something that isn't a tree,
445 I->replaceAllUsesWith(Ops[0].Op);
447 // Now that we ordered and optimized the expressions, splat them back into
448 // the expression tree, removing any unneeded nodes.
449 RewriteExprTree(I, 0, Ops);
455 bool Reassociate::runOnFunction(Function &F) {
456 // Recalculate the rank map for F
460 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
463 // We are done with the rank map...
465 ValueRankMap.clear();