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