Refactor some code
[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 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);
70   };
71
72   RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
73 }
74
75 // Public interface to the Reassociate pass
76 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
77
78 void Reassociate::BuildRankMap(Function &F) {
79   unsigned i = 2;
80
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;
84
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;
89 }
90
91 unsigned Reassociate::getRank(Value *V) {
92   if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
93
94   Instruction *I = dyn_cast<Instruction>(V);
95   if (I == 0) return 0;  // Otherwise it's a global or constant, rank 0.
96
97   unsigned &CachedRank = ValueRankMap[I];
98   if (CachedRank) return CachedRank;    // Rank already known?
99   
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.
104   //
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()];
110   
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)));
116   
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)))
121     ++Rank;
122
123   DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
124         << Rank << "\n");
125   
126   return CachedRank = Rank;
127 }
128
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);
135   return 0;
136 }
137
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
141 // C.
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?");
148
149   DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
150
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);
154
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);
159   
160   ++NumLinear;
161   MadeChange = true;
162   DEBUG(std::cerr << "Linearized: " << *I);
163
164   // If D is part of this expression tree, tail recurse.
165   if (isReassociableOp(I->getOperand(1), I->getOpcode()))
166     LinearizeExpr(I);
167 }
168
169
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.
174 ///
175 /// This returns the rank of the RHS operand, which is known to be the highest
176 /// rank value in the expression tree.
177 ///
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();
182
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);
186
187   if (!LHSBO) {
188     if (!RHSBO) {
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));
193       return;
194     } else {
195       // Turn X+(Y+Z) -> (Y+Z)+X
196       std::swap(LHSBO, RHSBO);
197       std::swap(LHS, RHS);
198       bool Success = !I->swapOperands();
199       assert(Success && "swapOperands failed");
200       MadeChange = true;
201     }
202   } else if (RHSBO) {
203     // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the the RHS is not
204     // part of the expression tree.
205     LinearizeExpr(I);
206     LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
207     RHS = I->getOperand(1);
208     RHSBO = 0;
209   }
210
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!");
214
215   // Move LHS right before I to make sure that the tree expression dominates all
216   // values.
217   I->getParent()->getInstList().splice(I,
218                                       LHSBO->getParent()->getInstList(), LHSBO);
219
220   // Linearize the expression tree on the LHS.
221   LinearizeExprTree(LHSBO, Ops);
222
223   // Remember the RHS operand and its rank.
224   Ops.push_back(ValueEntry(getRank(RHS), RHS));
225 }
226
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
229 // tail recursive.
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);
239       MadeChange = true;
240       ++NumChanged;
241     }
242     return;
243   }
244   assert(i+2 < Ops.size() && "Ops index out of range!");
245
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);
250     MadeChange = true;
251     ++NumChanged;
252   }
253   RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
254 }
255
256
257
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.
262 //
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...
272   //
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);
277
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.
282       //
283       return BinaryOperator::create(Instruction::Add, LHS, RHS,
284                                     I->getName()+".neg", BI);
285     }
286
287   // Insert a 'neg' instruction that subtracts the value from zero to get the
288   // negation.
289   //
290   return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
291 }
292
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
295 /// reassociation.
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.
300
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)))
306     return 0;
307
308   // Convert a subtract into an add and a neg instruction... so that sub
309   // instructions can be commuted with other add instructions...
310   //
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...
313   //
314   std::string Name = Sub->getName();
315   Sub->setName("");
316   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
317   Instruction *New =
318     BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
319
320   // Everyone now refers to the add instruction.
321   Sub->replaceAllUsesWith(New);
322   Sub->eraseFromParent();
323   
324   DEBUG(std::cerr << "Negated: " << *New);
325   return New;
326 }
327
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
330 /// reassociation.
331 static Instruction *ConvertShiftToMul(Instruction *Shl) {
332   if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
333       !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
334     return 0;
335
336   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
337   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
338
339   std::string Name = Shl->getName();  Shl->setName("");
340   Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
341                                                Name, Shl);
342   Shl->replaceAllUsesWith(Mul);
343   Shl->eraseFromParent();
344   return Mul;
345 }
346
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.
351  FoldConstants:
352   if (Ops.size() == 1) return;
353
354   if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
355     if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
356       Ops.pop_back();
357       Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
358       goto FoldConstants;
359     }
360
361   // Check for destructive annihilation due to a constant being used.
362   if (ConstantIntegral *CstVal = dyn_cast<ConstantIntegral>(Ops.back().Op))
363     switch (Opcode) {
364     default: break;
365     case Instruction::And:
366       if (CstVal->isNullValue()) {           // ... & 0 -> 0
367         Ops[0].Op = CstVal;
368         Ops.erase(Ops.begin()+1, Ops.end());
369       } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
370         Ops.pop_back();
371       }
372       break;
373     case Instruction::Mul:
374       if (CstVal->isNullValue()) {           // ... * 0 -> 0
375         Ops[0].Op = CstVal;
376         Ops.erase(Ops.begin()+1, Ops.end());
377       } else if (cast<ConstantInt>(CstVal)->getRawValue() == 1) {
378         Ops.pop_back();                      // ... * 1 -> ...
379       }
380       break;
381     case Instruction::Or:
382       if (CstVal->isAllOnesValue()) {        // ... | -1 -> -1
383         Ops[0].Op = CstVal;
384         Ops.erase(Ops.begin()+1, Ops.end());
385       }
386       // FALLTHROUGH!
387     case Instruction::Add:
388     case Instruction::Xor:
389       if (CstVal->isNullValue())             // ... [|^+] 0 -> ...
390         Ops.pop_back();
391       break;
392     }
393
394   // Handle destructive annihilation do to identities between elements in the
395   // argument list here.
396 }
397
398
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)) {
407         MadeChange = true;
408         BI = NI;
409       }
410     if (BI->getOpcode() == Instruction::Shl &&
411         isa<ConstantInt>(BI->getOperand(1)))
412       if (Instruction *NI = ConvertShiftToMul(BI)) {
413         MadeChange = true;
414         BI = NI;
415       }
416
417     // If this instruction is a commutative binary operator, process it.
418     if (!BI->isAssociative()) continue;
419     BinaryOperator *I = cast<BinaryOperator>(BI);
420     
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()))
424       continue;
425
426     // First, walk the expression tree, linearizing the tree, collecting 
427     std::vector<ValueEntry> Ops;
428     LinearizeExprTree(I, Ops);
429
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
435     // the vector.
436     std::stable_sort(Ops.begin(), Ops.end());
437
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);
441
442     if (Ops.size() == 1) {
443       // This expression tree simplified to something that isn't a tree,
444       // eliminate it.
445       I->replaceAllUsesWith(Ops[0].Op);
446     } else {
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);
450     }
451   }
452 }
453
454
455 bool Reassociate::runOnFunction(Function &F) {
456   // Recalculate the rank map for F
457   BuildRankMap(F);
458
459   MadeChange = false;
460   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
461     ReassociateBB(FI);
462
463   // We are done with the rank map...
464   RankMap.clear();
465   ValueRankMap.clear();
466   return MadeChange;
467 }
468