Teach SCCP about insertvalue and extractvalue, and about
[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 is distributed under the University of Illinois Open Source
6 // 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/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/InstVisitor.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include <algorithm>
44 #include <map>
45 using namespace llvm;
46
47 STATISTIC(NumInstRemoved, "Number of instructions removed");
48 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
50 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
51 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
52 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
55 namespace {
56 /// LatticeVal class - This class represents the different lattice values that
57 /// an LLVM value may occupy.  It is a simple class with value semantics.
58 ///
59 class VISIBILITY_HIDDEN LatticeVal {
60   enum {
61     /// undefined - This LLVM Value has no known value yet.
62     undefined,
63     
64     /// constant - This LLVM Value has a specific constant value.
65     constant,
66
67     /// forcedconstant - This LLVM Value was thought to be undef until
68     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
69     /// with another (different) constant, it goes to overdefined, instead of
70     /// asserting.
71     forcedconstant,
72     
73     /// overdefined - This instruction is not known to be constant, and we know
74     /// it has a value.
75     overdefined
76   } LatticeValue;    // The current lattice position
77   
78   Constant *ConstantVal; // If Constant value, the current value
79 public:
80   inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
81   
82   // markOverdefined - Return true if this is a new status to be in...
83   inline bool markOverdefined() {
84     if (LatticeValue != overdefined) {
85       LatticeValue = overdefined;
86       return true;
87     }
88     return false;
89   }
90
91   // markConstant - Return true if this is a new status for us.
92   inline bool markConstant(Constant *V) {
93     if (LatticeValue != constant) {
94       if (LatticeValue == undefined) {
95         LatticeValue = constant;
96         assert(V && "Marking constant with NULL");
97         ConstantVal = V;
98       } else {
99         assert(LatticeValue == forcedconstant && 
100                "Cannot move from overdefined to constant!");
101         // Stay at forcedconstant if the constant is the same.
102         if (V == ConstantVal) return false;
103         
104         // Otherwise, we go to overdefined.  Assumptions made based on the
105         // forced value are possibly wrong.  Assuming this is another constant
106         // could expose a contradiction.
107         LatticeValue = overdefined;
108       }
109       return true;
110     } else {
111       assert(ConstantVal == V && "Marking constant with different value");
112     }
113     return false;
114   }
115
116   inline void markForcedConstant(Constant *V) {
117     assert(LatticeValue == undefined && "Can't force a defined value!");
118     LatticeValue = forcedconstant;
119     ConstantVal = V;
120   }
121   
122   inline bool isUndefined() const { return LatticeValue == undefined; }
123   inline bool isConstant() const {
124     return LatticeValue == constant || LatticeValue == forcedconstant;
125   }
126   inline bool isOverdefined() const { return LatticeValue == overdefined; }
127
128   inline Constant *getConstant() const {
129     assert(isConstant() && "Cannot get the constant of a non-constant!");
130     return ConstantVal;
131   }
132 };
133
134 //===----------------------------------------------------------------------===//
135 //
136 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
137 /// Constant Propagation.
138 ///
139 class SCCPSolver : public InstVisitor<SCCPSolver> {
140   SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
141   std::map<Value*, LatticeVal> ValueState;  // The state each value is in.
142
143   /// GlobalValue - If we are tracking any values for the contents of a global
144   /// variable, we keep a mapping from the constant accessor to the element of
145   /// the global, to the currently known value.  If the value becomes
146   /// overdefined, it's entry is simply removed from this map.
147   DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
148
149   /// TrackedRetVals - If we are tracking arguments into and the return
150   /// value out of a function, it will have an entry in this map, indicating
151   /// what the known return value for the function is.
152   DenseMap<Function*, LatticeVal> TrackedRetVals;
153
154   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
155   /// that return multiple values.
156   std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
157
158   // The reason for two worklists is that overdefined is the lowest state
159   // on the lattice, and moving things to overdefined as fast as possible
160   // makes SCCP converge much faster.
161   // By having a separate worklist, we accomplish this because everything
162   // possibly overdefined will become overdefined at the soonest possible
163   // point.
164   std::vector<Value*> OverdefinedInstWorkList;
165   std::vector<Value*> InstWorkList;
166
167
168   std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
169
170   /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
171   /// overdefined, despite the fact that the PHI node is overdefined.
172   std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
173
174   /// KnownFeasibleEdges - Entries in this set are edges which have already had
175   /// PHI nodes retriggered.
176   typedef std::pair<BasicBlock*,BasicBlock*> Edge;
177   std::set<Edge> KnownFeasibleEdges;
178 public:
179
180   /// MarkBlockExecutable - This method can be used by clients to mark all of
181   /// the blocks that are known to be intrinsically live in the processed unit.
182   void MarkBlockExecutable(BasicBlock *BB) {
183     DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
184     BBExecutable.insert(BB);   // Basic block is executable!
185     BBWorkList.push_back(BB);  // Add the block to the work list!
186   }
187
188   /// TrackValueOfGlobalVariable - Clients can use this method to
189   /// inform the SCCPSolver that it should track loads and stores to the
190   /// specified global variable if it can.  This is only legal to call if
191   /// performing Interprocedural SCCP.
192   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
193     const Type *ElTy = GV->getType()->getElementType();
194     if (ElTy->isFirstClassType()) {
195       LatticeVal &IV = TrackedGlobals[GV];
196       if (!isa<UndefValue>(GV->getInitializer()))
197         IV.markConstant(GV->getInitializer());
198     }
199   }
200
201   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
202   /// and out of the specified function (which cannot have its address taken),
203   /// this method must be called.
204   void AddTrackedFunction(Function *F) {
205     assert(F->hasInternalLinkage() && "Can only track internal functions!");
206     // Add an entry, F -> undef.
207     if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
208       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
209         TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
210                                                      LatticeVal()));
211     } else
212       TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
213   }
214
215   /// Solve - Solve for constants and executable blocks.
216   ///
217   void Solve();
218
219   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
220   /// that branches on undef values cannot reach any of their successors.
221   /// However, this is not a safe assumption.  After we solve dataflow, this
222   /// method should be use to handle this.  If this returns true, the solver
223   /// should be rerun.
224   bool ResolvedUndefsIn(Function &F);
225
226   /// getExecutableBlocks - Once we have solved for constants, return the set of
227   /// blocks that is known to be executable.
228   SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
229     return BBExecutable;
230   }
231
232   /// getValueMapping - Once we have solved for constants, return the mapping of
233   /// LLVM values to LatticeVals.
234   std::map<Value*, LatticeVal> &getValueMapping() {
235     return ValueState;
236   }
237
238   /// getTrackedRetVals - Get the inferred return value map.
239   ///
240   const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
241     return TrackedRetVals;
242   }
243
244   /// getTrackedGlobals - Get and return the set of inferred initializers for
245   /// global variables.
246   const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
247     return TrackedGlobals;
248   }
249
250   inline void markOverdefined(Value *V) {
251     markOverdefined(ValueState[V], V);
252   }
253
254 private:
255   // markConstant - Make a value be marked as "constant".  If the value
256   // is not already a constant, add it to the instruction work list so that
257   // the users of the instruction are updated later.
258   //
259   inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
260     if (IV.markConstant(C)) {
261       DOUT << "markConstant: " << *C << ": " << *V;
262       InstWorkList.push_back(V);
263     }
264   }
265   
266   inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
267     IV.markForcedConstant(C);
268     DOUT << "markForcedConstant: " << *C << ": " << *V;
269     InstWorkList.push_back(V);
270   }
271   
272   inline void markConstant(Value *V, Constant *C) {
273     markConstant(ValueState[V], V, C);
274   }
275
276   // markOverdefined - Make a value be marked as "overdefined". If the
277   // value is not already overdefined, add it to the overdefined instruction
278   // work list so that the users of the instruction are updated later.
279   inline void markOverdefined(LatticeVal &IV, Value *V) {
280     if (IV.markOverdefined()) {
281       DEBUG(DOUT << "markOverdefined: ";
282             if (Function *F = dyn_cast<Function>(V))
283               DOUT << "Function '" << F->getName() << "'\n";
284             else
285               DOUT << *V);
286       // Only instructions go on the work list
287       OverdefinedInstWorkList.push_back(V);
288     }
289   }
290
291   inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
292     if (IV.isOverdefined() || MergeWithV.isUndefined())
293       return;  // Noop.
294     if (MergeWithV.isOverdefined())
295       markOverdefined(IV, V);
296     else if (IV.isUndefined())
297       markConstant(IV, V, MergeWithV.getConstant());
298     else if (IV.getConstant() != MergeWithV.getConstant())
299       markOverdefined(IV, V);
300   }
301   
302   inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
303     return mergeInValue(ValueState[V], V, MergeWithV);
304   }
305
306
307   // getValueState - Return the LatticeVal object that corresponds to the value.
308   // This function is necessary because not all values should start out in the
309   // underdefined state... Argument's should be overdefined, and
310   // constants should be marked as constants.  If a value is not known to be an
311   // Instruction object, then use this accessor to get its value from the map.
312   //
313   inline LatticeVal &getValueState(Value *V) {
314     std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
315     if (I != ValueState.end()) return I->second;  // Common case, in the map
316
317     if (Constant *C = dyn_cast<Constant>(V)) {
318       if (isa<UndefValue>(V)) {
319         // Nothing to do, remain undefined.
320       } else {
321         LatticeVal &LV = ValueState[C];
322         LV.markConstant(C);          // Constants are constant
323         return LV;
324       }
325     }
326     // All others are underdefined by default...
327     return ValueState[V];
328   }
329
330   // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
331   // work list if it is not already executable...
332   //
333   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
334     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
335       return;  // This edge is already known to be executable!
336
337     if (BBExecutable.count(Dest)) {
338       DOUT << "Marking Edge Executable: " << Source->getNameStart()
339            << " -> " << Dest->getNameStart() << "\n";
340
341       // The destination is already executable, but we just made an edge
342       // feasible that wasn't before.  Revisit the PHI nodes in the block
343       // because they have potentially new operands.
344       for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
345         visitPHINode(*cast<PHINode>(I));
346
347     } else {
348       MarkBlockExecutable(Dest);
349     }
350   }
351
352   // getFeasibleSuccessors - Return a vector of booleans to indicate which
353   // successors are reachable from a given terminator instruction.
354   //
355   void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
356
357   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
358   // block to the 'To' basic block is currently feasible...
359   //
360   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
361
362   // OperandChangedState - This method is invoked on all of the users of an
363   // instruction that was just changed state somehow....  Based on this
364   // information, we need to update the specified user of this instruction.
365   //
366   void OperandChangedState(User *U) {
367     // Only instructions use other variable values!
368     Instruction &I = cast<Instruction>(*U);
369     if (BBExecutable.count(I.getParent()))   // Inst is executable?
370       visit(I);
371   }
372
373 private:
374   friend class InstVisitor<SCCPSolver>;
375
376   // visit implementations - Something changed in this instruction... Either an
377   // operand made a transition, or the instruction is newly executable.  Change
378   // the value type of I to reflect these changes if appropriate.
379   //
380   void visitPHINode(PHINode &I);
381
382   // Terminators
383   void visitReturnInst(ReturnInst &I);
384   void visitTerminatorInst(TerminatorInst &TI);
385
386   void visitCastInst(CastInst &I);
387   void visitGetResultInst(GetResultInst &GRI);
388   void visitSelectInst(SelectInst &I);
389   void visitBinaryOperator(Instruction &I);
390   void visitCmpInst(CmpInst &I);
391   void visitExtractElementInst(ExtractElementInst &I);
392   void visitInsertElementInst(InsertElementInst &I);
393   void visitShuffleVectorInst(ShuffleVectorInst &I);
394   void visitExtractValueInst(ExtractValueInst &EVI);
395   void visitInsertValueInst(InsertValueInst &IVI);
396
397   // Instructions that cannot be folded away...
398   void visitStoreInst     (Instruction &I);
399   void visitLoadInst      (LoadInst &I);
400   void visitGetElementPtrInst(GetElementPtrInst &I);
401   void visitCallInst      (CallInst &I) { visitCallSite(CallSite::get(&I)); }
402   void visitInvokeInst    (InvokeInst &II) {
403     visitCallSite(CallSite::get(&II));
404     visitTerminatorInst(II);
405   }
406   void visitCallSite      (CallSite CS);
407   void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
408   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
409   void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
410   void visitVANextInst    (Instruction &I) { markOverdefined(&I); }
411   void visitVAArgInst     (Instruction &I) { markOverdefined(&I); }
412   void visitFreeInst      (Instruction &I) { /*returns void*/ }
413
414   void visitInstruction(Instruction &I) {
415     // If a new instruction is added to LLVM that we don't handle...
416     cerr << "SCCP: Don't know how to handle: " << I;
417     markOverdefined(&I);   // Just in case
418   }
419 };
420
421 } // end anonymous namespace
422
423
424 // getFeasibleSuccessors - Return a vector of booleans to indicate which
425 // successors are reachable from a given terminator instruction.
426 //
427 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
428                                        SmallVector<bool, 16> &Succs) {
429   Succs.resize(TI.getNumSuccessors());
430   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
431     if (BI->isUnconditional()) {
432       Succs[0] = true;
433     } else {
434       LatticeVal &BCValue = getValueState(BI->getCondition());
435       if (BCValue.isOverdefined() ||
436           (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
437         // Overdefined condition variables, and branches on unfoldable constant
438         // conditions, mean the branch could go either way.
439         Succs[0] = Succs[1] = true;
440       } else if (BCValue.isConstant()) {
441         // Constant condition variables mean the branch can only go a single way
442         Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
443       }
444     }
445   } else if (isa<InvokeInst>(&TI)) {
446     // Invoke instructions successors are always executable.
447     Succs[0] = Succs[1] = true;
448   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
449     LatticeVal &SCValue = getValueState(SI->getCondition());
450     if (SCValue.isOverdefined() ||   // Overdefined condition?
451         (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
452       // All destinations are executable!
453       Succs.assign(TI.getNumSuccessors(), true);
454     } else if (SCValue.isConstant())
455       Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
456   } else {
457     assert(0 && "SCCP: Don't know how to handle this terminator!");
458   }
459 }
460
461
462 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
463 // block to the 'To' basic block is currently feasible...
464 //
465 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
466   assert(BBExecutable.count(To) && "Dest should always be alive!");
467
468   // Make sure the source basic block is executable!!
469   if (!BBExecutable.count(From)) return false;
470
471   // Check to make sure this edge itself is actually feasible now...
472   TerminatorInst *TI = From->getTerminator();
473   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
474     if (BI->isUnconditional())
475       return true;
476     else {
477       LatticeVal &BCValue = getValueState(BI->getCondition());
478       if (BCValue.isOverdefined()) {
479         // Overdefined condition variables mean the branch could go either way.
480         return true;
481       } else if (BCValue.isConstant()) {
482         // Not branching on an evaluatable constant?
483         if (!isa<ConstantInt>(BCValue.getConstant())) return true;
484
485         // Constant condition variables mean the branch can only go a single way
486         return BI->getSuccessor(BCValue.getConstant() ==
487                                        ConstantInt::getFalse()) == To;
488       }
489       return false;
490     }
491   } else if (isa<InvokeInst>(TI)) {
492     // Invoke instructions successors are always executable.
493     return true;
494   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
495     LatticeVal &SCValue = getValueState(SI->getCondition());
496     if (SCValue.isOverdefined()) {  // Overdefined condition?
497       // All destinations are executable!
498       return true;
499     } else if (SCValue.isConstant()) {
500       Constant *CPV = SCValue.getConstant();
501       if (!isa<ConstantInt>(CPV))
502         return true;  // not a foldable constant?
503
504       // Make sure to skip the "default value" which isn't a value
505       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
506         if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
507           return SI->getSuccessor(i) == To;
508
509       // Constant value not equal to any of the branches... must execute
510       // default branch then...
511       return SI->getDefaultDest() == To;
512     }
513     return false;
514   } else {
515     cerr << "Unknown terminator instruction: " << *TI;
516     abort();
517   }
518 }
519
520 // visit Implementations - Something changed in this instruction... Either an
521 // operand made a transition, or the instruction is newly executable.  Change
522 // the value type of I to reflect these changes if appropriate.  This method
523 // makes sure to do the following actions:
524 //
525 // 1. If a phi node merges two constants in, and has conflicting value coming
526 //    from different branches, or if the PHI node merges in an overdefined
527 //    value, then the PHI node becomes overdefined.
528 // 2. If a phi node merges only constants in, and they all agree on value, the
529 //    PHI node becomes a constant value equal to that.
530 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
531 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
532 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
533 // 6. If a conditional branch has a value that is constant, make the selected
534 //    destination executable
535 // 7. If a conditional branch has a value that is overdefined, make all
536 //    successors executable.
537 //
538 void SCCPSolver::visitPHINode(PHINode &PN) {
539   LatticeVal &PNIV = getValueState(&PN);
540   if (PNIV.isOverdefined()) {
541     // There may be instructions using this PHI node that are not overdefined
542     // themselves.  If so, make sure that they know that the PHI node operand
543     // changed.
544     std::multimap<PHINode*, Instruction*>::iterator I, E;
545     tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
546     if (I != E) {
547       SmallVector<Instruction*, 16> Users;
548       for (; I != E; ++I) Users.push_back(I->second);
549       while (!Users.empty()) {
550         visit(Users.back());
551         Users.pop_back();
552       }
553     }
554     return;  // Quick exit
555   }
556
557   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
558   // and slow us down a lot.  Just mark them overdefined.
559   if (PN.getNumIncomingValues() > 64) {
560     markOverdefined(PNIV, &PN);
561     return;
562   }
563
564   // Look at all of the executable operands of the PHI node.  If any of them
565   // are overdefined, the PHI becomes overdefined as well.  If they are all
566   // constant, and they agree with each other, the PHI becomes the identical
567   // constant.  If they are constant and don't agree, the PHI is overdefined.
568   // If there are no executable operands, the PHI remains undefined.
569   //
570   Constant *OperandVal = 0;
571   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
572     LatticeVal &IV = getValueState(PN.getIncomingValue(i));
573     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
574
575     if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
576       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
577         markOverdefined(PNIV, &PN);
578         return;
579       }
580
581       if (OperandVal == 0) {   // Grab the first value...
582         OperandVal = IV.getConstant();
583       } else {                // Another value is being merged in!
584         // There is already a reachable operand.  If we conflict with it,
585         // then the PHI node becomes overdefined.  If we agree with it, we
586         // can continue on.
587
588         // Check to see if there are two different constants merging...
589         if (IV.getConstant() != OperandVal) {
590           // Yes there is.  This means the PHI node is not constant.
591           // You must be overdefined poor PHI.
592           //
593           markOverdefined(PNIV, &PN);    // The PHI node now becomes overdefined
594           return;    // I'm done analyzing you
595         }
596       }
597     }
598   }
599
600   // If we exited the loop, this means that the PHI node only has constant
601   // arguments that agree with each other(and OperandVal is the constant) or
602   // OperandVal is null because there are no defined incoming arguments.  If
603   // this is the case, the PHI remains undefined.
604   //
605   if (OperandVal)
606     markConstant(PNIV, &PN, OperandVal);      // Acquire operand value
607 }
608
609 void SCCPSolver::visitReturnInst(ReturnInst &I) {
610   if (I.getNumOperands() == 0) return;  // Ret void
611
612   Function *F = I.getParent()->getParent();
613   // If we are tracking the return value of this function, merge it in.
614   if (!F->hasInternalLinkage())
615     return;
616
617   if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
618     DenseMap<Function*, LatticeVal>::iterator TFRVI =
619       TrackedRetVals.find(F);
620     if (TFRVI != TrackedRetVals.end() &&
621         !TFRVI->second.isOverdefined()) {
622       LatticeVal &IV = getValueState(I.getOperand(0));
623       mergeInValue(TFRVI->second, F, IV);
624       return;
625     }
626   }
627   
628   // Handle functions that return multiple values.
629   if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
630     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
631       std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
632         It = TrackedMultipleRetVals.find(std::make_pair(F, i));
633       if (It == TrackedMultipleRetVals.end()) break;
634       mergeInValue(It->second, F, getValueState(I.getOperand(i)));
635     }
636   } else if (!TrackedMultipleRetVals.empty() &&
637              I.getNumOperands() == 1 &&
638              isa<StructType>(I.getOperand(0)->getType())) {
639     for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
640          i != e; ++i) {
641       std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
642         It = TrackedMultipleRetVals.find(std::make_pair(F, i));
643       if (It == TrackedMultipleRetVals.end()) break;
644       Value *Val = FindInsertedValue(I.getOperand(0), i);
645       mergeInValue(It->second, F, getValueState(Val));
646     }
647   }
648 }
649
650 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
651   SmallVector<bool, 16> SuccFeasible;
652   getFeasibleSuccessors(TI, SuccFeasible);
653
654   BasicBlock *BB = TI.getParent();
655
656   // Mark all feasible successors executable...
657   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
658     if (SuccFeasible[i])
659       markEdgeExecutable(BB, TI.getSuccessor(i));
660 }
661
662 void SCCPSolver::visitCastInst(CastInst &I) {
663   Value *V = I.getOperand(0);
664   LatticeVal &VState = getValueState(V);
665   if (VState.isOverdefined())          // Inherit overdefinedness of operand
666     markOverdefined(&I);
667   else if (VState.isConstant())        // Propagate constant value
668     markConstant(&I, ConstantExpr::getCast(I.getOpcode(), 
669                                            VState.getConstant(), I.getType()));
670 }
671
672 void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
673   Value *Aggr = GRI.getOperand(0);
674
675   // If the operand to the getresult is an undef, the result is undef.
676   if (isa<UndefValue>(Aggr))
677     return;
678   
679   Function *F;
680   if (CallInst *CI = dyn_cast<CallInst>(Aggr))
681     F = CI->getCalledFunction();
682   else
683     F = cast<InvokeInst>(Aggr)->getCalledFunction();
684
685   // TODO: If IPSCCP resolves the callee of this function, we could propagate a
686   // result back!
687   if (F == 0 || TrackedMultipleRetVals.empty()) {
688     markOverdefined(&GRI);
689     return;
690   }
691   
692   // See if we are tracking the result of the callee.
693   std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
694     It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
695
696   // If not tracking this function (for example, it is a declaration) just move
697   // to overdefined.
698   if (It == TrackedMultipleRetVals.end()) {
699     markOverdefined(&GRI);
700     return;
701   }
702   
703   // Otherwise, the value will be merged in here as a result of CallSite
704   // handling.
705 }
706
707 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
708   Value *Aggr = EVI.getOperand(0);
709
710   // If the operand to the getresult is an undef, the result is undef.
711   if (isa<UndefValue>(Aggr))
712     return;
713
714   // Currently only handle single-index extractvalues.
715   if (EVI.getNumIndices() != 1) {
716     markOverdefined(&EVI);
717     return;
718   }
719   
720   Function *F = 0;
721   if (CallInst *CI = dyn_cast<CallInst>(Aggr))
722     F = CI->getCalledFunction();
723   else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
724     F = II->getCalledFunction();
725
726   // TODO: If IPSCCP resolves the callee of this function, we could propagate a
727   // result back!
728   if (F == 0 || TrackedMultipleRetVals.empty()) {
729     markOverdefined(&EVI);
730     return;
731   }
732   
733   // See if we are tracking the result of the callee.
734   std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
735     It = TrackedMultipleRetVals.find(std::make_pair(F, *EVI.idx_begin()));
736
737   // If not tracking this function (for example, it is a declaration) just move
738   // to overdefined.
739   if (It == TrackedMultipleRetVals.end()) {
740     markOverdefined(&EVI);
741     return;
742   }
743   
744   // Otherwise, the value will be merged in here as a result of CallSite
745   // handling.
746 }
747
748 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
749   Value *Aggr = IVI.getOperand(0);
750   Value *Val = IVI.getOperand(1);
751
752   // If the operand to the getresult is an undef, the result is undef.
753   if (isa<UndefValue>(Aggr))
754     return;
755
756   // Currently only handle single-index insertvalues.
757   if (IVI.getNumIndices() != 1) {
758     markOverdefined(&IVI);
759     return;
760   }
761   
762   // See if we are tracking the result of the callee.
763   Function *F = IVI.getParent()->getParent();
764   std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
765     It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
766
767   // Merge in the inserted member value.
768   if (It != TrackedMultipleRetVals.end())
769     mergeInValue(It->second, F, getValueState(Val));
770
771   // Mark the aggregate result of the IVI overdefined; any tracking that we do will
772   // be done on the individual member values.
773   markOverdefined(&IVI);
774 }
775
776 void SCCPSolver::visitSelectInst(SelectInst &I) {
777   LatticeVal &CondValue = getValueState(I.getCondition());
778   if (CondValue.isUndefined())
779     return;
780   if (CondValue.isConstant()) {
781     if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
782       mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
783                                                           : I.getFalseValue()));
784       return;
785     }
786   }
787   
788   // Otherwise, the condition is overdefined or a constant we can't evaluate.
789   // See if we can produce something better than overdefined based on the T/F
790   // value.
791   LatticeVal &TVal = getValueState(I.getTrueValue());
792   LatticeVal &FVal = getValueState(I.getFalseValue());
793   
794   // select ?, C, C -> C.
795   if (TVal.isConstant() && FVal.isConstant() && 
796       TVal.getConstant() == FVal.getConstant()) {
797     markConstant(&I, FVal.getConstant());
798     return;
799   }
800
801   if (TVal.isUndefined()) {  // select ?, undef, X -> X.
802     mergeInValue(&I, FVal);
803   } else if (FVal.isUndefined()) {  // select ?, X, undef -> X.
804     mergeInValue(&I, TVal);
805   } else {
806     markOverdefined(&I);
807   }
808 }
809
810 // Handle BinaryOperators and Shift Instructions...
811 void SCCPSolver::visitBinaryOperator(Instruction &I) {
812   LatticeVal &IV = ValueState[&I];
813   if (IV.isOverdefined()) return;
814
815   LatticeVal &V1State = getValueState(I.getOperand(0));
816   LatticeVal &V2State = getValueState(I.getOperand(1));
817
818   if (V1State.isOverdefined() || V2State.isOverdefined()) {
819     // If this is an AND or OR with 0 or -1, it doesn't matter that the other
820     // operand is overdefined.
821     if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
822       LatticeVal *NonOverdefVal = 0;
823       if (!V1State.isOverdefined()) {
824         NonOverdefVal = &V1State;
825       } else if (!V2State.isOverdefined()) {
826         NonOverdefVal = &V2State;
827       }
828
829       if (NonOverdefVal) {
830         if (NonOverdefVal->isUndefined()) {
831           // Could annihilate value.
832           if (I.getOpcode() == Instruction::And)
833             markConstant(IV, &I, Constant::getNullValue(I.getType()));
834           else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
835             markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
836           else
837             markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
838           return;
839         } else {
840           if (I.getOpcode() == Instruction::And) {
841             if (NonOverdefVal->getConstant()->isNullValue()) {
842               markConstant(IV, &I, NonOverdefVal->getConstant());
843               return;      // X and 0 = 0
844             }
845           } else {
846             if (ConstantInt *CI =
847                      dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
848               if (CI->isAllOnesValue()) {
849                 markConstant(IV, &I, NonOverdefVal->getConstant());
850                 return;    // X or -1 = -1
851               }
852           }
853         }
854       }
855     }
856
857
858     // If both operands are PHI nodes, it is possible that this instruction has
859     // a constant value, despite the fact that the PHI node doesn't.  Check for
860     // this condition now.
861     if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
862       if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
863         if (PN1->getParent() == PN2->getParent()) {
864           // Since the two PHI nodes are in the same basic block, they must have
865           // entries for the same predecessors.  Walk the predecessor list, and
866           // if all of the incoming values are constants, and the result of
867           // evaluating this expression with all incoming value pairs is the
868           // same, then this expression is a constant even though the PHI node
869           // is not a constant!
870           LatticeVal Result;
871           for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
872             LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
873             BasicBlock *InBlock = PN1->getIncomingBlock(i);
874             LatticeVal &In2 =
875               getValueState(PN2->getIncomingValueForBlock(InBlock));
876
877             if (In1.isOverdefined() || In2.isOverdefined()) {
878               Result.markOverdefined();
879               break;  // Cannot fold this operation over the PHI nodes!
880             } else if (In1.isConstant() && In2.isConstant()) {
881               Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
882                                               In2.getConstant());
883               if (Result.isUndefined())
884                 Result.markConstant(V);
885               else if (Result.isConstant() && Result.getConstant() != V) {
886                 Result.markOverdefined();
887                 break;
888               }
889             }
890           }
891
892           // If we found a constant value here, then we know the instruction is
893           // constant despite the fact that the PHI nodes are overdefined.
894           if (Result.isConstant()) {
895             markConstant(IV, &I, Result.getConstant());
896             // Remember that this instruction is virtually using the PHI node
897             // operands.
898             UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
899             UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
900             return;
901           } else if (Result.isUndefined()) {
902             return;
903           }
904
905           // Okay, this really is overdefined now.  Since we might have
906           // speculatively thought that this was not overdefined before, and
907           // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
908           // make sure to clean out any entries that we put there, for
909           // efficiency.
910           std::multimap<PHINode*, Instruction*>::iterator It, E;
911           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
912           while (It != E) {
913             if (It->second == &I) {
914               UsersOfOverdefinedPHIs.erase(It++);
915             } else
916               ++It;
917           }
918           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
919           while (It != E) {
920             if (It->second == &I) {
921               UsersOfOverdefinedPHIs.erase(It++);
922             } else
923               ++It;
924           }
925         }
926
927     markOverdefined(IV, &I);
928   } else if (V1State.isConstant() && V2State.isConstant()) {
929     markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
930                                            V2State.getConstant()));
931   }
932 }
933
934 // Handle ICmpInst instruction...
935 void SCCPSolver::visitCmpInst(CmpInst &I) {
936   LatticeVal &IV = ValueState[&I];
937   if (IV.isOverdefined()) return;
938
939   LatticeVal &V1State = getValueState(I.getOperand(0));
940   LatticeVal &V2State = getValueState(I.getOperand(1));
941
942   if (V1State.isOverdefined() || V2State.isOverdefined()) {
943     // If both operands are PHI nodes, it is possible that this instruction has
944     // a constant value, despite the fact that the PHI node doesn't.  Check for
945     // this condition now.
946     if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
947       if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
948         if (PN1->getParent() == PN2->getParent()) {
949           // Since the two PHI nodes are in the same basic block, they must have
950           // entries for the same predecessors.  Walk the predecessor list, and
951           // if all of the incoming values are constants, and the result of
952           // evaluating this expression with all incoming value pairs is the
953           // same, then this expression is a constant even though the PHI node
954           // is not a constant!
955           LatticeVal Result;
956           for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
957             LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
958             BasicBlock *InBlock = PN1->getIncomingBlock(i);
959             LatticeVal &In2 =
960               getValueState(PN2->getIncomingValueForBlock(InBlock));
961
962             if (In1.isOverdefined() || In2.isOverdefined()) {
963               Result.markOverdefined();
964               break;  // Cannot fold this operation over the PHI nodes!
965             } else if (In1.isConstant() && In2.isConstant()) {
966               Constant *V = ConstantExpr::getCompare(I.getPredicate(), 
967                                                      In1.getConstant(), 
968                                                      In2.getConstant());
969               if (Result.isUndefined())
970                 Result.markConstant(V);
971               else if (Result.isConstant() && Result.getConstant() != V) {
972                 Result.markOverdefined();
973                 break;
974               }
975             }
976           }
977
978           // If we found a constant value here, then we know the instruction is
979           // constant despite the fact that the PHI nodes are overdefined.
980           if (Result.isConstant()) {
981             markConstant(IV, &I, Result.getConstant());
982             // Remember that this instruction is virtually using the PHI node
983             // operands.
984             UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
985             UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
986             return;
987           } else if (Result.isUndefined()) {
988             return;
989           }
990
991           // Okay, this really is overdefined now.  Since we might have
992           // speculatively thought that this was not overdefined before, and
993           // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
994           // make sure to clean out any entries that we put there, for
995           // efficiency.
996           std::multimap<PHINode*, Instruction*>::iterator It, E;
997           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
998           while (It != E) {
999             if (It->second == &I) {
1000               UsersOfOverdefinedPHIs.erase(It++);
1001             } else
1002               ++It;
1003           }
1004           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1005           while (It != E) {
1006             if (It->second == &I) {
1007               UsersOfOverdefinedPHIs.erase(It++);
1008             } else
1009               ++It;
1010           }
1011         }
1012
1013     markOverdefined(IV, &I);
1014   } else if (V1State.isConstant() && V2State.isConstant()) {
1015     markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(), 
1016                                                   V1State.getConstant(), 
1017                                                   V2State.getConstant()));
1018   }
1019 }
1020
1021 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1022   // FIXME : SCCP does not handle vectors properly.
1023   markOverdefined(&I);
1024   return;
1025
1026 #if 0
1027   LatticeVal &ValState = getValueState(I.getOperand(0));
1028   LatticeVal &IdxState = getValueState(I.getOperand(1));
1029
1030   if (ValState.isOverdefined() || IdxState.isOverdefined())
1031     markOverdefined(&I);
1032   else if(ValState.isConstant() && IdxState.isConstant())
1033     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1034                                                      IdxState.getConstant()));
1035 #endif
1036 }
1037
1038 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1039   // FIXME : SCCP does not handle vectors properly.
1040   markOverdefined(&I);
1041   return;
1042 #if 0
1043   LatticeVal &ValState = getValueState(I.getOperand(0));
1044   LatticeVal &EltState = getValueState(I.getOperand(1));
1045   LatticeVal &IdxState = getValueState(I.getOperand(2));
1046
1047   if (ValState.isOverdefined() || EltState.isOverdefined() ||
1048       IdxState.isOverdefined())
1049     markOverdefined(&I);
1050   else if(ValState.isConstant() && EltState.isConstant() &&
1051           IdxState.isConstant())
1052     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1053                                                     EltState.getConstant(),
1054                                                     IdxState.getConstant()));
1055   else if (ValState.isUndefined() && EltState.isConstant() &&
1056            IdxState.isConstant()) 
1057     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1058                                                    EltState.getConstant(),
1059                                                    IdxState.getConstant()));
1060 #endif
1061 }
1062
1063 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1064   // FIXME : SCCP does not handle vectors properly.
1065   markOverdefined(&I);
1066   return;
1067 #if 0
1068   LatticeVal &V1State   = getValueState(I.getOperand(0));
1069   LatticeVal &V2State   = getValueState(I.getOperand(1));
1070   LatticeVal &MaskState = getValueState(I.getOperand(2));
1071
1072   if (MaskState.isUndefined() ||
1073       (V1State.isUndefined() && V2State.isUndefined()))
1074     return;  // Undefined output if mask or both inputs undefined.
1075   
1076   if (V1State.isOverdefined() || V2State.isOverdefined() ||
1077       MaskState.isOverdefined()) {
1078     markOverdefined(&I);
1079   } else {
1080     // A mix of constant/undef inputs.
1081     Constant *V1 = V1State.isConstant() ? 
1082         V1State.getConstant() : UndefValue::get(I.getType());
1083     Constant *V2 = V2State.isConstant() ? 
1084         V2State.getConstant() : UndefValue::get(I.getType());
1085     Constant *Mask = MaskState.isConstant() ? 
1086       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1087     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1088   }
1089 #endif
1090 }
1091
1092 // Handle getelementptr instructions... if all operands are constants then we
1093 // can turn this into a getelementptr ConstantExpr.
1094 //
1095 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1096   LatticeVal &IV = ValueState[&I];
1097   if (IV.isOverdefined()) return;
1098
1099   SmallVector<Constant*, 8> Operands;
1100   Operands.reserve(I.getNumOperands());
1101
1102   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1103     LatticeVal &State = getValueState(I.getOperand(i));
1104     if (State.isUndefined())
1105       return;  // Operands are not resolved yet...
1106     else if (State.isOverdefined()) {
1107       markOverdefined(IV, &I);
1108       return;
1109     }
1110     assert(State.isConstant() && "Unknown state!");
1111     Operands.push_back(State.getConstant());
1112   }
1113
1114   Constant *Ptr = Operands[0];
1115   Operands.erase(Operands.begin());  // Erase the pointer from idx list...
1116
1117   markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1118                                                       Operands.size()));
1119 }
1120
1121 void SCCPSolver::visitStoreInst(Instruction &SI) {
1122   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1123     return;
1124   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1125   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1126   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1127
1128   // Get the value we are storing into the global.
1129   LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1130
1131   mergeInValue(I->second, GV, PtrVal);
1132   if (I->second.isOverdefined())
1133     TrackedGlobals.erase(I);      // No need to keep tracking this!
1134 }
1135
1136
1137 // Handle load instructions.  If the operand is a constant pointer to a constant
1138 // global, we can replace the load with the loaded constant value!
1139 void SCCPSolver::visitLoadInst(LoadInst &I) {
1140   LatticeVal &IV = ValueState[&I];
1141   if (IV.isOverdefined()) return;
1142
1143   LatticeVal &PtrVal = getValueState(I.getOperand(0));
1144   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
1145   if (PtrVal.isConstant() && !I.isVolatile()) {
1146     Value *Ptr = PtrVal.getConstant();
1147     // TODO: Consider a target hook for valid address spaces for this xform.
1148     if (isa<ConstantPointerNull>(Ptr) && 
1149         cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
1150       // load null -> null
1151       markConstant(IV, &I, Constant::getNullValue(I.getType()));
1152       return;
1153     }
1154
1155     // Transform load (constant global) into the value loaded.
1156     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1157       if (GV->isConstant()) {
1158         if (!GV->isDeclaration()) {
1159           markConstant(IV, &I, GV->getInitializer());
1160           return;
1161         }
1162       } else if (!TrackedGlobals.empty()) {
1163         // If we are tracking this global, merge in the known value for it.
1164         DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1165           TrackedGlobals.find(GV);
1166         if (It != TrackedGlobals.end()) {
1167           mergeInValue(IV, &I, It->second);
1168           return;
1169         }
1170       }
1171     }
1172
1173     // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1174     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1175       if (CE->getOpcode() == Instruction::GetElementPtr)
1176     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1177       if (GV->isConstant() && !GV->isDeclaration())
1178         if (Constant *V =
1179              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1180           markConstant(IV, &I, V);
1181           return;
1182         }
1183   }
1184
1185   // Otherwise we cannot say for certain what value this load will produce.
1186   // Bail out.
1187   markOverdefined(IV, &I);
1188 }
1189
1190 void SCCPSolver::visitCallSite(CallSite CS) {
1191   Function *F = CS.getCalledFunction();
1192   Instruction *I = CS.getInstruction();
1193   
1194   // The common case is that we aren't tracking the callee, either because we
1195   // are not doing interprocedural analysis or the callee is indirect, or is
1196   // external.  Handle these cases first.
1197   if (F == 0 || !F->hasInternalLinkage()) {
1198 CallOverdefined:
1199     // Void return and not tracking callee, just bail.
1200     if (I->getType() == Type::VoidTy) return;
1201     
1202     // Otherwise, if we have a single return value case, and if the function is
1203     // a declaration, maybe we can constant fold it.
1204     if (!isa<StructType>(I->getType()) && F && F->isDeclaration() && 
1205         canConstantFoldCallTo(F)) {
1206       
1207       SmallVector<Constant*, 8> Operands;
1208       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1209            AI != E; ++AI) {
1210         LatticeVal &State = getValueState(*AI);
1211         if (State.isUndefined())
1212           return;  // Operands are not resolved yet.
1213         else if (State.isOverdefined()) {
1214           markOverdefined(I);
1215           return;
1216         }
1217         assert(State.isConstant() && "Unknown state!");
1218         Operands.push_back(State.getConstant());
1219       }
1220      
1221       // If we can constant fold this, mark the result of the call as a
1222       // constant.
1223       if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1224         markConstant(I, C);
1225         return;
1226       }
1227     }
1228
1229     // Otherwise, we don't know anything about this call, mark it overdefined.
1230     markOverdefined(I);
1231     return;
1232   }
1233
1234   // If this is a single/zero retval case, see if we're tracking the function.
1235   DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1236   if (TFRVI != TrackedRetVals.end()) {
1237     // If so, propagate the return value of the callee into this call result.
1238     mergeInValue(I, TFRVI->second);
1239   } else if (isa<StructType>(I->getType())) {
1240     // Check to see if we're tracking this callee, if not, handle it in the
1241     // common path above.
1242     std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1243       TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1244     if (TMRVI == TrackedMultipleRetVals.end())
1245       goto CallOverdefined;
1246     
1247     // If we are tracking this callee, propagate the return values of the call
1248     // into this call site.  We do this by walking all the uses. Single-index
1249     // ExtractValueInst uses can be tracked; anything more complicated is
1250     // currently handled conservatively.
1251     for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1252          UI != E; ++UI) {
1253       if (GetResultInst *GRI = dyn_cast<GetResultInst>(*UI)) {
1254         mergeInValue(GRI, 
1255                      TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1256         continue;
1257       }
1258       if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1259         if (EVI->getNumIndices() == 1) {
1260           mergeInValue(EVI, 
1261                        TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
1262           continue;
1263         }
1264       }
1265       // The aggregate value is used in a way not handled here. Assume nothing.
1266       markOverdefined(*UI);
1267     }
1268   } else {
1269     // Otherwise we're not tracking this callee, so handle it in the
1270     // common path above.
1271     goto CallOverdefined;
1272   }
1273    
1274   // Finally, if this is the first call to the function hit, mark its entry
1275   // block executable.
1276   if (!BBExecutable.count(F->begin()))
1277     MarkBlockExecutable(F->begin());
1278   
1279   // Propagate information from this call site into the callee.
1280   CallSite::arg_iterator CAI = CS.arg_begin();
1281   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1282        AI != E; ++AI, ++CAI) {
1283     LatticeVal &IV = ValueState[AI];
1284     if (!IV.isOverdefined())
1285       mergeInValue(IV, AI, getValueState(*CAI));
1286   }
1287 }
1288
1289
1290 void SCCPSolver::Solve() {
1291   // Process the work lists until they are empty!
1292   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1293          !OverdefinedInstWorkList.empty()) {
1294     // Process the instruction work list...
1295     while (!OverdefinedInstWorkList.empty()) {
1296       Value *I = OverdefinedInstWorkList.back();
1297       OverdefinedInstWorkList.pop_back();
1298
1299       DOUT << "\nPopped off OI-WL: " << *I;
1300
1301       // "I" got into the work list because it either made the transition from
1302       // bottom to constant
1303       //
1304       // Anything on this worklist that is overdefined need not be visited
1305       // since all of its users will have already been marked as overdefined
1306       // Update all of the users of this instruction's value...
1307       //
1308       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1309            UI != E; ++UI)
1310         OperandChangedState(*UI);
1311     }
1312     // Process the instruction work list...
1313     while (!InstWorkList.empty()) {
1314       Value *I = InstWorkList.back();
1315       InstWorkList.pop_back();
1316
1317       DOUT << "\nPopped off I-WL: " << *I;
1318
1319       // "I" got into the work list because it either made the transition from
1320       // bottom to constant
1321       //
1322       // Anything on this worklist that is overdefined need not be visited
1323       // since all of its users will have already been marked as overdefined.
1324       // Update all of the users of this instruction's value...
1325       //
1326       if (!getValueState(I).isOverdefined())
1327         for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1328              UI != E; ++UI)
1329           OperandChangedState(*UI);
1330     }
1331
1332     // Process the basic block work list...
1333     while (!BBWorkList.empty()) {
1334       BasicBlock *BB = BBWorkList.back();
1335       BBWorkList.pop_back();
1336
1337       DOUT << "\nPopped off BBWL: " << *BB;
1338
1339       // Notify all instructions in this basic block that they are newly
1340       // executable.
1341       visit(BB);
1342     }
1343   }
1344 }
1345
1346 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1347 /// that branches on undef values cannot reach any of their successors.
1348 /// However, this is not a safe assumption.  After we solve dataflow, this
1349 /// method should be use to handle this.  If this returns true, the solver
1350 /// should be rerun.
1351 ///
1352 /// This method handles this by finding an unresolved branch and marking it one
1353 /// of the edges from the block as being feasible, even though the condition
1354 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1355 /// CFG and only slightly pessimizes the analysis results (by marking one,
1356 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1357 /// constraints on the condition of the branch, as that would impact other users
1358 /// of the value.
1359 ///
1360 /// This scan also checks for values that use undefs, whose results are actually
1361 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
1362 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1363 /// even if X isn't defined.
1364 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1365   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1366     if (!BBExecutable.count(BB))
1367       continue;
1368     
1369     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1370       // Look for instructions which produce undef values.
1371       if (I->getType() == Type::VoidTy) continue;
1372       
1373       LatticeVal &LV = getValueState(I);
1374       if (!LV.isUndefined()) continue;
1375
1376       // Get the lattice values of the first two operands for use below.
1377       LatticeVal &Op0LV = getValueState(I->getOperand(0));
1378       LatticeVal Op1LV;
1379       if (I->getNumOperands() == 2) {
1380         // If this is a two-operand instruction, and if both operands are
1381         // undefs, the result stays undef.
1382         Op1LV = getValueState(I->getOperand(1));
1383         if (Op0LV.isUndefined() && Op1LV.isUndefined())
1384           continue;
1385       }
1386       
1387       // If this is an instructions whose result is defined even if the input is
1388       // not fully defined, propagate the information.
1389       const Type *ITy = I->getType();
1390       switch (I->getOpcode()) {
1391       default: break;          // Leave the instruction as an undef.
1392       case Instruction::ZExt:
1393         // After a zero extend, we know the top part is zero.  SExt doesn't have
1394         // to be handled here, because we don't know whether the top part is 1's
1395         // or 0's.
1396         assert(Op0LV.isUndefined());
1397         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1398         return true;
1399       case Instruction::Mul:
1400       case Instruction::And:
1401         // undef * X -> 0.   X could be zero.
1402         // undef & X -> 0.   X could be zero.
1403         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1404         return true;
1405
1406       case Instruction::Or:
1407         // undef | X -> -1.   X could be -1.
1408         if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1409           markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
1410         else          
1411           markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1412         return true;
1413
1414       case Instruction::SDiv:
1415       case Instruction::UDiv:
1416       case Instruction::SRem:
1417       case Instruction::URem:
1418         // X / undef -> undef.  No change.
1419         // X % undef -> undef.  No change.
1420         if (Op1LV.isUndefined()) break;
1421         
1422         // undef / X -> 0.   X could be maxint.
1423         // undef % X -> 0.   X could be 1.
1424         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1425         return true;
1426         
1427       case Instruction::AShr:
1428         // undef >>s X -> undef.  No change.
1429         if (Op0LV.isUndefined()) break;
1430         
1431         // X >>s undef -> X.  X could be 0, X could have the high-bit known set.
1432         if (Op0LV.isConstant())
1433           markForcedConstant(LV, I, Op0LV.getConstant());
1434         else
1435           markOverdefined(LV, I);
1436         return true;
1437       case Instruction::LShr:
1438       case Instruction::Shl:
1439         // undef >> X -> undef.  No change.
1440         // undef << X -> undef.  No change.
1441         if (Op0LV.isUndefined()) break;
1442         
1443         // X >> undef -> 0.  X could be 0.
1444         // X << undef -> 0.  X could be 0.
1445         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1446         return true;
1447       case Instruction::Select:
1448         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
1449         if (Op0LV.isUndefined()) {
1450           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
1451             Op1LV = getValueState(I->getOperand(2));
1452         } else if (Op1LV.isUndefined()) {
1453           // c ? undef : undef -> undef.  No change.
1454           Op1LV = getValueState(I->getOperand(2));
1455           if (Op1LV.isUndefined())
1456             break;
1457           // Otherwise, c ? undef : x -> x.
1458         } else {
1459           // Leave Op1LV as Operand(1)'s LatticeValue.
1460         }
1461         
1462         if (Op1LV.isConstant())
1463           markForcedConstant(LV, I, Op1LV.getConstant());
1464         else
1465           markOverdefined(LV, I);
1466         return true;
1467       case Instruction::Call:
1468         // If a call has an undef result, it is because it is constant foldable
1469         // but one of the inputs was undef.  Just force the result to
1470         // overdefined.
1471         markOverdefined(LV, I);
1472         return true;
1473       }
1474     }
1475   
1476     TerminatorInst *TI = BB->getTerminator();
1477     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1478       if (!BI->isConditional()) continue;
1479       if (!getValueState(BI->getCondition()).isUndefined())
1480         continue;
1481     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1482       if (SI->getNumSuccessors()<2)   // no cases
1483         continue;
1484       if (!getValueState(SI->getCondition()).isUndefined())
1485         continue;
1486     } else {
1487       continue;
1488     }
1489     
1490     // If the edge to the second successor isn't thought to be feasible yet,
1491     // mark it so now.  We pick the second one so that this goes to some
1492     // enumerated value in a switch instead of going to the default destination.
1493     if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1494       continue;
1495     
1496     // Otherwise, it isn't already thought to be feasible.  Mark it as such now
1497     // and return.  This will make other blocks reachable, which will allow new
1498     // values to be discovered and existing ones to be moved in the lattice.
1499     markEdgeExecutable(BB, TI->getSuccessor(1));
1500     
1501     // This must be a conditional branch of switch on undef.  At this point,
1502     // force the old terminator to branch to the first successor.  This is
1503     // required because we are now influencing the dataflow of the function with
1504     // the assumption that this edge is taken.  If we leave the branch condition
1505     // as undef, then further analysis could think the undef went another way
1506     // leading to an inconsistent set of conclusions.
1507     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1508       BI->setCondition(ConstantInt::getFalse());
1509     } else {
1510       SwitchInst *SI = cast<SwitchInst>(TI);
1511       SI->setCondition(SI->getCaseValue(1));
1512     }
1513     
1514     return true;
1515   }
1516
1517   return false;
1518 }
1519
1520
1521 namespace {
1522   //===--------------------------------------------------------------------===//
1523   //
1524   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1525   /// Sparse Conditional Constant Propagator.
1526   ///
1527   struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1528     static char ID; // Pass identification, replacement for typeid
1529     SCCP() : FunctionPass((intptr_t)&ID) {}
1530
1531     // runOnFunction - Run the Sparse Conditional Constant Propagation
1532     // algorithm, and return true if the function was modified.
1533     //
1534     bool runOnFunction(Function &F);
1535
1536     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1537       AU.setPreservesCFG();
1538     }
1539   };
1540 } // end anonymous namespace
1541
1542 char SCCP::ID = 0;
1543 static RegisterPass<SCCP>
1544 X("sccp", "Sparse Conditional Constant Propagation");
1545
1546 // createSCCPPass - This is the public interface to this file...
1547 FunctionPass *llvm::createSCCPPass() {
1548   return new SCCP();
1549 }
1550
1551
1552 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1553 // and return true if the function was modified.
1554 //
1555 bool SCCP::runOnFunction(Function &F) {
1556   DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
1557   SCCPSolver Solver;
1558
1559   // Mark the first block of the function as being executable.
1560   Solver.MarkBlockExecutable(F.begin());
1561
1562   // Mark all arguments to the function as being overdefined.
1563   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1564     Solver.markOverdefined(AI);
1565
1566   // Solve for constants.
1567   bool ResolvedUndefs = true;
1568   while (ResolvedUndefs) {
1569     Solver.Solve();
1570     DOUT << "RESOLVING UNDEFs\n";
1571     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1572   }
1573
1574   bool MadeChanges = false;
1575
1576   // If we decided that there are basic blocks that are dead in this function,
1577   // delete their contents now.  Note that we cannot actually delete the blocks,
1578   // as we cannot modify the CFG of the function.
1579   //
1580   SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1581   SmallVector<Instruction*, 32> Insts;
1582   std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1583
1584   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1585     if (!ExecutableBBs.count(BB)) {
1586       DOUT << "  BasicBlock Dead:" << *BB;
1587       ++NumDeadBlocks;
1588
1589       // Delete the instructions backwards, as it has a reduced likelihood of
1590       // having to update as many def-use and use-def chains.
1591       for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1592            I != E; ++I)
1593         Insts.push_back(I);
1594       while (!Insts.empty()) {
1595         Instruction *I = Insts.back();
1596         Insts.pop_back();
1597         if (!I->use_empty())
1598           I->replaceAllUsesWith(UndefValue::get(I->getType()));
1599         BB->getInstList().erase(I);
1600         MadeChanges = true;
1601         ++NumInstRemoved;
1602       }
1603     } else {
1604       // Iterate over all of the instructions in a function, replacing them with
1605       // constants if we have found them to be of constant values.
1606       //
1607       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1608         Instruction *Inst = BI++;
1609         if (Inst->getType() == Type::VoidTy ||
1610             isa<StructType>(Inst->getType()) ||
1611             isa<TerminatorInst>(Inst))
1612           continue;
1613         
1614         LatticeVal &IV = Values[Inst];
1615         if (!IV.isConstant() && !IV.isUndefined())
1616           continue;
1617         
1618         Constant *Const = IV.isConstant()
1619           ? IV.getConstant() : UndefValue::get(Inst->getType());
1620         DOUT << "  Constant: " << *Const << " = " << *Inst;
1621
1622         // Replaces all of the uses of a variable with uses of the constant.
1623         Inst->replaceAllUsesWith(Const);
1624         
1625         // Delete the instruction.
1626         Inst->eraseFromParent();
1627         
1628         // Hey, we just changed something!
1629         MadeChanges = true;
1630         ++NumInstRemoved;
1631       }
1632     }
1633
1634   return MadeChanges;
1635 }
1636
1637 namespace {
1638   //===--------------------------------------------------------------------===//
1639   //
1640   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1641   /// Constant Propagation.
1642   ///
1643   struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1644     static char ID;
1645     IPSCCP() : ModulePass((intptr_t)&ID) {}
1646     bool runOnModule(Module &M);
1647   };
1648 } // end anonymous namespace
1649
1650 char IPSCCP::ID = 0;
1651 static RegisterPass<IPSCCP>
1652 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1653
1654 // createIPSCCPPass - This is the public interface to this file...
1655 ModulePass *llvm::createIPSCCPPass() {
1656   return new IPSCCP();
1657 }
1658
1659
1660 static bool AddressIsTaken(GlobalValue *GV) {
1661   // Delete any dead constantexpr klingons.
1662   GV->removeDeadConstantUsers();
1663
1664   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1665        UI != E; ++UI)
1666     if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1667       if (SI->getOperand(0) == GV || SI->isVolatile())
1668         return true;  // Storing addr of GV.
1669     } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1670       // Make sure we are calling the function, not passing the address.
1671       CallSite CS = CallSite::get(cast<Instruction>(*UI));
1672       for (CallSite::arg_iterator AI = CS.arg_begin(),
1673              E = CS.arg_end(); AI != E; ++AI)
1674         if (*AI == GV)
1675           return true;
1676     } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1677       if (LI->isVolatile())
1678         return true;
1679     } else {
1680       return true;
1681     }
1682   return false;
1683 }
1684
1685 bool IPSCCP::runOnModule(Module &M) {
1686   SCCPSolver Solver;
1687
1688   // Loop over all functions, marking arguments to those with their addresses
1689   // taken or that are external as overdefined.
1690   //
1691   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1692     if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1693       if (!F->isDeclaration())
1694         Solver.MarkBlockExecutable(F->begin());
1695       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1696            AI != E; ++AI)
1697         Solver.markOverdefined(AI);
1698     } else {
1699       Solver.AddTrackedFunction(F);
1700     }
1701
1702   // Loop over global variables.  We inform the solver about any internal global
1703   // variables that do not have their 'addresses taken'.  If they don't have
1704   // their addresses taken, we can propagate constants through them.
1705   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1706        G != E; ++G)
1707     if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1708       Solver.TrackValueOfGlobalVariable(G);
1709
1710   // Solve for constants.
1711   bool ResolvedUndefs = true;
1712   while (ResolvedUndefs) {
1713     Solver.Solve();
1714
1715     DOUT << "RESOLVING UNDEFS\n";
1716     ResolvedUndefs = false;
1717     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1718       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1719   }
1720
1721   bool MadeChanges = false;
1722
1723   // Iterate over all of the instructions in the module, replacing them with
1724   // constants if we have found them to be of constant values.
1725   //
1726   SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1727   SmallVector<Instruction*, 32> Insts;
1728   SmallVector<BasicBlock*, 32> BlocksToErase;
1729   std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1730
1731   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1732     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1733          AI != E; ++AI)
1734       if (!AI->use_empty()) {
1735         LatticeVal &IV = Values[AI];
1736         if (IV.isConstant() || IV.isUndefined()) {
1737           Constant *CST = IV.isConstant() ?
1738             IV.getConstant() : UndefValue::get(AI->getType());
1739           DOUT << "***  Arg " << *AI << " = " << *CST <<"\n";
1740
1741           // Replaces all of the uses of a variable with uses of the
1742           // constant.
1743           AI->replaceAllUsesWith(CST);
1744           ++IPNumArgsElimed;
1745         }
1746       }
1747
1748     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1749       if (!ExecutableBBs.count(BB)) {
1750         DOUT << "  BasicBlock Dead:" << *BB;
1751         ++IPNumDeadBlocks;
1752
1753         // Delete the instructions backwards, as it has a reduced likelihood of
1754         // having to update as many def-use and use-def chains.
1755         TerminatorInst *TI = BB->getTerminator();
1756         for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1757           Insts.push_back(I);
1758
1759         while (!Insts.empty()) {
1760           Instruction *I = Insts.back();
1761           Insts.pop_back();
1762           if (!I->use_empty())
1763             I->replaceAllUsesWith(UndefValue::get(I->getType()));
1764           BB->getInstList().erase(I);
1765           MadeChanges = true;
1766           ++IPNumInstRemoved;
1767         }
1768
1769         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1770           BasicBlock *Succ = TI->getSuccessor(i);
1771           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1772             TI->getSuccessor(i)->removePredecessor(BB);
1773         }
1774         if (!TI->use_empty())
1775           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1776         BB->getInstList().erase(TI);
1777
1778         if (&*BB != &F->front())
1779           BlocksToErase.push_back(BB);
1780         else
1781           new UnreachableInst(BB);
1782
1783       } else {
1784         for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1785           Instruction *Inst = BI++;
1786           if (Inst->getType() == Type::VoidTy ||
1787               isa<StructType>(Inst->getType()) ||
1788               isa<TerminatorInst>(Inst))
1789             continue;
1790           
1791           LatticeVal &IV = Values[Inst];
1792           if (!IV.isConstant() && !IV.isUndefined())
1793             continue;
1794           
1795           Constant *Const = IV.isConstant()
1796             ? IV.getConstant() : UndefValue::get(Inst->getType());
1797           DOUT << "  Constant: " << *Const << " = " << *Inst;
1798
1799           // Replaces all of the uses of a variable with uses of the
1800           // constant.
1801           Inst->replaceAllUsesWith(Const);
1802           
1803           // Delete the instruction.
1804           if (!isa<CallInst>(Inst))
1805             Inst->eraseFromParent();
1806
1807           // Hey, we just changed something!
1808           MadeChanges = true;
1809           ++IPNumInstRemoved;
1810         }
1811       }
1812
1813     // Now that all instructions in the function are constant folded, erase dead
1814     // blocks, because we can now use ConstantFoldTerminator to get rid of
1815     // in-edges.
1816     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1817       // If there are any PHI nodes in this successor, drop entries for BB now.
1818       BasicBlock *DeadBB = BlocksToErase[i];
1819       while (!DeadBB->use_empty()) {
1820         Instruction *I = cast<Instruction>(DeadBB->use_back());
1821         bool Folded = ConstantFoldTerminator(I->getParent());
1822         if (!Folded) {
1823           // The constant folder may not have been able to fold the terminator
1824           // if this is a branch or switch on undef.  Fold it manually as a
1825           // branch to the first successor.
1826           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1827             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1828                    "Branch should be foldable!");
1829           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1830             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1831           } else {
1832             assert(0 && "Didn't fold away reference to block!");
1833           }
1834           
1835           // Make this an uncond branch to the first successor.
1836           TerminatorInst *TI = I->getParent()->getTerminator();
1837           BranchInst::Create(TI->getSuccessor(0), TI);
1838           
1839           // Remove entries in successor phi nodes to remove edges.
1840           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1841             TI->getSuccessor(i)->removePredecessor(TI->getParent());
1842           
1843           // Remove the old terminator.
1844           TI->eraseFromParent();
1845         }
1846       }
1847
1848       // Finally, delete the basic block.
1849       F->getBasicBlockList().erase(DeadBB);
1850     }
1851     BlocksToErase.clear();
1852   }
1853
1854   // If we inferred constant or undef return values for a function, we replaced
1855   // all call uses with the inferred value.  This means we don't need to bother
1856   // actually returning anything from the function.  Replace all return
1857   // instructions with return undef.
1858   // TODO: Process multiple value ret instructions also.
1859   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1860   for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1861          E = RV.end(); I != E; ++I)
1862     if (!I->second.isOverdefined() &&
1863         I->first->getReturnType() != Type::VoidTy) {
1864       Function *F = I->first;
1865       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1866         if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1867           if (!isa<UndefValue>(RI->getOperand(0)))
1868             RI->setOperand(0, UndefValue::get(F->getReturnType()));
1869     }
1870
1871   // If we infered constant or undef values for globals variables, we can delete
1872   // the global and any stores that remain to it.
1873   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1874   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1875          E = TG.end(); I != E; ++I) {
1876     GlobalVariable *GV = I->first;
1877     assert(!I->second.isOverdefined() &&
1878            "Overdefined values should have been taken out of the map!");
1879     DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
1880     while (!GV->use_empty()) {
1881       StoreInst *SI = cast<StoreInst>(GV->use_back());
1882       SI->eraseFromParent();
1883     }
1884     M.getGlobalList().erase(GV);
1885     ++IPNumGlobalConst;
1886   }
1887
1888   return MadeChanges;
1889 }