1//===- TestDeadCodeAnalysis.cpp - Test dead code 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/Analysis/DataFlow/ConstantPropagationAnalysis.h"
10#include "mlir/Analysis/DataFlow/DeadCodeAnalysis.h"
11#include "mlir/IR/Matchers.h"
12#include "mlir/Pass/Pass.h"
13
14using namespace mlir;
15using namespace mlir::dataflow;
16
17/// Print the liveness of every block, control-flow edge, and the predecessors
18/// of all regions, callables, and calls.
19static void printAnalysisResults(DataFlowSolver &solver, Operation *op,
20 raw_ostream &os) {
21 op->walk(callback: [&](Operation *op) {
22 auto tag = op->getDiscardableAttrOfType<StringAttr>(name: "tag");
23 if (!tag)
24 return;
25 os << tag.getValue() << ":\n";
26 for (Region &region : op->getRegions()) {
27 os << " region #" << region.getRegionNumber() << "\n";
28 for (Block &block : region) {
29 os << " ";
30 block.printAsOperand(os);
31 os << " = ";
32 auto *live = solver.lookupState<Executable>(
33 anchor: solver.getProgramPointBefore(block: &block));
34 if (live)
35 os << *live;
36 else
37 os << "dead";
38 os << "\n";
39 for (Block *pred : block.getPredecessors()) {
40 os << " from ";
41 pred->printAsOperand(os);
42 os << " = ";
43 auto *live = solver.lookupState<Executable>(
44 anchor: solver.getLatticeAnchor<CFGEdge>(args&: pred, args: &block));
45 if (live)
46 os << *live;
47 else
48 os << "dead";
49 os << "\n";
50 }
51 }
52 if (!region.empty()) {
53 auto *preds = solver.lookupState<PredecessorState>(
54 anchor: solver.getProgramPointBefore(block: &region.front()));
55 if (preds)
56 os << "region_preds: " << *preds << "\n";
57 }
58 }
59 auto *preds =
60 solver.lookupState<PredecessorState>(anchor: solver.getProgramPointAfter(op));
61 if (preds)
62 os << "op_preds: " << *preds << "\n";
63 });
64}
65
66namespace {
67/// This is a simple analysis that implements a transfer function for constant
68/// operations.
69struct ConstantAnalysis : public DataFlowAnalysis {
70 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConstantAnalysis)
71
72 using DataFlowAnalysis::DataFlowAnalysis;
73
74 LogicalResult initialize(Operation *top) override {
75 WalkResult result = top->walk(callback: [&](Operation *op) {
76 if (failed(Result: visit(point: getProgramPointAfter(op))))
77 return WalkResult::interrupt();
78 return WalkResult::advance();
79 });
80 return success(IsSuccess: !result.wasInterrupted());
81 }
82
83 LogicalResult visit(ProgramPoint *point) override {
84 Operation *op = point->getPrevOp();
85 Attribute value;
86 if (matchPattern(op, pattern: m_Constant(bind_value: &value))) {
87 auto *constant = getOrCreate<Lattice<ConstantValue>>(anchor: op->getResult(idx: 0));
88 propagateIfChanged(
89 state: constant, changed: constant->join(rhs: ConstantValue(value, op->getDialect())));
90 return success();
91 }
92 setAllToUnknownConstants(op->getResults());
93 for (Region &region : op->getRegions())
94 setAllToUnknownConstants(region.getArguments());
95 return success();
96 }
97
98 /// Set all given values as not constants.
99 void setAllToUnknownConstants(ValueRange values) {
100 for (Value value : values) {
101 auto *constant = getOrCreate<Lattice<ConstantValue>>(anchor: value);
102 propagateIfChanged(state: constant,
103 changed: constant->join(rhs: ConstantValue::getUnknownConstant()));
104 }
105 }
106};
107
108/// This is a simple pass that runs dead code analysis with a constant value
109/// provider that only understands constant operations.
110struct TestDeadCodeAnalysisPass
111 : public PassWrapper<TestDeadCodeAnalysisPass, OperationPass<>> {
112 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestDeadCodeAnalysisPass)
113
114 StringRef getArgument() const override { return "test-dead-code-analysis"; }
115
116 void runOnOperation() override {
117 Operation *op = getOperation();
118
119 DataFlowSolver solver;
120 solver.load<DeadCodeAnalysis>();
121 solver.load<ConstantAnalysis>();
122 if (failed(Result: solver.initializeAndRun(top: op)))
123 return signalPassFailure();
124 printAnalysisResults(solver, op, os&: llvm::errs());
125 }
126};
127} // end anonymous namespace
128
129namespace mlir {
130namespace test {
131void registerTestDeadCodeAnalysisPass() {
132 PassRegistration<TestDeadCodeAnalysisPass>();
133}
134} // end namespace test
135} // end namespace mlir
136