Handle some simple cases where we can see that values get annihilated.
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass reassociates commutative expressions in an order that is designed
11 // to promote better constant propagation, GCSE, LICM, PRE...
12 //
13 // For example: 4 + (x + 5) -> x + (4 + 5)
14 //
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.
20 //
21 //===----------------------------------------------------------------------===//
22
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"
34 #include <algorithm>
35 using namespace llvm;
36
37 namespace {
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");
41
42   struct ValueEntry {
43     unsigned Rank;
44     Value *Op;
45     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
46   };
47   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
48     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
49   }
50
51   class Reassociate : public FunctionPass {
52     std::map<BasicBlock*, unsigned> RankMap;
53     std::map<Value*, unsigned> ValueRankMap;
54     bool MadeChange;
55   public:
56     bool runOnFunction(Function &F);
57
58     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59       AU.setPreservesCFG();
60     }
61   private:
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);
69   };
70
71   RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
72 }
73
74 // Public interface to the Reassociate pass
75 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
76
77 void Reassociate::BuildRankMap(Function &F) {
78   unsigned i = 2;
79
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;
83
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;
88 }
89
90 unsigned Reassociate::getRank(Value *V) {
91   if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
92
93   Instruction *I = dyn_cast<Instruction>(V);
94   if (I == 0) return 0;  // Otherwise it's a global or constant, rank 0.
95
96   unsigned &CachedRank = ValueRankMap[I];
97   if (CachedRank) return CachedRank;    // Rank already known?
98   
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.
103   //
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()];
109   
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)));
115   
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)))
120     ++Rank;
121
122   DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
123         << Rank << "\n");
124   
125   return CachedRank = Rank;
126 }
127
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);
134   return 0;
135 }
136
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
140 // C.
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?");
147
148   DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
149
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);
153
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);
158   
159   ++NumLinear;
160   MadeChange = true;
161   DEBUG(std::cerr << "Linearized: " << *I);
162
163   // If D is part of this expression tree, tail recurse.
164   if (isReassociableOp(I->getOperand(1), I->getOpcode()))
165     LinearizeExpr(I);
166 }
167
168
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.
173 ///
174 /// This returns the rank of the RHS operand, which is known to be the highest
175 /// rank value in the expression tree.
176 ///
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();
181
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);
185
186   if (!LHSBO) {
187     if (!RHSBO) {
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));
192       return;
193     } else {
194       // Turn X+(Y+Z) -> (Y+Z)+X
195       std::swap(LHSBO, RHSBO);
196       std::swap(LHS, RHS);
197       bool Success = !I->swapOperands();
198       assert(Success && "swapOperands failed");
199       MadeChange = true;
200     }
201   } else if (RHSBO) {
202     // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the the RHS is not
203     // part of the expression tree.
204     LinearizeExpr(I);
205     LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
206     RHS = I->getOperand(1);
207     RHSBO = 0;
208   }
209
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!");
213
214   // Move LHS right before I to make sure that the tree expression dominates all
215   // values.
216   I->getParent()->getInstList().splice(I,
217                                       LHSBO->getParent()->getInstList(), LHSBO);
218
219   // Linearize the expression tree on the LHS.
220   LinearizeExprTree(LHSBO, Ops);
221
222   // Remember the RHS operand and its rank.
223   Ops.push_back(ValueEntry(getRank(RHS), RHS));
224 }
225
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
228 // tail recursive.
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);
238       MadeChange = true;
239       ++NumChanged;
240     }
241     return;
242   }
243   assert(i+2 < Ops.size() && "Ops index out of range!");
244
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);
249     MadeChange = true;
250     ++NumChanged;
251   }
252   RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
253 }
254
255
256
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.
261 //
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...
271   //
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);
276
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.
281       //
282       return BinaryOperator::create(Instruction::Add, LHS, RHS,
283                                     I->getName()+".neg", BI);
284     }
285
286   // Insert a 'neg' instruction that subtracts the value from zero to get the
287   // negation.
288   //
289   return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
290 }
291
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
294 /// reassociation.
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.
299
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)))
305     return 0;
306
307   // Convert a subtract into an add and a neg instruction... so that sub
308   // instructions can be commuted with other add instructions...
309   //
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...
312   //
313   std::string Name = Sub->getName();
314   Sub->setName("");
315   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
316   Instruction *New =
317     BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
318
319   // Everyone now refers to the add instruction.
320   Sub->replaceAllUsesWith(New);
321   Sub->eraseFromParent();
322   
323   DEBUG(std::cerr << "Negated: " << *New);
324   return New;
325 }
326
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
329 /// reassociation.
330 static Instruction *ConvertShiftToMul(Instruction *Shl) {
331   if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
332       !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
333     return 0;
334
335   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
336   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
337
338   std::string Name = Shl->getName();  Shl->setName("");
339   Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
340                                                Name, Shl);
341   Shl->replaceAllUsesWith(Mul);
342   Shl->eraseFromParent();
343   return Mul;
344 }
345
346
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)) {
355         MadeChange = true;
356         BI = NI;
357       }
358     if (BI->getOpcode() == Instruction::Shl &&
359         isa<ConstantInt>(BI->getOperand(1)))
360       if (Instruction *NI = ConvertShiftToMul(BI)) {
361         MadeChange = true;
362         BI = NI;
363       }
364
365     // If this instruction is a commutative binary operator, process it.
366     if (!BI->isAssociative()) continue;
367     BinaryOperator *I = cast<BinaryOperator>(BI);
368     
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()))
372       continue;
373
374     // First, walk the expression tree, linearizing the tree, collecting 
375     std::vector<ValueEntry> Ops;
376     LinearizeExprTree(I, Ops);
377
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
383     // the vector.
384     std::stable_sort(Ops.begin(), Ops.end());
385
386     // Now that we have the linearized expression tree, try to optimize it.
387     // Start by folding any constants that we found.
388   FoldConstants:
389     if (Ops.size() > 1)
390       if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
391         if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
392           Ops.pop_back();
393           Ops.back().Op = ConstantExpr::get(I->getOpcode(), V1, V2);
394           goto FoldConstants;
395         }
396
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()) {
401         default: break;
402         case Instruction::And:
403           if (CstVal->isNullValue()) {           // ... & 0 -> 0
404             Ops[0].Op = CstVal;
405             Ops.erase(Ops.begin()+1, Ops.end());
406           } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
407             Ops.pop_back();
408           }
409           break;
410         case Instruction::Mul:
411           if (CstVal->isNullValue()) {           // ... * 0 -> 0
412             Ops[0].Op = CstVal;
413             Ops.erase(Ops.begin()+1, Ops.end());
414           } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
415             Ops.pop_back();                      // ... * 1 -> ...
416           }
417           break;
418         case Instruction::Or:
419           if (CstVal->isAllOnesValue()) {        // ... | -1 -> -1
420             Ops[0].Op = CstVal;
421             Ops.erase(Ops.begin()+1, Ops.end());
422           }
423           // FALLTHROUGH!
424         case Instruction::Add:
425         case Instruction::Xor:
426           if (CstVal->isNullValue())             // ... [|^+] 0 -> ...
427             Ops.pop_back();
428           break;
429         }
430     }
431
432     if (Ops.size() == 1) {
433       // This expression tree simplified to something that isn't a tree,
434       // eliminate it.
435       I->replaceAllUsesWith(Ops[0].Op);
436     } else {
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);
440     }
441   }
442 }
443
444
445 bool Reassociate::runOnFunction(Function &F) {
446   // Recalculate the rank map for F
447   BuildRankMap(F);
448
449   MadeChange = false;
450   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
451     ReassociateBB(FI);
452
453   // We are done with the rank map...
454   RankMap.clear();
455   ValueRankMap.clear();
456   return MadeChange;
457 }
458