21#include "llvm/ADT/STLExtras.h"
22#include "llvm/Support/DebugLog.h"
29#define DEBUG_TYPE "dataflow"
61 for (
Value argument : region.front().getArguments())
65 return initializeRecursively(top);
69AbstractSparseForwardDataFlowAnalysis::initializeRecursively(
Operation *op) {
70 LDBG() <<
"Initializing recursively for operation: "
75 if (failed(visitOperation(op))) {
76 LDBG() <<
"Failed to visit operation: "
82 LDBG() <<
"Processing region with " << region.getBlocks().size()
84 for (
Block &block : region) {
85 LDBG() <<
"Processing block with " << block.getNumArguments()
88 ->blockContentSubscribe(
this);
91 LDBG() <<
"Recursively initializing nested operation: "
93 if (failed(initializeRecursively(&op))) {
94 LDBG() <<
"Failed to initialize nested operation: "
102 LDBG() <<
"Successfully completed recursive initialization for operation: "
103 << OpWithFlags(op, OpPrintingFlags().skipRegions());
110 return visitOperation(point->
getPrevOp());
116AbstractSparseForwardDataFlowAnalysis::visitOperation(
Operation *op) {
131 resultLattices.push_back(resultLattice);
135 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op)) {
148 operandLattices.push_back(operandLattice);
151 if (
auto call = dyn_cast<CallOpInterface>(op))
158void AbstractSparseForwardDataFlowAnalysis::visitBlock(
Block *block) {
168 SmallVector<AbstractSparseLattice *> argLattices;
172 argLattices.push_back(argLattice);
179 auto callable = dyn_cast<CallableOpInterface>(block->
getParentOp());
180 if (callable && callable.getCallableRegion() == block->
getParent())
184 if (
auto branch = dyn_cast<RegionBranchOpInterface>(block->
getParentOp())) {
198 Block *predecessor = *it;
202 auto *edgeExecutable =
204 edgeExecutable->blockContentSubscribe(
this);
205 if (!edgeExecutable->isLive())
211 SuccessorOperands operands =
212 branch.getSuccessorOperands(it.getSuccessorIndex());
213 for (
auto [idx, lattice] : llvm::enumerate(argLattices)) {
214 if (Value operand = operands[idx]) {
230 CallOpInterface call,
235 auto isExternalCallable = [&]() {
237 dyn_cast_if_present<CallableOpInterface>(call.resolveCallable());
238 return callable && !callable.getCallableRegion();
251 if (!predecessors->allPredecessorsKnown()) {
259 ResultRange forwardedResults = call.getForwardedResults();
260 unsigned firstForwarded = forwardedResults.empty()
261 ? resultLattices.size()
262 : forwardedResults[0].getResultNumber();
265 resultLattices.drop_front(firstForwarded + forwardedResults.size()));
267 resultLattices.slice(firstForwarded, forwardedResults.size());
269 for (
Operation *predecessor : predecessors->getKnownPredecessors())
270 for (
auto &&[operand, resLattice] :
271 llvm::zip_equal(predecessor->getOperands(), forwardedResultLattices))
278 CallableOpInterface callable,
280 Block *entryBlock = &callable.getCallableRegion()->
front();
285 if (!callsites->allPredecessorsKnown() ||
289 for (
Operation *callsite : callsites->getKnownPredecessors()) {
290 auto call = cast<CallOpInterface>(callsite);
291 for (
auto it : llvm::zip(call.getArgOperands(), argLattices))
292 join(std::get<1>(it),
298void AbstractSparseForwardDataFlowAnalysis::visitRegionSuccessors(
302 assert(predecessors->allPredecessorsKnown() &&
303 "unexpected unresolved region successors");
305 for (
Operation *op : predecessors->getKnownPredecessors()) {
307 std::optional<OperandRange> operands;
311 operands = branch.getEntrySuccessorOperands(successor);
313 }
else if (
auto regionTerminator =
314 dyn_cast<RegionBranchTerminatorOpInterface>(op)) {
315 operands = regionTerminator.getSuccessorOperands(successor);
323 ValueRange inputs = predecessors->getSuccessorInputs(op);
324 assert(inputs.size() == operands->size() &&
325 "expected the same number of successor inputs as operands");
328 unsigned firstIndex = 0;
329 if (inputs.size() != lattices.size()) {
332 firstIndex = cast<OpResult>(inputs.front()).getResultNumber();
333 SmallVector<Value> nonSuccessorInputs =
334 branch.getNonSuccessorInputs(successor);
335 SmallVector<AbstractSparseLattice *> nonSuccessorInputLattices =
336 llvm::map_to_vector(nonSuccessorInputs, valueToLattices);
338 nonSuccessorInputLattices);
341 firstIndex = cast<BlockArgument>(inputs.front()).getArgNumber();
343 SmallVector<Value> nonSuccessorInputs =
344 branch.getNonSuccessorInputs(RegionSuccessor(region));
345 SmallVector<AbstractSparseLattice *> nonSuccessorInputLattices =
346 llvm::map_to_vector(nonSuccessorInputs, valueToLattices);
349 nonSuccessorInputLattices);
353 for (
auto [lattice, operand] :
354 llvm::zip(lattices.drop_front(firstIndex), *operands))
390 return initializeRecursively(top);
394AbstractSparseBackwardDataFlowAnalysis::initializeRecursively(
Operation *op) {
395 if (failed(visitOperation(op)))
399 for (
Block &block : region) {
401 ->blockContentSubscribe(
this);
405 for (
auto it = block.
rbegin(); it != block.
rend(); it++)
406 if (failed(initializeRecursively(&*it)))
421 return visitOperation(point->
getPrevOp());
427 resultLattices.reserve(values.size());
430 resultLattices.push_back(resultLattice);
432 return resultLattices;
436AbstractSparseBackwardDataFlowAnalysis::getLatticeElementsFor(
439 resultLattices.reserve(values.size());
442 getLatticeElementFor(point,
result);
443 resultLattices.push_back(resultLattice);
445 return resultLattices;
453AbstractSparseBackwardDataFlowAnalysis::visitOperation(Operation *op) {
454 LDBG() <<
"Visiting operation: "
455 << OpWithFlags(op, OpPrintingFlags().skipRegions()) <<
" with "
463 LDBG() <<
"Operation is in dead block, bailing out";
467 LDBG() <<
"Creating lattice elements for " << op->
getNumOperands()
469 SmallVector<AbstractSparseLattice *> operandLattices =
471 SmallVector<const AbstractSparseLattice *> resultLattices =
476 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op)) {
477 LDBG() <<
"Processing RegionBranchOpInterface operation";
478 visitRegionSuccessors(branch, operandLattices);
482 if (
auto branch = dyn_cast<BranchOpInterface>(op)) {
483 LDBG() <<
"Processing BranchOpInterface operation with "
493 for (
auto [index, block] : llvm::enumerate(op->
getSuccessors())) {
494 SuccessorOperands successorOperands = branch.getSuccessorOperands(index);
496 if (!forwarded.empty()) {
497 MutableArrayRef<OpOperand> operands = op->
getOpOperands().slice(
499 for (OpOperand &operand : operands) {
500 unaccounted.reset(operand.getOperandNumber());
501 if (std::optional<BlockArgument> blockArg =
503 successorOperands, operand.getOperandNumber(), block)) {
512 for (
int index : unaccounted.set_bits()) {
521 if (
auto call = dyn_cast<CallOpInterface>(op)) {
522 LDBG() <<
"Processing CallOpInterface operation";
523 Operation *callableOp = call.resolveCallableInTable(&symbolTable);
524 if (
auto callable = dyn_cast_or_null<CallableOpInterface>(callableOp)) {
532 OperandRange argOperands = call.getArgOperands();
533 MutableArrayRef<OpOperand> argOpOperands =
535 Region *region = callable.getCallableRegion();
536 if (!region || region->
empty() ||
545 for (
auto [blockArg, argOpOperand] :
549 unaccounted.reset(argOpOperand.getOperandNumber());
554 for (
int index : unaccounted.set_bits()) {
572 if (
auto terminator = dyn_cast<RegionBranchTerminatorOpInterface>(op)) {
573 LDBG() <<
"Processing RegionBranchTerminatorOpInterface operation";
574 if (
auto branch = dyn_cast<RegionBranchOpInterface>(op->
getParentOp())) {
575 visitRegionSuccessorsFromTerminator(terminator, branch);
580 if (op->
hasTrait<OpTrait::ReturnLike>()) {
581 LDBG() <<
"Processing ReturnLike operation";
584 if (
auto callable = dyn_cast<CallableOpInterface>(op->
getParentOp())) {
585 LDBG() <<
"Callable parent found, visiting callable operation";
590 LDBG() <<
"Using default visitOperationImpl for operation: "
591 << OpWithFlags(op, OpPrintingFlags().skipRegions());
596 Operation *op, CallableOpInterface callable,
605 cast<CallOpInterface>(call).getForwardedResults();
608 for (
auto [op,
result] : llvm::zip(operandLattices, callResultLattices))
620void AbstractSparseBackwardDataFlowAnalysis::visitRegionSuccessors(
621 RegionBranchOpInterface branch,
625 BitVector unaccounted(branch->getNumOperands(),
true);
628 for (
const auto &[operand, inputs] : mapping) {
629 for (
Value input : inputs) {
632 unaccounted.reset(operand->getOperandNumber());
638 branch.getEntrySuccessorRegions(operands, successors);
642 auto valueToArgument = [](
Value value) {
643 return cast<BlockArgument>(value);
645 SmallVector<BlockArgument> noControlFlowArguments = llvm::map_to_vector(
646 branch.getNonSuccessorInputs(successor), valueToArgument);
652 for (
int index : unaccounted.set_bits()) {
657void AbstractSparseBackwardDataFlowAnalysis::
658 visitRegionSuccessorsFromTerminator(
659 RegionBranchTerminatorOpInterface terminator,
660 RegionBranchOpInterface branch) {
661 assert(terminator->getParentOp() == branch.getOperation() &&
662 "expected `branch` to be the parent op of `terminator`");
666 BitVector unaccounted(terminator->getNumOperands(),
true);
669 branch.getSuccessorOperandInputMapping(mapping,
670 RegionBranchPoint(terminator));
671 for (
const auto &[operand, inputs] : mapping) {
672 for (Value input : inputs) {
675 unaccounted.reset(operand->getOperandNumber());
681 for (
int index : unaccounted.set_bits()) {
687AbstractSparseBackwardDataFlowAnalysis::getLatticeElementFor(
688 ProgramPoint *point, Value value) {
static MutableArrayRef< OpOperand > operandsToOpOperands(OperandRange &operands)
virtual void onUpdate(DataFlowSolver *solver) const
This function is called by the solver when the analysis state is updated to enqueue more work items.
LatticeAnchor anchor
The lattice anchor to which the state belongs.
friend class DataFlowSolver
Allow the framework to access the dependents.
Block represents an ordered list of Operations.
unsigned getNumArguments()
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
pred_iterator pred_begin()
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgListType getArguments()
PredecessorIterator pred_iterator
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
reverse_iterator rbegin()
Base class for all data-flow analyses.
void addDependency(AnalysisState *state, ProgramPoint *point)
Create a dependency between the given analysis state and lattice anchor on this analysis.
ProgramPoint * getProgramPointBefore(Operation *op)
Get a uniqued program point instance.
void propagateIfChanged(AnalysisState *state, ChangeResult changed)
Propagate an update to a state if it changed.
const DataFlowConfig & getSolverConfig() const
Return the configuration of the solver used for this analysis.
StateT * getOrCreate(AnchorT anchor)
Get the analysis state associated with the lattice anchor.
ProgramPoint * getProgramPointAfter(Operation *op)
DataFlowAnalysis(DataFlowSolver &solver)
Create an analysis with a reference to the parent solver.
AnchorT * getLatticeAnchor(Args &&...args)
Get or create a custom lattice anchor.
void registerAnchorKind()
Register a custom lattice anchor class.
friend class DataFlowSolver
Allow the data-flow solver to access the internals of this class.
const StateT * getOrCreateFor(ProgramPoint *dependent, AnchorT anchor)
Get a read-only analysis state for the given point and create a dependency on dependent.
void enqueue(WorkItem item)
Push a work item onto the worklist.
ProgramPoint * getProgramPointAfter(Operation *op)
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...
This class implements the operand iterators for the Operation class.
unsigned getBeginOperandIndex() const
Return the operand index of the first element of this range.
Operation is the basic unit of execution within MLIR.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
unsigned getNumSuccessors()
Block * getBlock()
Returns the operation block that contains this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
MutableArrayRef< OpOperand > getOpOperands()
unsigned getNumOperands()
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
operand_range getOperands()
Returns an iterator on the underlying Value's.
SuccessorRange getSuccessors()
result_range getResults()
OpOperand & getOpOperand(unsigned idx)
unsigned getNumResults()
Return the number of results held by this operation.
static constexpr RegionBranchPoint parent()
Returns an instance of RegionBranchPoint representing the parent operation.
This class represents a successor of a region.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
This class implements the result iterators for the Operation class.
OperandRange getForwardedOperands() const
Get the range of operands that are simply forwarded to the successor.
This class represents a collection of SymbolTables.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
virtual void setToExitState(AbstractSparseLattice *lattice)=0
Set the given lattice element(s) at control flow exit point(s) and propagate the update if it chaned.
SmallVector< AbstractSparseLattice * > getLatticeElements(ValueRange values)
Get the lattice elements for a range of values.
AbstractSparseBackwardDataFlowAnalysis(DataFlowSolver &solver, SymbolTableCollection &symbolTable)
virtual AbstractSparseLattice * getLatticeElement(Value value)=0
Get the lattice element for a value.
virtual void visitBranchOperand(OpOperand &operand)=0
virtual void visitCallOperand(OpOperand &operand)=0
virtual void visitNonControlFlowArguments(RegionSuccessor &successor, ArrayRef< BlockArgument > arguments)=0
LogicalResult visit(ProgramPoint *point) override
Visit a program point.
void meet(AbstractSparseLattice *lhs, const AbstractSparseLattice &rhs)
Join the lattice element and propagate and update if it changed.
virtual LogicalResult visitCallableOperation(Operation *op, CallableOpInterface callable, ArrayRef< AbstractSparseLattice * > operandLattices)
Visits a callable operation.
virtual void visitExternalCallImpl(CallOpInterface call, ArrayRef< AbstractSparseLattice * > operandLattices, ArrayRef< const AbstractSparseLattice * > resultLattices)=0
The transfer function for calls to external functions.
LogicalResult initialize(Operation *top) override
Initialize the analysis by visiting the operation and everything nested under it.
void setAllToExitStates(ArrayRef< AbstractSparseLattice * > lattices)
Set the given lattice element(s) at control flow exit point(s) and propagate the update if it chaned.
virtual LogicalResult visitOperationImpl(Operation *op, ArrayRef< AbstractSparseLattice * > operandLattices, ArrayRef< const AbstractSparseLattice * > resultLattices)=0
The operation transfer function.
LogicalResult visit(ProgramPoint *point) override
Visit a program point.
LogicalResult initialize(Operation *top) override
Initialize the analysis by visiting every owner of an SSA value: all operations and blocks.
virtual void visitExternalCallImpl(CallOpInterface call, ArrayRef< const AbstractSparseLattice * > argumentLattices, ArrayRef< AbstractSparseLattice * > resultLattices)=0
The transfer function for calls to external functions.
AbstractSparseForwardDataFlowAnalysis(DataFlowSolver &solver)
void setAllToEntryStates(ArrayRef< AbstractSparseLattice * > lattices)
virtual void setToEntryState(AbstractSparseLattice *lattice)=0
Set the given lattice element(s) at control flow entry point(s).
const AbstractSparseLattice * getLatticeElementFor(ProgramPoint *point, Value value)
Get a read-only lattice element for a value and add it as a dependency to a program point.
virtual LogicalResult visitCallOperation(CallOpInterface call, ArrayRef< const AbstractSparseLattice * > operandLattices, ArrayRef< AbstractSparseLattice * > resultLattices)
Visits a call operation.
virtual void visitCallableOperation(CallableOpInterface callable, ArrayRef< AbstractSparseLattice * > argLattices)
Visits a callable operation.
virtual AbstractSparseLattice * getLatticeElement(Value value)=0
Get the lattice element of a value.
virtual void visitNonControlFlowArgumentsImpl(Operation *op, const RegionSuccessor &successor, ValueRange nonSuccessorInputs, ArrayRef< AbstractSparseLattice * > nonSuccessorInputLattices)=0
Given an operation with region control-flow, the lattices of the operands, and a region successor,...
virtual LogicalResult visitOperationImpl(Operation *op, ArrayRef< const AbstractSparseLattice * > operandLattices, ArrayRef< AbstractSparseLattice * > resultLattices)=0
The operation transfer function.
void join(AbstractSparseLattice *lhs, const AbstractSparseLattice &rhs)
Join the lattice element and propagate and update if it changed.
This class represents an abstract lattice.
void onUpdate(DataFlowSolver *solver) const override
When the lattice gets updated, propagate an update to users of the value using its use-def chain to s...
void useDefSubscribe(DataFlowAnalysis *analysis)
Subscribe an analysis to updates of the lattice.
This analysis state represents a set of live control-flow "predecessors" of a program point (either a...
ArrayRef< Operation * > getKnownPredecessors() const
Get the known predecessors.
bool allPredecessorsKnown() const
Returns true if all predecessors are known.
std::optional< BlockArgument > getBranchSuccessorArgument(const SuccessorOperands &operands, unsigned operandIndex, Block *successor)
Return the BlockArgument corresponding to operand operandIndex in some successor if operandIndex is w...
Include the generated interface declarations.
DenseMap< OpOperand *, SmallVector< Value > > RegionBranchSuccessorMapping
A mapping from successor operands to successor inputs.
Program point represents a specific location in the execution of a program.
bool isBlockStart() const
Block * getBlock() const
Get the block contains this program point.
Operation * getPrevOp() const
Get the previous operation of this program point.