SCCP.cpp revision dade2d22babb0877fcbfd13fecd3742991bebed9
1//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements sparse conditional constant propagation and merging:
11//
12// Specifically, this:
13//   * Assumes values are constant unless proven otherwise
14//   * Assumes BasicBlocks are dead unless proven otherwise
15//   * Proves values to be constant, and replaces them with constants
16//   * Proves conditional branches to be unconditional
17//
18// Notice that:
19//   * This pass has a habit of making definitions be dead.  It is a good idea
20//     to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
24#define DEBUG_TYPE "sccp"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/IPO.h"
27#include "llvm/Constants.h"
28#include "llvm/DerivedTypes.h"
29#include "llvm/Instructions.h"
30#include "llvm/Pass.h"
31#include "llvm/Support/InstVisitor.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/Support/CallSite.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/ADT/hash_map"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
38#include <algorithm>
39#include <set>
40using namespace llvm;
41
42// LatticeVal class - This class represents the different lattice values that an
43// instruction may occupy.  It is a simple class with value semantics.
44//
45namespace {
46
47class LatticeVal {
48  enum {
49    undefined,           // This instruction has no known value
50    constant,            // This instruction has a constant value
51    overdefined          // This instruction has an unknown value
52  } LatticeValue;        // The current lattice position
53  Constant *ConstantVal; // If Constant value, the current value
54public:
55  inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
56
57  // markOverdefined - Return true if this is a new status to be in...
58  inline bool markOverdefined() {
59    if (LatticeValue != overdefined) {
60      LatticeValue = overdefined;
61      return true;
62    }
63    return false;
64  }
65
66  // markConstant - Return true if this is a new status for us...
67  inline bool markConstant(Constant *V) {
68    if (LatticeValue != constant) {
69      LatticeValue = constant;
70      ConstantVal = V;
71      return true;
72    } else {
73      assert(ConstantVal == V && "Marking constant with different value");
74    }
75    return false;
76  }
77
78  inline bool isUndefined()   const { return LatticeValue == undefined; }
79  inline bool isConstant()    const { return LatticeValue == constant; }
80  inline bool isOverdefined() const { return LatticeValue == overdefined; }
81
82  inline Constant *getConstant() const {
83    assert(isConstant() && "Cannot get the constant of a non-constant!");
84    return ConstantVal;
85  }
86};
87
88} // end anonymous namespace
89
90
91//===----------------------------------------------------------------------===//
92//
93/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
94/// Constant Propagation.
95///
96class SCCPSolver : public InstVisitor<SCCPSolver> {
97  std::set<BasicBlock*>     BBExecutable;// The basic blocks that are executable
98  hash_map<Value*, LatticeVal> ValueState;  // The state each value is in...
99
100  /// GlobalValue - If we are tracking any values for the contents of a global
101  /// variable, we keep a mapping from the constant accessor to the element of
102  /// the global, to the currently known value.  If the value becomes
103  /// overdefined, it's entry is simply removed from this map.
104  hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
105
106  /// TrackedFunctionRetVals - If we are tracking arguments into and the return
107  /// value out of a function, it will have an entry in this map, indicating
108  /// what the known return value for the function is.
109  hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
110
111  // The reason for two worklists is that overdefined is the lowest state
112  // on the lattice, and moving things to overdefined as fast as possible
113  // makes SCCP converge much faster.
114  // By having a separate worklist, we accomplish this because everything
115  // possibly overdefined will become overdefined at the soonest possible
116  // point.
117  std::vector<Value*> OverdefinedInstWorkList;
118  std::vector<Value*> InstWorkList;
119
120
121  std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
122
123  /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
124  /// overdefined, despite the fact that the PHI node is overdefined.
125  std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
126
127  /// KnownFeasibleEdges - Entries in this set are edges which have already had
128  /// PHI nodes retriggered.
129  typedef std::pair<BasicBlock*,BasicBlock*> Edge;
130  std::set<Edge> KnownFeasibleEdges;
131public:
132
133  /// MarkBlockExecutable - This method can be used by clients to mark all of
134  /// the blocks that are known to be intrinsically live in the processed unit.
135  void MarkBlockExecutable(BasicBlock *BB) {
136    DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
137    BBExecutable.insert(BB);   // Basic block is executable!
138    BBWorkList.push_back(BB);  // Add the block to the work list!
139  }
140
141  /// TrackValueOfGlobalVariable - Clients can use this method to
142  /// inform the SCCPSolver that it should track loads and stores to the
143  /// specified global variable if it can.  This is only legal to call if
144  /// performing Interprocedural SCCP.
145  void TrackValueOfGlobalVariable(GlobalVariable *GV) {
146    const Type *ElTy = GV->getType()->getElementType();
147    if (ElTy->isFirstClassType()) {
148      LatticeVal &IV = TrackedGlobals[GV];
149      if (!isa<UndefValue>(GV->getInitializer()))
150        IV.markConstant(GV->getInitializer());
151    }
152  }
153
154  /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
155  /// and out of the specified function (which cannot have its address taken),
156  /// this method must be called.
157  void AddTrackedFunction(Function *F) {
158    assert(F->hasInternalLinkage() && "Can only track internal functions!");
159    // Add an entry, F -> undef.
160    TrackedFunctionRetVals[F];
161  }
162
163  /// Solve - Solve for constants and executable blocks.
164  ///
165  void Solve();
166
167  /// ResolveBranchesIn - While solving the dataflow for a function, we assume
168  /// that branches on undef values cannot reach any of their successors.
169  /// However, this is not a safe assumption.  After we solve dataflow, this
170  /// method should be use to handle this.  If this returns true, the solver
171  /// should be rerun.
172  bool ResolveBranchesIn(Function &F);
173
174  /// getExecutableBlocks - Once we have solved for constants, return the set of
175  /// blocks that is known to be executable.
176  std::set<BasicBlock*> &getExecutableBlocks() {
177    return BBExecutable;
178  }
179
180  /// getValueMapping - Once we have solved for constants, return the mapping of
181  /// LLVM values to LatticeVals.
182  hash_map<Value*, LatticeVal> &getValueMapping() {
183    return ValueState;
184  }
185
186  /// getTrackedFunctionRetVals - Get the inferred return value map.
187  ///
188  const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
189    return TrackedFunctionRetVals;
190  }
191
192  /// getTrackedGlobals - Get and return the set of inferred initializers for
193  /// global variables.
194  const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
195    return TrackedGlobals;
196  }
197
198
199private:
200  // markConstant - Make a value be marked as "constant".  If the value
201  // is not already a constant, add it to the instruction work list so that
202  // the users of the instruction are updated later.
203  //
204  inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
205    if (IV.markConstant(C)) {
206      DEBUG(std::cerr << "markConstant: " << *C << ": " << *V);
207      InstWorkList.push_back(V);
208    }
209  }
210  inline void markConstant(Value *V, Constant *C) {
211    markConstant(ValueState[V], V, C);
212  }
213
214  // markOverdefined - Make a value be marked as "overdefined". If the
215  // value is not already overdefined, add it to the overdefined instruction
216  // work list so that the users of the instruction are updated later.
217
218  inline void markOverdefined(LatticeVal &IV, Value *V) {
219    if (IV.markOverdefined()) {
220      DEBUG(std::cerr << "markOverdefined: ";
221            if (Function *F = dyn_cast<Function>(V))
222              std::cerr << "Function '" << F->getName() << "'\n";
223            else
224              std::cerr << *V);
225      // Only instructions go on the work list
226      OverdefinedInstWorkList.push_back(V);
227    }
228  }
229  inline void markOverdefined(Value *V) {
230    markOverdefined(ValueState[V], V);
231  }
232
233  inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
234    if (IV.isOverdefined() || MergeWithV.isUndefined())
235      return;  // Noop.
236    if (MergeWithV.isOverdefined())
237      markOverdefined(IV, V);
238    else if (IV.isUndefined())
239      markConstant(IV, V, MergeWithV.getConstant());
240    else if (IV.getConstant() != MergeWithV.getConstant())
241      markOverdefined(IV, V);
242  }
243
244  // getValueState - Return the LatticeVal object that corresponds to the value.
245  // This function is necessary because not all values should start out in the
246  // underdefined state... Argument's should be overdefined, and
247  // constants should be marked as constants.  If a value is not known to be an
248  // Instruction object, then use this accessor to get its value from the map.
249  //
250  inline LatticeVal &getValueState(Value *V) {
251    hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
252    if (I != ValueState.end()) return I->second;  // Common case, in the map
253
254    if (Constant *CPV = dyn_cast<Constant>(V)) {
255      if (isa<UndefValue>(V)) {
256        // Nothing to do, remain undefined.
257      } else {
258        ValueState[CPV].markConstant(CPV);          // Constants are constant
259      }
260    }
261    // All others are underdefined by default...
262    return ValueState[V];
263  }
264
265  // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
266  // work list if it is not already executable...
267  //
268  void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
269    if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
270      return;  // This edge is already known to be executable!
271
272    if (BBExecutable.count(Dest)) {
273      DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
274                      << " -> " << Dest->getName() << "\n");
275
276      // The destination is already executable, but we just made an edge
277      // feasible that wasn't before.  Revisit the PHI nodes in the block
278      // because they have potentially new operands.
279      for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
280        visitPHINode(*cast<PHINode>(I));
281
282    } else {
283      MarkBlockExecutable(Dest);
284    }
285  }
286
287  // getFeasibleSuccessors - Return a vector of booleans to indicate which
288  // successors are reachable from a given terminator instruction.
289  //
290  void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
291
292  // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
293  // block to the 'To' basic block is currently feasible...
294  //
295  bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
296
297  // OperandChangedState - This method is invoked on all of the users of an
298  // instruction that was just changed state somehow....  Based on this
299  // information, we need to update the specified user of this instruction.
300  //
301  void OperandChangedState(User *U) {
302    // Only instructions use other variable values!
303    Instruction &I = cast<Instruction>(*U);
304    if (BBExecutable.count(I.getParent()))   // Inst is executable?
305      visit(I);
306  }
307
308private:
309  friend class InstVisitor<SCCPSolver>;
310
311  // visit implementations - Something changed in this instruction... Either an
312  // operand made a transition, or the instruction is newly executable.  Change
313  // the value type of I to reflect these changes if appropriate.
314  //
315  void visitPHINode(PHINode &I);
316
317  // Terminators
318  void visitReturnInst(ReturnInst &I);
319  void visitTerminatorInst(TerminatorInst &TI);
320
321  void visitCastInst(CastInst &I);
322  void visitSelectInst(SelectInst &I);
323  void visitBinaryOperator(Instruction &I);
324  void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
325
326  // Instructions that cannot be folded away...
327  void visitStoreInst     (Instruction &I);
328  void visitLoadInst      (LoadInst &I);
329  void visitGetElementPtrInst(GetElementPtrInst &I);
330  void visitCallInst      (CallInst &I) { visitCallSite(CallSite::get(&I)); }
331  void visitInvokeInst    (InvokeInst &II) {
332    visitCallSite(CallSite::get(&II));
333    visitTerminatorInst(II);
334  }
335  void visitCallSite      (CallSite CS);
336  void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
337  void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
338  void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
339  void visitVANextInst    (Instruction &I) { markOverdefined(&I); }
340  void visitVAArgInst     (Instruction &I) { markOverdefined(&I); }
341  void visitFreeInst      (Instruction &I) { /*returns void*/ }
342
343  void visitInstruction(Instruction &I) {
344    // If a new instruction is added to LLVM that we don't handle...
345    std::cerr << "SCCP: Don't know how to handle: " << I;
346    markOverdefined(&I);   // Just in case
347  }
348};
349
350// getFeasibleSuccessors - Return a vector of booleans to indicate which
351// successors are reachable from a given terminator instruction.
352//
353void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
354                                       std::vector<bool> &Succs) {
355  Succs.resize(TI.getNumSuccessors());
356  if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
357    if (BI->isUnconditional()) {
358      Succs[0] = true;
359    } else {
360      LatticeVal &BCValue = getValueState(BI->getCondition());
361      if (BCValue.isOverdefined() ||
362          (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
363        // Overdefined condition variables, and branches on unfoldable constant
364        // conditions, mean the branch could go either way.
365        Succs[0] = Succs[1] = true;
366      } else if (BCValue.isConstant()) {
367        // Constant condition variables mean the branch can only go a single way
368        Succs[BCValue.getConstant() == ConstantBool::False] = true;
369      }
370    }
371  } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
372    // Invoke instructions successors are always executable.
373    Succs[0] = Succs[1] = true;
374  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
375    LatticeVal &SCValue = getValueState(SI->getCondition());
376    if (SCValue.isOverdefined() ||   // Overdefined condition?
377        (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
378      // All destinations are executable!
379      Succs.assign(TI.getNumSuccessors(), true);
380    } else if (SCValue.isConstant()) {
381      Constant *CPV = SCValue.getConstant();
382      // Make sure to skip the "default value" which isn't a value
383      for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
384        if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
385          Succs[i] = true;
386          return;
387        }
388      }
389
390      // Constant value not equal to any of the branches... must execute
391      // default branch then...
392      Succs[0] = true;
393    }
394  } else {
395    std::cerr << "SCCP: Don't know how to handle: " << TI;
396    Succs.assign(TI.getNumSuccessors(), true);
397  }
398}
399
400
401// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
402// block to the 'To' basic block is currently feasible...
403//
404bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
405  assert(BBExecutable.count(To) && "Dest should always be alive!");
406
407  // Make sure the source basic block is executable!!
408  if (!BBExecutable.count(From)) return false;
409
410  // Check to make sure this edge itself is actually feasible now...
411  TerminatorInst *TI = From->getTerminator();
412  if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
413    if (BI->isUnconditional())
414      return true;
415    else {
416      LatticeVal &BCValue = getValueState(BI->getCondition());
417      if (BCValue.isOverdefined()) {
418        // Overdefined condition variables mean the branch could go either way.
419        return true;
420      } else if (BCValue.isConstant()) {
421        // Not branching on an evaluatable constant?
422        if (!isa<ConstantBool>(BCValue.getConstant())) return true;
423
424        // Constant condition variables mean the branch can only go a single way
425        return BI->getSuccessor(BCValue.getConstant() ==
426                                       ConstantBool::False) == To;
427      }
428      return false;
429    }
430  } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
431    // Invoke instructions successors are always executable.
432    return true;
433  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
434    LatticeVal &SCValue = getValueState(SI->getCondition());
435    if (SCValue.isOverdefined()) {  // Overdefined condition?
436      // All destinations are executable!
437      return true;
438    } else if (SCValue.isConstant()) {
439      Constant *CPV = SCValue.getConstant();
440      if (!isa<ConstantInt>(CPV))
441        return true;  // not a foldable constant?
442
443      // Make sure to skip the "default value" which isn't a value
444      for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
445        if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
446          return SI->getSuccessor(i) == To;
447
448      // Constant value not equal to any of the branches... must execute
449      // default branch then...
450      return SI->getDefaultDest() == To;
451    }
452    return false;
453  } else {
454    std::cerr << "Unknown terminator instruction: " << *TI;
455    abort();
456  }
457}
458
459// visit Implementations - Something changed in this instruction... Either an
460// operand made a transition, or the instruction is newly executable.  Change
461// the value type of I to reflect these changes if appropriate.  This method
462// makes sure to do the following actions:
463//
464// 1. If a phi node merges two constants in, and has conflicting value coming
465//    from different branches, or if the PHI node merges in an overdefined
466//    value, then the PHI node becomes overdefined.
467// 2. If a phi node merges only constants in, and they all agree on value, the
468//    PHI node becomes a constant value equal to that.
469// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
470// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
471// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
472// 6. If a conditional branch has a value that is constant, make the selected
473//    destination executable
474// 7. If a conditional branch has a value that is overdefined, make all
475//    successors executable.
476//
477void SCCPSolver::visitPHINode(PHINode &PN) {
478  LatticeVal &PNIV = getValueState(&PN);
479  if (PNIV.isOverdefined()) {
480    // There may be instructions using this PHI node that are not overdefined
481    // themselves.  If so, make sure that they know that the PHI node operand
482    // changed.
483    std::multimap<PHINode*, Instruction*>::iterator I, E;
484    tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
485    if (I != E) {
486      std::vector<Instruction*> Users;
487      Users.reserve(std::distance(I, E));
488      for (; I != E; ++I) Users.push_back(I->second);
489      while (!Users.empty()) {
490        visit(Users.back());
491        Users.pop_back();
492      }
493    }
494    return;  // Quick exit
495  }
496
497  // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
498  // and slow us down a lot.  Just mark them overdefined.
499  if (PN.getNumIncomingValues() > 64) {
500    markOverdefined(PNIV, &PN);
501    return;
502  }
503
504  // Look at all of the executable operands of the PHI node.  If any of them
505  // are overdefined, the PHI becomes overdefined as well.  If they are all
506  // constant, and they agree with each other, the PHI becomes the identical
507  // constant.  If they are constant and don't agree, the PHI is overdefined.
508  // If there are no executable operands, the PHI remains undefined.
509  //
510  Constant *OperandVal = 0;
511  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
512    LatticeVal &IV = getValueState(PN.getIncomingValue(i));
513    if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
514
515    if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
516      if (IV.isOverdefined()) {   // PHI node becomes overdefined!
517        markOverdefined(PNIV, &PN);
518        return;
519      }
520
521      if (OperandVal == 0) {   // Grab the first value...
522        OperandVal = IV.getConstant();
523      } else {                // Another value is being merged in!
524        // There is already a reachable operand.  If we conflict with it,
525        // then the PHI node becomes overdefined.  If we agree with it, we
526        // can continue on.
527
528        // Check to see if there are two different constants merging...
529        if (IV.getConstant() != OperandVal) {
530          // Yes there is.  This means the PHI node is not constant.
531          // You must be overdefined poor PHI.
532          //
533          markOverdefined(PNIV, &PN);    // The PHI node now becomes overdefined
534          return;    // I'm done analyzing you
535        }
536      }
537    }
538  }
539
540  // If we exited the loop, this means that the PHI node only has constant
541  // arguments that agree with each other(and OperandVal is the constant) or
542  // OperandVal is null because there are no defined incoming arguments.  If
543  // this is the case, the PHI remains undefined.
544  //
545  if (OperandVal)
546    markConstant(PNIV, &PN, OperandVal);      // Acquire operand value
547}
548
549void SCCPSolver::visitReturnInst(ReturnInst &I) {
550  if (I.getNumOperands() == 0) return;  // Ret void
551
552  // If we are tracking the return value of this function, merge it in.
553  Function *F = I.getParent()->getParent();
554  if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
555    hash_map<Function*, LatticeVal>::iterator TFRVI =
556      TrackedFunctionRetVals.find(F);
557    if (TFRVI != TrackedFunctionRetVals.end() &&
558        !TFRVI->second.isOverdefined()) {
559      LatticeVal &IV = getValueState(I.getOperand(0));
560      mergeInValue(TFRVI->second, F, IV);
561    }
562  }
563}
564
565
566void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
567  std::vector<bool> SuccFeasible;
568  getFeasibleSuccessors(TI, SuccFeasible);
569
570  BasicBlock *BB = TI.getParent();
571
572  // Mark all feasible successors executable...
573  for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
574    if (SuccFeasible[i])
575      markEdgeExecutable(BB, TI.getSuccessor(i));
576}
577
578void SCCPSolver::visitCastInst(CastInst &I) {
579  Value *V = I.getOperand(0);
580  LatticeVal &VState = getValueState(V);
581  if (VState.isOverdefined())          // Inherit overdefinedness of operand
582    markOverdefined(&I);
583  else if (VState.isConstant())        // Propagate constant value
584    markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
585}
586
587void SCCPSolver::visitSelectInst(SelectInst &I) {
588  LatticeVal &CondValue = getValueState(I.getCondition());
589  if (CondValue.isOverdefined())
590    markOverdefined(&I);
591  else if (CondValue.isConstant()) {
592    if (CondValue.getConstant() == ConstantBool::True) {
593      LatticeVal &Val = getValueState(I.getTrueValue());
594      if (Val.isOverdefined())
595        markOverdefined(&I);
596      else if (Val.isConstant())
597        markConstant(&I, Val.getConstant());
598    } else if (CondValue.getConstant() == ConstantBool::False) {
599      LatticeVal &Val = getValueState(I.getFalseValue());
600      if (Val.isOverdefined())
601        markOverdefined(&I);
602      else if (Val.isConstant())
603        markConstant(&I, Val.getConstant());
604    } else
605      markOverdefined(&I);
606  }
607}
608
609// Handle BinaryOperators and Shift Instructions...
610void SCCPSolver::visitBinaryOperator(Instruction &I) {
611  LatticeVal &IV = ValueState[&I];
612  if (IV.isOverdefined()) return;
613
614  LatticeVal &V1State = getValueState(I.getOperand(0));
615  LatticeVal &V2State = getValueState(I.getOperand(1));
616
617  if (V1State.isOverdefined() || V2State.isOverdefined()) {
618    // If both operands are PHI nodes, it is possible that this instruction has
619    // a constant value, despite the fact that the PHI node doesn't.  Check for
620    // this condition now.
621    if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
622      if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
623        if (PN1->getParent() == PN2->getParent()) {
624          // Since the two PHI nodes are in the same basic block, they must have
625          // entries for the same predecessors.  Walk the predecessor list, and
626          // if all of the incoming values are constants, and the result of
627          // evaluating this expression with all incoming value pairs is the
628          // same, then this expression is a constant even though the PHI node
629          // is not a constant!
630          LatticeVal Result;
631          for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
632            LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
633            BasicBlock *InBlock = PN1->getIncomingBlock(i);
634            LatticeVal &In2 =
635              getValueState(PN2->getIncomingValueForBlock(InBlock));
636
637            if (In1.isOverdefined() || In2.isOverdefined()) {
638              Result.markOverdefined();
639              break;  // Cannot fold this operation over the PHI nodes!
640            } else if (In1.isConstant() && In2.isConstant()) {
641              Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
642                                              In2.getConstant());
643              if (Result.isUndefined())
644                Result.markConstant(V);
645              else if (Result.isConstant() && Result.getConstant() != V) {
646                Result.markOverdefined();
647                break;
648              }
649            }
650          }
651
652          // If we found a constant value here, then we know the instruction is
653          // constant despite the fact that the PHI nodes are overdefined.
654          if (Result.isConstant()) {
655            markConstant(IV, &I, Result.getConstant());
656            // Remember that this instruction is virtually using the PHI node
657            // operands.
658            UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
659            UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
660            return;
661          } else if (Result.isUndefined()) {
662            return;
663          }
664
665          // Okay, this really is overdefined now.  Since we might have
666          // speculatively thought that this was not overdefined before, and
667          // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
668          // make sure to clean out any entries that we put there, for
669          // efficiency.
670          std::multimap<PHINode*, Instruction*>::iterator It, E;
671          tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
672          while (It != E) {
673            if (It->second == &I) {
674              UsersOfOverdefinedPHIs.erase(It++);
675            } else
676              ++It;
677          }
678          tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
679          while (It != E) {
680            if (It->second == &I) {
681              UsersOfOverdefinedPHIs.erase(It++);
682            } else
683              ++It;
684          }
685        }
686
687    markOverdefined(IV, &I);
688  } else if (V1State.isConstant() && V2State.isConstant()) {
689    markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
690                                           V2State.getConstant()));
691  }
692}
693
694// Handle getelementptr instructions... if all operands are constants then we
695// can turn this into a getelementptr ConstantExpr.
696//
697void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
698  LatticeVal &IV = ValueState[&I];
699  if (IV.isOverdefined()) return;
700
701  std::vector<Constant*> Operands;
702  Operands.reserve(I.getNumOperands());
703
704  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
705    LatticeVal &State = getValueState(I.getOperand(i));
706    if (State.isUndefined())
707      return;  // Operands are not resolved yet...
708    else if (State.isOverdefined()) {
709      markOverdefined(IV, &I);
710      return;
711    }
712    assert(State.isConstant() && "Unknown state!");
713    Operands.push_back(State.getConstant());
714  }
715
716  Constant *Ptr = Operands[0];
717  Operands.erase(Operands.begin());  // Erase the pointer from idx list...
718
719  markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
720}
721
722/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
723/// return the constant value being addressed by the constant expression, or
724/// null if something is funny.
725///
726static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
727  if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
728    return 0;  // Do not allow stepping over the value!
729
730  // Loop over all of the operands, tracking down which value we are
731  // addressing...
732  for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
733    if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
734      ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
735      if (CS == 0) return 0;
736      if (CU->getValue() >= CS->getNumOperands()) return 0;
737      C = CS->getOperand(CU->getValue());
738    } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
739      ConstantArray *CA = dyn_cast<ConstantArray>(C);
740      if (CA == 0) return 0;
741      if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
742      C = CA->getOperand(CS->getValue());
743    } else
744      return 0;
745  return C;
746}
747
748void SCCPSolver::visitStoreInst(Instruction &SI) {
749  if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
750    return;
751  GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
752  hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
753  if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
754
755  // Get the value we are storing into the global.
756  LatticeVal &PtrVal = getValueState(SI.getOperand(0));
757
758  mergeInValue(I->second, GV, PtrVal);
759  if (I->second.isOverdefined())
760    TrackedGlobals.erase(I);      // No need to keep tracking this!
761}
762
763
764// Handle load instructions.  If the operand is a constant pointer to a constant
765// global, we can replace the load with the loaded constant value!
766void SCCPSolver::visitLoadInst(LoadInst &I) {
767  LatticeVal &IV = ValueState[&I];
768  if (IV.isOverdefined()) return;
769
770  LatticeVal &PtrVal = getValueState(I.getOperand(0));
771  if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
772  if (PtrVal.isConstant() && !I.isVolatile()) {
773    Value *Ptr = PtrVal.getConstant();
774    if (isa<ConstantPointerNull>(Ptr)) {
775      // load null -> null
776      markConstant(IV, &I, Constant::getNullValue(I.getType()));
777      return;
778    }
779
780    // Transform load (constant global) into the value loaded.
781    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
782      if (GV->isConstant()) {
783        if (!GV->isExternal()) {
784          markConstant(IV, &I, GV->getInitializer());
785          return;
786        }
787      } else if (!TrackedGlobals.empty()) {
788        // If we are tracking this global, merge in the known value for it.
789        hash_map<GlobalVariable*, LatticeVal>::iterator It =
790          TrackedGlobals.find(GV);
791        if (It != TrackedGlobals.end()) {
792          mergeInValue(IV, &I, It->second);
793          return;
794        }
795      }
796    }
797
798    // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
799    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
800      if (CE->getOpcode() == Instruction::GetElementPtr)
801	if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
802	  if (GV->isConstant() && !GV->isExternal())
803	    if (Constant *V =
804		GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
805	      markConstant(IV, &I, V);
806	      return;
807	    }
808  }
809
810  // Otherwise we cannot say for certain what value this load will produce.
811  // Bail out.
812  markOverdefined(IV, &I);
813}
814
815void SCCPSolver::visitCallSite(CallSite CS) {
816  Function *F = CS.getCalledFunction();
817
818  // If we are tracking this function, we must make sure to bind arguments as
819  // appropriate.
820  hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
821  if (F && F->hasInternalLinkage())
822    TFRVI = TrackedFunctionRetVals.find(F);
823
824  if (TFRVI != TrackedFunctionRetVals.end()) {
825    // If this is the first call to the function hit, mark its entry block
826    // executable.
827    if (!BBExecutable.count(F->begin()))
828      MarkBlockExecutable(F->begin());
829
830    CallSite::arg_iterator CAI = CS.arg_begin();
831    for (Function::aiterator AI = F->abegin(), E = F->aend();
832         AI != E; ++AI, ++CAI) {
833      LatticeVal &IV = ValueState[AI];
834      if (!IV.isOverdefined())
835        mergeInValue(IV, AI, getValueState(*CAI));
836    }
837  }
838  Instruction *I = CS.getInstruction();
839  if (I->getType() == Type::VoidTy) return;
840
841  LatticeVal &IV = ValueState[I];
842  if (IV.isOverdefined()) return;
843
844  // Propagate the return value of the function to the value of the instruction.
845  if (TFRVI != TrackedFunctionRetVals.end()) {
846    mergeInValue(IV, I, TFRVI->second);
847    return;
848  }
849
850  if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
851    markOverdefined(IV, I);
852    return;
853  }
854
855  std::vector<Constant*> Operands;
856  Operands.reserve(I->getNumOperands()-1);
857
858  for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
859       AI != E; ++AI) {
860    LatticeVal &State = getValueState(*AI);
861    if (State.isUndefined())
862      return;  // Operands are not resolved yet...
863    else if (State.isOverdefined()) {
864      markOverdefined(IV, I);
865      return;
866    }
867    assert(State.isConstant() && "Unknown state!");
868    Operands.push_back(State.getConstant());
869  }
870
871  if (Constant *C = ConstantFoldCall(F, Operands))
872    markConstant(IV, I, C);
873  else
874    markOverdefined(IV, I);
875}
876
877
878void SCCPSolver::Solve() {
879  // Process the work lists until they are empty!
880  while (!BBWorkList.empty() || !InstWorkList.empty() ||
881	 !OverdefinedInstWorkList.empty()) {
882    // Process the instruction work list...
883    while (!OverdefinedInstWorkList.empty()) {
884      Value *I = OverdefinedInstWorkList.back();
885      OverdefinedInstWorkList.pop_back();
886
887      DEBUG(std::cerr << "\nPopped off OI-WL: " << *I);
888
889      // "I" got into the work list because it either made the transition from
890      // bottom to constant
891      //
892      // Anything on this worklist that is overdefined need not be visited
893      // since all of its users will have already been marked as overdefined
894      // Update all of the users of this instruction's value...
895      //
896      for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
897           UI != E; ++UI)
898        OperandChangedState(*UI);
899    }
900    // Process the instruction work list...
901    while (!InstWorkList.empty()) {
902      Value *I = InstWorkList.back();
903      InstWorkList.pop_back();
904
905      DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
906
907      // "I" got into the work list because it either made the transition from
908      // bottom to constant
909      //
910      // Anything on this worklist that is overdefined need not be visited
911      // since all of its users will have already been marked as overdefined.
912      // Update all of the users of this instruction's value...
913      //
914      if (!getValueState(I).isOverdefined())
915        for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
916             UI != E; ++UI)
917          OperandChangedState(*UI);
918    }
919
920    // Process the basic block work list...
921    while (!BBWorkList.empty()) {
922      BasicBlock *BB = BBWorkList.back();
923      BBWorkList.pop_back();
924
925      DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
926
927      // Notify all instructions in this basic block that they are newly
928      // executable.
929      visit(BB);
930    }
931  }
932}
933
934/// ResolveBranchesIn - While solving the dataflow for a function, we assume
935/// that branches on undef values cannot reach any of their successors.
936/// However, this is not a safe assumption.  After we solve dataflow, this
937/// method should be use to handle this.  If this returns true, the solver
938/// should be rerun.
939bool SCCPSolver::ResolveBranchesIn(Function &F) {
940  bool BranchesResolved = false;
941  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
942    if (BBExecutable.count(BB)) {
943      TerminatorInst *TI = BB->getTerminator();
944      if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
945        if (BI->isConditional()) {
946          LatticeVal &BCValue = getValueState(BI->getCondition());
947          if (BCValue.isUndefined()) {
948            BI->setCondition(ConstantBool::True);
949            BranchesResolved = true;
950            visit(BI);
951          }
952        }
953      } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
954        LatticeVal &SCValue = getValueState(SI->getCondition());
955        if (SCValue.isUndefined()) {
956          const Type *CondTy = SI->getCondition()->getType();
957          SI->setCondition(Constant::getNullValue(CondTy));
958          BranchesResolved = true;
959          visit(SI);
960        }
961      }
962    }
963
964  return BranchesResolved;
965}
966
967
968namespace {
969  Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
970  Statistic<> NumDeadBlocks ("sccp", "Number of basic blocks unreachable");
971
972  //===--------------------------------------------------------------------===//
973  //
974  /// SCCP Class - This class uses the SCCPSolver to implement a per-function
975  /// Sparse Conditional COnstant Propagator.
976  ///
977  struct SCCP : public FunctionPass {
978    // runOnFunction - Run the Sparse Conditional Constant Propagation
979    // algorithm, and return true if the function was modified.
980    //
981    bool runOnFunction(Function &F);
982
983    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
984      AU.setPreservesCFG();
985    }
986  };
987
988  RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
989} // end anonymous namespace
990
991
992// createSCCPPass - This is the public interface to this file...
993FunctionPass *llvm::createSCCPPass() {
994  return new SCCP();
995}
996
997
998// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
999// and return true if the function was modified.
1000//
1001bool SCCP::runOnFunction(Function &F) {
1002  DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
1003  SCCPSolver Solver;
1004
1005  // Mark the first block of the function as being executable.
1006  Solver.MarkBlockExecutable(F.begin());
1007
1008  // Mark all arguments to the function as being overdefined.
1009  hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1010  for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
1011    Values[AI].markOverdefined();
1012
1013  // Solve for constants.
1014  bool ResolvedBranches = true;
1015  while (ResolvedBranches) {
1016    Solver.Solve();
1017    DEBUG(std::cerr << "RESOLVING UNDEF BRANCHES\n");
1018    ResolvedBranches = Solver.ResolveBranchesIn(F);
1019  }
1020
1021  bool MadeChanges = false;
1022
1023  // If we decided that there are basic blocks that are dead in this function,
1024  // delete their contents now.  Note that we cannot actually delete the blocks,
1025  // as we cannot modify the CFG of the function.
1026  //
1027  std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1028  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1029    if (!ExecutableBBs.count(BB)) {
1030      DEBUG(std::cerr << "  BasicBlock Dead:" << *BB);
1031      ++NumDeadBlocks;
1032
1033      // Delete the instructions backwards, as it has a reduced likelihood of
1034      // having to update as many def-use and use-def chains.
1035      std::vector<Instruction*> Insts;
1036      for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1037           I != E; ++I)
1038        Insts.push_back(I);
1039      while (!Insts.empty()) {
1040        Instruction *I = Insts.back();
1041        Insts.pop_back();
1042        if (!I->use_empty())
1043          I->replaceAllUsesWith(UndefValue::get(I->getType()));
1044        BB->getInstList().erase(I);
1045        MadeChanges = true;
1046        ++NumInstRemoved;
1047      }
1048    } else {
1049      // Iterate over all of the instructions in a function, replacing them with
1050      // constants if we have found them to be of constant values.
1051      //
1052      for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1053        Instruction *Inst = BI++;
1054        if (Inst->getType() != Type::VoidTy) {
1055          LatticeVal &IV = Values[Inst];
1056          if (IV.isConstant() || IV.isUndefined() &&
1057              !isa<TerminatorInst>(Inst)) {
1058            Constant *Const = IV.isConstant()
1059              ? IV.getConstant() : UndefValue::get(Inst->getType());
1060            DEBUG(std::cerr << "  Constant: " << *Const << " = " << *Inst);
1061
1062            // Replaces all of the uses of a variable with uses of the constant.
1063            Inst->replaceAllUsesWith(Const);
1064
1065            // Delete the instruction.
1066            BB->getInstList().erase(Inst);
1067
1068            // Hey, we just changed something!
1069            MadeChanges = true;
1070            ++NumInstRemoved;
1071          }
1072        }
1073      }
1074    }
1075
1076  return MadeChanges;
1077}
1078
1079namespace {
1080  Statistic<> IPNumInstRemoved("ipsccp", "Number of instructions removed");
1081  Statistic<> IPNumDeadBlocks ("ipsccp", "Number of basic blocks unreachable");
1082  Statistic<> IPNumArgsElimed ("ipsccp",
1083                               "Number of arguments constant propagated");
1084  Statistic<> IPNumGlobalConst("ipsccp",
1085                               "Number of globals found to be constant");
1086
1087  //===--------------------------------------------------------------------===//
1088  //
1089  /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1090  /// Constant Propagation.
1091  ///
1092  struct IPSCCP : public ModulePass {
1093    bool runOnModule(Module &M);
1094  };
1095
1096  RegisterOpt<IPSCCP>
1097  Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1098} // end anonymous namespace
1099
1100// createIPSCCPPass - This is the public interface to this file...
1101ModulePass *llvm::createIPSCCPPass() {
1102  return new IPSCCP();
1103}
1104
1105
1106static bool AddressIsTaken(GlobalValue *GV) {
1107  for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1108       UI != E; ++UI)
1109    if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1110      if (SI->getOperand(0) == GV || SI->isVolatile())
1111        return true;  // Storing addr of GV.
1112    } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1113      // Make sure we are calling the function, not passing the address.
1114      CallSite CS = CallSite::get(cast<Instruction>(*UI));
1115      for (CallSite::arg_iterator AI = CS.arg_begin(),
1116             E = CS.arg_end(); AI != E; ++AI)
1117        if (*AI == GV)
1118          return true;
1119    } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1120      if (LI->isVolatile())
1121        return true;
1122    } else {
1123      return true;
1124    }
1125  return false;
1126}
1127
1128bool IPSCCP::runOnModule(Module &M) {
1129  SCCPSolver Solver;
1130
1131  // Loop over all functions, marking arguments to those with their addresses
1132  // taken or that are external as overdefined.
1133  //
1134  hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1135  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1136    if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1137      if (!F->isExternal())
1138        Solver.MarkBlockExecutable(F->begin());
1139      for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1140        Values[AI].markOverdefined();
1141    } else {
1142      Solver.AddTrackedFunction(F);
1143    }
1144
1145  // Loop over global variables.  We inform the solver about any internal global
1146  // variables that do not have their 'addresses taken'.  If they don't have
1147  // their addresses taken, we can propagate constants through them.
1148  for (Module::giterator G = M.gbegin(), E = M.gend(); G != E; ++G)
1149    if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1150      Solver.TrackValueOfGlobalVariable(G);
1151
1152  // Solve for constants.
1153  bool ResolvedBranches = true;
1154  while (ResolvedBranches) {
1155    Solver.Solve();
1156
1157    DEBUG(std::cerr << "RESOLVING UNDEF BRANCHES\n");
1158    ResolvedBranches = false;
1159    for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1160      ResolvedBranches |= Solver.ResolveBranchesIn(*F);
1161  }
1162
1163  bool MadeChanges = false;
1164
1165  // Iterate over all of the instructions in the module, replacing them with
1166  // constants if we have found them to be of constant values.
1167  //
1168  std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1169  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1170    for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1171      if (!AI->use_empty()) {
1172        LatticeVal &IV = Values[AI];
1173        if (IV.isConstant() || IV.isUndefined()) {
1174          Constant *CST = IV.isConstant() ?
1175            IV.getConstant() : UndefValue::get(AI->getType());
1176          DEBUG(std::cerr << "***  Arg " << *AI << " = " << *CST <<"\n");
1177
1178          // Replaces all of the uses of a variable with uses of the
1179          // constant.
1180          AI->replaceAllUsesWith(CST);
1181          ++IPNumArgsElimed;
1182        }
1183      }
1184
1185    std::vector<BasicBlock*> BlocksToErase;
1186    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1187      if (!ExecutableBBs.count(BB)) {
1188        DEBUG(std::cerr << "  BasicBlock Dead:" << *BB);
1189        ++IPNumDeadBlocks;
1190
1191        // Delete the instructions backwards, as it has a reduced likelihood of
1192        // having to update as many def-use and use-def chains.
1193        std::vector<Instruction*> Insts;
1194        TerminatorInst *TI = BB->getTerminator();
1195        for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1196          Insts.push_back(I);
1197
1198        while (!Insts.empty()) {
1199          Instruction *I = Insts.back();
1200          Insts.pop_back();
1201          if (!I->use_empty())
1202            I->replaceAllUsesWith(UndefValue::get(I->getType()));
1203          BB->getInstList().erase(I);
1204          MadeChanges = true;
1205          ++IPNumInstRemoved;
1206        }
1207
1208        for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1209          BasicBlock *Succ = TI->getSuccessor(i);
1210          if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1211            TI->getSuccessor(i)->removePredecessor(BB);
1212        }
1213        if (!TI->use_empty())
1214          TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1215        BB->getInstList().erase(TI);
1216
1217        if (&*BB != &F->front())
1218          BlocksToErase.push_back(BB);
1219        else
1220          new UnreachableInst(BB);
1221
1222      } else {
1223        for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1224          Instruction *Inst = BI++;
1225          if (Inst->getType() != Type::VoidTy) {
1226            LatticeVal &IV = Values[Inst];
1227            if (IV.isConstant() || IV.isUndefined() &&
1228                !isa<TerminatorInst>(Inst)) {
1229              Constant *Const = IV.isConstant()
1230                ? IV.getConstant() : UndefValue::get(Inst->getType());
1231              DEBUG(std::cerr << "  Constant: " << *Const << " = " << *Inst);
1232
1233              // Replaces all of the uses of a variable with uses of the
1234              // constant.
1235              Inst->replaceAllUsesWith(Const);
1236
1237              // Delete the instruction.
1238              if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1239                BB->getInstList().erase(Inst);
1240
1241              // Hey, we just changed something!
1242              MadeChanges = true;
1243              ++IPNumInstRemoved;
1244            }
1245          }
1246        }
1247      }
1248
1249    // Now that all instructions in the function are constant folded, erase dead
1250    // blocks, because we can now use ConstantFoldTerminator to get rid of
1251    // in-edges.
1252    for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1253      // If there are any PHI nodes in this successor, drop entries for BB now.
1254      BasicBlock *DeadBB = BlocksToErase[i];
1255      while (!DeadBB->use_empty()) {
1256        Instruction *I = cast<Instruction>(DeadBB->use_back());
1257        bool Folded = ConstantFoldTerminator(I->getParent());
1258        assert(Folded && "Didn't fold away reference to block!");
1259      }
1260
1261      // Finally, delete the basic block.
1262      F->getBasicBlockList().erase(DeadBB);
1263    }
1264  }
1265
1266  // If we inferred constant or undef return values for a function, we replaced
1267  // all call uses with the inferred value.  This means we don't need to bother
1268  // actually returning anything from the function.  Replace all return
1269  // instructions with return undef.
1270  const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1271  for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1272         E = RV.end(); I != E; ++I)
1273    if (!I->second.isOverdefined() &&
1274        I->first->getReturnType() != Type::VoidTy) {
1275      Function *F = I->first;
1276      for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1277        if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1278          if (!isa<UndefValue>(RI->getOperand(0)))
1279            RI->setOperand(0, UndefValue::get(F->getReturnType()));
1280    }
1281
1282  // If we infered constant or undef values for globals variables, we can delete
1283  // the global and any stores that remain to it.
1284  const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1285  for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1286         E = TG.end(); I != E; ++I) {
1287    GlobalVariable *GV = I->first;
1288    assert(!I->second.isOverdefined() &&
1289           "Overdefined values should have been taken out of the map!");
1290    DEBUG(std::cerr << "Found that GV '" << GV->getName()<< "' is constant!\n");
1291    while (!GV->use_empty()) {
1292      StoreInst *SI = cast<StoreInst>(GV->use_back());
1293      SI->eraseFromParent();
1294    }
1295    M.getGlobalList().erase(GV);
1296    ++IPNumGlobalConst;
1297  }
1298
1299  return MadeChanges;
1300}
1301