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 LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
67 void LinearizeExpr(BinaryOperator *I);
68 void ReassociateBB(BasicBlock *BB);
71 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
74 // Public interface to the Reassociate pass
75 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
77 void Reassociate::BuildRankMap(Function &F) {
80 // Assign distinct ranks to function arguments
81 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
82 ValueRankMap[I] = ++i;
84 ReversePostOrderTraversal<Function*> RPOT(&F);
85 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
86 E = RPOT.end(); I != E; ++I)
87 RankMap[*I] = ++i << 16;
90 unsigned Reassociate::getRank(Value *V) {
91 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
93 Instruction *I = dyn_cast<Instruction>(V);
94 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
96 unsigned &CachedRank = ValueRankMap[I];
97 if (CachedRank) return CachedRank; // Rank already known?
99 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
100 // we can reassociate expressions for code motion! Since we do not recurse
101 // for PHI nodes, we cannot have infinite recursion here, because there
102 // cannot be loops in the value graph that do not go through PHI nodes.
104 if (I->getOpcode() == Instruction::PHI ||
105 I->getOpcode() == Instruction::Alloca ||
106 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
107 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
108 return RankMap[I->getParent()];
110 // If not, compute it!
111 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
112 for (unsigned i = 0, e = I->getNumOperands();
113 i != e && Rank != MaxRank; ++i)
114 Rank = std::max(Rank, getRank(I->getOperand(i)));
116 // If this is a not or neg instruction, do not count it for rank. This
117 // assures us that X and ~X will have the same rank.
118 if (!I->getType()->isIntegral() ||
119 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
122 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
125 return CachedRank = Rank;
128 /// isReassociableOp - Return true if V is an instruction of the specified
129 /// opcode and if it only has one use.
130 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
131 if (V->hasOneUse() && isa<Instruction>(V) &&
132 cast<Instruction>(V)->getOpcode() == Opcode)
133 return cast<BinaryOperator>(V);
137 // Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
138 // Note that if D is also part of the expression tree that we recurse to
139 // linearize it as well. Besides that case, this does not recurse into A,B, or
141 void Reassociate::LinearizeExpr(BinaryOperator *I) {
142 BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
143 BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
144 assert(isReassociableOp(LHS, I->getOpcode()) &&
145 isReassociableOp(RHS, I->getOpcode()) &&
146 "Not an expression that needs linearization?");
148 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
150 // Move the RHS instruction to live immediately before I, avoiding breaking
151 // dominator properties.
152 I->getParent()->getInstList().splice(I, RHS->getParent()->getInstList(), RHS);
154 // Move operands around to do the linearization.
155 I->setOperand(1, RHS->getOperand(0));
156 RHS->setOperand(0, LHS);
157 I->setOperand(0, RHS);
161 DEBUG(std::cerr << "Linearized: " << *I);
163 // If D is part of this expression tree, tail recurse.
164 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
169 /// LinearizeExprTree - Given an associative binary expression tree, traverse
170 /// all of the uses putting it into canonical form. This forces a left-linear
171 /// form of the the expression (((a+b)+c)+d), and collects information about the
172 /// rank of the non-tree operands.
174 /// This returns the rank of the RHS operand, which is known to be the highest
175 /// rank value in the expression tree.
177 void Reassociate::LinearizeExprTree(BinaryOperator *I,
178 std::vector<ValueEntry> &Ops) {
179 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
180 unsigned Opcode = I->getOpcode();
182 // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
183 BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
184 BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
188 // Neither the LHS or RHS as part of the tree, thus this is a leaf. As
189 // such, just remember these operands and their rank.
190 Ops.push_back(ValueEntry(getRank(LHS), LHS));
191 Ops.push_back(ValueEntry(getRank(RHS), RHS));
194 // Turn X+(Y+Z) -> (Y+Z)+X
195 std::swap(LHSBO, RHSBO);
197 bool Success = !I->swapOperands();
198 assert(Success && "swapOperands failed");
202 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
203 // part of the expression tree.
205 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
206 RHS = I->getOperand(1);
210 // Okay, now we know that the LHS is a nested expression and that the RHS is
211 // not. Perform reassociation.
212 assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
214 // Move LHS right before I to make sure that the tree expression dominates all
216 I->getParent()->getInstList().splice(I,
217 LHSBO->getParent()->getInstList(), LHSBO);
219 // Linearize the expression tree on the LHS.
220 LinearizeExprTree(LHSBO, Ops);
222 // Remember the RHS operand and its rank.
223 Ops.push_back(ValueEntry(getRank(RHS), RHS));
226 // RewriteExprTree - Now that the operands for this expression tree are
227 // linearized and optimized, emit them in-order. This function is written to be
229 void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
230 std::vector<ValueEntry> &Ops) {
231 if (i+2 == Ops.size()) {
232 if (I->getOperand(0) != Ops[i].Op ||
233 I->getOperand(1) != Ops[i+1].Op) {
234 DEBUG(std::cerr << "RA: " << *I);
235 I->setOperand(0, Ops[i].Op);
236 I->setOperand(1, Ops[i+1].Op);
237 DEBUG(std::cerr << "TO: " << *I);
243 assert(i+2 < Ops.size() && "Ops index out of range!");
245 if (I->getOperand(1) != Ops[i].Op) {
246 DEBUG(std::cerr << "RA: " << *I);
247 I->setOperand(1, Ops[i].Op);
248 DEBUG(std::cerr << "TO: " << *I);
252 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
257 // NegateValue - Insert instructions before the instruction pointed to by BI,
258 // that computes the negative version of the value specified. The negative
259 // version of the value is returned, and BI is left pointing at the instruction
260 // that should be processed next by the reassociation pass.
262 static Value *NegateValue(Value *V, Instruction *BI) {
263 // We are trying to expose opportunity for reassociation. One of the things
264 // that we want to do to achieve this is to push a negation as deep into an
265 // expression chain as possible, to expose the add instructions. In practice,
266 // this means that we turn this:
267 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
268 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
269 // the constants. We assume that instcombine will clean up the mess later if
270 // we introduce tons of unnecessary negation instructions...
272 if (Instruction *I = dyn_cast<Instruction>(V))
273 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
274 Value *RHS = NegateValue(I->getOperand(1), BI);
275 Value *LHS = NegateValue(I->getOperand(0), BI);
277 // We must actually insert a new add instruction here, because the neg
278 // instructions do not dominate the old add instruction in general. By
279 // adding it now, we are assured that the neg instructions we just
280 // inserted dominate the instruction we are about to insert after them.
282 return BinaryOperator::create(Instruction::Add, LHS, RHS,
283 I->getName()+".neg", BI);
286 // Insert a 'neg' instruction that subtracts the value from zero to get the
289 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
292 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
293 /// only used by an add, transform this into (X+(0-Y)) to promote better
295 static Instruction *BreakUpSubtract(Instruction *Sub) {
296 // Reject cases where it is pointless to do this.
297 if (Sub->getType()->isFloatingPoint())
298 return 0; // Floating point adds are not associative.
300 // Don't bother to break this up unless either the LHS is an associable add or
301 // if this is only used by one.
302 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
303 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
304 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
307 // Convert a subtract into an add and a neg instruction... so that sub
308 // instructions can be commuted with other add instructions...
310 // Calculate the negative value of Operand 1 of the sub instruction...
311 // and set it as the RHS of the add instruction we just made...
313 std::string Name = Sub->getName();
315 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
317 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
319 // Everyone now refers to the add instruction.
320 Sub->replaceAllUsesWith(New);
321 Sub->eraseFromParent();
323 DEBUG(std::cerr << "Negated: " << *New);
327 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
328 /// by one, change this into a multiply by a constant to assist with further
330 static Instruction *ConvertShiftToMul(Instruction *Shl) {
331 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
332 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
335 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
336 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
338 std::string Name = Shl->getName(); Shl->setName("");
339 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
341 Shl->replaceAllUsesWith(Mul);
342 Shl->eraseFromParent();
347 /// ReassociateBB - Inspect all of the instructions in this basic block,
348 /// reassociating them as we go.
349 void Reassociate::ReassociateBB(BasicBlock *BB) {
350 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
351 // If this is a subtract instruction which is not already in negate form,
352 // see if we can convert it to X+-Y.
353 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
354 if (Instruction *NI = BreakUpSubtract(BI)) {
358 if (BI->getOpcode() == Instruction::Shl &&
359 isa<ConstantInt>(BI->getOperand(1)))
360 if (Instruction *NI = ConvertShiftToMul(BI)) {
365 // If this instruction is a commutative binary operator, process it.
366 if (!BI->isAssociative()) continue;
367 BinaryOperator *I = cast<BinaryOperator>(BI);
369 // If this is an interior node of a reassociable tree, ignore it until we
370 // get to the root of the tree, to avoid N^2 analysis.
371 if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
374 // First, walk the expression tree, linearizing the tree, collecting
375 std::vector<ValueEntry> Ops;
376 LinearizeExprTree(I, Ops);
378 // Now that we have linearized the tree to a list and have gathered all of
379 // the operands and their ranks, sort the operands by their rank. Use a
380 // stable_sort so that values with equal ranks will have their relative
381 // positions maintained (and so the compiler is deterministic). Note that
382 // this sorts so that the highest ranking values end up at the beginning of
384 std::stable_sort(Ops.begin(), Ops.end());
386 // Now that we have the linearized expression tree, try to optimize it.
387 // Start by folding any constants that we found.
390 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
391 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
393 Ops.back().Op = ConstantExpr::get(I->getOpcode(), V1, V2);
397 // Check for destructive annihilation due to a constant being used.
398 if (Ops.size() != 1) { // Nothing to annihilate?
399 if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
400 switch (I->getOpcode()) {
402 case Instruction::And:
403 if (CstVal->isNullValue()) { // ... & 0 -> 0
405 Ops.erase(Ops.begin()+1, Ops.end());
406 } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
410 case Instruction::Mul:
411 if (CstVal->isNullValue()) { // ... * 0 -> 0
413 Ops.erase(Ops.begin()+1, Ops.end());
414 } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
415 Ops.pop_back(); // ... * 1 -> ...
418 case Instruction::Or:
419 if (CstVal->isAllOnesValue()) { // ... | -1 -> -1
421 Ops.erase(Ops.begin()+1, Ops.end());
424 case Instruction::Add:
425 case Instruction::Xor:
426 if (CstVal->isNullValue()) // ... [|^+] 0 -> ...
432 if (Ops.size() == 1) {
433 // This expression tree simplified to something that isn't a tree,
435 I->replaceAllUsesWith(Ops[0].Op);
437 // Now that we ordered and optimized the expressions, splat them back into
438 // the expression tree, removing any unneeded nodes.
439 RewriteExprTree(I, 0, Ops);
445 bool Reassociate::runOnFunction(Function &F) {
446 // Recalculate the rank map for F
450 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
453 // We are done with the rank map...
455 ValueRankMap.clear();