LLVM API Documentation

SparsePropagation.cpp

Go to the documentation of this file.
00001 //===- SparsePropagation.cpp - Sparse Conditional Property 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 an abstract sparse conditional propagation algorithm,
00011 // modeled after SCCP, but with a customizable lattice function.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "sparseprop"
00016 #include "llvm/Analysis/SparsePropagation.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/Function.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Support/Debug.h"
00021 using namespace llvm;
00022 
00023 //===----------------------------------------------------------------------===//
00024 //                  AbstractLatticeFunction Implementation
00025 //===----------------------------------------------------------------------===//
00026 
00027 AbstractLatticeFunction::~AbstractLatticeFunction() {}
00028 
00029 /// PrintValue - Render the specified lattice value to the specified stream.
00030 void AbstractLatticeFunction::PrintValue(LatticeVal V, std::ostream &OS) {
00031   if (V == UndefVal)
00032     OS << "undefined";
00033   else if (V == OverdefinedVal)
00034     OS << "overdefined";
00035   else if (V == UntrackedVal)
00036     OS << "untracked";
00037   else
00038     OS << "unknown lattice value";
00039 }
00040 
00041 //===----------------------------------------------------------------------===//
00042 //                          SparseSolver Implementation
00043 //===----------------------------------------------------------------------===//
00044 
00045 /// getOrInitValueState - Return the LatticeVal object that corresponds to the
00046 /// value, initializing the value's state if it hasn't been entered into the
00047 /// map yet.   This function is necessary because not all values should start
00048 /// out in the underdefined state... Arguments should be overdefined, and
00049 /// constants should be marked as constants.
00050 ///
00051 SparseSolver::LatticeVal SparseSolver::getOrInitValueState(Value *V) {
00052   DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
00053   if (I != ValueState.end()) return I->second;  // Common case, in the map
00054   
00055   LatticeVal LV;
00056   if (LatticeFunc->IsUntrackedValue(V))
00057     return LatticeFunc->getUntrackedVal();
00058   else if (Constant *C = dyn_cast<Constant>(V))
00059     LV = LatticeFunc->ComputeConstant(C);
00060   else if (Argument *A = dyn_cast<Argument>(V))
00061     LV = LatticeFunc->ComputeArgument(A);
00062   else if (!isa<Instruction>(V))
00063     // All other non-instructions are overdefined.
00064     LV = LatticeFunc->getOverdefinedVal();
00065   else
00066     // All instructions are underdefined by default.
00067     LV = LatticeFunc->getUndefVal();
00068   
00069   // If this value is untracked, don't add it to the map.
00070   if (LV == LatticeFunc->getUntrackedVal())
00071     return LV;
00072   return ValueState[V] = LV;
00073 }
00074 
00075 /// UpdateState - When the state for some instruction is potentially updated,
00076 /// this function notices and adds I to the worklist if needed.
00077 void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
00078   DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
00079   if (I != ValueState.end() && I->second == V)
00080     return;  // No change.
00081   
00082   // An update.  Visit uses of I.
00083   ValueState[&Inst] = V;
00084   InstWorkList.push_back(&Inst);
00085 }
00086 
00087 /// MarkBlockExecutable - This method can be used by clients to mark all of
00088 /// the blocks that are known to be intrinsically live in the processed unit.
00089 void SparseSolver::MarkBlockExecutable(BasicBlock *BB) {
00090   DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
00091   BBExecutable.insert(BB);   // Basic block is executable!
00092   BBWorkList.push_back(BB);  // Add the block to the work list!
00093 }
00094 
00095 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
00096 /// work list if it is not already executable...
00097 void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
00098   if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
00099     return;  // This edge is already known to be executable!
00100   
00101   DOUT << "Marking Edge Executable: " << Source->getNameStart()
00102        << " -> " << Dest->getNameStart() << "\n";
00103 
00104   if (BBExecutable.count(Dest)) {
00105     // The destination is already executable, but we just made an edge
00106     // feasible that wasn't before.  Revisit the PHI nodes in the block
00107     // because they have potentially new operands.
00108     for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
00109       visitPHINode(*cast<PHINode>(I));
00110     
00111   } else {
00112     MarkBlockExecutable(Dest);
00113   }
00114 }
00115 
00116 
00117 /// getFeasibleSuccessors - Return a vector of booleans to indicate which
00118 /// successors are reachable from a given terminator instruction.
00119 void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
00120                                          SmallVectorImpl<bool> &Succs,
00121                                          bool AggressiveUndef) {
00122   Succs.resize(TI.getNumSuccessors());
00123   if (TI.getNumSuccessors() == 0) return;
00124   
00125   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
00126     if (BI->isUnconditional()) {
00127       Succs[0] = true;
00128       return;
00129     }
00130     
00131     LatticeVal BCValue;
00132     if (AggressiveUndef)
00133       BCValue = getOrInitValueState(BI->getCondition());
00134     else
00135       BCValue = getLatticeState(BI->getCondition());
00136     
00137     if (BCValue == LatticeFunc->getOverdefinedVal() ||
00138         BCValue == LatticeFunc->getUntrackedVal()) {
00139       // Overdefined condition variables can branch either way.
00140       Succs[0] = Succs[1] = true;
00141       return;
00142     }
00143 
00144     // If undefined, neither is feasible yet.
00145     if (BCValue == LatticeFunc->getUndefVal())
00146       return;
00147 
00148     Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
00149     if (C == 0 || !isa<ConstantInt>(C)) {
00150       // Non-constant values can go either way.
00151       Succs[0] = Succs[1] = true;
00152       return;
00153     }
00154 
00155     // Constant condition variables mean the branch can only go a single way
00156     Succs[C == ConstantInt::getFalse()] = true;
00157     return;
00158   }
00159   
00160   if (isa<InvokeInst>(TI)) {
00161     // Invoke instructions successors are always executable.
00162     // TODO: Could ask the lattice function if the value can throw.
00163     Succs[0] = Succs[1] = true;
00164     return;
00165   }
00166   
00167   SwitchInst &SI = cast<SwitchInst>(TI);
00168   LatticeVal SCValue;
00169   if (AggressiveUndef)
00170     SCValue = getOrInitValueState(SI.getCondition());
00171   else
00172     SCValue = getLatticeState(SI.getCondition());
00173   
00174   if (SCValue == LatticeFunc->getOverdefinedVal() ||
00175       SCValue == LatticeFunc->getUntrackedVal()) {
00176     // All destinations are executable!
00177     Succs.assign(TI.getNumSuccessors(), true);
00178     return;
00179   }
00180   
00181   // If undefined, neither is feasible yet.
00182   if (SCValue == LatticeFunc->getUndefVal())
00183     return;
00184   
00185   Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
00186   if (C == 0 || !isa<ConstantInt>(C)) {
00187     // All destinations are executable!
00188     Succs.assign(TI.getNumSuccessors(), true);
00189     return;
00190   }
00191   
00192   Succs[SI.findCaseValue(cast<ConstantInt>(C))] = true;
00193 }
00194 
00195 
00196 /// isEdgeFeasible - Return true if the control flow edge from the 'From'
00197 /// basic block to the 'To' basic block is currently feasible...
00198 bool SparseSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To,
00199                                   bool AggressiveUndef) {
00200   SmallVector<bool, 16> SuccFeasible;
00201   TerminatorInst *TI = From->getTerminator();
00202   getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
00203   
00204   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00205     if (TI->getSuccessor(i) == To && SuccFeasible[i])
00206       return true;
00207   
00208   return false;
00209 }
00210 
00211 void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
00212   SmallVector<bool, 16> SuccFeasible;
00213   getFeasibleSuccessors(TI, SuccFeasible, true);
00214   
00215   BasicBlock *BB = TI.getParent();
00216   
00217   // Mark all feasible successors executable...
00218   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
00219     if (SuccFeasible[i])
00220       markEdgeExecutable(BB, TI.getSuccessor(i));
00221 }
00222 
00223 void SparseSolver::visitPHINode(PHINode &PN) {
00224   LatticeVal PNIV = getOrInitValueState(&PN);
00225   LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
00226   
00227   // If this value is already overdefined (common) just return.
00228   if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
00229     return;  // Quick exit
00230   
00231   // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
00232   // and slow us down a lot.  Just mark them overdefined.
00233   if (PN.getNumIncomingValues() > 64) {
00234     UpdateState(PN, Overdefined);
00235     return;
00236   }
00237   
00238   // Look at all of the executable operands of the PHI node.  If any of them
00239   // are overdefined, the PHI becomes overdefined as well.  Otherwise, ask the
00240   // transfer function to give us the merge of the incoming values.
00241   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
00242     // If the edge is not yet known to be feasible, it doesn't impact the PHI.
00243     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
00244       continue;
00245     
00246     // Merge in this value.
00247     LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
00248     if (OpVal != PNIV)
00249       PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
00250     
00251     if (PNIV == Overdefined)
00252       break;  // Rest of input values don't matter.
00253   }
00254 
00255   // Update the PHI with the compute value, which is the merge of the inputs.
00256   UpdateState(PN, PNIV);
00257 }
00258 
00259 
00260 void SparseSolver::visitInst(Instruction &I) {
00261   // PHIs are handled by the propagation logic, they are never passed into the
00262   // transfer functions.
00263   if (PHINode *PN = dyn_cast<PHINode>(&I))
00264     return visitPHINode(*PN);
00265   
00266   // Otherwise, ask the transfer function what the result is.  If this is
00267   // something that we care about, remember it.
00268   LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
00269   if (IV != LatticeFunc->getUntrackedVal())
00270     UpdateState(I, IV);
00271   
00272   if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
00273     visitTerminatorInst(*TI);
00274 }
00275 
00276 void SparseSolver::Solve(Function &F) {
00277   MarkBlockExecutable(&F.getEntryBlock());
00278   
00279   // Process the work lists until they are empty!
00280   while (!BBWorkList.empty() || !InstWorkList.empty()) {
00281     // Process the instruction work list.
00282     while (!InstWorkList.empty()) {
00283       Instruction *I = InstWorkList.back();
00284       InstWorkList.pop_back();
00285 
00286       DOUT << "\nPopped off I-WL: " << *I;
00287 
00288       // "I" got into the work list because it made a transition.  See if any
00289       // users are both live and in need of updating.
00290       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
00291            UI != E; ++UI) {
00292         Instruction *U = cast<Instruction>(*UI);
00293         if (BBExecutable.count(U->getParent()))   // Inst is executable?
00294           visitInst(*U);
00295       }
00296     }
00297 
00298     // Process the basic block work list.
00299     while (!BBWorkList.empty()) {
00300       BasicBlock *BB = BBWorkList.back();
00301       BBWorkList.pop_back();
00302 
00303       DOUT << "\nPopped off BBWL: " << *BB;
00304 
00305       // Notify all instructions in this basic block that they are newly
00306       // executable.
00307       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00308         visitInst(*I);
00309     }
00310   }
00311 }
00312 
00313 void SparseSolver::Print(Function &F, std::ostream &OS) {
00314   OS << "\nFUNCTION: " << F.getNameStr() << "\n";
00315   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00316     if (!BBExecutable.count(BB))
00317       OS << "INFEASIBLE: ";
00318     OS << "\t";
00319     if (BB->hasName())
00320       OS << BB->getNameStr() << ":\n";
00321     else
00322       OS << "; anon bb\n";
00323     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00324       LatticeFunc->PrintValue(getLatticeState(I), OS);
00325       OS << *I;
00326     }
00327     
00328     OS << "\n";
00329   }
00330 }
00331