CIRCT 24.0.0git
Loading...
Searching...
No Matches
FoldValueFormatters.cpp
Go to the documentation of this file.
1//===- FoldValueFormatters.cpp - Fold constant value formatters -----------===//
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// This pass converts `sim.fmt.* %cst` operations with constant inputs to
10// `sim.fmt.literal` operations.
11//
12//===----------------------------------------------------------------------===//
13
16#include "mlir/Pass/Pass.h"
17
18namespace circt {
19namespace sim {
20#define GEN_PASS_DEF_FOLDVALUEFORMATTERS
21#include "circt/Dialect/Sim/SimPasses.h.inc"
22} // namespace sim
23} // namespace circt
24
25using namespace circt;
26using namespace sim;
27
28namespace {
29struct FoldValueFormattersPass
30 : impl::FoldValueFormattersBase<FoldValueFormattersPass> {
31public:
32 void runOnOperation() override;
33};
34} // namespace
35
36void FoldValueFormattersPass::runOnOperation() {
37
38 bool anyChanged = false;
39 OpBuilder builder(getOperation());
40
41 getOperation().getBody()->walk([&](Operation *op) {
42 // Check if this is a value formatter with a constant input.
43 if (!isa_and_nonnull<SimDialect>(op->getDialect()))
44 return;
45 auto valFmtOp = dyn_cast<ValueFormatter>(op);
46 if (!valFmtOp)
47 return;
48 auto fmtValue = getFormattedValue(op);
49 auto *valDefOp = fmtValue.getDefiningOp();
50 if (!valDefOp || !valDefOp->hasTrait<OpTrait::ConstantLike>())
51 return;
52 // Call the defining op's fold method to get the constant attribute.
53 SmallVector<OpFoldResult, 1> foldResult;
54 if (failed(valDefOp->fold((foldResult))))
55 return;
56 auto opResultIdx = cast<OpResult>(fmtValue).getResultNumber();
57 assert((foldResult.size() > opResultIdx &&
58 isa<Attribute>(foldResult[opResultIdx])) &&
59 "ConstantLike operation should fold to constant attributes");
60 // Perform the formatting
61 auto stringConst =
62 valFmtOp.formatConstant(cast<Attribute>(foldResult[opResultIdx]));
63 if (!stringConst)
64 return;
65 // Replace the operation with a literal.
66 builder.setInsertionPoint(valFmtOp);
67 auto literalOp =
68 FormatLiteralOp::create(builder, valFmtOp.getLoc(), stringConst);
69 assert(valFmtOp.getOperation()->getNumResults() == 1);
70 valFmtOp.getOperation()->getResult(0).replaceAllUsesWith(
71 literalOp.getResult());
72 valFmtOp.getOperation()->erase();
73 anyChanged = true;
74 });
75
76 if (!anyChanged)
77 markAllAnalysesPreserved();
78}
assert(baseType &&"element must be base type")
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition sim.py:1