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