Broad superficial changes:
[oota-llvm.git] / lib / Transforms / Scalar / SCCP.cpp
1 //===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===//
2 //
3 // This file implements sparse conditional constant propogation and merging:
4 //
5 // Specifically, this:
6 //   * Assumes values are constant unless proven otherwise
7 //   * Assumes BasicBlocks are dead unless proven otherwise
8 //   * Proves values to be constant, and replaces them with constants
9 //   . Proves conditional branches constant, and unconditionalizes them
10 //   * Folds multiple identical constants in the constant pool together
11 //
12 // Notice that:
13 //   * This pass has a habit of making definitions be dead.  It is a good idea
14 //     to to run a DCE pass sometime after running this pass.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Optimizations/ConstantProp.h"
19 #include "llvm/Optimizations/ConstantHandling.h"
20 #include "llvm/Method.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/ConstPoolVals.h"
23 #include "llvm/ConstantPool.h"
24 #include "llvm/InstrTypes.h"
25 #include "llvm/iOther.h"
26 #include "llvm/iTerminators.h"
27 #include "llvm/Tools/STLExtras.h"
28 //#include "llvm/Assembly/Writer.h"
29 #include <algorithm>
30 #include <map>
31 #include <set>
32
33 // InstVal class - This class represents the different lattice values that an 
34 // instruction may occupy.  It is a simple class with value semantics.  The
35 // potential constant value that is pointed to is owned by the constant pool
36 // for the method being optimized.
37 //
38 class InstVal {
39   enum { 
40     Undefined,           // This instruction has no known value
41     Constant,            // This instruction has a constant value
42     // Range,            // This instruction is known to fall within a range
43     Overdefined          // This instruction has an unknown value
44   } LatticeValue;    // The current lattice position
45   ConstPoolVal *ConstantVal;     // If Constant value, the current value
46 public:
47   inline InstVal() : LatticeValue(Undefined), ConstantVal(0) {}
48
49   // markOverdefined - Return true if this is a new status to be in...
50   inline bool markOverdefined() {
51     if (LatticeValue != Overdefined) {
52       LatticeValue = Overdefined;
53       return true;
54     }
55     return false;
56   }
57
58   // markConstant - Return true if this is a new status for us...
59   inline bool markConstant(ConstPoolVal *V) {
60     if (LatticeValue != Constant) {
61       LatticeValue = Constant;
62       ConstantVal = V;
63       return true;
64     } else {
65       assert(ConstantVal->equals(V) && "Marking constant with different value");
66     }
67     return false;
68   }
69
70   inline bool isUndefined()   const { return LatticeValue == Undefined; }
71   inline bool isConstant()    const { return LatticeValue == Constant; }
72   inline bool isOverdefined() const { return LatticeValue == Overdefined; }
73
74   inline ConstPoolVal *getConstant() const { return ConstantVal; }
75 };
76
77
78
79 //===----------------------------------------------------------------------===//
80 // SCCP Class
81 //
82 // This class does all of the work of Sparse Conditional Constant Propogation.
83 // It's public interface consists of a constructor and a doSCCP() method.
84 //
85 class SCCP {
86   Method *M;                            // The method that we are working on...
87
88   set<BasicBlock*>       BBExecutable;  // The basic blocks that are executable
89   map<Value*, InstVal>   ValueState;    // The state each value is in...
90
91   vector<Instruction*>   InstWorkList;  // The instruction work list
92   vector<BasicBlock*>    BBWorkList;    // The BasicBlock work list
93
94   //===--------------------------------------------------------------------===//
95   // The public interface for this class
96   //
97 public:
98
99   // SCCP Ctor - Save the method to operate on...
100   inline SCCP(Method *m) : M(m) {}
101
102   // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 
103   // return true if the method was modified.
104   bool doSCCP();
105
106   //===--------------------------------------------------------------------===//
107   // The implementation of this class
108   //
109 private:
110
111   // markValueOverdefined - Make a value be marked as "constant".  If the value
112   // is not already a constant, add it to the instruction work list so that 
113   // the users of the instruction are updated later.
114   //
115   inline bool markConstant(Instruction *I, ConstPoolVal *V) {
116     //cerr << "markConstant: " << V << " = " << I;
117     if (ValueState[I].markConstant(V)) {
118       InstWorkList.push_back(I);
119       return true;
120     }
121     return false;
122   }
123
124   // markValueOverdefined - Make a value be marked as "overdefined". If the
125   // value is not already overdefined, add it to the instruction work list so
126   // that the users of the instruction are updated later.
127   //
128   inline bool markOverdefined(Value *V) {
129     if (ValueState[V].markOverdefined()) {
130       if (Instruction *I = V->castInstruction()) {
131         //cerr << "markOverdefined: " << V;
132         InstWorkList.push_back(I);  // Only instructions go on the work list
133       }
134       return true;
135     }
136     return false;
137   }
138
139   // getValueState - Return the InstVal object that corresponds to the value.
140   // This function is neccesary because not all values should start out in the
141   // underdefined state... MethodArgument's should be overdefined, and constants
142   // should be marked as constants.  If a value is not known to be an
143   // Instruction object, then use this accessor to get its value from the map.
144   //
145   inline InstVal &getValueState(Value *V) {
146     map<Value*, InstVal>::iterator I = ValueState.find(V);
147     if (I != ValueState.end()) return I->second;  // Common case, in the map
148       
149     if (ConstPoolVal *CPV = V->castConstant()) {  // Constants are constant
150       ValueState[CPV].markConstant(CPV);
151     } else if (V->isMethodArgument()) {           // MethodArgs are overdefined
152       ValueState[V].markOverdefined();
153     } 
154     // All others are underdefined by default...
155     return ValueState[V];
156   }
157
158   // markExecutable - Mark a basic block as executable, adding it to the BB 
159   // work list if it is not already executable...
160   // 
161   void markExecutable(BasicBlock *BB) {
162     if (BBExecutable.count(BB)) return;
163     //cerr << "Marking BB Executable: " << BB;
164     BBExecutable.insert(BB);   // Basic block is executable!
165     BBWorkList.push_back(BB);  // Add the block to the work list!
166   }
167
168
169   // UpdateInstruction - Something changed in this instruction... Either an 
170   // operand made a transition, or the instruction is newly executable.  Change
171   // the value type of I to reflect these changes if appropriate.
172   //
173   void UpdateInstruction(Instruction *I);
174
175   // OperandChangedState - This method is invoked on all of the users of an
176   // instruction that was just changed state somehow....  Based on this
177   // information, we need to update the specified user of this instruction.
178   //
179   void OperandChangedState(User *U);
180 };
181
182
183 //===----------------------------------------------------------------------===//
184 // SCCP Class Implementation
185
186
187 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 
188 // return true if the method was modified.
189 //
190 bool SCCP::doSCCP() {
191   // Mark the first block of the method as being executable...
192   markExecutable(M->front());
193
194   // Process the work lists until their are empty!
195   while (!BBWorkList.empty() || !InstWorkList.empty()) {
196     // Process the instruction work list...
197     while (!InstWorkList.empty()) {
198       Instruction *I = InstWorkList.back();
199       InstWorkList.pop_back();
200
201       //cerr << "\nPopped off I-WL: " << I;
202
203       
204       // "I" got into the work list because it either made the transition from
205       // bottom to constant, or to Overdefined.
206       //
207       // Update all of the users of this instruction's value...
208       //
209       for_each(I->use_begin(), I->use_end(),
210                bind_obj(this, &SCCP::OperandChangedState));
211     }
212
213     // Process the basic block work list...
214     while (!BBWorkList.empty()) {
215       BasicBlock *BB = BBWorkList.back();
216       BBWorkList.pop_back();
217
218       //cerr << "\nPopped off BBWL: " << BB;
219
220       // If this block only has a single successor, mark it as executable as
221       // well... if not, terminate the do loop.
222       //
223       if (BB->getTerminator()->getNumSuccessors() == 1)
224         markExecutable(BB->getTerminator()->getSuccessor(0));
225
226       // Loop over all of the instructions and notify them that they are newly
227       // executable...
228       for_each(BB->begin(), BB->end(),
229                bind_obj(this, &SCCP::UpdateInstruction));
230     }
231   }
232
233 #if 0
234   for (Method::iterator BBI = M->begin(), BBEnd = M->end(); BBI != BBEnd; ++BBI)
235     if (!BBExecutable.count(*BBI))
236       cerr << "BasicBlock Dead:" << *BBI;
237 #endif
238
239
240   // Iterate over all of the instructions in a method, replacing them with
241   // constants if we have found them to be of constant values.
242   //
243   bool MadeChanges = false;
244   for (Method::inst_iterator II = M->inst_begin(); II != M->inst_end(); ) {
245     Instruction *Inst = *II;
246     InstVal &IV = ValueState[Inst];
247     if (IV.isConstant()) {
248       ConstPoolVal *Const = IV.getConstant();
249       // cerr << "Constant: " << Inst << "  is: " << Const;
250       
251       // Replaces all of the uses of a variable with uses of the constant.
252       Inst->replaceAllUsesWith(Const);
253
254       // Remove the operator from the list of definitions...
255       Inst->getParent()->getInstList().remove(II.getInstructionIterator());
256       
257       // The new constant inherits the old name of the operator...
258       if (Inst->hasName() && !Const->hasName())
259         Const->setName(Inst->getName());
260   
261       // Delete the operator now...
262       delete Inst;
263
264       // Incrementing the iterator in an unchecked manner could mess up the
265       // internals of 'II'.  To make sure everything is happy, tell it we might
266       // have broken it.
267       II.resyncInstructionIterator();
268
269       // Hey, we just changed something!
270       MadeChanges = true;
271       continue;   // Skip the ++II at the end of the loop here...
272     } else if (Inst->isTerminator()) {
273       MadeChanges |= opt::ConstantFoldTerminator((TerminatorInst*)Inst);
274     }
275
276     ++II;
277   }
278
279   // Merge identical constants last: this is important because we may have just
280   // introduced constants that already exist, and we don't want to pollute later
281   // stages with extraneous constants.
282   //
283   return MadeChanges | opt::DoConstantPoolMerging(M->getConstantPool());
284 }
285
286
287 // UpdateInstruction - Something changed in this instruction... Either an 
288 // operand made a transition, or the instruction is newly executable.  Change
289 // the value type of I to reflect these changes if appropriate.  This method
290 // makes sure to do the following actions:
291 //
292 // 1. If a phi node merges two constants in, and has conflicting value coming
293 //    from different branches, or if the PHI node merges in an overdefined
294 //    value, then the PHI node becomes overdefined.
295 // 2. If a phi node merges only constants in, and they all agree on value, the
296 //    PHI node becomes a constant value equal to that.
297 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
298 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
299 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
300 // 6. If a conditional branch has a value that is constant, make the selected
301 //    destination executable
302 // 7. If a conditional branch has a value that is overdefined, make all
303 //    successors executable.
304 //
305 void SCCP::UpdateInstruction(Instruction *I) {
306   InstVal &IValue = ValueState[I];
307   if (IValue.isOverdefined())
308     return; // If already overdefined, we aren't going to effect anything
309
310   switch (I->getOpcode()) {
311     //===-----------------------------------------------------------------===//
312     // Handle PHI nodes...
313     //
314   case Instruction::PHINode: {
315     PHINode *PN = (PHINode*)I;
316     unsigned NumValues = PN->getNumIncomingValues(), i;
317     InstVal *OperandIV = 0;
318
319     // Look at all of the executable operands of the PHI node.  If any of them
320     // are overdefined, the PHI becomes overdefined as well.  If they are all
321     // constant, and they agree with each other, the PHI becomes the identical
322     // constant.  If they are constant and don't agree, the PHI is overdefined.
323     // If there are no executable operands, the PHI remains undefined.
324     //
325     for (i = 0; i < NumValues; ++i) {
326       if (BBExecutable.count(PN->getIncomingBlock(i))) {
327         InstVal &IV = getValueState(PN->getIncomingValue(i));
328         if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
329         if (IV.isOverdefined()) {   // PHI node becomes overdefined!
330           markOverdefined(PN);
331           return;
332         }
333
334         if (OperandIV == 0) {   // Grab the first value...
335           OperandIV = &IV;
336         } else {                // Another value is being merged in!
337           // There is already a reachable operand.  If we conflict with it,
338           // then the PHI node becomes overdefined.  If we agree with it, we
339           // can continue on.
340           
341           // Check to see if there are two different constants merging...
342           if (!IV.getConstant()->equals(OperandIV->getConstant())) {
343             // Yes there is.  This means the PHI node is not constant.
344             // You must be overdefined poor PHI.
345             //
346             markOverdefined(I);         // The PHI node now becomes overdefined
347             return;    // I'm done analyzing you
348           }
349         }
350       }
351     }
352
353     // If we exited the loop, this means that the PHI node only has constant
354     // arguments that agree with each other(and OperandIV is a pointer to one
355     // of their InstVal's) or OperandIV is null because there are no defined
356     // incoming arguments.  If this is the case, the PHI remains undefined.
357     //
358     if (OperandIV) {
359       assert(OperandIV->isConstant() && "Should only be here for constants!");
360       markConstant(I, OperandIV->getConstant());  // Aquire operand value
361     }
362     return;
363   }
364
365     //===-----------------------------------------------------------------===//
366     // Handle instructions that unconditionally provide overdefined values...
367     //
368   case Instruction::Malloc:
369   case Instruction::Free:
370   case Instruction::Alloca:
371   case Instruction::Load:
372   case Instruction::Store:
373     // TODO: getfield/putfield?
374   case Instruction::Call:
375     markOverdefined(I);          // Memory and call's are all overdefined
376     return;
377
378     //===-----------------------------------------------------------------===//
379     // Handle Terminator instructions...
380     //
381   case Instruction::Ret: return;  // Method return doesn't affect anything
382   case Instruction::Br: {        // Handle conditional branches...
383     BranchInst *BI = (BranchInst*)I;
384     if (BI->isUnconditional()) 
385       return; // Unconditional branches are already handled!
386
387     InstVal &BCValue = getValueState(BI->getCondition());
388     if (BCValue.isOverdefined()) {
389       // Overdefined condition variables mean the branch could go either way.
390       markExecutable(BI->getSuccessor(0));
391       markExecutable(BI->getSuccessor(1));
392     } else if (BCValue.isConstant()) {
393       // Constant condition variables mean the branch can only go a single way.
394       ConstPoolBool *CPB = (ConstPoolBool*)BCValue.getConstant();
395       if (CPB->getValue())       // If the branch condition is TRUE...
396         markExecutable(BI->getSuccessor(0));
397       else                       // Else if the br cond is FALSE...
398         markExecutable(BI->getSuccessor(1));
399     }
400     return;
401   }
402
403   case Instruction::Switch: {
404     SwitchInst *SI = (SwitchInst*)I;
405     InstVal &SCValue = getValueState(SI->getCondition());
406     if (SCValue.isOverdefined()) {  // Overdefined condition?  All dests are exe
407       for(unsigned i = 0; BasicBlock *Succ = SI->getSuccessor(i); ++i)
408         markExecutable(Succ);
409     } else if (SCValue.isConstant()) {
410       ConstPoolVal *CPV = SCValue.getConstant();
411       // Make sure to skip the "default value" which isn't a value
412       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
413         if (SI->getSuccessorValue(i)->equals(CPV)) {// Found the right branch...
414           markExecutable(SI->getSuccessor(i));
415           return;
416         }
417       }
418       
419       // Constant value not equal to any of the branches... must execute 
420       // default branch then...
421       markExecutable(SI->getDefaultDest());
422     }
423     return;
424   }
425
426   default: break;  // Handle math operators as groups.
427   } // end switch(I->getOpcode())
428
429   
430   //===-------------------------------------------------------------------===//
431   // Handle Unary instructions...
432   //
433   if (I->isUnaryOp()) {
434     Value *V = I->getOperand(0);
435     InstVal &VState = getValueState(V);
436     if (VState.isOverdefined()) {        // Inherit overdefinedness of operand
437       markOverdefined(I);
438     } else if (VState.isConstant()) {    // Propogate constant value
439       ConstPoolVal *Result = 
440         opt::ConstantFoldUnaryInstruction(I->getOpcode(), 
441                                           VState.getConstant());
442
443       if (Result) {
444         // This instruction constant folds!  The only problem is that the value
445         // returned is newly allocated.  Make sure to stick it into the methods
446         // constant pool...
447         M->getConstantPool().insert(Result);
448         markConstant(I, Result);
449       } else {
450         markOverdefined(I);   // Don't know how to fold this instruction.  :(
451       }
452     }
453     return;
454   }
455
456   //===-----------------------------------------------------------------===//
457   // Handle Binary instructions...
458   //
459   if (I->isBinaryOp()) {
460     Value *V1 = I->getOperand(0);
461     Value *V2 = I->getOperand(1);
462
463     InstVal &V1State = getValueState(V1);
464     InstVal &V2State = getValueState(V2);
465     if (V1State.isOverdefined() || V2State.isOverdefined()) {
466       markOverdefined(I);
467     } else if (V1State.isConstant() && V2State.isConstant()) {
468       ConstPoolVal *Result = 
469         opt::ConstantFoldBinaryInstruction(I->getOpcode(), 
470                                            V1State.getConstant(),
471                                            V2State.getConstant());
472       if (Result) {
473         // This instruction constant folds!  The only problem is that the value
474         // returned is newly allocated.  Make sure to stick it into the methods
475         // constant pool...
476         M->getConstantPool().insert(Result);
477         markConstant(I, Result);
478       } else {
479         markOverdefined(I);   // Don't know how to fold this instruction.  :(
480       }
481     }
482     return;
483   }
484   
485   // Shouldn't get here... either the switch statement or one of the group
486   // handlers should have kicked in...
487   //
488   cerr << "SCCP: Don't know how to handle: " << I;
489   markOverdefined(I);   // Just in case
490 }
491
492
493
494 // OperandChangedState - This method is invoked on all of the users of an
495 // instruction that was just changed state somehow....  Based on this
496 // information, we need to update the specified user of this instruction.
497 //
498 void SCCP::OperandChangedState(User *U) {
499   // Only instructions use other variable values!
500   Instruction *I = U->castInstructionAsserting();
501   if (!BBExecutable.count(I->getParent())) return;  // Inst not executable yet!
502
503   UpdateInstruction(I);
504 }
505
506
507 // DoSparseConditionalConstantProp - Use Sparse Conditional Constant Propogation
508 // to prove whether a value is constant and whether blocks are used.
509 //
510 bool opt::DoSCCP(Method *M) {
511   SCCP S(M);
512   return S.doSCCP();
513 }