CIRCT 23.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 llvm;
26using namespace circt;
27using namespace sim;
28
29namespace {
30struct FoldValueFormattersPass
31 : impl::FoldValueFormattersBase<FoldValueFormattersPass> {
32public:
33 void runOnOperation() override;
34};
35} // namespace
36
37void FoldValueFormattersPass::runOnOperation() {
38
39 bool anyChanged = false;
40 OpBuilder builder(getOperation());
41
42 getOperation().getBody()->walk([&](Operation *op) {
43 // Check if this is a value formatter with a constant input.
44 if (!isa_and_nonnull<SimDialect>(op->getDialect()))
45 return;
46 auto valFmtOp = dyn_cast<ValueFormatter>(op);
47 if (!valFmtOp)
48 return;
49 auto fmtValue = getFormattedValue(op);
50 auto *valDefOp = fmtValue.getDefiningOp();
51 if (!valDefOp || !valDefOp->hasTrait<OpTrait::ConstantLike>())
52 return;
53 // Call the defining op's fold method to get the constant attribute.
54 SmallVector<OpFoldResult, 1> foldResult;
55 if (failed(valDefOp->fold((foldResult))))
56 return;
57 auto opResultIdx = cast<OpResult>(fmtValue).getResultNumber();
58 assert((foldResult.size() > opResultIdx &&
59 isa<Attribute>(foldResult[opResultIdx])) &&
60 "ConstantLike operation should fold to constant attributes");
61 // Perform the formatting
62 auto stringConst =
63 valFmtOp.formatConstant(cast<Attribute>(foldResult[opResultIdx]));
64 if (!stringConst)
65 return;
66 // Replace the operation with a literal.
67 builder.setInsertionPoint(valFmtOp);
68 auto literalOp =
69 FormatLiteralOp::create(builder, valFmtOp.getLoc(), stringConst);
70 assert(valFmtOp.getOperation()->getNumResults() == 1);
71 valFmtOp.getOperation()->getResult(0).replaceAllUsesWith(
72 literalOp.getResult());
73 valFmtOp.getOperation()->erase();
74 anyChanged = true;
75 });
76
77 if (!anyChanged)
78 markAllAnalysesPreserved();
79}
assert(baseType &&"element must be base type")
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition sim.py:1