1 //===- SparsePropagation.cpp - Sparse Conditional Property Propagation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements an abstract sparse conditional propagation algorithm,
11 // modeled after SCCP, but with a customizable lattice function.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "sparseprop"
16 #include "llvm/Analysis/SparsePropagation.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/Debug.h"
23 //===----------------------------------------------------------------------===//
24 // AbstractLatticeFunction Implementation
25 //===----------------------------------------------------------------------===//
27 AbstractLatticeFunction::~AbstractLatticeFunction() {}
29 /// PrintValue - Render the specified lattice value to the specified stream.
30 void AbstractLatticeFunction::PrintValue(LatticeVal V, std::ostream &OS) {
33 else if (V == OverdefinedVal)
35 else if (V == UntrackedVal)
38 OS << "unknown lattice value";
41 //===----------------------------------------------------------------------===//
42 // SparseSolver Implementation
43 //===----------------------------------------------------------------------===//
45 /// getOrInitValueState - Return the LatticeVal object that corresponds to the
46 /// value, initializing the value's state if it hasn't been entered into the
47 /// map yet. This function is necessary because not all values should start
48 /// out in the underdefined state... Arguments should be overdefined, and
49 /// constants should be marked as constants.
51 SparseSolver::LatticeVal SparseSolver::getOrInitValueState(Value *V) {
52 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
53 if (I != ValueState.end()) return I->second; // Common case, in the map
56 if (LatticeFunc->IsUntrackedValue(V))
57 return LatticeFunc->getUntrackedVal();
58 else if (Constant *C = dyn_cast<Constant>(V))
59 LV = LatticeFunc->ComputeConstant(C);
60 else if (!isa<Instruction>(V))
61 // Non-instructions (e.g. formal arguments) are overdefined.
62 LV = LatticeFunc->getOverdefinedVal();
64 // All instructions are underdefined by default.
65 LV = LatticeFunc->getUndefVal();
67 // If this value is untracked, don't add it to the map.
68 if (LV == LatticeFunc->getUntrackedVal())
70 return ValueState[V] = LV;
73 /// UpdateState - When the state for some instruction is potentially updated,
74 /// this function notices and adds I to the worklist if needed.
75 void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
76 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
77 if (I != ValueState.end() && I->second == V)
80 // An update. Visit uses of I.
81 ValueState[&Inst] = V;
82 InstWorkList.push_back(&Inst);
85 /// MarkBlockExecutable - This method can be used by clients to mark all of
86 /// the blocks that are known to be intrinsically live in the processed unit.
87 void SparseSolver::MarkBlockExecutable(BasicBlock *BB) {
88 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
89 BBExecutable.insert(BB); // Basic block is executable!
90 BBWorkList.push_back(BB); // Add the block to the work list!
93 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
94 /// work list if it is not already executable...
95 void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
96 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
97 return; // This edge is already known to be executable!
99 DOUT << "Marking Edge Executable: " << Source->getNameStart()
100 << " -> " << Dest->getNameStart() << "\n";
102 if (BBExecutable.count(Dest)) {
103 // The destination is already executable, but we just made an edge
104 // feasible that wasn't before. Revisit the PHI nodes in the block
105 // because they have potentially new operands.
106 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
107 visitPHINode(*cast<PHINode>(I));
110 MarkBlockExecutable(Dest);
115 /// getFeasibleSuccessors - Return a vector of booleans to indicate which
116 /// successors are reachable from a given terminator instruction.
117 void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
118 SmallVectorImpl<bool> &Succs,
119 bool AggressiveUndef) {
120 Succs.resize(TI.getNumSuccessors());
121 if (TI.getNumSuccessors() == 0) return;
123 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
124 if (BI->isUnconditional()) {
131 BCValue = getOrInitValueState(BI->getCondition());
133 BCValue = getLatticeState(BI->getCondition());
135 if (BCValue == LatticeFunc->getOverdefinedVal() ||
136 BCValue == LatticeFunc->getUntrackedVal()) {
137 // Overdefined condition variables can branch either way.
138 Succs[0] = Succs[1] = true;
142 // If undefined, neither is feasible yet.
143 if (BCValue == LatticeFunc->getUndefVal())
146 Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
147 if (C == 0 || !isa<ConstantInt>(C)) {
148 // Non-constant values can go either way.
149 Succs[0] = Succs[1] = true;
153 // Constant condition variables mean the branch can only go a single way
154 Succs[C == ConstantInt::getFalse()] = true;
158 if (isa<InvokeInst>(TI)) {
159 // Invoke instructions successors are always executable.
160 // TODO: Could ask the lattice function if the value can throw.
161 Succs[0] = Succs[1] = true;
165 SwitchInst &SI = cast<SwitchInst>(TI);
168 SCValue = getOrInitValueState(SI.getCondition());
170 SCValue = getLatticeState(SI.getCondition());
172 if (SCValue == LatticeFunc->getOverdefinedVal() ||
173 SCValue == LatticeFunc->getUntrackedVal()) {
174 // All destinations are executable!
175 Succs.assign(TI.getNumSuccessors(), true);
179 // If undefined, neither is feasible yet.
180 if (SCValue == LatticeFunc->getUndefVal())
183 Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
184 if (C == 0 || !isa<ConstantInt>(C)) {
185 // All destinations are executable!
186 Succs.assign(TI.getNumSuccessors(), true);
190 Succs[SI.findCaseValue(cast<ConstantInt>(C))] = true;
194 /// isEdgeFeasible - Return true if the control flow edge from the 'From'
195 /// basic block to the 'To' basic block is currently feasible...
196 bool SparseSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To,
197 bool AggressiveUndef) {
198 SmallVector<bool, 16> SuccFeasible;
199 TerminatorInst *TI = From->getTerminator();
200 getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
202 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
203 if (TI->getSuccessor(i) == To && SuccFeasible[i])
209 void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
210 SmallVector<bool, 16> SuccFeasible;
211 getFeasibleSuccessors(TI, SuccFeasible, true);
213 BasicBlock *BB = TI.getParent();
215 // Mark all feasible successors executable...
216 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
218 markEdgeExecutable(BB, TI.getSuccessor(i));
221 void SparseSolver::visitPHINode(PHINode &PN) {
222 LatticeVal PNIV = getOrInitValueState(&PN);
223 LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
225 // If this value is already overdefined (common) just return.
226 if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
227 return; // Quick exit
229 // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
230 // and slow us down a lot. Just mark them overdefined.
231 if (PN.getNumIncomingValues() > 64) {
232 UpdateState(PN, Overdefined);
236 // Look at all of the executable operands of the PHI node. If any of them
237 // are overdefined, the PHI becomes overdefined as well. Otherwise, ask the
238 // transfer function to give us the merge of the incoming values.
239 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
240 // If the edge is not yet known to be feasible, it doesn't impact the PHI.
241 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
244 // Merge in this value.
245 LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
247 PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
249 if (PNIV == Overdefined)
250 break; // Rest of input values don't matter.
253 // Update the PHI with the compute value, which is the merge of the inputs.
254 UpdateState(PN, PNIV);
258 void SparseSolver::visitInst(Instruction &I) {
259 // PHIs are handled by the propagation logic, they are never passed into the
260 // transfer functions.
261 if (PHINode *PN = dyn_cast<PHINode>(&I))
262 return visitPHINode(*PN);
264 // Otherwise, ask the transfer function what the result is. If this is
265 // something that we care about, remember it.
266 LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
267 if (IV != LatticeFunc->getUntrackedVal())
270 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
271 visitTerminatorInst(*TI);
274 void SparseSolver::Solve(Function &F) {
275 MarkBlockExecutable(&F.getEntryBlock());
277 // Process the work lists until they are empty!
278 while (!BBWorkList.empty() || !InstWorkList.empty()) {
279 // Process the instruction work list.
280 while (!InstWorkList.empty()) {
281 Instruction *I = InstWorkList.back();
282 InstWorkList.pop_back();
284 DOUT << "\nPopped off I-WL: " << *I;
286 // "I" got into the work list because it made a transition. See if any
287 // users are both live and in need of updating.
288 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
290 Instruction *U = cast<Instruction>(*UI);
291 if (BBExecutable.count(U->getParent())) // Inst is executable?
296 // Process the basic block work list.
297 while (!BBWorkList.empty()) {
298 BasicBlock *BB = BBWorkList.back();
299 BBWorkList.pop_back();
301 DOUT << "\nPopped off BBWL: " << *BB;
303 // Notify all instructions in this basic block that they are newly
305 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
311 void SparseSolver::Print(Function &F, std::ostream &OS) {
312 OS << "\nFUNCTION: " << F.getNameStr() << "\n";
313 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
314 if (!BBExecutable.count(BB))
315 OS << "INFEASIBLE: ";
318 OS << BB->getNameStr() << ":\n";
321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
322 LatticeFunc->PrintValue(getLatticeState(I), OS);