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