SCCP.cpp revision 785a7a97da06ce5108d1d194b26f6cf73d3cffb0
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/Transforms/Utils/Local.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetLibraryInfo.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 <algorithm>
43using namespace llvm;
44
45STATISTIC(NumInstRemoved, "Number of instructions removed");
46STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47
48STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
49STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
51
52namespace {
53/// LatticeVal class - This class represents the different lattice values that
54/// an LLVM value may occupy.  It is a simple class with value semantics.
55///
56class LatticeVal {
57  enum LatticeValueTy {
58    /// undefined - This LLVM Value has no known value yet.
59    undefined,
60
61    /// constant - This LLVM Value has a specific constant value.
62    constant,
63
64    /// forcedconstant - This LLVM Value was thought to be undef until
65    /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
66    /// with another (different) constant, it goes to overdefined, instead of
67    /// asserting.
68    forcedconstant,
69
70    /// overdefined - This instruction is not known to be constant, and we know
71    /// it has a value.
72    overdefined
73  };
74
75  /// Val: This stores the current lattice value along with the Constant* for
76  /// the constant if this is a 'constant' or 'forcedconstant' value.
77  PointerIntPair<Constant *, 2, LatticeValueTy> Val;
78
79  LatticeValueTy getLatticeValue() const {
80    return Val.getInt();
81  }
82
83public:
84  LatticeVal() : Val(0, undefined) {}
85
86  bool isUndefined() const { return getLatticeValue() == undefined; }
87  bool isConstant() const {
88    return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
89  }
90  bool isOverdefined() const { return getLatticeValue() == overdefined; }
91
92  Constant *getConstant() const {
93    assert(isConstant() && "Cannot get the constant of a non-constant!");
94    return Val.getPointer();
95  }
96
97  /// markOverdefined - Return true if this is a change in status.
98  bool markOverdefined() {
99    if (isOverdefined())
100      return false;
101
102    Val.setInt(overdefined);
103    return true;
104  }
105
106  /// markConstant - Return true if this is a change in status.
107  bool markConstant(Constant *V) {
108    if (getLatticeValue() == constant) { // Constant but not forcedconstant.
109      assert(getConstant() == V && "Marking constant with different value");
110      return false;
111    }
112
113    if (isUndefined()) {
114      Val.setInt(constant);
115      assert(V && "Marking constant with NULL");
116      Val.setPointer(V);
117    } else {
118      assert(getLatticeValue() == forcedconstant &&
119             "Cannot move from overdefined to constant!");
120      // Stay at forcedconstant if the constant is the same.
121      if (V == getConstant()) return false;
122
123      // Otherwise, we go to overdefined.  Assumptions made based on the
124      // forced value are possibly wrong.  Assuming this is another constant
125      // could expose a contradiction.
126      Val.setInt(overdefined);
127    }
128    return true;
129  }
130
131  /// getConstantInt - If this is a constant with a ConstantInt value, return it
132  /// otherwise return null.
133  ConstantInt *getConstantInt() const {
134    if (isConstant())
135      return dyn_cast<ConstantInt>(getConstant());
136    return 0;
137  }
138
139  void markForcedConstant(Constant *V) {
140    assert(isUndefined() && "Can't force a defined value!");
141    Val.setInt(forcedconstant);
142    Val.setPointer(V);
143  }
144};
145} // end anonymous namespace.
146
147
148namespace {
149
150//===----------------------------------------------------------------------===//
151//
152/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
153/// Constant Propagation.
154///
155class SCCPSolver : public InstVisitor<SCCPSolver> {
156  const TargetData *TD;
157  const TargetLibraryInfo *TLI;
158  SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
159  DenseMap<Value*, LatticeVal> ValueState;  // The state each value is in.
160
161  /// StructValueState - This maintains ValueState for values that have
162  /// StructType, for example for formal arguments, calls, insertelement, etc.
163  ///
164  DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
165
166  /// GlobalValue - If we are tracking any values for the contents of a global
167  /// variable, we keep a mapping from the constant accessor to the element of
168  /// the global, to the currently known value.  If the value becomes
169  /// overdefined, it's entry is simply removed from this map.
170  DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
171
172  /// TrackedRetVals - If we are tracking arguments into and the return
173  /// value out of a function, it will have an entry in this map, indicating
174  /// what the known return value for the function is.
175  DenseMap<Function*, LatticeVal> TrackedRetVals;
176
177  /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
178  /// that return multiple values.
179  DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
180
181  /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
182  /// represented here for efficient lookup.
183  SmallPtrSet<Function*, 16> MRVFunctionsTracked;
184
185  /// TrackingIncomingArguments - This is the set of functions for whose
186  /// arguments we make optimistic assumptions about and try to prove as
187  /// constants.
188  SmallPtrSet<Function*, 16> TrackingIncomingArguments;
189
190  /// The reason for two worklists is that overdefined is the lowest state
191  /// on the lattice, and moving things to overdefined as fast as possible
192  /// makes SCCP converge much faster.
193  ///
194  /// By having a separate worklist, we accomplish this because everything
195  /// possibly overdefined will become overdefined at the soonest possible
196  /// point.
197  SmallVector<Value*, 64> OverdefinedInstWorkList;
198  SmallVector<Value*, 64> InstWorkList;
199
200
201  SmallVector<BasicBlock*, 64>  BBWorkList;  // The BasicBlock work list
202
203  /// KnownFeasibleEdges - Entries in this set are edges which have already had
204  /// PHI nodes retriggered.
205  typedef std::pair<BasicBlock*, BasicBlock*> Edge;
206  DenseSet<Edge> KnownFeasibleEdges;
207public:
208  SCCPSolver(const TargetData *td, const TargetLibraryInfo *tli)
209    : TD(td), TLI(tli) {}
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
308private:
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
466private:
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//
523void 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//
589bool 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//
666void 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
724void 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
751void 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
763void 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
773void 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
794void 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
827void 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.
862void 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.
920void 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
939void 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
955void 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
979void 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//
1010void 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
1033void 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!
1054void 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
1096void 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()) {
1104CallOverdefined:
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, TLI))
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
1184void 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.
1260bool 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
1513namespace {
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    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1521      AU.addRequired<TargetLibraryInfo>();
1522    }
1523    static char ID; // Pass identification, replacement for typeid
1524    SCCP() : FunctionPass(ID) {
1525      initializeSCCPPass(*PassRegistry::getPassRegistry());
1526    }
1527
1528    // runOnFunction - Run the Sparse Conditional Constant Propagation
1529    // algorithm, and return true if the function was modified.
1530    //
1531    bool runOnFunction(Function &F);
1532  };
1533} // end anonymous namespace
1534
1535char SCCP::ID = 0;
1536INITIALIZE_PASS(SCCP, "sccp",
1537                "Sparse Conditional Constant Propagation", false, false)
1538
1539// createSCCPPass - This is the public interface to this file.
1540FunctionPass *llvm::createSCCPPass() {
1541  return new SCCP();
1542}
1543
1544static void DeleteInstructionInBlock(BasicBlock *BB) {
1545  DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
1546  ++NumDeadBlocks;
1547
1548  // Check to see if there are non-terminating instructions to delete.
1549  if (isa<TerminatorInst>(BB->begin()))
1550    return;
1551
1552  // Delete the instructions backwards, as it has a reduced likelihood of having
1553  // to update as many def-use and use-def chains.
1554  Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1555  while (EndInst != BB->begin()) {
1556    // Delete the next to last instruction.
1557    BasicBlock::iterator I = EndInst;
1558    Instruction *Inst = --I;
1559    if (!Inst->use_empty())
1560      Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1561    if (isa<LandingPadInst>(Inst)) {
1562      EndInst = Inst;
1563      continue;
1564    }
1565    BB->getInstList().erase(Inst);
1566    ++NumInstRemoved;
1567  }
1568}
1569
1570// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1571// and return true if the function was modified.
1572//
1573bool SCCP::runOnFunction(Function &F) {
1574  DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1575  const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1576  const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1577  SCCPSolver Solver(TD, TLI);
1578
1579  // Mark the first block of the function as being executable.
1580  Solver.MarkBlockExecutable(F.begin());
1581
1582  // Mark all arguments to the function as being overdefined.
1583  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1584    Solver.markAnythingOverdefined(AI);
1585
1586  // Solve for constants.
1587  bool ResolvedUndefs = true;
1588  while (ResolvedUndefs) {
1589    Solver.Solve();
1590    DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1591    ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1592  }
1593
1594  bool MadeChanges = false;
1595
1596  // If we decided that there are basic blocks that are dead in this function,
1597  // delete their contents now.  Note that we cannot actually delete the blocks,
1598  // as we cannot modify the CFG of the function.
1599
1600  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1601    if (!Solver.isBlockExecutable(BB)) {
1602      DeleteInstructionInBlock(BB);
1603      MadeChanges = true;
1604      continue;
1605    }
1606
1607    // Iterate over all of the instructions in a function, replacing them with
1608    // constants if we have found them to be of constant values.
1609    //
1610    for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1611      Instruction *Inst = BI++;
1612      if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1613        continue;
1614
1615      // TODO: Reconstruct structs from their elements.
1616      if (Inst->getType()->isStructTy())
1617        continue;
1618
1619      LatticeVal IV = Solver.getLatticeValueFor(Inst);
1620      if (IV.isOverdefined())
1621        continue;
1622
1623      Constant *Const = IV.isConstant()
1624        ? IV.getConstant() : UndefValue::get(Inst->getType());
1625      DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst);
1626
1627      // Replaces all of the uses of a variable with uses of the constant.
1628      Inst->replaceAllUsesWith(Const);
1629
1630      // Delete the instruction.
1631      Inst->eraseFromParent();
1632
1633      // Hey, we just changed something!
1634      MadeChanges = true;
1635      ++NumInstRemoved;
1636    }
1637  }
1638
1639  return MadeChanges;
1640}
1641
1642namespace {
1643  //===--------------------------------------------------------------------===//
1644  //
1645  /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1646  /// Constant Propagation.
1647  ///
1648  struct IPSCCP : public ModulePass {
1649    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1650      AU.addRequired<TargetLibraryInfo>();
1651    }
1652    static char ID;
1653    IPSCCP() : ModulePass(ID) {
1654      initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1655    }
1656    bool runOnModule(Module &M);
1657  };
1658} // end anonymous namespace
1659
1660char IPSCCP::ID = 0;
1661INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1662                "Interprocedural Sparse Conditional Constant Propagation",
1663                false, false)
1664INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1665INITIALIZE_PASS_END(IPSCCP, "ipsccp",
1666                "Interprocedural Sparse Conditional Constant Propagation",
1667                false, false)
1668
1669// createIPSCCPPass - This is the public interface to this file.
1670ModulePass *llvm::createIPSCCPPass() {
1671  return new IPSCCP();
1672}
1673
1674
1675static bool AddressIsTaken(const GlobalValue *GV) {
1676  // Delete any dead constantexpr klingons.
1677  GV->removeDeadConstantUsers();
1678
1679  for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1680       UI != E; ++UI) {
1681    const User *U = *UI;
1682    if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1683      if (SI->getOperand(0) == GV || SI->isVolatile())
1684        return true;  // Storing addr of GV.
1685    } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1686      // Make sure we are calling the function, not passing the address.
1687      ImmutableCallSite CS(cast<Instruction>(U));
1688      if (!CS.isCallee(UI))
1689        return true;
1690    } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1691      if (LI->isVolatile())
1692        return true;
1693    } else if (isa<BlockAddress>(U)) {
1694      // blockaddress doesn't take the address of the function, it takes addr
1695      // of label.
1696    } else {
1697      return true;
1698    }
1699  }
1700  return false;
1701}
1702
1703bool IPSCCP::runOnModule(Module &M) {
1704  const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1705  const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1706  SCCPSolver Solver(TD, TLI);
1707
1708  // AddressTakenFunctions - This set keeps track of the address-taken functions
1709  // that are in the input.  As IPSCCP runs through and simplifies code,
1710  // functions that were address taken can end up losing their
1711  // address-taken-ness.  Because of this, we keep track of their addresses from
1712  // the first pass so we can use them for the later simplification pass.
1713  SmallPtrSet<Function*, 32> AddressTakenFunctions;
1714
1715  // Loop over all functions, marking arguments to those with their addresses
1716  // taken or that are external as overdefined.
1717  //
1718  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1719    if (F->isDeclaration())
1720      continue;
1721
1722    // If this is a strong or ODR definition of this function, then we can
1723    // propagate information about its result into callsites of it.
1724    if (!F->mayBeOverridden())
1725      Solver.AddTrackedFunction(F);
1726
1727    // If this function only has direct calls that we can see, we can track its
1728    // arguments and return value aggressively, and can assume it is not called
1729    // unless we see evidence to the contrary.
1730    if (F->hasLocalLinkage()) {
1731      if (AddressIsTaken(F))
1732        AddressTakenFunctions.insert(F);
1733      else {
1734        Solver.AddArgumentTrackedFunction(F);
1735        continue;
1736      }
1737    }
1738
1739    // Assume the function is called.
1740    Solver.MarkBlockExecutable(F->begin());
1741
1742    // Assume nothing about the incoming arguments.
1743    for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1744         AI != E; ++AI)
1745      Solver.markAnythingOverdefined(AI);
1746  }
1747
1748  // Loop over global variables.  We inform the solver about any internal global
1749  // variables that do not have their 'addresses taken'.  If they don't have
1750  // their addresses taken, we can propagate constants through them.
1751  for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1752       G != E; ++G)
1753    if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1754      Solver.TrackValueOfGlobalVariable(G);
1755
1756  // Solve for constants.
1757  bool ResolvedUndefs = true;
1758  while (ResolvedUndefs) {
1759    Solver.Solve();
1760
1761    DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1762    ResolvedUndefs = false;
1763    for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1764      ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1765  }
1766
1767  bool MadeChanges = false;
1768
1769  // Iterate over all of the instructions in the module, replacing them with
1770  // constants if we have found them to be of constant values.
1771  //
1772  SmallVector<BasicBlock*, 512> BlocksToErase;
1773
1774  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1775    if (Solver.isBlockExecutable(F->begin())) {
1776      for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1777           AI != E; ++AI) {
1778        if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1779
1780        // TODO: Could use getStructLatticeValueFor to find out if the entire
1781        // result is a constant and replace it entirely if so.
1782
1783        LatticeVal IV = Solver.getLatticeValueFor(AI);
1784        if (IV.isOverdefined()) continue;
1785
1786        Constant *CST = IV.isConstant() ?
1787        IV.getConstant() : UndefValue::get(AI->getType());
1788        DEBUG(dbgs() << "***  Arg " << *AI << " = " << *CST <<"\n");
1789
1790        // Replaces all of the uses of a variable with uses of the
1791        // constant.
1792        AI->replaceAllUsesWith(CST);
1793        ++IPNumArgsElimed;
1794      }
1795    }
1796
1797    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1798      if (!Solver.isBlockExecutable(BB)) {
1799        DeleteInstructionInBlock(BB);
1800        MadeChanges = true;
1801
1802        TerminatorInst *TI = BB->getTerminator();
1803        for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1804          BasicBlock *Succ = TI->getSuccessor(i);
1805          if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1806            TI->getSuccessor(i)->removePredecessor(BB);
1807        }
1808        if (!TI->use_empty())
1809          TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1810        TI->eraseFromParent();
1811
1812        if (&*BB != &F->front())
1813          BlocksToErase.push_back(BB);
1814        else
1815          new UnreachableInst(M.getContext(), BB);
1816        continue;
1817      }
1818
1819      for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1820        Instruction *Inst = BI++;
1821        if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1822          continue;
1823
1824        // TODO: Could use getStructLatticeValueFor to find out if the entire
1825        // result is a constant and replace it entirely if so.
1826
1827        LatticeVal IV = Solver.getLatticeValueFor(Inst);
1828        if (IV.isOverdefined())
1829          continue;
1830
1831        Constant *Const = IV.isConstant()
1832          ? IV.getConstant() : UndefValue::get(Inst->getType());
1833        DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst);
1834
1835        // Replaces all of the uses of a variable with uses of the
1836        // constant.
1837        Inst->replaceAllUsesWith(Const);
1838
1839        // Delete the instruction.
1840        if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1841          Inst->eraseFromParent();
1842
1843        // Hey, we just changed something!
1844        MadeChanges = true;
1845        ++IPNumInstRemoved;
1846      }
1847    }
1848
1849    // Now that all instructions in the function are constant folded, erase dead
1850    // blocks, because we can now use ConstantFoldTerminator to get rid of
1851    // in-edges.
1852    for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1853      // If there are any PHI nodes in this successor, drop entries for BB now.
1854      BasicBlock *DeadBB = BlocksToErase[i];
1855      for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1856           UI != UE; ) {
1857        // Grab the user and then increment the iterator early, as the user
1858        // will be deleted. Step past all adjacent uses from the same user.
1859        Instruction *I = dyn_cast<Instruction>(*UI);
1860        do { ++UI; } while (UI != UE && *UI == I);
1861
1862        // Ignore blockaddress users; BasicBlock's dtor will handle them.
1863        if (!I) continue;
1864
1865        bool Folded = ConstantFoldTerminator(I->getParent());
1866        if (!Folded) {
1867          // The constant folder may not have been able to fold the terminator
1868          // if this is a branch or switch on undef.  Fold it manually as a
1869          // branch to the first successor.
1870#ifndef NDEBUG
1871          if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1872            assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1873                   "Branch should be foldable!");
1874          } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1875            assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1876          } else {
1877            llvm_unreachable("Didn't fold away reference to block!");
1878          }
1879#endif
1880
1881          // Make this an uncond branch to the first successor.
1882          TerminatorInst *TI = I->getParent()->getTerminator();
1883          BranchInst::Create(TI->getSuccessor(0), TI);
1884
1885          // Remove entries in successor phi nodes to remove edges.
1886          for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1887            TI->getSuccessor(i)->removePredecessor(TI->getParent());
1888
1889          // Remove the old terminator.
1890          TI->eraseFromParent();
1891        }
1892      }
1893
1894      // Finally, delete the basic block.
1895      F->getBasicBlockList().erase(DeadBB);
1896    }
1897    BlocksToErase.clear();
1898  }
1899
1900  // If we inferred constant or undef return values for a function, we replaced
1901  // all call uses with the inferred value.  This means we don't need to bother
1902  // actually returning anything from the function.  Replace all return
1903  // instructions with return undef.
1904  //
1905  // Do this in two stages: first identify the functions we should process, then
1906  // actually zap their returns.  This is important because we can only do this
1907  // if the address of the function isn't taken.  In cases where a return is the
1908  // last use of a function, the order of processing functions would affect
1909  // whether other functions are optimizable.
1910  SmallVector<ReturnInst*, 8> ReturnsToZap;
1911
1912  // TODO: Process multiple value ret instructions also.
1913  const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1914  for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1915       E = RV.end(); I != E; ++I) {
1916    Function *F = I->first;
1917    if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1918      continue;
1919
1920    // We can only do this if we know that nothing else can call the function.
1921    if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1922      continue;
1923
1924    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1925      if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1926        if (!isa<UndefValue>(RI->getOperand(0)))
1927          ReturnsToZap.push_back(RI);
1928  }
1929
1930  // Zap all returns which we've identified as zap to change.
1931  for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1932    Function *F = ReturnsToZap[i]->getParent()->getParent();
1933    ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1934  }
1935
1936  // If we inferred constant or undef values for globals variables, we can delete
1937  // the global and any stores that remain to it.
1938  const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1939  for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1940         E = TG.end(); I != E; ++I) {
1941    GlobalVariable *GV = I->first;
1942    assert(!I->second.isOverdefined() &&
1943           "Overdefined values should have been taken out of the map!");
1944    DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1945    while (!GV->use_empty()) {
1946      StoreInst *SI = cast<StoreInst>(GV->use_back());
1947      SI->eraseFromParent();
1948    }
1949    M.getGlobalList().erase(GV);
1950    ++IPNumGlobalConst;
1951  }
1952
1953  return MadeChanges;
1954}
1955