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