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