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