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