MLIR 22.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
10#include <cassert>
12
13#include <llvm/Support/DebugLog.h>
17#include <mlir/IR/Operation.h>
18#include <mlir/IR/Value.h>
21#include <mlir/Support/LLVM.h>
22
23#define DEBUG_TYPE "liveness-analysis"
24
25using namespace mlir;
26using namespace mlir::dataflow;
27
28//===----------------------------------------------------------------------===//
29// Liveness
30//===----------------------------------------------------------------------===//
31
33 os << (isLive ? "live" : "not live");
34}
35
37 bool wasLive = isLive;
38 isLive = true;
40}
41
43 const auto *otherLiveness = reinterpret_cast<const Liveness *>(&other);
44 return otherLiveness->isLive ? markLive() : ChangeResult::NoChange;
45}
46
47//===----------------------------------------------------------------------===//
48// LivenessAnalysis
49//===----------------------------------------------------------------------===//
50
51/// For every value, liveness analysis determines whether or not it is "live".
52///
53/// A value is considered "live" iff it:
54/// (1) has memory effects OR
55/// (2) is returned by a public function OR
56/// (3) is used to compute a value of type (1) or (2) OR
57/// (4) is returned by a return-like op whose parent isn't a callable
58/// nor a RegionBranchOpInterface (e.g.: linalg.yield, gpu.yield,...)
59/// These ops have their own semantics, so we conservatively mark the
60/// the yield value as live.
61/// It is also to be noted that a value could be of multiple types (1/2/3) at
62/// the same time.
63///
64/// A value "has memory effects" iff it:
65/// (1.a) is an operand of an op with memory effects OR
66/// (1.b) is a non-forwarded branch operand and its branch op could take the
67/// control to a block that has an op with memory effects OR
68/// (1.c) is a non-forwarded branch operand and its branch op could result
69/// in different live result OR
70/// (1.d) is a non-forwarded call operand.
71///
72/// A value `A` is said to be "used to compute" value `B` iff `B` cannot be
73/// computed in the absence of `A`. Thus, in this implementation, we say that
74/// value `A` is used to compute value `B` iff:
75/// (3.a) `B` is a result of an op with operand `A` OR
76/// (3.b) `A` is used to compute some value `C` and `C` is used to compute
77/// `B`.
78
79LogicalResult
82 LDBG() << "[visitOperation] Enter: "
83 << OpWithFlags(op, OpPrintingFlags().skipRegions());
84 // This marks values of type (1.a) and (4) liveness as "live".
86 LDBG() << "[visitOperation] Operation has memory effects or is "
87 "return-like, marking operands live";
88 for (auto *operand : operands) {
89 LDBG() << " [visitOperation] Marking operand live: " << operand << " ("
90 << operand->isLive << ")";
91 propagateIfChanged(operand, operand->markLive());
92 }
93 }
94
95 // This marks values of type (3) liveness as "live".
96 bool foundLiveResult = false;
97 for (const Liveness *r : results) {
98 if (r->isLive && !foundLiveResult) {
99 LDBG() << "[visitOperation] Found live result, "
100 "meeting all operands with result: "
101 << r;
102 // It is assumed that each operand is used to compute each result of an
103 // op. Thus, if at least one result is live, each operand is live.
104 for (Liveness *operand : operands) {
105 LDBG() << " [visitOperation] Meeting operand: " << operand
106 << " with result: " << r;
107 meet(operand, *r);
108 }
109 foundLiveResult = true;
110 }
111 LDBG() << "[visitOperation] Adding dependency for result: " << r
112 << " after op: " << OpWithFlags(op, OpPrintingFlags().skipRegions());
113 addDependency(const_cast<Liveness *>(r), getProgramPointAfter(op));
114 }
115 return success();
116}
117
119 Operation *op = operand.getOwner();
120 LDBG() << "Visiting branch operand: " << operand.get()
121 << " in op: " << OpWithFlags(op, OpPrintingFlags().skipRegions());
122 // We know (at the moment) and assume (for the future) that `operand` is a
123 // non-forwarded branch operand of a `RegionBranchOpInterface`,
124 // `BranchOpInterface`, `RegionBranchTerminatorOpInterface` or return-like op.
125 assert((isa<RegionBranchOpInterface>(op) || isa<BranchOpInterface>(op) ||
126 isa<RegionBranchTerminatorOpInterface>(op)) &&
127 "expected the op to be `RegionBranchOpInterface`, "
128 "`BranchOpInterface` or `RegionBranchTerminatorOpInterface`");
129
130 // The lattices of the non-forwarded branch operands don't get updated like
131 // the forwarded branch operands or the non-branch operands. Thus they need
132 // to be handled separately. This is where we handle them.
133
134 // This marks values of type (1.b/1.c) liveness as "live". A non-forwarded
135 // branch operand will be live if a block where its op could take the control
136 // has an op with memory effects or could result in different results.
137 // Populating such blocks in `blocks`.
138 bool mayLive = false;
140 if (auto regionBranchOp = dyn_cast<RegionBranchOpInterface>(op)) {
141 if (op->getNumResults() != 0) {
142 // This mark value of type 1.c liveness as may live, because the region
143 // branch operation has a return value, and the non-forwarded operand can
144 // determine the region to jump to, it can thereby control the result of
145 // the region branch operation.
146 // Therefore, if the result value is live, we conservatively consider the
147 // non-forwarded operand of the region branch operation with result may
148 // live and record all result.
149 for (auto [resultIndex, result] : llvm::enumerate(op->getResults())) {
150 if (getLatticeElement(result)->isLive) {
151 mayLive = true;
152 LDBG() << "[visitBranchOperand] Non-forwarded branch operand may be "
153 "live due to live result #"
154 << resultIndex << ": "
155 << OpWithFlags(op, OpPrintingFlags().skipRegions());
156 break;
157 }
158 }
159 } else {
160 // When the op is a `RegionBranchOpInterface`, like an `scf.for` or an
161 // `scf.index_switch` op, its branch operand controls the flow into this
162 // op's regions.
163 for (Region &region : op->getRegions()) {
164 for (Block &block : region)
165 blocks.push_back(&block);
166 }
167 }
168 } else if (isa<BranchOpInterface>(op)) {
169 // We cannot track all successor blocks of the branch operation(More
170 // specifically, it's the successor's successor). Additionally, different
171 // blocks might also lead to the different block argument described in 1.c.
172 // Therefore, we conservatively consider the non-forwarded operand of the
173 // branch operation may live.
174 mayLive = true;
175 LDBG() << "[visitBranchOperand] Non-forwarded branch operand may "
176 "be live due to branch op interface";
177 } else {
178 Operation *parentOp = op->getParentOp();
179 assert(isa<RegionBranchOpInterface>(parentOp) &&
180 "expected parent op to implement `RegionBranchOpInterface`");
181 if (parentOp->getNumResults() != 0) {
182 // This mark value of type 1.c liveness as may live, because the region
183 // branch operation has a return value, and the non-forwarded operand can
184 // determine the region to jump to, it can thereby control the result of
185 // the region branch operation.
186 // Therefore, if the result value is live, we conservatively consider the
187 // non-forwarded operand of the region branch operation with result may
188 // live and record all result.
189 for (Value result : parentOp->getResults()) {
190 if (getLatticeElement(result)->isLive) {
191 mayLive = true;
192 LDBG() << "[visitBranchOperand] Non-forwarded branch "
193 "operand may be live due to parent live result: "
194 << result;
195 break;
196 }
197 }
198 } else {
199 // When the op is a `RegionBranchTerminatorOpInterface`, like an
200 // `scf.condition` op or return-like, like an `scf.yield` op, its branch
201 // operand controls the flow into this op's parent's (which is a
202 // `RegionBranchOpInterface`'s) regions.
203 for (Region &region : parentOp->getRegions()) {
204 for (Block &block : region)
205 blocks.push_back(&block);
206 }
207 }
208 }
209 for (Block *block : blocks) {
210 if (mayLive)
211 break;
212 for (Operation &nestedOp : *block) {
213 if (!isMemoryEffectFree(&nestedOp)) {
214 mayLive = true;
215 LDBG() << "Non-forwarded branch operand may be "
216 "live due to memory effect in block: "
217 << block;
218 break;
219 }
220 }
221 }
222
223 if (mayLive) {
224 Liveness *operandLiveness = getLatticeElement(operand.get());
225 LDBG() << "Marking branch operand live: " << operand.get();
226 propagateIfChanged(operandLiveness, operandLiveness->markLive());
227 }
228
229 // Now that we have checked for memory-effecting ops in the blocks of concern,
230 // we will simply visit the op with this non-forwarded operand to potentially
231 // mark it "live" due to type (1.a/3) liveness.
232 SmallVector<Liveness *, 4> operandLiveness;
233 operandLiveness.push_back(getLatticeElement(operand.get()));
234 SmallVector<const Liveness *, 4> resultsLiveness;
235 for (const Value result : op->getResults())
236 resultsLiveness.push_back(getLatticeElement(result));
237 LDBG() << "Visiting operation for non-forwarded branch operand: "
238 << OpWithFlags(op, OpPrintingFlags().skipRegions());
239 (void)visitOperation(op, operandLiveness, resultsLiveness);
240
241 // We also visit the parent op with the parent's results and this operand if
242 // `op` is a `RegionBranchTerminatorOpInterface` because its non-forwarded
243 // operand depends on not only its memory effects/results but also on those of
244 // its parent's.
245 if (!isa<RegionBranchTerminatorOpInterface>(op))
246 return;
247 Operation *parentOp = op->getParentOp();
248 SmallVector<const Liveness *, 4> parentResultsLiveness;
249 for (const Value parentResult : parentOp->getResults())
250 parentResultsLiveness.push_back(getLatticeElement(parentResult));
251 LDBG() << "Visiting parent operation for non-forwarded branch operand: "
252 << *parentOp;
253 (void)visitOperation(parentOp, operandLiveness, parentResultsLiveness);
254}
255
257 LDBG() << "Visiting call operand: " << operand.get()
258 << " in op: " << *operand.getOwner();
259 // We know (at the moment) and assume (for the future) that `operand` is a
260 // non-forwarded call operand of an op implementing `CallOpInterface`.
261 assert(isa<CallOpInterface>(operand.getOwner()) &&
262 "expected the op to implement `CallOpInterface`");
263
264 // The lattices of the non-forwarded call operands don't get updated like the
265 // forwarded call operands or the non-call operands. Thus they need to be
266 // handled separately. This is where we handle them.
267
268 // This marks values of type (1.c) liveness as "live". A non-forwarded
269 // call operand is live.
270 Liveness *operandLiveness = getLatticeElement(operand.get());
271 LDBG() << "Marking call operand live: " << operand.get();
272 propagateIfChanged(operandLiveness, operandLiveness->markLive());
273}
274
276 RegionSuccessor &successor, ArrayRef<BlockArgument> arguments) {
277 Operation *parentOp = successor.getSuccessor()->getParentOp();
278 LDBG() << "visitNonControlFlowArguments visit the region # "
279 << successor.getSuccessor()->getRegionNumber() << "of "
280 << OpWithFlags(parentOp, OpPrintingFlags().skipRegions());
281 auto valuesToLattices = [&](Value value) { return getLatticeElement(value); };
282 SmallVector<Liveness *> argumentLattices =
283 llvm::map_to_vector(arguments, valuesToLattices);
284 SmallVector<Liveness *> parentResultLattices =
285 llvm::map_to_vector(parentOp->getResults(), valuesToLattices);
286
287 for (Liveness *resultLattice : parentResultLattices) {
288 if (resultLattice->isLive) {
289 for (Liveness *argumentLattice : argumentLattices) {
290 LDBG() << "make lattice: " << argumentLattice << " live";
291 propagateIfChanged(argumentLattice, argumentLattice->markLive());
292 }
293 return;
294 }
295 }
296 (void)visitOperation(parentOp, argumentLattices, parentResultLattices);
297}
298
300 LDBG() << "setToExitState for lattice: " << lattice;
301 if (lattice->isLive) {
302 LDBG() << "Lattice already live, nothing to do";
303 return;
304 }
305 // This marks values of type (2) liveness as "live".
306 LDBG() << "Marking lattice live due to exit state";
307 (void)lattice->markLive();
309}
310
311//===----------------------------------------------------------------------===//
312// RunLivenessAnalysis
313//===----------------------------------------------------------------------===//
314
316 LDBG() << "Constructing RunLivenessAnalysis for op: " << op->getName();
317 SymbolTableCollection symbolTable;
318
319 loadBaselineAnalyses(solver);
320 solver.load<LivenessAnalysis>(symbolTable);
321 LDBG() << "Initializing and running solver";
322 (void)solver.initializeAndRun(op);
323 LDBG() << "RunLivenessAnalysis initialized for op: " << op->getName()
324 << " check on unreachable code now:";
325 // The framework doesn't visit operations in dead blocks, so we need to
326 // explicitly mark them as dead.
327 op->walk([&](Operation *op) {
328 for (auto result : llvm::enumerate(op->getResults())) {
329 if (getLiveness(result.value()))
330 continue;
331 LDBG() << "Result: " << result.index() << " of "
332 << OpWithFlags(op, OpPrintingFlags().skipRegions())
333 << " has no liveness info (unreachable), mark dead";
334 solver.getOrCreateState<Liveness>(result.value());
335 }
336 for (auto &region : op->getRegions()) {
337 for (auto &block : region) {
338 for (auto blockArg : llvm::enumerate(block.getArguments())) {
339 if (getLiveness(blockArg.value()))
340 continue;
341 LDBG() << "Block argument: " << blockArg.index() << " of "
342 << OpWithFlags(op, OpPrintingFlags().skipRegions())
343 << " has no liveness info, mark dead";
344 solver.getOrCreateState<Liveness>(blockArg.value());
345 }
346 }
347 }
348 });
349}
350
352 return solver.lookupState<Liveness>(val);
353}
return success()
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)
IRValueT get() const
Return the current value being used by this operand.
This class represents an operand of an operation.
Definition Value.h:257
Set of flags used to control the behavior of the various IR print methods (e.g.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1111
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:749
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:234
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:119
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:677
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:797
result_range getResults()
Definition Operation.h:415
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:404
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
unsigned getRegionNumber()
Return the number of this region in the parent operation.
Definition Region.cpp:62
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:200
This class represents a collection of SymbolTables.
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.
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
void visitNonControlFlowArguments(RegionSuccessor &successor, ArrayRef< BlockArgument > arguments) 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".
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
void loadBaselineAnalyses(DataFlowSolver &solver)
Populates a DataFlowSolver with analyses that are required to ensure user-defined analyses are run pr...
Definition Utils.h:29
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 trait indicates that a terminator operation is "return-like".
This lattice represents, for a given value, whether or not it is "live".
void print(raw_ostream &os) const override
AbstractSparseLattice(Value value)
Lattices can only be created for values.
ChangeResult meet(const AbstractSparseLattice &other) override
Meet (intersect) the information in this lattice with 'rhs'.
const Liveness * getLiveness(Value val)