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