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