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