MLIR  21.0.0git
LivenessAnalysis.cpp
Go to the documentation of this file.
1 //===- LivenessAnalysis.cpp - Liveness analysis ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/IR/SymbolTable.h"
10 #include <cassert>
12 
17 #include <mlir/IR/Operation.h>
18 #include <mlir/IR/Value.h>
21 #include <mlir/Support/LLVM.h>
22 
23 using namespace mlir;
24 using namespace mlir::dataflow;
25 
26 //===----------------------------------------------------------------------===//
27 // Liveness
28 //===----------------------------------------------------------------------===//
29 
30 void Liveness::print(raw_ostream &os) const {
31  os << (isLive ? "live" : "not live");
32 }
33 
35  bool wasLive = isLive;
36  isLive = true;
38 }
39 
41  const auto *otherLiveness = reinterpret_cast<const Liveness *>(&other);
42  return otherLiveness->isLive ? markLive() : ChangeResult::NoChange;
43 }
44 
45 //===----------------------------------------------------------------------===//
46 // LivenessAnalysis
47 //===----------------------------------------------------------------------===//
48 
49 /// For every value, liveness analysis determines whether or not it is "live".
50 ///
51 /// A value is considered "live" iff it:
52 /// (1) has memory effects OR
53 /// (2) is returned by a public function OR
54 /// (3) is used to compute a value of type (1) or (2).
55 /// It is also to be noted that a value could be of multiple types (1/2/3) at
56 /// the same time.
57 ///
58 /// A value "has memory effects" iff it:
59 /// (1.a) is an operand of an op with memory effects OR
60 /// (1.b) is a non-forwarded branch operand and its branch op could take the
61 /// control to a block that has an op with memory effects OR
62 /// (1.c) is a non-forwarded branch operand and its branch op could result
63 /// in different live result OR
64 /// (1.d) is a non-forwarded call operand.
65 ///
66 /// A value `A` is said to be "used to compute" value `B` iff `B` cannot be
67 /// computed in the absence of `A`. Thus, in this implementation, we say that
68 /// value `A` is used to compute value `B` iff:
69 /// (3.a) `B` is a result of an op with operand `A` OR
70 /// (3.b) `A` is used to compute some value `C` and `C` is used to compute
71 /// `B`.
72 
73 LogicalResult
76  // This marks values of type (1.a) liveness as "live".
77  if (!isMemoryEffectFree(op)) {
78  for (auto *operand : operands)
79  propagateIfChanged(operand, operand->markLive());
80  }
81 
82  // This marks values of type (3) liveness as "live".
83  bool foundLiveResult = false;
84  for (const Liveness *r : results) {
85  if (r->isLive && !foundLiveResult) {
86  // It is assumed that each operand is used to compute each result of an
87  // op. Thus, if at least one result is live, each operand is live.
88  for (Liveness *operand : operands)
89  meet(operand, *r);
90  foundLiveResult = true;
91  }
92  addDependency(const_cast<Liveness *>(r), getProgramPointAfter(op));
93  }
94  return success();
95 }
96 
98  // We know (at the moment) and assume (for the future) that `operand` is a
99  // non-forwarded branch operand of a `RegionBranchOpInterface`,
100  // `BranchOpInterface`, `RegionBranchTerminatorOpInterface` or return-like op.
101  Operation *op = operand.getOwner();
102  assert((isa<RegionBranchOpInterface>(op) || isa<BranchOpInterface>(op) ||
103  isa<RegionBranchTerminatorOpInterface>(op)) &&
104  "expected the op to be `RegionBranchOpInterface`, "
105  "`BranchOpInterface` or `RegionBranchTerminatorOpInterface`");
106 
107  // The lattices of the non-forwarded branch operands don't get updated like
108  // the forwarded branch operands or the non-branch operands. Thus they need
109  // to be handled separately. This is where we handle them.
110 
111  // This marks values of type (1.b/1.c) liveness as "live". A non-forwarded
112  // branch operand will be live if a block where its op could take the control
113  // has an op with memory effects or could result in different results.
114  // Populating such blocks in `blocks`.
115  bool mayLive = false;
117  if (isa<RegionBranchOpInterface>(op)) {
118  if (op->getNumResults() != 0) {
119  // This mark value of type 1.c liveness as may live, because the region
120  // branch operation has a return value, and the non-forwarded operand can
121  // determine the region to jump to, it can thereby control the result of
122  // the region branch operation.
123  // Therefore, if the result value is live, we conservatively consider the
124  // non-forwarded operand of the region branch operation with result may
125  // live and record all result.
126  for (Value result : op->getResults()) {
127  if (getLatticeElement(result)->isLive) {
128  mayLive = true;
129  break;
130  }
131  }
132  } else {
133  // When the op is a `RegionBranchOpInterface`, like an `scf.for` or an
134  // `scf.index_switch` op, its branch operand controls the flow into this
135  // op's regions.
136  for (Region &region : op->getRegions()) {
137  for (Block &block : region)
138  blocks.push_back(&block);
139  }
140  }
141  } else if (isa<BranchOpInterface>(op)) {
142  // We cannot track all successor blocks of the branch operation(More
143  // specifically, it's the successor's successor). Additionally, different
144  // blocks might also lead to the different block argument described in 1.c.
145  // Therefore, we conservatively consider the non-forwarded operand of the
146  // branch operation may live.
147  mayLive = true;
148  } else {
149  Operation *parentOp = op->getParentOp();
150  assert(isa<RegionBranchOpInterface>(parentOp) &&
151  "expected parent op to implement `RegionBranchOpInterface`");
152  if (parentOp->getNumResults() != 0) {
153  // This mark value of type 1.c liveness as may live, because the region
154  // branch operation has a return value, and the non-forwarded operand can
155  // determine the region to jump to, it can thereby control the result of
156  // the region branch operation.
157  // Therefore, if the result value is live, we conservatively consider the
158  // non-forwarded operand of the region branch operation with result may
159  // live and record all result.
160  for (Value result : parentOp->getResults()) {
161  if (getLatticeElement(result)->isLive) {
162  mayLive = true;
163  break;
164  }
165  }
166  } else {
167  // When the op is a `RegionBranchTerminatorOpInterface`, like an
168  // `scf.condition` op or return-like, like an `scf.yield` op, its branch
169  // operand controls the flow into this op's parent's (which is a
170  // `RegionBranchOpInterface`'s) regions.
171  for (Region &region : parentOp->getRegions()) {
172  for (Block &block : region)
173  blocks.push_back(&block);
174  }
175  }
176  }
177  for (Block *block : blocks) {
178  if (mayLive)
179  break;
180  for (Operation &nestedOp : *block) {
181  if (!isMemoryEffectFree(&nestedOp)) {
182  mayLive = true;
183  break;
184  }
185  }
186  }
187 
188  if (mayLive) {
189  Liveness *operandLiveness = getLatticeElement(operand.get());
190  propagateIfChanged(operandLiveness, operandLiveness->markLive());
191  }
192 
193  // Now that we have checked for memory-effecting ops in the blocks of concern,
194  // we will simply visit the op with this non-forwarded operand to potentially
195  // mark it "live" due to type (1.a/3) liveness.
196  SmallVector<Liveness *, 4> operandLiveness;
197  operandLiveness.push_back(getLatticeElement(operand.get()));
198  SmallVector<const Liveness *, 4> resultsLiveness;
199  for (const Value result : op->getResults())
200  resultsLiveness.push_back(getLatticeElement(result));
201  (void)visitOperation(op, operandLiveness, resultsLiveness);
202 
203  // We also visit the parent op with the parent's results and this operand if
204  // `op` is a `RegionBranchTerminatorOpInterface` because its non-forwarded
205  // operand depends on not only its memory effects/results but also on those of
206  // its parent's.
207  if (!isa<RegionBranchTerminatorOpInterface>(op))
208  return;
209  Operation *parentOp = op->getParentOp();
210  SmallVector<const Liveness *, 4> parentResultsLiveness;
211  for (const Value parentResult : parentOp->getResults())
212  parentResultsLiveness.push_back(getLatticeElement(parentResult));
213  (void)visitOperation(parentOp, operandLiveness, parentResultsLiveness);
214 }
215 
217  // We know (at the moment) and assume (for the future) that `operand` is a
218  // non-forwarded call operand of an op implementing `CallOpInterface`.
219  assert(isa<CallOpInterface>(operand.getOwner()) &&
220  "expected the op to implement `CallOpInterface`");
221 
222  // The lattices of the non-forwarded call operands don't get updated like the
223  // forwarded call operands or the non-call operands. Thus they need to be
224  // handled separately. This is where we handle them.
225 
226  // This marks values of type (1.c) liveness as "live". A non-forwarded
227  // call operand is live.
228  Liveness *operandLiveness = getLatticeElement(operand.get());
229  propagateIfChanged(operandLiveness, operandLiveness->markLive());
230 }
231 
233  if (lattice->isLive) {
234  return;
235  }
236  // This marks values of type (2) liveness as "live".
237  (void)lattice->markLive();
239 }
240 
241 //===----------------------------------------------------------------------===//
242 // RunLivenessAnalysis
243 //===----------------------------------------------------------------------===//
244 
246  SymbolTableCollection symbolTable;
247 
248  solver.load<DeadCodeAnalysis>();
250  solver.load<LivenessAnalysis>(symbolTable);
251  (void)solver.initializeAndRun(op);
252 }
253 
255  return solver.lookupState<Liveness>(val);
256 }
Block represents an ordered list of Operations.
Definition: Block.h:33
void addDependency(AnalysisState *state, ProgramPoint *point)
Create a dependency between the given analysis state and lattice anchor on this analysis.
void propagateIfChanged(AnalysisState *state, ChangeResult changed)
Propagate an update to a state if it changed.
ProgramPoint * getProgramPointAfter(Operation *op)
const StateT * lookupState(AnchorT anchor) const
Lookup an analysis state for the given lattice anchor.
AnalysisT * load(Args &&...args)
Load an analysis into the solver. Return the analysis instance.
LogicalResult initializeAndRun(Operation *top)
Initialize the children analyses starting from the provided top-level operation and run the analysis ...
IRValueT get() const
Return the current value being used by this operand.
Definition: UseDefLists.h:160
This class represents an operand of an operation.
Definition: Value.h:243
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition: Operation.h:677
result_range getResults()
Definition: Operation.h:415
unsigned getNumResults()
Return the number of results held by this operation.
Definition: Operation.h:404
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
This class represents a collection of SymbolTables.
Definition: SymbolTable.h:283
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
void meet(AbstractSparseLattice *lhs, const AbstractSparseLattice &rhs)
Join the lattice element and propagate and update if it changed.
This class represents an abstract lattice.
Dead code analysis analyzes control-flow, as understood by RegionBranchOpInterface and BranchOpInterf...
An analysis that, by going backwards along the dataflow graph, annotates each value with a boolean st...
void setToExitState(Liveness *lattice) override
Set the given lattice element(s) at control flow exit point(s).
void visitBranchOperand(OpOperand &operand) override
void visitCallOperand(OpOperand &operand) override
LogicalResult visitOperation(Operation *op, ArrayRef< Liveness * > operands, ArrayRef< const Liveness * > results) override
For every value, liveness analysis determines whether or not it is "live".
Liveness * getLatticeElement(Value value) override
Get the lattice element for a value.
This analysis implements sparse constant propagation, which attempts to determine constant-valued res...
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
Include the generated interface declarations.
ChangeResult
A result type used to indicate if a change happened.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
This lattice represents, for a given value, whether or not it is "live".
void print(raw_ostream &os) const override
Print the contents of the analysis state.
ChangeResult meet(const AbstractSparseLattice &other) override
Meet (intersect) the information in this lattice with 'rhs'.
const Liveness * getLiveness(Value val)