Minor changes:
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2 //
3 // This pass reassociates commutative expressions in an order that is designed
4 // to promote better constant propogation, GCSE, LICM, PRE...
5 //
6 // For example: 4 + (x + 5) -> x + (4 + 5)
7 //
8 // Note that this pass works best if left shifts have been promoted to explicit
9 // multiplies before this pass executes.
10 //
11 // In the implementation of this algorithm, constants are assigned rank = 0,
12 // function arguments are rank = 1, and other values are assigned ranks
13 // corresponding to the reverse post order traversal of current function
14 // (starting at 2), which effectively gives values in deep loops higher rank
15 // than values not in loops.
16 //
17 // This code was originally written by Chris Lattner, and was then cleaned up
18 // and perfected by Casey Carter.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Function.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/Type.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Constant.h"
28 #include "llvm/Support/CFG.h"
29 #include "Support/PostOrderIterator.h"
30 #include "Support/Statistic.h"
31
32 namespace {
33   Statistic<> NumLinear ("reassociate","Number of insts linearized");
34   Statistic<> NumChanged("reassociate","Number of insts reassociated");
35   Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
36
37   class Reassociate : public FunctionPass {
38     std::map<BasicBlock*, unsigned> RankMap;
39   public:
40     bool runOnFunction(Function &F);
41
42     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43       AU.setPreservesCFG();
44     }
45   private:
46     void BuildRankMap(Function &F);
47     unsigned getRank(Value *V);
48     bool ReassociateExpr(BinaryOperator *I);
49     bool ReassociateBB(BasicBlock *BB);
50   };
51
52   RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
53 }
54
55 Pass *createReassociatePass() { return new Reassociate(); }
56
57 void Reassociate::BuildRankMap(Function &F) {
58   unsigned i = 1;
59   ReversePostOrderTraversal<Function*> RPOT(&F);
60   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
61          E = RPOT.end(); I != E; ++I)
62     RankMap[*I] = ++i;
63 }
64
65 unsigned Reassociate::getRank(Value *V) {
66   if (isa<Argument>(V)) return 1;   // Function argument...
67   if (Instruction *I = dyn_cast<Instruction>(V)) {
68     // If this is an expression, return the MAX(rank(LHS), rank(RHS)) so that we
69     // can reassociate expressions for code motion!  Since we do not recurse for
70     // PHI nodes, we cannot have infinite recursion here, because there cannot
71     // be loops in the value graph that do not go through PHI nodes.
72     //
73     if (I->getOpcode() == Instruction::PHINode ||
74         I->getOpcode() == Instruction::Alloca ||
75         I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
76         I->hasSideEffects())
77       return RankMap[I->getParent()];
78
79     unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
80     for (unsigned i = 0, e = I->getNumOperands();
81          i != e && Rank != MaxRank; ++i)
82       Rank = std::max(Rank, getRank(I->getOperand(i)));
83
84     return Rank;
85   }
86
87   // Otherwise it's a global or constant, rank 0.
88   return 0;
89 }
90
91
92 bool Reassociate::ReassociateExpr(BinaryOperator *I) {
93   Value *LHS = I->getOperand(0);
94   Value *RHS = I->getOperand(1);
95   unsigned LHSRank = getRank(LHS);
96   unsigned RHSRank = getRank(RHS);
97   
98   bool Changed = false;
99
100   // Make sure the LHS of the operand always has the greater rank...
101   if (LHSRank < RHSRank) {
102     bool Success = !I->swapOperands();
103     assert(Success && "swapOperands failed");
104
105     std::swap(LHS, RHS);
106     std::swap(LHSRank, RHSRank);
107     Changed = true;
108     ++NumSwapped;
109     DEBUG(std::cerr << "Transposed: " << I
110           /* << " Result BB: " << I->getParent()*/);
111   }
112   
113   // If the LHS is the same operator as the current one is, and if we are the
114   // only expression using it...
115   //
116   if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
117     if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) {
118       // If the rank of our current RHS is less than the rank of the LHS's LHS,
119       // then we reassociate the two instructions...
120       if (RHSRank < getRank(LHSI->getOperand(0))) {
121         unsigned TakeOp = 0;
122         if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
123           if (IOp->getOpcode() == LHSI->getOpcode())
124             TakeOp = 1;   // Hoist out non-tree portion
125
126         // Convert ((a + 12) + 10) into (a + (12 + 10))
127         I->setOperand(0, LHSI->getOperand(TakeOp));
128         LHSI->setOperand(TakeOp, RHS);
129         I->setOperand(1, LHSI);
130
131         // Move the LHS expression forward, to ensure that it is dominated by
132         // its operands.
133         LHSI->getParent()->getInstList().remove(LHSI);
134         I->getParent()->getInstList().insert(I, LHSI);
135
136         ++NumChanged;
137         DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: "
138                                                    << I->getParent()*/);
139
140         // Since we modified the RHS instruction, make sure that we recheck it.
141         ReassociateExpr(LHSI);
142         return true;
143       }
144     }
145
146   return Changed;
147 }
148
149
150 // NegateValue - Insert instructions before the instruction pointed to by BI,
151 // that computes the negative version of the value specified.  The negative
152 // version of the value is returned, and BI is left pointing at the instruction
153 // that should be processed next by the reassociation pass.
154 //
155 static Value *NegateValue(Value *V, BasicBlock::iterator &BI) {
156   // We are trying to expose opportunity for reassociation.  One of the things
157   // that we want to do to achieve this is to push a negation as deep into an
158   // expression chain as possible, to expose the add instructions.  In practice,
159   // this means that we turn this:
160   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
161   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
162   // the constants.  We assume that instcombine will clean up the mess later if
163   // we introduce tons of unneccesary negation instructions...
164   //
165   if (Instruction *I = dyn_cast<Instruction>(V))
166     if (I->getOpcode() == Instruction::Add && I->use_size() == 1) {
167       Value *RHS = NegateValue(I->getOperand(1), BI);
168       Value *LHS = NegateValue(I->getOperand(0), BI);
169
170       // We must actually insert a new add instruction here, because the neg
171       // instructions do not dominate the old add instruction in general.  By
172       // adding it now, we are assured that the neg instructions we just
173       // inserted dominate the instruction we are about to insert after them.
174       //
175       return BinaryOperator::create(Instruction::Add, LHS, RHS,
176                                     I->getName()+".neg",
177                                     cast<Instruction>(RHS)->getNext());
178     }
179
180   // Insert a 'neg' instruction that subtracts the value from zero to get the
181   // negation.
182   //
183   return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
184 }
185
186
187 bool Reassociate::ReassociateBB(BasicBlock *BB) {
188   bool Changed = false;
189   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
190
191     DEBUG(std::cerr << "Processing: " << *BI);
192     if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) {
193       // Convert a subtract into an add and a neg instruction... so that sub
194       // instructions can be commuted with other add instructions...
195       //
196       // Calculate the negative value of Operand 1 of the sub instruction...
197       // and set it as the RHS of the add instruction we just made...
198       //
199       std::string Name = BI->getName();
200       BI->setName("");
201       Instruction *New =
202         BinaryOperator::create(Instruction::Add, BI->getOperand(0),
203                                BI->getOperand(1), Name, BI);
204
205       // Everyone now refers to the add instruction...
206       BI->replaceAllUsesWith(New);
207
208       // Put the new add in the place of the subtract... deleting the subtract
209       BB->getInstList().erase(BI);
210
211       BI = New;
212       New->setOperand(1, NegateValue(New->getOperand(1), BI));
213       
214       Changed = true;
215       DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/);
216     }
217
218     // If this instruction is a commutative binary operator, and the ranks of
219     // the two operands are sorted incorrectly, fix it now.
220     //
221     if (BI->isAssociative()) {
222       BinaryOperator *I = cast<BinaryOperator>(&*BI);
223       if (!I->use_empty()) {
224         // Make sure that we don't have a tree-shaped computation.  If we do,
225         // linearize it.  Convert (A+B)+(C+D) into ((A+B)+C)+D
226         //
227         Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
228         Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
229         if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
230             RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
231             RHSI->use_size() == 1) {
232           // Insert a new temporary instruction... (A+B)+C
233           BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
234                                                        RHSI->getOperand(0),
235                                                        RHSI->getName()+".ra",
236                                                        BI);
237           BI = Tmp;
238           I->setOperand(0, Tmp);
239           I->setOperand(1, RHSI->getOperand(1));
240
241           // Process the temporary instruction for reassociation now.
242           I = Tmp;
243           ++NumLinear;
244           Changed = true;
245           DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/);
246         }
247
248         // Make sure that this expression is correctly reassociated with respect
249         // to it's used values...
250         //
251         Changed |= ReassociateExpr(I);
252       }
253     }
254   }
255
256   return Changed;
257 }
258
259
260 bool Reassociate::runOnFunction(Function &F) {
261   // Recalculate the rank map for F
262   BuildRankMap(F);
263
264   bool Changed = false;
265   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
266     Changed |= ReassociateBB(FI);
267
268   // We are done with the rank map...
269   RankMap.clear();
270   return Changed;
271 }