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