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