blob: 2fda64c733502ff7605f6cf83a1045d40b790e74 [file] [log] [blame]
Chris Lattnerab7d9cc2008-05-12 01:12:24 +00001//===- SparsePropagation.cpp - Sparse Conditional Property Propagation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements an abstract sparse conditional propagation algorithm,
11// modeled after SCCP, but with a customizable lattice function.
12//
13//===----------------------------------------------------------------------===//
14
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"
Chris Lattnerab7d9cc2008-05-12 01:12:24 +000020#include "llvm/Support/Debug.h"
Chris Lattnerab7d9cc2008-05-12 01:12:24 +000021using namespace llvm;
22
23//===----------------------------------------------------------------------===//
24// AbstractLatticeFunction Implementation
25//===----------------------------------------------------------------------===//
26
27AbstractLatticeFunction::~AbstractLatticeFunction() {}
28
29/// PrintValue - Render the specified lattice value to the specified stream.
30void AbstractLatticeFunction::PrintValue(LatticeVal V, std::ostream &OS) {
31 if (V == UndefVal)
32 OS << "undefined";
33 else if (V == OverdefinedVal)
34 OS << "overdefined";
35 else if (V == UntrackedVal)
36 OS << "untracked";
37 else
38 OS << "unknown lattice value";
39}
40
41//===----------------------------------------------------------------------===//
42// SparseSolver Implementation
43//===----------------------------------------------------------------------===//
44
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.
50///
51SparseSolver::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
54
55 LatticeVal LV;
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();
63 else
64 // All instructions are underdefined by default.
65 LV = LatticeFunc->getUndefVal();
66
67 // If this value is untracked, don't add it to the map.
68 if (LV == LatticeFunc->getUntrackedVal())
69 return LV;
70 return ValueState[V] = LV;
71}
72
73/// UpdateState - When the state for some instruction is potentially updated,
74/// this function notices and adds I to the worklist if needed.
75void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
76 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
77 if (I != ValueState.end() && I->second == V)
78 return; // No change.
79
80 // An update. Visit uses of I.
81 ValueState[&Inst] = V;
82 InstWorkList.push_back(&Inst);
83}
84
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.
87void 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!
91}
92
93/// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
94/// work list if it is not already executable...
95void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
96 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
97 return; // This edge is already known to be executable!
98
Dan Gohmanb22d6ac2008-05-27 20:47:30 +000099 DOUT << "Marking Edge Executable: " << Source->getNameStart()
100 << " -> " << Dest->getNameStart() << "\n";
101
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000102 if (BBExecutable.count(Dest)) {
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000103 // 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));
108
109 } else {
110 MarkBlockExecutable(Dest);
111 }
112}
113
114
115/// getFeasibleSuccessors - Return a vector of booleans to indicate which
116/// successors are reachable from a given terminator instruction.
117void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000118 SmallVectorImpl<bool> &Succs,
119 bool AggressiveUndef) {
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000120 Succs.resize(TI.getNumSuccessors());
121 if (TI.getNumSuccessors() == 0) return;
122
123 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
124 if (BI->isUnconditional()) {
125 Succs[0] = true;
126 return;
127 }
128
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000129 LatticeVal BCValue;
130 if (AggressiveUndef)
131 BCValue = getOrInitValueState(BI->getCondition());
132 else
133 BCValue = getLatticeState(BI->getCondition());
134
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000135 if (BCValue == LatticeFunc->getOverdefinedVal() ||
136 BCValue == LatticeFunc->getUntrackedVal()) {
137 // Overdefined condition variables can branch either way.
138 Succs[0] = Succs[1] = true;
139 return;
140 }
141
142 // If undefined, neither is feasible yet.
143 if (BCValue == LatticeFunc->getUndefVal())
144 return;
145
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;
150 return;
151 }
152
153 // Constant condition variables mean the branch can only go a single way
154 Succs[C == ConstantInt::getFalse()] = true;
155 return;
156 }
157
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;
162 return;
163 }
164
165 SwitchInst &SI = cast<SwitchInst>(TI);
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000166 LatticeVal SCValue;
167 if (AggressiveUndef)
168 SCValue = getOrInitValueState(SI.getCondition());
169 else
170 SCValue = getLatticeState(SI.getCondition());
171
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000172 if (SCValue == LatticeFunc->getOverdefinedVal() ||
173 SCValue == LatticeFunc->getUntrackedVal()) {
174 // All destinations are executable!
175 Succs.assign(TI.getNumSuccessors(), true);
176 return;
177 }
178
179 // If undefined, neither is feasible yet.
180 if (SCValue == LatticeFunc->getUndefVal())
181 return;
182
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);
187 return;
188 }
189
190 Succs[SI.findCaseValue(cast<ConstantInt>(C))] = true;
191}
192
193
194/// isEdgeFeasible - Return true if the control flow edge from the 'From'
195/// basic block to the 'To' basic block is currently feasible...
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000196bool SparseSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To,
197 bool AggressiveUndef) {
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000198 SmallVector<bool, 16> SuccFeasible;
199 TerminatorInst *TI = From->getTerminator();
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000200 getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000201
202 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
203 if (TI->getSuccessor(i) == To && SuccFeasible[i])
204 return true;
205
206 return false;
207}
208
209void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
210 SmallVector<bool, 16> SuccFeasible;
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000211 getFeasibleSuccessors(TI, SuccFeasible, true);
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000212
213 BasicBlock *BB = TI.getParent();
214
215 // Mark all feasible successors executable...
216 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
217 if (SuccFeasible[i])
218 markEdgeExecutable(BB, TI.getSuccessor(i));
219}
220
221void SparseSolver::visitPHINode(PHINode &PN) {
222 LatticeVal PNIV = getOrInitValueState(&PN);
223 LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
224
225 // If this value is already overdefined (common) just return.
226 if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
227 return; // Quick exit
228
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);
233 return;
234 }
235
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.
Chris Lattner28a8dbc2008-05-20 03:39:39 +0000241 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000242 continue;
243
244 // Merge in this value.
245 LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
246 if (OpVal != PNIV)
247 PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
248
249 if (PNIV == Overdefined)
250 break; // Rest of input values don't matter.
251 }
252
253 // Update the PHI with the compute value, which is the merge of the inputs.
254 UpdateState(PN, PNIV);
255}
256
257
258void 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);
263
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())
268 UpdateState(I, IV);
269
270 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
271 visitTerminatorInst(*TI);
272}
273
274void SparseSolver::Solve(Function &F) {
Dan Gohmanef61af02008-05-27 20:55:29 +0000275 MarkBlockExecutable(&F.getEntryBlock());
Chris Lattnerab7d9cc2008-05-12 01:12:24 +0000276
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();
283
284 DOUT << "\nPopped off I-WL: " << *I;
285
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();
289 UI != E; ++UI) {
290 Instruction *U = cast<Instruction>(*UI);
291 if (BBExecutable.count(U->getParent())) // Inst is executable?
292 visitInst(*U);
293 }
294 }
295
296 // Process the basic block work list.
297 while (!BBWorkList.empty()) {
298 BasicBlock *BB = BBWorkList.back();
299 BBWorkList.pop_back();
300
301 DOUT << "\nPopped off BBWL: " << *BB;
302
303 // Notify all instructions in this basic block that they are newly
304 // executable.
305 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
306 visitInst(*I);
307 }
308 }
309}
310
311void 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: ";
316 OS << "\t";
317 if (BB->hasName())
318 OS << BB->getNameStr() << ":\n";
319 else
320 OS << "; anon bb\n";
321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
322 LatticeFunc->PrintValue(getLatticeState(I), OS);
323 OS << *I;
324 }
325
326 OS << "\n";
327 }
328}
329