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