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