LLVM  6.0.0svn
SparsePropagation.cpp
Go to the documentation of this file.
1 //===- 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 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/IR/Argument.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/User.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Debug.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "sparseprop"
34 
35 //===----------------------------------------------------------------------===//
36 // AbstractLatticeFunction Implementation
37 //===----------------------------------------------------------------------===//
38 
40 
41 /// PrintValue - Render the specified lattice value to the specified stream.
43  if (V == UndefVal)
44  OS << "undefined";
45  else if (V == OverdefinedVal)
46  OS << "overdefined";
47  else if (V == UntrackedVal)
48  OS << "untracked";
49  else
50  OS << "unknown lattice value";
51 }
52 
53 //===----------------------------------------------------------------------===//
54 // SparseSolver Implementation
55 //===----------------------------------------------------------------------===//
56 
57 /// getOrInitValueState - Return the LatticeVal object that corresponds to the
58 /// value, initializing the value's state if it hasn't been entered into the
59 /// map yet. This function is necessary because not all values should start
60 /// out in the underdefined state... Arguments should be overdefined, and
61 /// constants should be marked as constants.
62 SparseSolver::LatticeVal SparseSolver::getOrInitValueState(Value *V) {
63  DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
64  if (I != ValueState.end()) return I->second; // Common case, in the map
65 
66  LatticeVal LV;
67  if (LatticeFunc->IsUntrackedValue(V))
68  return LatticeFunc->getUntrackedVal();
69  else if (Constant *C = dyn_cast<Constant>(V))
70  LV = LatticeFunc->ComputeConstant(C);
71  else if (Argument *A = dyn_cast<Argument>(V))
72  LV = LatticeFunc->ComputeArgument(A);
73  else if (!isa<Instruction>(V))
74  // All other non-instructions are overdefined.
75  LV = LatticeFunc->getOverdefinedVal();
76  else
77  // All instructions are underdefined by default.
78  LV = LatticeFunc->getUndefVal();
79 
80  // If this value is untracked, don't add it to the map.
81  if (LV == LatticeFunc->getUntrackedVal())
82  return LV;
83  return ValueState[V] = LV;
84 }
85 
86 /// UpdateState - When the state for some instruction is potentially updated,
87 /// this function notices and adds I to the worklist if needed.
88 void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
89  DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
90  if (I != ValueState.end() && I->second == V)
91  return; // No change.
92 
93  // An update. Visit uses of I.
94  ValueState[&Inst] = V;
95  InstWorkList.push_back(&Inst);
96 }
97 
98 /// MarkBlockExecutable - This method can be used by clients to mark all of
99 /// the blocks that are known to be intrinsically live in the processed unit.
100 void SparseSolver::MarkBlockExecutable(BasicBlock *BB) {
101  DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
102  BBExecutable.insert(BB); // Basic block is executable!
103  BBWorkList.push_back(BB); // Add the block to the work list!
104 }
105 
106 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
107 /// work list if it is not already executable...
108 void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
109  if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
110  return; // This edge is already known to be executable!
111 
112  DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
113  << " -> " << Dest->getName() << "\n");
114 
115  if (BBExecutable.count(Dest)) {
116  // The destination is already executable, but we just made an edge
117  // feasible that wasn't before. Revisit the PHI nodes in the block
118  // because they have potentially new operands.
119  for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
120  visitPHINode(*cast<PHINode>(I));
121  } else {
122  MarkBlockExecutable(Dest);
123  }
124 }
125 
126 /// getFeasibleSuccessors - Return a vector of booleans to indicate which
127 /// successors are reachable from a given terminator instruction.
128 void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
129  SmallVectorImpl<bool> &Succs,
130  bool AggressiveUndef) {
131  Succs.resize(TI.getNumSuccessors());
132  if (TI.getNumSuccessors() == 0) return;
133 
134  if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
135  if (BI->isUnconditional()) {
136  Succs[0] = true;
137  return;
138  }
139 
140  LatticeVal BCValue;
141  if (AggressiveUndef)
142  BCValue = getOrInitValueState(BI->getCondition());
143  else
144  BCValue = getLatticeState(BI->getCondition());
145 
146  if (BCValue == LatticeFunc->getOverdefinedVal() ||
147  BCValue == LatticeFunc->getUntrackedVal()) {
148  // Overdefined condition variables can branch either way.
149  Succs[0] = Succs[1] = true;
150  return;
151  }
152 
153  // If undefined, neither is feasible yet.
154  if (BCValue == LatticeFunc->getUndefVal())
155  return;
156 
157  Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
158  if (!C || !isa<ConstantInt>(C)) {
159  // Non-constant values can go either way.
160  Succs[0] = Succs[1] = true;
161  return;
162  }
163 
164  // Constant condition variables mean the branch can only go a single way
165  Succs[C->isNullValue()] = true;
166  return;
167  }
168 
169  if (isa<InvokeInst>(TI)) {
170  // Invoke instructions successors are always executable.
171  // TODO: Could ask the lattice function if the value can throw.
172  Succs[0] = Succs[1] = true;
173  return;
174  }
175 
176  if (isa<IndirectBrInst>(TI)) {
177  Succs.assign(Succs.size(), true);
178  return;
179  }
180 
181  SwitchInst &SI = cast<SwitchInst>(TI);
182  LatticeVal SCValue;
183  if (AggressiveUndef)
184  SCValue = getOrInitValueState(SI.getCondition());
185  else
186  SCValue = getLatticeState(SI.getCondition());
187 
188  if (SCValue == LatticeFunc->getOverdefinedVal() ||
189  SCValue == LatticeFunc->getUntrackedVal()) {
190  // All destinations are executable!
191  Succs.assign(TI.getNumSuccessors(), true);
192  return;
193  }
194 
195  // If undefined, neither is feasible yet.
196  if (SCValue == LatticeFunc->getUndefVal())
197  return;
198 
199  Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
200  if (!C || !isa<ConstantInt>(C)) {
201  // All destinations are executable!
202  Succs.assign(TI.getNumSuccessors(), true);
203  return;
204  }
205  SwitchInst::CaseHandle Case = *SI.findCaseValue(cast<ConstantInt>(C));
206  Succs[Case.getSuccessorIndex()] = true;
207 }
208 
209 /// isEdgeFeasible - Return true if the control flow edge from the 'From'
210 /// basic block to the 'To' basic block is currently feasible...
212  bool AggressiveUndef) {
213  SmallVector<bool, 16> SuccFeasible;
214  TerminatorInst *TI = From->getTerminator();
215  getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
216 
217  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
218  if (TI->getSuccessor(i) == To && SuccFeasible[i])
219  return true;
220 
221  return false;
222 }
223 
224 void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
225  SmallVector<bool, 16> SuccFeasible;
226  getFeasibleSuccessors(TI, SuccFeasible, true);
227 
228  BasicBlock *BB = TI.getParent();
229 
230  // Mark all feasible successors executable...
231  for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
232  if (SuccFeasible[i])
233  markEdgeExecutable(BB, TI.getSuccessor(i));
234 }
235 
236 void SparseSolver::visitPHINode(PHINode &PN) {
237  // The lattice function may store more information on a PHINode than could be
238  // computed from its incoming values. For example, SSI form stores its sigma
239  // functions as PHINodes with a single incoming value.
240  if (LatticeFunc->IsSpecialCasedPHI(&PN)) {
241  LatticeVal IV = LatticeFunc->ComputeInstructionState(PN, *this);
242  if (IV != LatticeFunc->getUntrackedVal())
243  UpdateState(PN, IV);
244  return;
245  }
246 
247  LatticeVal PNIV = getOrInitValueState(&PN);
248  LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
249 
250  // If this value is already overdefined (common) just return.
251  if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
252  return; // Quick exit
253 
254  // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
255  // and slow us down a lot. Just mark them overdefined.
256  if (PN.getNumIncomingValues() > 64) {
257  UpdateState(PN, Overdefined);
258  return;
259  }
260 
261  // Look at all of the executable operands of the PHI node. If any of them
262  // are overdefined, the PHI becomes overdefined as well. Otherwise, ask the
263  // transfer function to give us the merge of the incoming values.
264  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
265  // If the edge is not yet known to be feasible, it doesn't impact the PHI.
266  if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
267  continue;
268 
269  // Merge in this value.
270  LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
271  if (OpVal != PNIV)
272  PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
273 
274  if (PNIV == Overdefined)
275  break; // Rest of input values don't matter.
276  }
277 
278  // Update the PHI with the compute value, which is the merge of the inputs.
279  UpdateState(PN, PNIV);
280 }
281 
282 void SparseSolver::visitInst(Instruction &I) {
283  // PHIs are handled by the propagation logic, they are never passed into the
284  // transfer functions.
285  if (PHINode *PN = dyn_cast<PHINode>(&I))
286  return visitPHINode(*PN);
287 
288  // Otherwise, ask the transfer function what the result is. If this is
289  // something that we care about, remember it.
290  LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
291  if (IV != LatticeFunc->getUntrackedVal())
292  UpdateState(I, IV);
293 
294  if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
295  visitTerminatorInst(*TI);
296 }
297 
299  MarkBlockExecutable(&F.getEntryBlock());
300 
301  // Process the work lists until they are empty!
302  while (!BBWorkList.empty() || !InstWorkList.empty()) {
303  // Process the instruction work list.
304  while (!InstWorkList.empty()) {
305  Instruction *I = InstWorkList.back();
306  InstWorkList.pop_back();
307 
308  DEBUG(dbgs() << "\nPopped off I-WL: " << *I << "\n");
309 
310  // "I" got into the work list because it made a transition. See if any
311  // users are both live and in need of updating.
312  for (User *U : I->users()) {
313  Instruction *UI = cast<Instruction>(U);
314  if (BBExecutable.count(UI->getParent())) // Inst is executable?
315  visitInst(*UI);
316  }
317  }
318 
319  // Process the basic block work list.
320  while (!BBWorkList.empty()) {
321  BasicBlock *BB = BBWorkList.back();
322  BBWorkList.pop_back();
323 
324  DEBUG(dbgs() << "\nPopped off BBWL: " << *BB);
325 
326  // Notify all instructions in this basic block that they are newly
327  // executable.
328  for (Instruction &I : *BB)
329  visitInst(I);
330  }
331  }
332 }
333 
335  OS << "\nFUNCTION: " << F.getName() << "\n";
336  for (auto &BB : F) {
337  if (!BBExecutable.count(&BB))
338  OS << "INFEASIBLE: ";
339  OS << "\t";
340  if (BB.hasName())
341  OS << BB.getName() << ":\n";
342  else
343  OS << "; anon bb\n";
344  for (auto &I : BB) {
345  LatticeFunc->PrintValue(getLatticeState(&I), OS);
346  OS << I << "\n";
347  }
348 
349  OS << "\n";
350  }
351 }
uint64_t CallInst * C
LatticeVal getOrInitValueState(Value *V)
getOrInitValueState - Return the LatticeVal object that corresponds to the value, initializing the va...
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
void Solve(Function &F)
Solve - Solve for constants and executable blocks.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To, bool AggressiveUndef=false)
isEdgeFeasible - Return true if the control flow edge from the &#39;From&#39; basic block to the &#39;To&#39; basic b...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
Value * getCondition() const
F(f)
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
void assign(size_type NumElts, const T &Elt)
Definition: SmallVector.h:427
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:86
const BasicBlock & getEntryBlock() const
Definition: Function.h:572
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & back() const
Definition: BasicBlock.h:266
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Iterator for intrusive lists based on ilist_node.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
unsigned getNumIncomingValues() const
Return the number of incoming edges.
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
virtual void PrintValue(LatticeVal V, raw_ostream &OS)
PrintValue - Render the specified lattice value to the specified stream.
iterator_range< user_iterator > users()
Definition: Value.h:395
unsigned getSuccessorIndex() const
Returns TerminatorInst&#39;s successor index for current case successor.
void Print(Function &F, raw_ostream &OS) const
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
#define I(x, y, z)
Definition: MD5.cpp:58
Multiway switch.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
LLVM Value Representation.
Definition: Value.h:73
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:118
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
const BasicBlock * getParent() const
Definition: Instruction.h:66
void resize(size_type N)
Definition: SmallVector.h:355