1//===- TestSingleFold.cpp - Pass to test single-pass folding --------------===//
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 "../IR/DumpNotifications.h"
10#include "mlir/Pass/Pass.h"
11#include "mlir/Transforms/FoldUtils.h"
12#include "llvm/ADT/SetVector.h"
13
14using namespace mlir;
15
16namespace {
17/// Test pass for single-pass constant folding.
18///
19/// This pass tests the behavior of operations when folded exactly once. Unlike
20/// canonicalization passes that may apply multiple rounds of folding, this pass
21/// ensures that each operation is folded at most once, which is useful for
22/// testing scenarios where the fold implementation should handle complex cases
23/// without requiring multiple iterations.
24///
25/// The pass also removes dead constants after folding to clean up unused
26/// intermediate results.
27struct TestSingleFold : public PassWrapper<TestSingleFold, OperationPass<>>,
28 public RewriterBase::Listener {
29 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestSingleFold)
30
31 TestSingleFold() = default;
32 TestSingleFold(const TestSingleFold &pass) : PassWrapper(pass) {}
33
34 StringRef getArgument() const final { return "test-single-fold"; }
35 StringRef getDescription() const final {
36 return "Test single-pass operation folding and dead constant elimination";
37 }
38 // Moves can report the same constant more than once. Keep each constant
39 // once so that cleanup cannot visit an operation after erasing it.
40 llvm::SmallSetVector<Operation *, 8> existingConstants;
41
42 void foldOperation(Operation *op, OperationFolder &helper);
43 void runOnOperation() override;
44
45 void notifyOperationInserted(Operation *op,
46 OpBuilder::InsertPoint previous) override {
47 if (dumpNotifications)
48 notificationPrinter.notifyOperationInserted(op, previous);
49 existingConstants.insert(X: op);
50 }
51 void notifyOperationErased(Operation *op) override {
52 if (dumpNotifications)
53 notificationPrinter.notifyOperationErased(op);
54 existingConstants.remove(X: op);
55 }
56
57 DumpNotifications notificationPrinter;
58 Option<bool> dumpNotifications{
59 *this, "dump-notifications",
60 llvm::cl::desc("Print insertion and erasure notifications"),
61 llvm::cl::init(Val: false)};
62 Option<int> maxIterations{*this, "max-iterations",
63 llvm::cl::desc("Max iterations in the tryToFold"),
64 llvm::cl::init(Val: 1)};
65};
66} // namespace
67
68void TestSingleFold::foldOperation(Operation *op, OperationFolder &helper) {
69 // Attempt to fold the specified operation, including handling unused or
70 // duplicated constants.
71 bool inPlaceUpdate = false;
72 (void)helper.tryToFold(op, inPlaceUpdate: &inPlaceUpdate, maxIterations);
73}
74
75void TestSingleFold::runOnOperation() {
76 existingConstants.clear();
77
78 // Collect and fold the operations within the operation.
79 SmallVector<Operation *, 8> ops;
80 getOperation()->walk<mlir::WalkOrder::PreOrder>(
81 callback: [&](Operation *op) { ops.push_back(Elt: op); });
82
83 // Fold the constants in reverse so that the last generated constants from
84 // folding are at the beginning. This creates somewhat of a linear ordering to
85 // the newly generated constants that matches the operation order and improves
86 // the readability of test cases.
87 OperationFolder helper(&getContext(), /*listener=*/this);
88 for (Operation *op : llvm::reverse(C&: ops))
89 foldOperation(op, helper);
90
91 // By the time we are done, we may have simplified a bunch of code, leaving
92 // around dead constants. Check for them now and remove them.
93 for (auto *cst : existingConstants) {
94 if (cst->use_empty())
95 cst->erase();
96 }
97}
98
99namespace mlir {
100namespace test {
101void registerTestSingleFold() { PassRegistration<TestSingleFold>(); }
102} // namespace test
103} // namespace mlir
104