Remove unused files: This is the old induction varaible cannonicalization
[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/Transforms/Scalar/ConstantProp.h"
19 #include "llvm/ConstantHandling.h"
20 #include "llvm/Function.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/STLExtras.h"
28 #include <algorithm>
29 #include <set>
30 #include <iostream>
31 using std::cerr;
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.
35 //
36 class InstVal {
37   enum { 
38     undefined,           // This instruction has no known value
39     constant,            // This instruction has a constant value
40     // Range,            // This instruction is known to fall within a range
41     overdefined          // This instruction has an unknown value
42   } LatticeValue;        // The current lattice position
43   Constant *ConstantVal; // If Constant value, the current value
44 public:
45   inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
46
47   // markOverdefined - Return true if this is a new status to be in...
48   inline bool markOverdefined() {
49     if (LatticeValue != overdefined) {
50       LatticeValue = overdefined;
51       return true;
52     }
53     return false;
54   }
55
56   // markConstant - Return true if this is a new status for us...
57   inline bool markConstant(Constant *V) {
58     if (LatticeValue != constant) {
59       LatticeValue = constant;
60       ConstantVal = V;
61       return true;
62     } else {
63       assert(ConstantVal == V && "Marking constant with different value");
64     }
65     return false;
66   }
67
68   inline bool isUndefined()   const { return LatticeValue == undefined; }
69   inline bool isConstant()    const { return LatticeValue == constant; }
70   inline bool isOverdefined() const { return LatticeValue == overdefined; }
71
72   inline Constant *getConstant() const { return ConstantVal; }
73 };
74
75
76
77 //===----------------------------------------------------------------------===//
78 // SCCP Class
79 //
80 // This class does all of the work of Sparse Conditional Constant Propogation.
81 // It's public interface consists of a constructor and a doSCCP() function.
82 //
83 class SCCP : public InstVisitor<SCCP> {
84   Function *M;                           // The function that we are working on
85
86   std::set<BasicBlock*>     BBExecutable;// The basic blocks that are executable
87   std::map<Value*, InstVal> ValueState;  // The state each value is in...
88
89   std::vector<Instruction*> InstWorkList;// The instruction work list
90   std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
91
92   //===--------------------------------------------------------------------===//
93   // The public interface for this class
94   //
95 public:
96
97   // SCCP Ctor - Save the function to operate on...
98   inline SCCP(Function *f) : M(f) {}
99
100   // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 
101   // return true if the function was modified.
102   bool doSCCP();
103
104   //===--------------------------------------------------------------------===//
105   // The implementation of this class
106   //
107 private:
108   friend class InstVisitor<SCCP>;        // Allow callbacks from visitor
109
110   // markValueOverdefined - Make a value be marked as "constant".  If the value
111   // is not already a constant, add it to the instruction work list so that 
112   // the users of the instruction are updated later.
113   //
114   inline bool markConstant(Instruction *I, Constant *V) {
115     //cerr << "markConstant: " << V << " = " << I;
116     if (ValueState[I].markConstant(V)) {
117       InstWorkList.push_back(I);
118       return true;
119     }
120     return false;
121   }
122
123   // markValueOverdefined - Make a value be marked as "overdefined". If the
124   // value is not already overdefined, add it to the instruction work list so
125   // that the users of the instruction are updated later.
126   //
127   inline bool markOverdefined(Value *V) {
128     if (ValueState[V].markOverdefined()) {
129       if (Instruction *I = dyn_cast<Instruction>(V)) {
130         //cerr << "markOverdefined: " << V;
131         InstWorkList.push_back(I);  // Only instructions go on the work list
132       }
133       return true;
134     }
135     return false;
136   }
137
138   // getValueState - Return the InstVal object that corresponds to the value.
139   // This function is neccesary because not all values should start out in the
140   // underdefined state... Argument's should be overdefined, and
141   // constants should be marked as constants.  If a value is not known to be an
142   // Instruction object, then use this accessor to get its value from the map.
143   //
144   inline InstVal &getValueState(Value *V) {
145     std::map<Value*, InstVal>::iterator I = ValueState.find(V);
146     if (I != ValueState.end()) return I->second;  // Common case, in the map
147       
148     if (Constant *CPV = dyn_cast<Constant>(V)) {  // Constants are constant
149       ValueState[CPV].markConstant(CPV);
150     } else if (isa<Argument>(V)) {                // Arguments are overdefined
151       ValueState[V].markOverdefined();
152     } 
153     // All others are underdefined by default...
154     return ValueState[V];
155   }
156
157   // markExecutable - Mark a basic block as executable, adding it to the BB 
158   // work list if it is not already executable...
159   // 
160   void markExecutable(BasicBlock *BB) {
161     if (BBExecutable.count(BB)) return;
162     //cerr << "Marking BB Executable: " << BB;
163     BBExecutable.insert(BB);   // Basic block is executable!
164     BBWorkList.push_back(BB);  // Add the block to the work list!
165   }
166
167
168   // visit implementations - Something changed in this instruction... Either an 
169   // operand made a transition, or the instruction is newly executable.  Change
170   // the value type of I to reflect these changes if appropriate.
171   //
172   void visitPHINode(PHINode *I);
173
174   // Terminators
175   void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
176   void visitBranchInst(BranchInst *I);
177   void visitSwitchInst(SwitchInst *I);
178
179   void visitUnaryOperator(Instruction *I);
180   void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
181   void visitBinaryOperator(Instruction *I);
182   void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
183
184   // Instructions that cannot be folded away...
185   void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
186   void visitCallInst      (Instruction *I) { markOverdefined(I); }
187   void visitInvokeInst    (Instruction *I) { markOverdefined(I); }
188   void visitAllocationInst(Instruction *I) { markOverdefined(I); }
189   void visitFreeInst      (Instruction *I) { markOverdefined(I); }
190
191   void visitInstruction(Instruction *I) {
192     // If a new instruction is added to LLVM that we don't handle...
193     cerr << "SCCP: Don't know how to handle: " << I;
194     markOverdefined(I);   // Just in case
195   }
196
197   // OperandChangedState - This method is invoked on all of the users of an
198   // instruction that was just changed state somehow....  Based on this
199   // information, we need to update the specified user of this instruction.
200   //
201   void OperandChangedState(User *U);
202 };
203
204
205 //===----------------------------------------------------------------------===//
206 // SCCP Class Implementation
207
208
209 // doSCCP() - Run the Sparse Conditional Constant Propogation algorithm, and 
210 // return true if the function was modified.
211 //
212 bool SCCP::doSCCP() {
213   // Mark the first block of the function as being executable...
214   markExecutable(M->front());
215
216   // Process the work lists until their are empty!
217   while (!BBWorkList.empty() || !InstWorkList.empty()) {
218     // Process the instruction work list...
219     while (!InstWorkList.empty()) {
220       Instruction *I = InstWorkList.back();
221       InstWorkList.pop_back();
222
223       //cerr << "\nPopped off I-WL: " << I;
224
225       
226       // "I" got into the work list because it either made the transition from
227       // bottom to constant, or to Overdefined.
228       //
229       // Update all of the users of this instruction's value...
230       //
231       for_each(I->use_begin(), I->use_end(),
232                bind_obj(this, &SCCP::OperandChangedState));
233     }
234
235     // Process the basic block work list...
236     while (!BBWorkList.empty()) {
237       BasicBlock *BB = BBWorkList.back();
238       BBWorkList.pop_back();
239
240       //cerr << "\nPopped off BBWL: " << BB;
241
242       // If this block only has a single successor, mark it as executable as
243       // well... if not, terminate the do loop.
244       //
245       if (BB->getTerminator()->getNumSuccessors() == 1)
246         markExecutable(BB->getTerminator()->getSuccessor(0));
247
248       // Notify all instructions in this basic block that they are newly
249       // executable.
250       visit(BB);
251     }
252   }
253
254 #if 0
255   for (Function::iterator BBI = M->begin(), BBEnd = M->end();
256        BBI != BBEnd; ++BBI)
257     if (!BBExecutable.count(*BBI))
258       cerr << "BasicBlock Dead:" << *BBI;
259 #endif
260
261
262   // Iterate over all of the instructions in a function, replacing them with
263   // constants if we have found them to be of constant values.
264   //
265   bool MadeChanges = false;
266   for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
267     BasicBlock *BB = *MI;
268     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
269       Instruction *Inst = *BI;
270       InstVal &IV = ValueState[Inst];
271       if (IV.isConstant()) {
272         Constant *Const = IV.getConstant();
273         // cerr << "Constant: " << Inst << "  is: " << Const;
274
275         // Replaces all of the uses of a variable with uses of the constant.
276         Inst->replaceAllUsesWith(Const);
277
278         // Remove the operator from the list of definitions...
279         BB->getInstList().remove(BI);
280
281         // The new constant inherits the old name of the operator...
282         if (Inst->hasName() && !Const->hasName())
283           Const->setName(Inst->getName(), M->getSymbolTableSure());
284
285         // Delete the operator now...
286         delete Inst;
287
288         // Hey, we just changed something!
289         MadeChanges = true;
290       } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
291         MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
292       }
293
294       ++BI;
295     }
296   }
297
298   // Merge identical constants last: this is important because we may have just
299   // introduced constants that already exist, and we don't want to pollute later
300   // stages with extraneous constants.
301   //
302   return MadeChanges;
303 }
304
305
306 // visit Implementations - Something changed in this instruction... Either an
307 // operand made a transition, or the instruction is newly executable.  Change
308 // the value type of I to reflect these changes if appropriate.  This method
309 // makes sure to do the following actions:
310 //
311 // 1. If a phi node merges two constants in, and has conflicting value coming
312 //    from different branches, or if the PHI node merges in an overdefined
313 //    value, then the PHI node becomes overdefined.
314 // 2. If a phi node merges only constants in, and they all agree on value, the
315 //    PHI node becomes a constant value equal to that.
316 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
317 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
318 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
319 // 6. If a conditional branch has a value that is constant, make the selected
320 //    destination executable
321 // 7. If a conditional branch has a value that is overdefined, make all
322 //    successors executable.
323 //
324
325 void SCCP::visitPHINode(PHINode *PN) {
326   unsigned NumValues = PN->getNumIncomingValues(), i;
327   InstVal *OperandIV = 0;
328
329   // Look at all of the executable operands of the PHI node.  If any of them
330   // are overdefined, the PHI becomes overdefined as well.  If they are all
331   // constant, and they agree with each other, the PHI becomes the identical
332   // constant.  If they are constant and don't agree, the PHI is overdefined.
333   // If there are no executable operands, the PHI remains undefined.
334   //
335   for (i = 0; i < NumValues; ++i) {
336     if (BBExecutable.count(PN->getIncomingBlock(i))) {
337       InstVal &IV = getValueState(PN->getIncomingValue(i));
338       if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
339       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
340         markOverdefined(PN);
341         return;
342       }
343
344       if (OperandIV == 0) {   // Grab the first value...
345         OperandIV = &IV;
346       } else {                // Another value is being merged in!
347         // There is already a reachable operand.  If we conflict with it,
348         // then the PHI node becomes overdefined.  If we agree with it, we
349         // can continue on.
350
351         // Check to see if there are two different constants merging...
352         if (IV.getConstant() != OperandIV->getConstant()) {
353           // Yes there is.  This means the PHI node is not constant.
354           // You must be overdefined poor PHI.
355           //
356           markOverdefined(PN);         // The PHI node now becomes overdefined
357           return;    // I'm done analyzing you
358         }
359       }
360     }
361   }
362
363   // If we exited the loop, this means that the PHI node only has constant
364   // arguments that agree with each other(and OperandIV is a pointer to one
365   // of their InstVal's) or OperandIV is null because there are no defined
366   // incoming arguments.  If this is the case, the PHI remains undefined.
367   //
368   if (OperandIV) {
369     assert(OperandIV->isConstant() && "Should only be here for constants!");
370     markConstant(PN, OperandIV->getConstant());  // Aquire operand value
371   }
372 }
373
374 void SCCP::visitBranchInst(BranchInst *BI) {
375   if (BI->isUnconditional())
376     return; // Unconditional branches are already handled!
377
378   InstVal &BCValue = getValueState(BI->getCondition());
379   if (BCValue.isOverdefined()) {
380     // Overdefined condition variables mean the branch could go either way.
381     markExecutable(BI->getSuccessor(0));
382     markExecutable(BI->getSuccessor(1));
383   } else if (BCValue.isConstant()) {
384     // Constant condition variables mean the branch can only go a single way.
385     if (BCValue.getConstant() == ConstantBool::True)
386       markExecutable(BI->getSuccessor(0));
387     else
388       markExecutable(BI->getSuccessor(1));
389   }
390 }
391
392 void SCCP::visitSwitchInst(SwitchInst *SI) {
393   InstVal &SCValue = getValueState(SI->getCondition());
394   if (SCValue.isOverdefined()) {  // Overdefined condition?  All dests are exe
395     for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i)
396       markExecutable(SI->getSuccessor(i));
397   } else if (SCValue.isConstant()) {
398     Constant *CPV = SCValue.getConstant();
399     // Make sure to skip the "default value" which isn't a value
400     for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
401       if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
402         markExecutable(SI->getSuccessor(i));
403         return;
404       }
405     }
406
407     // Constant value not equal to any of the branches... must execute
408     // default branch then...
409     markExecutable(SI->getDefaultDest());
410   }
411 }
412
413 void SCCP::visitUnaryOperator(Instruction *I) {
414   Value *V = I->getOperand(0);
415   InstVal &VState = getValueState(V);
416   if (VState.isOverdefined()) {        // Inherit overdefinedness of operand
417     markOverdefined(I);
418   } else if (VState.isConstant()) {    // Propogate constant value
419     Constant *Result = isa<CastInst>(I)
420       ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
421       : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
422
423     if (Result) {
424       // This instruction constant folds!
425       markConstant(I, Result);
426     } else {
427       markOverdefined(I);   // Don't know how to fold this instruction.  :(
428     }
429   }
430 }
431
432 // Handle BinaryOperators and Shift Instructions...
433 void SCCP::visitBinaryOperator(Instruction *I) {
434   InstVal &V1State = getValueState(I->getOperand(0));
435   InstVal &V2State = getValueState(I->getOperand(1));
436   if (V1State.isOverdefined() || V2State.isOverdefined()) {
437     markOverdefined(I);
438   } else if (V1State.isConstant() && V2State.isConstant()) {
439     Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(),
440                                                      V1State.getConstant(),
441                                                      V2State.getConstant());
442     if (Result)
443       markConstant(I, Result);      // This instruction constant fold!s
444     else
445       markOverdefined(I);   // Don't know how to fold this instruction.  :(
446   }
447 }
448
449 // OperandChangedState - This method is invoked on all of the users of an
450 // instruction that was just changed state somehow....  Based on this
451 // information, we need to update the specified user of this instruction.
452 //
453 void SCCP::OperandChangedState(User *U) {
454   // Only instructions use other variable values!
455   Instruction *I = cast<Instruction>(U);
456   if (!BBExecutable.count(I->getParent())) return;  // Inst not executable yet!
457
458   visit(I);
459 }
460
461 namespace {
462   // SCCPPass - Use Sparse Conditional Constant Propogation
463   // to prove whether a value is constant and whether blocks are used.
464   //
465   struct SCCPPass : public FunctionPass {
466     const char *getPassName() const {
467       return "Sparse Conditional Constant Propogation";
468     }
469
470     inline bool runOnFunction(Function *F) {
471       SCCP S(F);
472       return S.doSCCP();
473     }
474     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
475       // FIXME: SCCP does not preserve the CFG because it folds terminators!
476       //AU.preservesCFG();
477     }
478   };
479 }
480
481 Pass *createSCCPPass() {
482   return new SCCPPass();
483 }