LLVM API Documentation

SCCP.cpp
Go to the documentation of this file.
00001 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements sparse conditional constant propagation and merging:
00011 //
00012 // Specifically, this:
00013 //   * Assumes values are constant unless proven otherwise
00014 //   * Assumes BasicBlocks are dead unless proven otherwise
00015 //   * Proves values to be constant, and replaces them with constants
00016 //   * Proves conditional branches to be unconditional
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #define DEBUG_TYPE "sccp"
00021 #include "llvm/Transforms/Scalar.h"
00022 #include "llvm/ADT/DenseMap.h"
00023 #include "llvm/ADT/DenseSet.h"
00024 #include "llvm/ADT/PointerIntPair.h"
00025 #include "llvm/ADT/SmallPtrSet.h"
00026 #include "llvm/ADT/SmallVector.h"
00027 #include "llvm/ADT/Statistic.h"
00028 #include "llvm/Analysis/ConstantFolding.h"
00029 #include "llvm/IR/CallSite.h"
00030 #include "llvm/IR/Constants.h"
00031 #include "llvm/IR/DataLayout.h"
00032 #include "llvm/IR/DerivedTypes.h"
00033 #include "llvm/IR/InstVisitor.h"
00034 #include "llvm/IR/Instructions.h"
00035 #include "llvm/Pass.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/ErrorHandling.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 #include "llvm/Target/TargetLibraryInfo.h"
00040 #include "llvm/Transforms/IPO.h"
00041 #include "llvm/Transforms/Utils/Local.h"
00042 #include <algorithm>
00043 using namespace llvm;
00044 
00045 STATISTIC(NumInstRemoved, "Number of instructions removed");
00046 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
00047 
00048 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
00049 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
00050 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
00051 
00052 namespace {
00053 /// LatticeVal class - This class represents the different lattice values that
00054 /// an LLVM value may occupy.  It is a simple class with value semantics.
00055 ///
00056 class LatticeVal {
00057   enum LatticeValueTy {
00058     /// undefined - This LLVM Value has no known value yet.
00059     undefined,
00060 
00061     /// constant - This LLVM Value has a specific constant value.
00062     constant,
00063 
00064     /// forcedconstant - This LLVM Value was thought to be undef until
00065     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
00066     /// with another (different) constant, it goes to overdefined, instead of
00067     /// asserting.
00068     forcedconstant,
00069 
00070     /// overdefined - This instruction is not known to be constant, and we know
00071     /// it has a value.
00072     overdefined
00073   };
00074 
00075   /// Val: This stores the current lattice value along with the Constant* for
00076   /// the constant if this is a 'constant' or 'forcedconstant' value.
00077   PointerIntPair<Constant *, 2, LatticeValueTy> Val;
00078 
00079   LatticeValueTy getLatticeValue() const {
00080     return Val.getInt();
00081   }
00082 
00083 public:
00084   LatticeVal() : Val(0, undefined) {}
00085 
00086   bool isUndefined() const { return getLatticeValue() == undefined; }
00087   bool isConstant() const {
00088     return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
00089   }
00090   bool isOverdefined() const { return getLatticeValue() == overdefined; }
00091 
00092   Constant *getConstant() const {
00093     assert(isConstant() && "Cannot get the constant of a non-constant!");
00094     return Val.getPointer();
00095   }
00096 
00097   /// markOverdefined - Return true if this is a change in status.
00098   bool markOverdefined() {
00099     if (isOverdefined())
00100       return false;
00101 
00102     Val.setInt(overdefined);
00103     return true;
00104   }
00105 
00106   /// markConstant - Return true if this is a change in status.
00107   bool markConstant(Constant *V) {
00108     if (getLatticeValue() == constant) { // Constant but not forcedconstant.
00109       assert(getConstant() == V && "Marking constant with different value");
00110       return false;
00111     }
00112 
00113     if (isUndefined()) {
00114       Val.setInt(constant);
00115       assert(V && "Marking constant with NULL");
00116       Val.setPointer(V);
00117     } else {
00118       assert(getLatticeValue() == forcedconstant &&
00119              "Cannot move from overdefined to constant!");
00120       // Stay at forcedconstant if the constant is the same.
00121       if (V == getConstant()) return false;
00122 
00123       // Otherwise, we go to overdefined.  Assumptions made based on the
00124       // forced value are possibly wrong.  Assuming this is another constant
00125       // could expose a contradiction.
00126       Val.setInt(overdefined);
00127     }
00128     return true;
00129   }
00130 
00131   /// getConstantInt - If this is a constant with a ConstantInt value, return it
00132   /// otherwise return null.
00133   ConstantInt *getConstantInt() const {
00134     if (isConstant())
00135       return dyn_cast<ConstantInt>(getConstant());
00136     return 0;
00137   }
00138 
00139   void markForcedConstant(Constant *V) {
00140     assert(isUndefined() && "Can't force a defined value!");
00141     Val.setInt(forcedconstant);
00142     Val.setPointer(V);
00143   }
00144 };
00145 } // end anonymous namespace.
00146 
00147 
00148 namespace {
00149 
00150 //===----------------------------------------------------------------------===//
00151 //
00152 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
00153 /// Constant Propagation.
00154 ///
00155 class SCCPSolver : public InstVisitor<SCCPSolver> {
00156   const DataLayout *DL;
00157   const TargetLibraryInfo *TLI;
00158   SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
00159   DenseMap<Value*, LatticeVal> ValueState;  // The state each value is in.
00160 
00161   /// StructValueState - This maintains ValueState for values that have
00162   /// StructType, for example for formal arguments, calls, insertelement, etc.
00163   ///
00164   DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
00165 
00166   /// GlobalValue - If we are tracking any values for the contents of a global
00167   /// variable, we keep a mapping from the constant accessor to the element of
00168   /// the global, to the currently known value.  If the value becomes
00169   /// overdefined, it's entry is simply removed from this map.
00170   DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
00171 
00172   /// TrackedRetVals - If we are tracking arguments into and the return
00173   /// value out of a function, it will have an entry in this map, indicating
00174   /// what the known return value for the function is.
00175   DenseMap<Function*, LatticeVal> TrackedRetVals;
00176 
00177   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
00178   /// that return multiple values.
00179   DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
00180 
00181   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
00182   /// represented here for efficient lookup.
00183   SmallPtrSet<Function*, 16> MRVFunctionsTracked;
00184 
00185   /// TrackingIncomingArguments - This is the set of functions for whose
00186   /// arguments we make optimistic assumptions about and try to prove as
00187   /// constants.
00188   SmallPtrSet<Function*, 16> TrackingIncomingArguments;
00189 
00190   /// The reason for two worklists is that overdefined is the lowest state
00191   /// on the lattice, and moving things to overdefined as fast as possible
00192   /// makes SCCP converge much faster.
00193   ///
00194   /// By having a separate worklist, we accomplish this because everything
00195   /// possibly overdefined will become overdefined at the soonest possible
00196   /// point.
00197   SmallVector<Value*, 64> OverdefinedInstWorkList;
00198   SmallVector<Value*, 64> InstWorkList;
00199 
00200 
00201   SmallVector<BasicBlock*, 64>  BBWorkList;  // The BasicBlock work list
00202 
00203   /// KnownFeasibleEdges - Entries in this set are edges which have already had
00204   /// PHI nodes retriggered.
00205   typedef std::pair<BasicBlock*, BasicBlock*> Edge;
00206   DenseSet<Edge> KnownFeasibleEdges;
00207 public:
00208   SCCPSolver(const DataLayout *DL, const TargetLibraryInfo *tli)
00209     : DL(DL), TLI(tli) {}
00210 
00211   /// MarkBlockExecutable - This method can be used by clients to mark all of
00212   /// the blocks that are known to be intrinsically live in the processed unit.
00213   ///
00214   /// This returns true if the block was not considered live before.
00215   bool MarkBlockExecutable(BasicBlock *BB) {
00216     if (!BBExecutable.insert(BB)) return false;
00217     DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
00218     BBWorkList.push_back(BB);  // Add the block to the work list!
00219     return true;
00220   }
00221 
00222   /// TrackValueOfGlobalVariable - Clients can use this method to
00223   /// inform the SCCPSolver that it should track loads and stores to the
00224   /// specified global variable if it can.  This is only legal to call if
00225   /// performing Interprocedural SCCP.
00226   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
00227     // We only track the contents of scalar globals.
00228     if (GV->getType()->getElementType()->isSingleValueType()) {
00229       LatticeVal &IV = TrackedGlobals[GV];
00230       if (!isa<UndefValue>(GV->getInitializer()))
00231         IV.markConstant(GV->getInitializer());
00232     }
00233   }
00234 
00235   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
00236   /// and out of the specified function (which cannot have its address taken),
00237   /// this method must be called.
00238   void AddTrackedFunction(Function *F) {
00239     // Add an entry, F -> undef.
00240     if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
00241       MRVFunctionsTracked.insert(F);
00242       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00243         TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
00244                                                      LatticeVal()));
00245     } else
00246       TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
00247   }
00248 
00249   void AddArgumentTrackedFunction(Function *F) {
00250     TrackingIncomingArguments.insert(F);
00251   }
00252 
00253   /// Solve - Solve for constants and executable blocks.
00254   ///
00255   void Solve();
00256 
00257   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
00258   /// that branches on undef values cannot reach any of their successors.
00259   /// However, this is not a safe assumption.  After we solve dataflow, this
00260   /// method should be use to handle this.  If this returns true, the solver
00261   /// should be rerun.
00262   bool ResolvedUndefsIn(Function &F);
00263 
00264   bool isBlockExecutable(BasicBlock *BB) const {
00265     return BBExecutable.count(BB);
00266   }
00267 
00268   LatticeVal getLatticeValueFor(Value *V) const {
00269     DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
00270     assert(I != ValueState.end() && "V is not in valuemap!");
00271     return I->second;
00272   }
00273 
00274   /// getTrackedRetVals - Get the inferred return value map.
00275   ///
00276   const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
00277     return TrackedRetVals;
00278   }
00279 
00280   /// getTrackedGlobals - Get and return the set of inferred initializers for
00281   /// global variables.
00282   const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
00283     return TrackedGlobals;
00284   }
00285 
00286   void markOverdefined(Value *V) {
00287     assert(!V->getType()->isStructTy() && "Should use other method");
00288     markOverdefined(ValueState[V], V);
00289   }
00290 
00291   /// markAnythingOverdefined - Mark the specified value overdefined.  This
00292   /// works with both scalars and structs.
00293   void markAnythingOverdefined(Value *V) {
00294     if (StructType *STy = dyn_cast<StructType>(V->getType()))
00295       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00296         markOverdefined(getStructValueState(V, i), V);
00297     else
00298       markOverdefined(V);
00299   }
00300 
00301 private:
00302   // markConstant - Make a value be marked as "constant".  If the value
00303   // is not already a constant, add it to the instruction work list so that
00304   // the users of the instruction are updated later.
00305   //
00306   void markConstant(LatticeVal &IV, Value *V, Constant *C) {
00307     if (!IV.markConstant(C)) return;
00308     DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
00309     if (IV.isOverdefined())
00310       OverdefinedInstWorkList.push_back(V);
00311     else
00312       InstWorkList.push_back(V);
00313   }
00314 
00315   void markConstant(Value *V, Constant *C) {
00316     assert(!V->getType()->isStructTy() && "Should use other method");
00317     markConstant(ValueState[V], V, C);
00318   }
00319 
00320   void markForcedConstant(Value *V, Constant *C) {
00321     assert(!V->getType()->isStructTy() && "Should use other method");
00322     LatticeVal &IV = ValueState[V];
00323     IV.markForcedConstant(C);
00324     DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
00325     if (IV.isOverdefined())
00326       OverdefinedInstWorkList.push_back(V);
00327     else
00328       InstWorkList.push_back(V);
00329   }
00330 
00331 
00332   // markOverdefined - Make a value be marked as "overdefined". If the
00333   // value is not already overdefined, add it to the overdefined instruction
00334   // work list so that the users of the instruction are updated later.
00335   void markOverdefined(LatticeVal &IV, Value *V) {
00336     if (!IV.markOverdefined()) return;
00337 
00338     DEBUG(dbgs() << "markOverdefined: ";
00339           if (Function *F = dyn_cast<Function>(V))
00340             dbgs() << "Function '" << F->getName() << "'\n";
00341           else
00342             dbgs() << *V << '\n');
00343     // Only instructions go on the work list
00344     OverdefinedInstWorkList.push_back(V);
00345   }
00346 
00347   void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
00348     if (IV.isOverdefined() || MergeWithV.isUndefined())
00349       return;  // Noop.
00350     if (MergeWithV.isOverdefined())
00351       markOverdefined(IV, V);
00352     else if (IV.isUndefined())
00353       markConstant(IV, V, MergeWithV.getConstant());
00354     else if (IV.getConstant() != MergeWithV.getConstant())
00355       markOverdefined(IV, V);
00356   }
00357 
00358   void mergeInValue(Value *V, LatticeVal MergeWithV) {
00359     assert(!V->getType()->isStructTy() && "Should use other method");
00360     mergeInValue(ValueState[V], V, MergeWithV);
00361   }
00362 
00363 
00364   /// getValueState - Return the LatticeVal object that corresponds to the
00365   /// value.  This function handles the case when the value hasn't been seen yet
00366   /// by properly seeding constants etc.
00367   LatticeVal &getValueState(Value *V) {
00368     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
00369 
00370     std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
00371       ValueState.insert(std::make_pair(V, LatticeVal()));
00372     LatticeVal &LV = I.first->second;
00373 
00374     if (!I.second)
00375       return LV;  // Common case, already in the map.
00376 
00377     if (Constant *C = dyn_cast<Constant>(V)) {
00378       // Undef values remain undefined.
00379       if (!isa<UndefValue>(V))
00380         LV.markConstant(C);          // Constants are constant
00381     }
00382 
00383     // All others are underdefined by default.
00384     return LV;
00385   }
00386 
00387   /// getStructValueState - Return the LatticeVal object that corresponds to the
00388   /// value/field pair.  This function handles the case when the value hasn't
00389   /// been seen yet by properly seeding constants etc.
00390   LatticeVal &getStructValueState(Value *V, unsigned i) {
00391     assert(V->getType()->isStructTy() && "Should use getValueState");
00392     assert(i < cast<StructType>(V->getType())->getNumElements() &&
00393            "Invalid element #");
00394 
00395     std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
00396               bool> I = StructValueState.insert(
00397                         std::make_pair(std::make_pair(V, i), LatticeVal()));
00398     LatticeVal &LV = I.first->second;
00399 
00400     if (!I.second)
00401       return LV;  // Common case, already in the map.
00402 
00403     if (Constant *C = dyn_cast<Constant>(V)) {
00404       Constant *Elt = C->getAggregateElement(i);
00405 
00406       if (Elt == 0)
00407         LV.markOverdefined();      // Unknown sort of constant.
00408       else if (isa<UndefValue>(Elt))
00409         ; // Undef values remain undefined.
00410       else
00411         LV.markConstant(Elt);      // Constants are constant.
00412     }
00413 
00414     // All others are underdefined by default.
00415     return LV;
00416   }
00417 
00418 
00419   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
00420   /// work list if it is not already executable.
00421   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
00422     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
00423       return;  // This edge is already known to be executable!
00424 
00425     if (!MarkBlockExecutable(Dest)) {
00426       // If the destination is already executable, we just made an *edge*
00427       // feasible that wasn't before.  Revisit the PHI nodes in the block
00428       // because they have potentially new operands.
00429       DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
00430             << " -> " << Dest->getName() << '\n');
00431 
00432       PHINode *PN;
00433       for (BasicBlock::iterator I = Dest->begin();
00434            (PN = dyn_cast<PHINode>(I)); ++I)
00435         visitPHINode(*PN);
00436     }
00437   }
00438 
00439   // getFeasibleSuccessors - Return a vector of booleans to indicate which
00440   // successors are reachable from a given terminator instruction.
00441   //
00442   void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
00443 
00444   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
00445   // block to the 'To' basic block is currently feasible.
00446   //
00447   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
00448 
00449   // OperandChangedState - This method is invoked on all of the users of an
00450   // instruction that was just changed state somehow.  Based on this
00451   // information, we need to update the specified user of this instruction.
00452   //
00453   void OperandChangedState(Instruction *I) {
00454     if (BBExecutable.count(I->getParent()))   // Inst is executable?
00455       visit(*I);
00456   }
00457 
00458 private:
00459   friend class InstVisitor<SCCPSolver>;
00460 
00461   // visit implementations - Something changed in this instruction.  Either an
00462   // operand made a transition, or the instruction is newly executable.  Change
00463   // the value type of I to reflect these changes if appropriate.
00464   void visitPHINode(PHINode &I);
00465 
00466   // Terminators
00467   void visitReturnInst(ReturnInst &I);
00468   void visitTerminatorInst(TerminatorInst &TI);
00469 
00470   void visitCastInst(CastInst &I);
00471   void visitSelectInst(SelectInst &I);
00472   void visitBinaryOperator(Instruction &I);
00473   void visitCmpInst(CmpInst &I);
00474   void visitExtractElementInst(ExtractElementInst &I);
00475   void visitInsertElementInst(InsertElementInst &I);
00476   void visitShuffleVectorInst(ShuffleVectorInst &I);
00477   void visitExtractValueInst(ExtractValueInst &EVI);
00478   void visitInsertValueInst(InsertValueInst &IVI);
00479   void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
00480 
00481   // Instructions that cannot be folded away.
00482   void visitStoreInst     (StoreInst &I);
00483   void visitLoadInst      (LoadInst &I);
00484   void visitGetElementPtrInst(GetElementPtrInst &I);
00485   void visitCallInst      (CallInst &I) {
00486     visitCallSite(&I);
00487   }
00488   void visitInvokeInst    (InvokeInst &II) {
00489     visitCallSite(&II);
00490     visitTerminatorInst(II);
00491   }
00492   void visitCallSite      (CallSite CS);
00493   void visitResumeInst    (TerminatorInst &I) { /*returns void*/ }
00494   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
00495   void visitFenceInst     (FenceInst &I) { /*returns void*/ }
00496   void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
00497   void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
00498   void visitAllocaInst    (Instruction &I) { markOverdefined(&I); }
00499   void visitVAArgInst     (Instruction &I) { markAnythingOverdefined(&I); }
00500 
00501   void visitInstruction(Instruction &I) {
00502     // If a new instruction is added to LLVM that we don't handle.
00503     dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
00504     markAnythingOverdefined(&I);   // Just in case
00505   }
00506 };
00507 
00508 } // end anonymous namespace
00509 
00510 
00511 // getFeasibleSuccessors - Return a vector of booleans to indicate which
00512 // successors are reachable from a given terminator instruction.
00513 //
00514 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
00515                                        SmallVectorImpl<bool> &Succs) {
00516   Succs.resize(TI.getNumSuccessors());
00517   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
00518     if (BI->isUnconditional()) {
00519       Succs[0] = true;
00520       return;
00521     }
00522 
00523     LatticeVal BCValue = getValueState(BI->getCondition());
00524     ConstantInt *CI = BCValue.getConstantInt();
00525     if (CI == 0) {
00526       // Overdefined condition variables, and branches on unfoldable constant
00527       // conditions, mean the branch could go either way.
00528       if (!BCValue.isUndefined())
00529         Succs[0] = Succs[1] = true;
00530       return;
00531     }
00532 
00533     // Constant condition variables mean the branch can only go a single way.
00534     Succs[CI->isZero()] = true;
00535     return;
00536   }
00537 
00538   if (isa<InvokeInst>(TI)) {
00539     // Invoke instructions successors are always executable.
00540     Succs[0] = Succs[1] = true;
00541     return;
00542   }
00543 
00544   if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
00545     if (!SI->getNumCases()) {
00546       Succs[0] = true;
00547       return;
00548     }
00549     LatticeVal SCValue = getValueState(SI->getCondition());
00550     ConstantInt *CI = SCValue.getConstantInt();
00551 
00552     if (CI == 0) {   // Overdefined or undefined condition?
00553       // All destinations are executable!
00554       if (!SCValue.isUndefined())
00555         Succs.assign(TI.getNumSuccessors(), true);
00556       return;
00557     }
00558 
00559     Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
00560     return;
00561   }
00562 
00563   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
00564   if (isa<IndirectBrInst>(&TI)) {
00565     // Just mark all destinations executable!
00566     Succs.assign(TI.getNumSuccessors(), true);
00567     return;
00568   }
00569 
00570 #ifndef NDEBUG
00571   dbgs() << "Unknown terminator instruction: " << TI << '\n';
00572 #endif
00573   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
00574 }
00575 
00576 
00577 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
00578 // block to the 'To' basic block is currently feasible.
00579 //
00580 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
00581   assert(BBExecutable.count(To) && "Dest should always be alive!");
00582 
00583   // Make sure the source basic block is executable!!
00584   if (!BBExecutable.count(From)) return false;
00585 
00586   // Check to make sure this edge itself is actually feasible now.
00587   TerminatorInst *TI = From->getTerminator();
00588   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00589     if (BI->isUnconditional())
00590       return true;
00591 
00592     LatticeVal BCValue = getValueState(BI->getCondition());
00593 
00594     // Overdefined condition variables mean the branch could go either way,
00595     // undef conditions mean that neither edge is feasible yet.
00596     ConstantInt *CI = BCValue.getConstantInt();
00597     if (CI == 0)
00598       return !BCValue.isUndefined();
00599 
00600     // Constant condition variables mean the branch can only go a single way.
00601     return BI->getSuccessor(CI->isZero()) == To;
00602   }
00603 
00604   // Invoke instructions successors are always executable.
00605   if (isa<InvokeInst>(TI))
00606     return true;
00607 
00608   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00609     if (SI->getNumCases() < 1)
00610       return true;
00611 
00612     LatticeVal SCValue = getValueState(SI->getCondition());
00613     ConstantInt *CI = SCValue.getConstantInt();
00614 
00615     if (CI == 0)
00616       return !SCValue.isUndefined();
00617 
00618     return SI->findCaseValue(CI).getCaseSuccessor() == To;
00619   }
00620 
00621   // Just mark all destinations executable!
00622   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
00623   if (isa<IndirectBrInst>(TI))
00624     return true;
00625 
00626 #ifndef NDEBUG
00627   dbgs() << "Unknown terminator instruction: " << *TI << '\n';
00628 #endif
00629   llvm_unreachable(0);
00630 }
00631 
00632 // visit Implementations - Something changed in this instruction, either an
00633 // operand made a transition, or the instruction is newly executable.  Change
00634 // the value type of I to reflect these changes if appropriate.  This method
00635 // makes sure to do the following actions:
00636 //
00637 // 1. If a phi node merges two constants in, and has conflicting value coming
00638 //    from different branches, or if the PHI node merges in an overdefined
00639 //    value, then the PHI node becomes overdefined.
00640 // 2. If a phi node merges only constants in, and they all agree on value, the
00641 //    PHI node becomes a constant value equal to that.
00642 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
00643 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
00644 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
00645 // 6. If a conditional branch has a value that is constant, make the selected
00646 //    destination executable
00647 // 7. If a conditional branch has a value that is overdefined, make all
00648 //    successors executable.
00649 //
00650 void SCCPSolver::visitPHINode(PHINode &PN) {
00651   // If this PN returns a struct, just mark the result overdefined.
00652   // TODO: We could do a lot better than this if code actually uses this.
00653   if (PN.getType()->isStructTy())
00654     return markAnythingOverdefined(&PN);
00655 
00656   if (getValueState(&PN).isOverdefined())
00657     return;  // Quick exit
00658 
00659   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
00660   // and slow us down a lot.  Just mark them overdefined.
00661   if (PN.getNumIncomingValues() > 64)
00662     return markOverdefined(&PN);
00663 
00664   // Look at all of the executable operands of the PHI node.  If any of them
00665   // are overdefined, the PHI becomes overdefined as well.  If they are all
00666   // constant, and they agree with each other, the PHI becomes the identical
00667   // constant.  If they are constant and don't agree, the PHI is overdefined.
00668   // If there are no executable operands, the PHI remains undefined.
00669   //
00670   Constant *OperandVal = 0;
00671   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
00672     LatticeVal IV = getValueState(PN.getIncomingValue(i));
00673     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
00674 
00675     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
00676       continue;
00677 
00678     if (IV.isOverdefined())    // PHI node becomes overdefined!
00679       return markOverdefined(&PN);
00680 
00681     if (OperandVal == 0) {   // Grab the first value.
00682       OperandVal = IV.getConstant();
00683       continue;
00684     }
00685 
00686     // There is already a reachable operand.  If we conflict with it,
00687     // then the PHI node becomes overdefined.  If we agree with it, we
00688     // can continue on.
00689 
00690     // Check to see if there are two different constants merging, if so, the PHI
00691     // node is overdefined.
00692     if (IV.getConstant() != OperandVal)
00693       return markOverdefined(&PN);
00694   }
00695 
00696   // If we exited the loop, this means that the PHI node only has constant
00697   // arguments that agree with each other(and OperandVal is the constant) or
00698   // OperandVal is null because there are no defined incoming arguments.  If
00699   // this is the case, the PHI remains undefined.
00700   //
00701   if (OperandVal)
00702     markConstant(&PN, OperandVal);      // Acquire operand value
00703 }
00704 
00705 void SCCPSolver::visitReturnInst(ReturnInst &I) {
00706   if (I.getNumOperands() == 0) return;  // ret void
00707 
00708   Function *F = I.getParent()->getParent();
00709   Value *ResultOp = I.getOperand(0);
00710 
00711   // If we are tracking the return value of this function, merge it in.
00712   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
00713     DenseMap<Function*, LatticeVal>::iterator TFRVI =
00714       TrackedRetVals.find(F);
00715     if (TFRVI != TrackedRetVals.end()) {
00716       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
00717       return;
00718     }
00719   }
00720 
00721   // Handle functions that return multiple values.
00722   if (!TrackedMultipleRetVals.empty()) {
00723     if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
00724       if (MRVFunctionsTracked.count(F))
00725         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00726           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
00727                        getStructValueState(ResultOp, i));
00728 
00729   }
00730 }
00731 
00732 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
00733   SmallVector<bool, 16> SuccFeasible;
00734   getFeasibleSuccessors(TI, SuccFeasible);
00735 
00736   BasicBlock *BB = TI.getParent();
00737 
00738   // Mark all feasible successors executable.
00739   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
00740     if (SuccFeasible[i])
00741       markEdgeExecutable(BB, TI.getSuccessor(i));
00742 }
00743 
00744 void SCCPSolver::visitCastInst(CastInst &I) {
00745   LatticeVal OpSt = getValueState(I.getOperand(0));
00746   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
00747     markOverdefined(&I);
00748   else if (OpSt.isConstant())        // Propagate constant value
00749     markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
00750                                            OpSt.getConstant(), I.getType()));
00751 }
00752 
00753 
00754 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
00755   // If this returns a struct, mark all elements over defined, we don't track
00756   // structs in structs.
00757   if (EVI.getType()->isStructTy())
00758     return markAnythingOverdefined(&EVI);
00759 
00760   // If this is extracting from more than one level of struct, we don't know.
00761   if (EVI.getNumIndices() != 1)
00762     return markOverdefined(&EVI);
00763 
00764   Value *AggVal = EVI.getAggregateOperand();
00765   if (AggVal->getType()->isStructTy()) {
00766     unsigned i = *EVI.idx_begin();
00767     LatticeVal EltVal = getStructValueState(AggVal, i);
00768     mergeInValue(getValueState(&EVI), &EVI, EltVal);
00769   } else {
00770     // Otherwise, must be extracting from an array.
00771     return markOverdefined(&EVI);
00772   }
00773 }
00774 
00775 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
00776   StructType *STy = dyn_cast<StructType>(IVI.getType());
00777   if (STy == 0)
00778     return markOverdefined(&IVI);
00779 
00780   // If this has more than one index, we can't handle it, drive all results to
00781   // undef.
00782   if (IVI.getNumIndices() != 1)
00783     return markAnythingOverdefined(&IVI);
00784 
00785   Value *Aggr = IVI.getAggregateOperand();
00786   unsigned Idx = *IVI.idx_begin();
00787 
00788   // Compute the result based on what we're inserting.
00789   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00790     // This passes through all values that aren't the inserted element.
00791     if (i != Idx) {
00792       LatticeVal EltVal = getStructValueState(Aggr, i);
00793       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
00794       continue;
00795     }
00796 
00797     Value *Val = IVI.getInsertedValueOperand();
00798     if (Val->getType()->isStructTy())
00799       // We don't track structs in structs.
00800       markOverdefined(getStructValueState(&IVI, i), &IVI);
00801     else {
00802       LatticeVal InVal = getValueState(Val);
00803       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
00804     }
00805   }
00806 }
00807 
00808 void SCCPSolver::visitSelectInst(SelectInst &I) {
00809   // If this select returns a struct, just mark the result overdefined.
00810   // TODO: We could do a lot better than this if code actually uses this.
00811   if (I.getType()->isStructTy())
00812     return markAnythingOverdefined(&I);
00813 
00814   LatticeVal CondValue = getValueState(I.getCondition());
00815   if (CondValue.isUndefined())
00816     return;
00817 
00818   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
00819     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
00820     mergeInValue(&I, getValueState(OpVal));
00821     return;
00822   }
00823 
00824   // Otherwise, the condition is overdefined or a constant we can't evaluate.
00825   // See if we can produce something better than overdefined based on the T/F
00826   // value.
00827   LatticeVal TVal = getValueState(I.getTrueValue());
00828   LatticeVal FVal = getValueState(I.getFalseValue());
00829 
00830   // select ?, C, C -> C.
00831   if (TVal.isConstant() && FVal.isConstant() &&
00832       TVal.getConstant() == FVal.getConstant())
00833     return markConstant(&I, FVal.getConstant());
00834 
00835   if (TVal.isUndefined())   // select ?, undef, X -> X.
00836     return mergeInValue(&I, FVal);
00837   if (FVal.isUndefined())   // select ?, X, undef -> X.
00838     return mergeInValue(&I, TVal);
00839   markOverdefined(&I);
00840 }
00841 
00842 // Handle Binary Operators.
00843 void SCCPSolver::visitBinaryOperator(Instruction &I) {
00844   LatticeVal V1State = getValueState(I.getOperand(0));
00845   LatticeVal V2State = getValueState(I.getOperand(1));
00846 
00847   LatticeVal &IV = ValueState[&I];
00848   if (IV.isOverdefined()) return;
00849 
00850   if (V1State.isConstant() && V2State.isConstant())
00851     return markConstant(IV, &I,
00852                         ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
00853                                           V2State.getConstant()));
00854 
00855   // If something is undef, wait for it to resolve.
00856   if (!V1State.isOverdefined() && !V2State.isOverdefined())
00857     return;
00858 
00859   // Otherwise, one of our operands is overdefined.  Try to produce something
00860   // better than overdefined with some tricks.
00861 
00862   // If this is an AND or OR with 0 or -1, it doesn't matter that the other
00863   // operand is overdefined.
00864   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
00865     LatticeVal *NonOverdefVal = 0;
00866     if (!V1State.isOverdefined())
00867       NonOverdefVal = &V1State;
00868     else if (!V2State.isOverdefined())
00869       NonOverdefVal = &V2State;
00870 
00871     if (NonOverdefVal) {
00872       if (NonOverdefVal->isUndefined()) {
00873         // Could annihilate value.
00874         if (I.getOpcode() == Instruction::And)
00875           markConstant(IV, &I, Constant::getNullValue(I.getType()));
00876         else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
00877           markConstant(IV, &I, Constant::getAllOnesValue(PT));
00878         else
00879           markConstant(IV, &I,
00880                        Constant::getAllOnesValue(I.getType()));
00881         return;
00882       }
00883 
00884       if (I.getOpcode() == Instruction::And) {
00885         // X and 0 = 0
00886         if (NonOverdefVal->getConstant()->isNullValue())
00887           return markConstant(IV, &I, NonOverdefVal->getConstant());
00888       } else {
00889         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
00890           if (CI->isAllOnesValue())     // X or -1 = -1
00891             return markConstant(IV, &I, NonOverdefVal->getConstant());
00892       }
00893     }
00894   }
00895 
00896 
00897   markOverdefined(&I);
00898 }
00899 
00900 // Handle ICmpInst instruction.
00901 void SCCPSolver::visitCmpInst(CmpInst &I) {
00902   LatticeVal V1State = getValueState(I.getOperand(0));
00903   LatticeVal V2State = getValueState(I.getOperand(1));
00904 
00905   LatticeVal &IV = ValueState[&I];
00906   if (IV.isOverdefined()) return;
00907 
00908   if (V1State.isConstant() && V2State.isConstant())
00909     return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
00910                                                          V1State.getConstant(),
00911                                                         V2State.getConstant()));
00912 
00913   // If operands are still undefined, wait for it to resolve.
00914   if (!V1State.isOverdefined() && !V2State.isOverdefined())
00915     return;
00916 
00917   markOverdefined(&I);
00918 }
00919 
00920 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
00921   // TODO : SCCP does not handle vectors properly.
00922   return markOverdefined(&I);
00923 
00924 #if 0
00925   LatticeVal &ValState = getValueState(I.getOperand(0));
00926   LatticeVal &IdxState = getValueState(I.getOperand(1));
00927 
00928   if (ValState.isOverdefined() || IdxState.isOverdefined())
00929     markOverdefined(&I);
00930   else if(ValState.isConstant() && IdxState.isConstant())
00931     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
00932                                                      IdxState.getConstant()));
00933 #endif
00934 }
00935 
00936 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
00937   // TODO : SCCP does not handle vectors properly.
00938   return markOverdefined(&I);
00939 #if 0
00940   LatticeVal &ValState = getValueState(I.getOperand(0));
00941   LatticeVal &EltState = getValueState(I.getOperand(1));
00942   LatticeVal &IdxState = getValueState(I.getOperand(2));
00943 
00944   if (ValState.isOverdefined() || EltState.isOverdefined() ||
00945       IdxState.isOverdefined())
00946     markOverdefined(&I);
00947   else if(ValState.isConstant() && EltState.isConstant() &&
00948           IdxState.isConstant())
00949     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
00950                                                     EltState.getConstant(),
00951                                                     IdxState.getConstant()));
00952   else if (ValState.isUndefined() && EltState.isConstant() &&
00953            IdxState.isConstant())
00954     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
00955                                                    EltState.getConstant(),
00956                                                    IdxState.getConstant()));
00957 #endif
00958 }
00959 
00960 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
00961   // TODO : SCCP does not handle vectors properly.
00962   return markOverdefined(&I);
00963 #if 0
00964   LatticeVal &V1State   = getValueState(I.getOperand(0));
00965   LatticeVal &V2State   = getValueState(I.getOperand(1));
00966   LatticeVal &MaskState = getValueState(I.getOperand(2));
00967 
00968   if (MaskState.isUndefined() ||
00969       (V1State.isUndefined() && V2State.isUndefined()))
00970     return;  // Undefined output if mask or both inputs undefined.
00971 
00972   if (V1State.isOverdefined() || V2State.isOverdefined() ||
00973       MaskState.isOverdefined()) {
00974     markOverdefined(&I);
00975   } else {
00976     // A mix of constant/undef inputs.
00977     Constant *V1 = V1State.isConstant() ?
00978         V1State.getConstant() : UndefValue::get(I.getType());
00979     Constant *V2 = V2State.isConstant() ?
00980         V2State.getConstant() : UndefValue::get(I.getType());
00981     Constant *Mask = MaskState.isConstant() ?
00982       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
00983     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
00984   }
00985 #endif
00986 }
00987 
00988 // Handle getelementptr instructions.  If all operands are constants then we
00989 // can turn this into a getelementptr ConstantExpr.
00990 //
00991 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
00992   if (ValueState[&I].isOverdefined()) return;
00993 
00994   SmallVector<Constant*, 8> Operands;
00995   Operands.reserve(I.getNumOperands());
00996 
00997   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
00998     LatticeVal State = getValueState(I.getOperand(i));
00999     if (State.isUndefined())
01000       return;  // Operands are not resolved yet.
01001 
01002     if (State.isOverdefined())
01003       return markOverdefined(&I);
01004 
01005     assert(State.isConstant() && "Unknown state!");
01006     Operands.push_back(State.getConstant());
01007   }
01008 
01009   Constant *Ptr = Operands[0];
01010   ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
01011   markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
01012 }
01013 
01014 void SCCPSolver::visitStoreInst(StoreInst &SI) {
01015   // If this store is of a struct, ignore it.
01016   if (SI.getOperand(0)->getType()->isStructTy())
01017     return;
01018 
01019   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
01020     return;
01021 
01022   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
01023   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
01024   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
01025 
01026   // Get the value we are storing into the global, then merge it.
01027   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
01028   if (I->second.isOverdefined())
01029     TrackedGlobals.erase(I);      // No need to keep tracking this!
01030 }
01031 
01032 
01033 // Handle load instructions.  If the operand is a constant pointer to a constant
01034 // global, we can replace the load with the loaded constant value!
01035 void SCCPSolver::visitLoadInst(LoadInst &I) {
01036   // If this load is of a struct, just mark the result overdefined.
01037   if (I.getType()->isStructTy())
01038     return markAnythingOverdefined(&I);
01039 
01040   LatticeVal PtrVal = getValueState(I.getOperand(0));
01041   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
01042 
01043   LatticeVal &IV = ValueState[&I];
01044   if (IV.isOverdefined()) return;
01045 
01046   if (!PtrVal.isConstant() || I.isVolatile())
01047     return markOverdefined(IV, &I);
01048 
01049   Constant *Ptr = PtrVal.getConstant();
01050 
01051   // load null -> null
01052   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
01053     return markConstant(IV, &I, Constant::getNullValue(I.getType()));
01054 
01055   // Transform load (constant global) into the value loaded.
01056   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
01057     if (!TrackedGlobals.empty()) {
01058       // If we are tracking this global, merge in the known value for it.
01059       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
01060         TrackedGlobals.find(GV);
01061       if (It != TrackedGlobals.end()) {
01062         mergeInValue(IV, &I, It->second);
01063         return;
01064       }
01065     }
01066   }
01067 
01068   // Transform load from a constant into a constant if possible.
01069   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
01070     return markConstant(IV, &I, C);
01071 
01072   // Otherwise we cannot say for certain what value this load will produce.
01073   // Bail out.
01074   markOverdefined(IV, &I);
01075 }
01076 
01077 void SCCPSolver::visitCallSite(CallSite CS) {
01078   Function *F = CS.getCalledFunction();
01079   Instruction *I = CS.getInstruction();
01080 
01081   // The common case is that we aren't tracking the callee, either because we
01082   // are not doing interprocedural analysis or the callee is indirect, or is
01083   // external.  Handle these cases first.
01084   if (F == 0 || F->isDeclaration()) {
01085 CallOverdefined:
01086     // Void return and not tracking callee, just bail.
01087     if (I->getType()->isVoidTy()) return;
01088 
01089     // Otherwise, if we have a single return value case, and if the function is
01090     // a declaration, maybe we can constant fold it.
01091     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
01092         canConstantFoldCallTo(F)) {
01093 
01094       SmallVector<Constant*, 8> Operands;
01095       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
01096            AI != E; ++AI) {
01097         LatticeVal State = getValueState(*AI);
01098 
01099         if (State.isUndefined())
01100           return;  // Operands are not resolved yet.
01101         if (State.isOverdefined())
01102           return markOverdefined(I);
01103         assert(State.isConstant() && "Unknown state!");
01104         Operands.push_back(State.getConstant());
01105       }
01106 
01107       // If we can constant fold this, mark the result of the call as a
01108       // constant.
01109       if (Constant *C = ConstantFoldCall(F, Operands, TLI))
01110         return markConstant(I, C);
01111     }
01112 
01113     // Otherwise, we don't know anything about this call, mark it overdefined.
01114     return markAnythingOverdefined(I);
01115   }
01116 
01117   // If this is a local function that doesn't have its address taken, mark its
01118   // entry block executable and merge in the actual arguments to the call into
01119   // the formal arguments of the function.
01120   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
01121     MarkBlockExecutable(F->begin());
01122 
01123     // Propagate information from this call site into the callee.
01124     CallSite::arg_iterator CAI = CS.arg_begin();
01125     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01126          AI != E; ++AI, ++CAI) {
01127       // If this argument is byval, and if the function is not readonly, there
01128       // will be an implicit copy formed of the input aggregate.
01129       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
01130         markOverdefined(AI);
01131         continue;
01132       }
01133 
01134       if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
01135         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01136           LatticeVal CallArg = getStructValueState(*CAI, i);
01137           mergeInValue(getStructValueState(AI, i), AI, CallArg);
01138         }
01139       } else {
01140         mergeInValue(AI, getValueState(*CAI));
01141       }
01142     }
01143   }
01144 
01145   // If this is a single/zero retval case, see if we're tracking the function.
01146   if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
01147     if (!MRVFunctionsTracked.count(F))
01148       goto CallOverdefined;  // Not tracking this callee.
01149 
01150     // If we are tracking this callee, propagate the result of the function
01151     // into this call site.
01152     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
01153       mergeInValue(getStructValueState(I, i), I,
01154                    TrackedMultipleRetVals[std::make_pair(F, i)]);
01155   } else {
01156     DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
01157     if (TFRVI == TrackedRetVals.end())
01158       goto CallOverdefined;  // Not tracking this callee.
01159 
01160     // If so, propagate the return value of the callee into this call result.
01161     mergeInValue(I, TFRVI->second);
01162   }
01163 }
01164 
01165 void SCCPSolver::Solve() {
01166   // Process the work lists until they are empty!
01167   while (!BBWorkList.empty() || !InstWorkList.empty() ||
01168          !OverdefinedInstWorkList.empty()) {
01169     // Process the overdefined instruction's work list first, which drives other
01170     // things to overdefined more quickly.
01171     while (!OverdefinedInstWorkList.empty()) {
01172       Value *I = OverdefinedInstWorkList.pop_back_val();
01173 
01174       DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
01175 
01176       // "I" got into the work list because it either made the transition from
01177       // bottom to constant, or to overdefined.
01178       //
01179       // Anything on this worklist that is overdefined need not be visited
01180       // since all of its users will have already been marked as overdefined
01181       // Update all of the users of this instruction's value.
01182       //
01183       for (User *U : I->users())
01184         if (Instruction *UI = dyn_cast<Instruction>(U))
01185           OperandChangedState(UI);
01186     }
01187 
01188     // Process the instruction work list.
01189     while (!InstWorkList.empty()) {
01190       Value *I = InstWorkList.pop_back_val();
01191 
01192       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
01193 
01194       // "I" got into the work list because it made the transition from undef to
01195       // constant.
01196       //
01197       // Anything on this worklist that is overdefined need not be visited
01198       // since all of its users will have already been marked as overdefined.
01199       // Update all of the users of this instruction's value.
01200       //
01201       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
01202         for (User *U : I->users())
01203           if (Instruction *UI = dyn_cast<Instruction>(U))
01204             OperandChangedState(UI);
01205     }
01206 
01207     // Process the basic block work list.
01208     while (!BBWorkList.empty()) {
01209       BasicBlock *BB = BBWorkList.back();
01210       BBWorkList.pop_back();
01211 
01212       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
01213 
01214       // Notify all instructions in this basic block that they are newly
01215       // executable.
01216       visit(BB);
01217     }
01218   }
01219 }
01220 
01221 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
01222 /// that branches on undef values cannot reach any of their successors.
01223 /// However, this is not a safe assumption.  After we solve dataflow, this
01224 /// method should be use to handle this.  If this returns true, the solver
01225 /// should be rerun.
01226 ///
01227 /// This method handles this by finding an unresolved branch and marking it one
01228 /// of the edges from the block as being feasible, even though the condition
01229 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
01230 /// CFG and only slightly pessimizes the analysis results (by marking one,
01231 /// potentially infeasible, edge feasible).  This cannot usefully modify the
01232 /// constraints on the condition of the branch, as that would impact other users
01233 /// of the value.
01234 ///
01235 /// This scan also checks for values that use undefs, whose results are actually
01236 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
01237 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
01238 /// even if X isn't defined.
01239 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
01240   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01241     if (!BBExecutable.count(BB))
01242       continue;
01243 
01244     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01245       // Look for instructions which produce undef values.
01246       if (I->getType()->isVoidTy()) continue;
01247 
01248       if (StructType *STy = dyn_cast<StructType>(I->getType())) {
01249         // Only a few things that can be structs matter for undef.
01250 
01251         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
01252         if (CallSite CS = CallSite(I))
01253           if (Function *F = CS.getCalledFunction())
01254             if (MRVFunctionsTracked.count(F))
01255               continue;
01256 
01257         // extractvalue and insertvalue don't need to be marked; they are
01258         // tracked as precisely as their operands.
01259         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
01260           continue;
01261 
01262         // Send the results of everything else to overdefined.  We could be
01263         // more precise than this but it isn't worth bothering.
01264         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01265           LatticeVal &LV = getStructValueState(I, i);
01266           if (LV.isUndefined())
01267             markOverdefined(LV, I);
01268         }
01269         continue;
01270       }
01271 
01272       LatticeVal &LV = getValueState(I);
01273       if (!LV.isUndefined()) continue;
01274 
01275       // extractvalue is safe; check here because the argument is a struct.
01276       if (isa<ExtractValueInst>(I))
01277         continue;
01278 
01279       // Compute the operand LatticeVals, for convenience below.
01280       // Anything taking a struct is conservatively assumed to require
01281       // overdefined markings.
01282       if (I->getOperand(0)->getType()->isStructTy()) {
01283         markOverdefined(I);
01284         return true;
01285       }
01286       LatticeVal Op0LV = getValueState(I->getOperand(0));
01287       LatticeVal Op1LV;
01288       if (I->getNumOperands() == 2) {
01289         if (I->getOperand(1)->getType()->isStructTy()) {
01290           markOverdefined(I);
01291           return true;
01292         }
01293 
01294         Op1LV = getValueState(I->getOperand(1));
01295       }
01296       // If this is an instructions whose result is defined even if the input is
01297       // not fully defined, propagate the information.
01298       Type *ITy = I->getType();
01299       switch (I->getOpcode()) {
01300       case Instruction::Add:
01301       case Instruction::Sub:
01302       case Instruction::Trunc:
01303       case Instruction::FPTrunc:
01304       case Instruction::BitCast:
01305         break; // Any undef -> undef
01306       case Instruction::FSub:
01307       case Instruction::FAdd:
01308       case Instruction::FMul:
01309       case Instruction::FDiv:
01310       case Instruction::FRem:
01311         // Floating-point binary operation: be conservative.
01312         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01313           markForcedConstant(I, Constant::getNullValue(ITy));
01314         else
01315           markOverdefined(I);
01316         return true;
01317       case Instruction::ZExt:
01318       case Instruction::SExt:
01319       case Instruction::FPToUI:
01320       case Instruction::FPToSI:
01321       case Instruction::FPExt:
01322       case Instruction::PtrToInt:
01323       case Instruction::IntToPtr:
01324       case Instruction::SIToFP:
01325       case Instruction::UIToFP:
01326         // undef -> 0; some outputs are impossible
01327         markForcedConstant(I, Constant::getNullValue(ITy));
01328         return true;
01329       case Instruction::Mul:
01330       case Instruction::And:
01331         // Both operands undef -> undef
01332         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01333           break;
01334         // undef * X -> 0.   X could be zero.
01335         // undef & X -> 0.   X could be zero.
01336         markForcedConstant(I, Constant::getNullValue(ITy));
01337         return true;
01338 
01339       case Instruction::Or:
01340         // Both operands undef -> undef
01341         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01342           break;
01343         // undef | X -> -1.   X could be -1.
01344         markForcedConstant(I, Constant::getAllOnesValue(ITy));
01345         return true;
01346 
01347       case Instruction::Xor:
01348         // undef ^ undef -> 0; strictly speaking, this is not strictly
01349         // necessary, but we try to be nice to people who expect this
01350         // behavior in simple cases
01351         if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
01352           markForcedConstant(I, Constant::getNullValue(ITy));
01353           return true;
01354         }
01355         // undef ^ X -> undef
01356         break;
01357 
01358       case Instruction::SDiv:
01359       case Instruction::UDiv:
01360       case Instruction::SRem:
01361       case Instruction::URem:
01362         // X / undef -> undef.  No change.
01363         // X % undef -> undef.  No change.
01364         if (Op1LV.isUndefined()) break;
01365 
01366         // undef / X -> 0.   X could be maxint.
01367         // undef % X -> 0.   X could be 1.
01368         markForcedConstant(I, Constant::getNullValue(ITy));
01369         return true;
01370 
01371       case Instruction::AShr:
01372         // X >>a undef -> undef.
01373         if (Op1LV.isUndefined()) break;
01374 
01375         // undef >>a X -> all ones
01376         markForcedConstant(I, Constant::getAllOnesValue(ITy));
01377         return true;
01378       case Instruction::LShr:
01379       case Instruction::Shl:
01380         // X << undef -> undef.
01381         // X >> undef -> undef.
01382         if (Op1LV.isUndefined()) break;
01383 
01384         // undef << X -> 0
01385         // undef >> X -> 0
01386         markForcedConstant(I, Constant::getNullValue(ITy));
01387         return true;
01388       case Instruction::Select:
01389         Op1LV = getValueState(I->getOperand(1));
01390         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
01391         if (Op0LV.isUndefined()) {
01392           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
01393             Op1LV = getValueState(I->getOperand(2));
01394         } else if (Op1LV.isUndefined()) {
01395           // c ? undef : undef -> undef.  No change.
01396           Op1LV = getValueState(I->getOperand(2));
01397           if (Op1LV.isUndefined())
01398             break;
01399           // Otherwise, c ? undef : x -> x.
01400         } else {
01401           // Leave Op1LV as Operand(1)'s LatticeValue.
01402         }
01403 
01404         if (Op1LV.isConstant())
01405           markForcedConstant(I, Op1LV.getConstant());
01406         else
01407           markOverdefined(I);
01408         return true;
01409       case Instruction::Load:
01410         // A load here means one of two things: a load of undef from a global,
01411         // a load from an unknown pointer.  Either way, having it return undef
01412         // is okay.
01413         break;
01414       case Instruction::ICmp:
01415         // X == undef -> undef.  Other comparisons get more complicated.
01416         if (cast<ICmpInst>(I)->isEquality())
01417           break;
01418         markOverdefined(I);
01419         return true;
01420       case Instruction::Call:
01421       case Instruction::Invoke: {
01422         // There are two reasons a call can have an undef result
01423         // 1. It could be tracked.
01424         // 2. It could be constant-foldable.
01425         // Because of the way we solve return values, tracked calls must
01426         // never be marked overdefined in ResolvedUndefsIn.
01427         if (Function *F = CallSite(I).getCalledFunction())
01428           if (TrackedRetVals.count(F))
01429             break;
01430 
01431         // If the call is constant-foldable, we mark it overdefined because
01432         // we do not know what return values are valid.
01433         markOverdefined(I);
01434         return true;
01435       }
01436       default:
01437         // If we don't know what should happen here, conservatively mark it
01438         // overdefined.
01439         markOverdefined(I);
01440         return true;
01441       }
01442     }
01443 
01444     // Check to see if we have a branch or switch on an undefined value.  If so
01445     // we force the branch to go one way or the other to make the successor
01446     // values live.  It doesn't really matter which way we force it.
01447     TerminatorInst *TI = BB->getTerminator();
01448     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01449       if (!BI->isConditional()) continue;
01450       if (!getValueState(BI->getCondition()).isUndefined())
01451         continue;
01452 
01453       // If the input to SCCP is actually branch on undef, fix the undef to
01454       // false.
01455       if (isa<UndefValue>(BI->getCondition())) {
01456         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
01457         markEdgeExecutable(BB, TI->getSuccessor(1));
01458         return true;
01459       }
01460 
01461       // Otherwise, it is a branch on a symbolic value which is currently
01462       // considered to be undef.  Handle this by forcing the input value to the
01463       // branch to false.
01464       markForcedConstant(BI->getCondition(),
01465                          ConstantInt::getFalse(TI->getContext()));
01466       return true;
01467     }
01468 
01469     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01470       if (!SI->getNumCases())
01471         continue;
01472       if (!getValueState(SI->getCondition()).isUndefined())
01473         continue;
01474 
01475       // If the input to SCCP is actually switch on undef, fix the undef to
01476       // the first constant.
01477       if (isa<UndefValue>(SI->getCondition())) {
01478         SI->setCondition(SI->case_begin().getCaseValue());
01479         markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
01480         return true;
01481       }
01482 
01483       markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
01484       return true;
01485     }
01486   }
01487 
01488   return false;
01489 }
01490 
01491 
01492 namespace {
01493   //===--------------------------------------------------------------------===//
01494   //
01495   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
01496   /// Sparse Conditional Constant Propagator.
01497   ///
01498   struct SCCP : public FunctionPass {
01499     void getAnalysisUsage(AnalysisUsage &AU) const override {
01500       AU.addRequired<TargetLibraryInfo>();
01501     }
01502     static char ID; // Pass identification, replacement for typeid
01503     SCCP() : FunctionPass(ID) {
01504       initializeSCCPPass(*PassRegistry::getPassRegistry());
01505     }
01506 
01507     // runOnFunction - Run the Sparse Conditional Constant Propagation
01508     // algorithm, and return true if the function was modified.
01509     //
01510     bool runOnFunction(Function &F) override;
01511   };
01512 } // end anonymous namespace
01513 
01514 char SCCP::ID = 0;
01515 INITIALIZE_PASS(SCCP, "sccp",
01516                 "Sparse Conditional Constant Propagation", false, false)
01517 
01518 // createSCCPPass - This is the public interface to this file.
01519 FunctionPass *llvm::createSCCPPass() {
01520   return new SCCP();
01521 }
01522 
01523 static void DeleteInstructionInBlock(BasicBlock *BB) {
01524   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
01525   ++NumDeadBlocks;
01526 
01527   // Check to see if there are non-terminating instructions to delete.
01528   if (isa<TerminatorInst>(BB->begin()))
01529     return;
01530 
01531   // Delete the instructions backwards, as it has a reduced likelihood of having
01532   // to update as many def-use and use-def chains.
01533   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
01534   while (EndInst != BB->begin()) {
01535     // Delete the next to last instruction.
01536     BasicBlock::iterator I = EndInst;
01537     Instruction *Inst = --I;
01538     if (!Inst->use_empty())
01539       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
01540     if (isa<LandingPadInst>(Inst)) {
01541       EndInst = Inst;
01542       continue;
01543     }
01544     BB->getInstList().erase(Inst);
01545     ++NumInstRemoved;
01546   }
01547 }
01548 
01549 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
01550 // and return true if the function was modified.
01551 //
01552 bool SCCP::runOnFunction(Function &F) {
01553   if (skipOptnoneFunction(F))
01554     return false;
01555 
01556   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
01557   const DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01558   const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
01559   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
01560   SCCPSolver Solver(DL, TLI);
01561 
01562   // Mark the first block of the function as being executable.
01563   Solver.MarkBlockExecutable(F.begin());
01564 
01565   // Mark all arguments to the function as being overdefined.
01566   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
01567     Solver.markAnythingOverdefined(AI);
01568 
01569   // Solve for constants.
01570   bool ResolvedUndefs = true;
01571   while (ResolvedUndefs) {
01572     Solver.Solve();
01573     DEBUG(dbgs() << "RESOLVING UNDEFs\n");
01574     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
01575   }
01576 
01577   bool MadeChanges = false;
01578 
01579   // If we decided that there are basic blocks that are dead in this function,
01580   // delete their contents now.  Note that we cannot actually delete the blocks,
01581   // as we cannot modify the CFG of the function.
01582 
01583   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01584     if (!Solver.isBlockExecutable(BB)) {
01585       DeleteInstructionInBlock(BB);
01586       MadeChanges = true;
01587       continue;
01588     }
01589 
01590     // Iterate over all of the instructions in a function, replacing them with
01591     // constants if we have found them to be of constant values.
01592     //
01593     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
01594       Instruction *Inst = BI++;
01595       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
01596         continue;
01597 
01598       // TODO: Reconstruct structs from their elements.
01599       if (Inst->getType()->isStructTy())
01600         continue;
01601 
01602       LatticeVal IV = Solver.getLatticeValueFor(Inst);
01603       if (IV.isOverdefined())
01604         continue;
01605 
01606       Constant *Const = IV.isConstant()
01607         ? IV.getConstant() : UndefValue::get(Inst->getType());
01608       DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst << '\n');
01609 
01610       // Replaces all of the uses of a variable with uses of the constant.
01611       Inst->replaceAllUsesWith(Const);
01612 
01613       // Delete the instruction.
01614       Inst->eraseFromParent();
01615 
01616       // Hey, we just changed something!
01617       MadeChanges = true;
01618       ++NumInstRemoved;
01619     }
01620   }
01621 
01622   return MadeChanges;
01623 }
01624 
01625 namespace {
01626   //===--------------------------------------------------------------------===//
01627   //
01628   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
01629   /// Constant Propagation.
01630   ///
01631   struct IPSCCP : public ModulePass {
01632     void getAnalysisUsage(AnalysisUsage &AU) const override {
01633       AU.addRequired<TargetLibraryInfo>();
01634     }
01635     static char ID;
01636     IPSCCP() : ModulePass(ID) {
01637       initializeIPSCCPPass(*PassRegistry::getPassRegistry());
01638     }
01639     bool runOnModule(Module &M) override;
01640   };
01641 } // end anonymous namespace
01642 
01643 char IPSCCP::ID = 0;
01644 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
01645                 "Interprocedural Sparse Conditional Constant Propagation",
01646                 false, false)
01647 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
01648 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
01649                 "Interprocedural Sparse Conditional Constant Propagation",
01650                 false, false)
01651 
01652 // createIPSCCPPass - This is the public interface to this file.
01653 ModulePass *llvm::createIPSCCPPass() {
01654   return new IPSCCP();
01655 }
01656 
01657 
01658 static bool AddressIsTaken(const GlobalValue *GV) {
01659   // Delete any dead constantexpr klingons.
01660   GV->removeDeadConstantUsers();
01661 
01662   for (const Use &U : GV->uses()) {
01663     const User *UR = U.getUser();
01664     if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
01665       if (SI->getOperand(0) == GV || SI->isVolatile())
01666         return true;  // Storing addr of GV.
01667     } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
01668       // Make sure we are calling the function, not passing the address.
01669       ImmutableCallSite CS(cast<Instruction>(UR));
01670       if (!CS.isCallee(&U))
01671         return true;
01672     } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
01673       if (LI->isVolatile())
01674         return true;
01675     } else if (isa<BlockAddress>(UR)) {
01676       // blockaddress doesn't take the address of the function, it takes addr
01677       // of label.
01678     } else {
01679       return true;
01680     }
01681   }
01682   return false;
01683 }
01684 
01685 bool IPSCCP::runOnModule(Module &M) {
01686   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01687   const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
01688   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
01689   SCCPSolver Solver(DL, TLI);
01690 
01691   // AddressTakenFunctions - This set keeps track of the address-taken functions
01692   // that are in the input.  As IPSCCP runs through and simplifies code,
01693   // functions that were address taken can end up losing their
01694   // address-taken-ness.  Because of this, we keep track of their addresses from
01695   // the first pass so we can use them for the later simplification pass.
01696   SmallPtrSet<Function*, 32> AddressTakenFunctions;
01697 
01698   // Loop over all functions, marking arguments to those with their addresses
01699   // taken or that are external as overdefined.
01700   //
01701   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01702     if (F->isDeclaration())
01703       continue;
01704 
01705     // If this is a strong or ODR definition of this function, then we can
01706     // propagate information about its result into callsites of it.
01707     if (!F->mayBeOverridden())
01708       Solver.AddTrackedFunction(F);
01709 
01710     // If this function only has direct calls that we can see, we can track its
01711     // arguments and return value aggressively, and can assume it is not called
01712     // unless we see evidence to the contrary.
01713     if (F->hasLocalLinkage()) {
01714       if (AddressIsTaken(F))
01715         AddressTakenFunctions.insert(F);
01716       else {
01717         Solver.AddArgumentTrackedFunction(F);
01718         continue;
01719       }
01720     }
01721 
01722     // Assume the function is called.
01723     Solver.MarkBlockExecutable(F->begin());
01724 
01725     // Assume nothing about the incoming arguments.
01726     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01727          AI != E; ++AI)
01728       Solver.markAnythingOverdefined(AI);
01729   }
01730 
01731   // Loop over global variables.  We inform the solver about any internal global
01732   // variables that do not have their 'addresses taken'.  If they don't have
01733   // their addresses taken, we can propagate constants through them.
01734   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
01735        G != E; ++G)
01736     if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
01737       Solver.TrackValueOfGlobalVariable(G);
01738 
01739   // Solve for constants.
01740   bool ResolvedUndefs = true;
01741   while (ResolvedUndefs) {
01742     Solver.Solve();
01743 
01744     DEBUG(dbgs() << "RESOLVING UNDEFS\n");
01745     ResolvedUndefs = false;
01746     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
01747       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
01748   }
01749 
01750   bool MadeChanges = false;
01751 
01752   // Iterate over all of the instructions in the module, replacing them with
01753   // constants if we have found them to be of constant values.
01754   //
01755   SmallVector<BasicBlock*, 512> BlocksToErase;
01756 
01757   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01758     if (Solver.isBlockExecutable(F->begin())) {
01759       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01760            AI != E; ++AI) {
01761         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
01762 
01763         // TODO: Could use getStructLatticeValueFor to find out if the entire
01764         // result is a constant and replace it entirely if so.
01765 
01766         LatticeVal IV = Solver.getLatticeValueFor(AI);
01767         if (IV.isOverdefined()) continue;
01768 
01769         Constant *CST = IV.isConstant() ?
01770         IV.getConstant() : UndefValue::get(AI->getType());
01771         DEBUG(dbgs() << "***  Arg " << *AI << " = " << *CST <<"\n");
01772 
01773         // Replaces all of the uses of a variable with uses of the
01774         // constant.
01775         AI->replaceAllUsesWith(CST);
01776         ++IPNumArgsElimed;
01777       }
01778     }
01779 
01780     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
01781       if (!Solver.isBlockExecutable(BB)) {
01782         DeleteInstructionInBlock(BB);
01783         MadeChanges = true;
01784 
01785         TerminatorInst *TI = BB->getTerminator();
01786         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
01787           BasicBlock *Succ = TI->getSuccessor(i);
01788           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
01789             TI->getSuccessor(i)->removePredecessor(BB);
01790         }
01791         if (!TI->use_empty())
01792           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
01793         TI->eraseFromParent();
01794 
01795         if (&*BB != &F->front())
01796           BlocksToErase.push_back(BB);
01797         else
01798           new UnreachableInst(M.getContext(), BB);
01799         continue;
01800       }
01801 
01802       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
01803         Instruction *Inst = BI++;
01804         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
01805           continue;
01806 
01807         // TODO: Could use getStructLatticeValueFor to find out if the entire
01808         // result is a constant and replace it entirely if so.
01809 
01810         LatticeVal IV = Solver.getLatticeValueFor(Inst);
01811         if (IV.isOverdefined())
01812           continue;
01813 
01814         Constant *Const = IV.isConstant()
01815           ? IV.getConstant() : UndefValue::get(Inst->getType());
01816         DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst << '\n');
01817 
01818         // Replaces all of the uses of a variable with uses of the
01819         // constant.
01820         Inst->replaceAllUsesWith(Const);
01821 
01822         // Delete the instruction.
01823         if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
01824           Inst->eraseFromParent();
01825 
01826         // Hey, we just changed something!
01827         MadeChanges = true;
01828         ++IPNumInstRemoved;
01829       }
01830     }
01831 
01832     // Now that all instructions in the function are constant folded, erase dead
01833     // blocks, because we can now use ConstantFoldTerminator to get rid of
01834     // in-edges.
01835     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
01836       // If there are any PHI nodes in this successor, drop entries for BB now.
01837       BasicBlock *DeadBB = BlocksToErase[i];
01838       for (Value::user_iterator UI = DeadBB->user_begin(),
01839                                 UE = DeadBB->user_end();
01840            UI != UE;) {
01841         // Grab the user and then increment the iterator early, as the user
01842         // will be deleted. Step past all adjacent uses from the same user.
01843         Instruction *I = dyn_cast<Instruction>(*UI);
01844         do { ++UI; } while (UI != UE && *UI == I);
01845 
01846         // Ignore blockaddress users; BasicBlock's dtor will handle them.
01847         if (!I) continue;
01848 
01849         bool Folded = ConstantFoldTerminator(I->getParent());
01850         if (!Folded) {
01851           // The constant folder may not have been able to fold the terminator
01852           // if this is a branch or switch on undef.  Fold it manually as a
01853           // branch to the first successor.
01854 #ifndef NDEBUG
01855           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
01856             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
01857                    "Branch should be foldable!");
01858           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
01859             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
01860           } else {
01861             llvm_unreachable("Didn't fold away reference to block!");
01862           }
01863 #endif
01864 
01865           // Make this an uncond branch to the first successor.
01866           TerminatorInst *TI = I->getParent()->getTerminator();
01867           BranchInst::Create(TI->getSuccessor(0), TI);
01868 
01869           // Remove entries in successor phi nodes to remove edges.
01870           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
01871             TI->getSuccessor(i)->removePredecessor(TI->getParent());
01872 
01873           // Remove the old terminator.
01874           TI->eraseFromParent();
01875         }
01876       }
01877 
01878       // Finally, delete the basic block.
01879       F->getBasicBlockList().erase(DeadBB);
01880     }
01881     BlocksToErase.clear();
01882   }
01883 
01884   // If we inferred constant or undef return values for a function, we replaced
01885   // all call uses with the inferred value.  This means we don't need to bother
01886   // actually returning anything from the function.  Replace all return
01887   // instructions with return undef.
01888   //
01889   // Do this in two stages: first identify the functions we should process, then
01890   // actually zap their returns.  This is important because we can only do this
01891   // if the address of the function isn't taken.  In cases where a return is the
01892   // last use of a function, the order of processing functions would affect
01893   // whether other functions are optimizable.
01894   SmallVector<ReturnInst*, 8> ReturnsToZap;
01895 
01896   // TODO: Process multiple value ret instructions also.
01897   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
01898   for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
01899        E = RV.end(); I != E; ++I) {
01900     Function *F = I->first;
01901     if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
01902       continue;
01903 
01904     // We can only do this if we know that nothing else can call the function.
01905     if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
01906       continue;
01907 
01908     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
01909       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
01910         if (!isa<UndefValue>(RI->getOperand(0)))
01911           ReturnsToZap.push_back(RI);
01912   }
01913 
01914   // Zap all returns which we've identified as zap to change.
01915   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
01916     Function *F = ReturnsToZap[i]->getParent()->getParent();
01917     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
01918   }
01919 
01920   // If we inferred constant or undef values for globals variables, we can
01921   // delete the global and any stores that remain to it.
01922   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
01923   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
01924          E = TG.end(); I != E; ++I) {
01925     GlobalVariable *GV = I->first;
01926     assert(!I->second.isOverdefined() &&
01927            "Overdefined values should have been taken out of the map!");
01928     DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
01929     while (!GV->use_empty()) {
01930       StoreInst *SI = cast<StoreInst>(GV->user_back());
01931       SI->eraseFromParent();
01932     }
01933     M.getGlobalList().erase(GV);
01934     ++IPNumGlobalConst;
01935   }
01936 
01937   return MadeChanges;
01938 }