15#include "mlir/IR/AttrTypeSubElements.h"
16#include "mlir/IR/Builders.h"
17#include "mlir/IR/IRMapping.h"
18#include "mlir/Pass/Pass.h"
19#include "mlir/Transforms/Inliner.h"
20#include "mlir/Transforms/InliningUtils.h"
21#include "llvm/ADT/PostOrderIterator.h"
23#define DEBUG_TYPE "hw-flatten-modules"
27#define GEN_PASS_DEF_FLATTENMODULES
28#include "circt/Dialect/HW/Passes.h.inc"
35using mlir::InlinerConfig;
36using mlir::InlinerInterface;
38using HierPathTable = DenseMap<hw::InnerRefAttr, SmallVector<hw::HierPathOp>>;
43static const StringRef innerSymAttrName =
45struct FlattenModulesPass
46 :
public circt::hw::impl::FlattenModulesBase<FlattenModulesPass> {
49 void runOnOperation()
override;
60struct PrefixingInliner :
public InlinerInterface {
65 DenseMap<StringAttr, StringAttr> *symMapping;
66 mlir::AttrTypeReplacer *replacer;
68 hw::InnerRefAttr instanceRef;
70 PrefixingInliner(MLIRContext *
context, StringRef prefix,
73 DenseMap<StringAttr, StringAttr> *symMapping,
75 hw::InnerRefAttr instanceRef)
76 : InlinerInterface(
context), prefix(prefix), ns(ns),
77 parentModule(parentModule), sourceModule(sourceModule),
78 symMapping(symMapping), replacer(replacer), pathsTable(pathsTable),
79 instanceRef(instanceRef) {}
81 bool isLegalToInline(Region *dest, Region *src,
bool wouldBeCloned,
82 IRMapping &valueMapping)
const override {
85 bool isLegalToInline(Operation *op, Region *dest,
bool wouldBeCloned,
86 IRMapping &valueMapping)
const override {
89 void handleTerminator(Operation *op,
90 mlir::ValueRange valuesToRepl)
const override {
91 assert(isa<hw::OutputOp>(op));
92 for (
auto [from, to] : llvm::zip(valuesToRepl, op->getOperands()))
93 from.replaceAllUsesWith(to);
96 void processInlinedBlocks(
97 iterator_range<Region::iterator> inlinedBlocks)
override {
98 for (Block &block : inlinedBlocks)
99 block.walk([&](Operation *op) {
101 updateInnerSymbols(op);
108 void updateHierPaths()
const {
114 auto it = pathsTable->find(instanceRef);
115 if (it == pathsTable->end())
119 for (hw::HierPathOp path : it->second) {
120 SmallVector<Attribute, 4> newPath;
121 for (
auto elem : path.getNamepath()) {
123 if (elem != instanceRef)
124 newPath.push_back(replacer->replace(elem));
126 path.setNamepathAttr(ArrayAttr::get(path.getContext(), newPath));
130 StringAttr
updateName(StringAttr attr)
const {
131 if (attr.getValue().empty())
133 return StringAttr::get(attr.getContext(), prefix +
"/" + attr.getValue());
136 void updateNames(Operation *op)
const {
137 if (
auto name = op->getAttrOfType<StringAttr>(
"name"))
139 if (
auto name = op->getAttrOfType<StringAttr>(
"instanceName"))
140 op->setAttr(
"instanceName",
updateName(name));
141 if (
auto namesAttr = op->getAttrOfType<ArrayAttr>(
"names")) {
142 SmallVector<Attribute> names(namesAttr.getValue().begin(),
143 namesAttr.getValue().end());
144 for (
auto &name : names)
145 if (
auto nameStr = dyn_cast<StringAttr>(name))
147 op->setAttr(
"names", ArrayAttr::get(namesAttr.getContext(), names));
151 void updateInnerSymbols(Operation *op)
const {
153 if (
auto innerSymAttr =
154 op->getAttrOfType<hw::InnerSymAttr>(innerSymAttrName)) {
155 StringAttr symName = innerSymAttr.getSymName();
156 auto it = symMapping->find(symName);
157 if (it != symMapping->end())
158 op->setAttr(innerSymAttrName, hw::InnerSymAttr::get(it->second));
162 replacer->replaceElementsIn(op);
165 bool allowSingleBlockOptimization(Block *inlinedBlock)
const final {
171bool FlattenModulesPass::shouldInline(
HWModuleOp module,
179 bool isEmpty = bodySize == 1;
180 bool hasNoOutputs =
module.getNumOutputPorts() == 0;
181 bool hasOneUse = instanceNode->
getNumUses() == 1;
182 bool hasState =
false;
183 module.walk([&](Operation *op) {
185 if (isa<seq::FirRegOp, seq::CompRegOp, seq::CompRegClockEnabledOp,
186 seq::ShiftRegOp, seq::FirMemOp, seq::HLMemOp>(op)) {
188 return WalkResult::interrupt();
190 return WalkResult::advance();
194 if (hasState && !this->inlineWithState)
198 return (this->inlineEmpty && isEmpty) ||
199 (this->inlineNoOutputs && hasNoOutputs) ||
200 (this->inlineSingleUse && hasOneUse) ||
201 (this->inlineSmall && bodySize < this->smallThreshold);
204void FlattenModulesPass::runOnOperation() {
205 auto &instanceGraph = getAnalysis<hw::InstanceGraph>();
206 DenseSet<Operation *> handled;
208 InlinerConfig config;
211 DenseSet<StringAttr> leafModules;
213 for (
auto path : getOperation().getOps<hw::HierPathOp>()) {
216 leafModules.insert(path.leafMod());
219 for (
auto name : path.getNamepath()) {
220 if (
auto ref = dyn_cast<hw::InnerRefAttr>(name))
221 pathsTable[ref].push_back(path);
227 DenseMap<HWModuleOp, std::unique_ptr<InnerSymbolNamespace>> nsCache;
231 for (
auto *startNode : instanceGraph) {
232 if (handled.count(startNode->getModule().getOperation()))
238 for (InstanceGraphNode *node : llvm::post_order(startNode)) {
239 if (!handled.insert(node->getModule().getOperation()).second)
242 unsigned numUsesLeft = node->getNumUses();
243 if (numUsesLeft == 0)
248 dyn_cast_or_null<HWModuleOp>(node->getModule().getOperation());
249 if (!module || (!module.isPrivate() && !this->inlinePublic))
253 if (leafModules.count(module.getNameAttr()))
257 auto *body =
module.getBodyBlock();
258 size_t bodySize = std::distance(body->begin(), body->end());
259 if (!shouldInline(module, node, bodySize))
263 DenseMap<StringAttr, StringAttr> inlineModuleInnerSyms;
264 mlir::AttrTypeReplacer innerRefReplacer;
267 module.walk([&](Operation *op) {
268 if (auto innerSymAttr =
269 op->getAttrOfType<hw::InnerSymAttr>(innerSymAttrName))
270 inlineModuleInnerSyms.insert(
271 {innerSymAttr.getSymName(), StringAttr()});
274 for (
auto *instRecord : node->uses()) {
276 auto inst = dyn_cast_or_null<InstanceOp>(
277 instRecord->getInstance().getOperation());
281 bool isLastModuleUse = --numUsesLeft == 0;
284 HWModuleOp parentModule = inst->getParentOfType<HWModuleOp>();
287 auto &nsPtr = nsCache[parentModule];
289 nsPtr = std::make_unique<InnerSymbolNamespace>(parentModule);
292 DenseMap<StringAttr, StringAttr> oldToNewInnerSyms;
293 for (
auto [oldSym, _] : inlineModuleInnerSyms)
294 oldToNewInnerSyms.insert(
295 {oldSym, StringAttr::get(&getContext(),
296 nsPtr->newName(oldSym.getValue()))});
299 mlir::AttrTypeReplacer instanceReplacer;
300 instanceReplacer.addReplacement(
301 [&](InnerRefAttr attr) -> std::pair<Attribute, WalkResult> {
302 if (attr.getModule() != module.getModuleNameAttr())
303 return {attr, WalkResult::skip()};
305 auto it = oldToNewInnerSyms.find(attr.getName());
306 if (it == oldToNewInnerSyms.end())
307 return {attr, WalkResult::skip()};
309 auto newAttr = InnerRefAttr::get(parentModule.getModuleNameAttr(),
311 return {newAttr, WalkResult::skip()};
315 hw::InnerRefAttr instanceRef;
316 if (
auto sym = inst.getInnerSymAttr())
317 instanceRef = inst.getInnerRef();
319 PrefixingInliner inliner(&getContext(), inst.getInstanceName(),
320 nsPtr.get(), parentModule, module,
321 &oldToNewInnerSyms, &instanceReplacer,
322 &pathsTable, instanceRef);
324 if (failed(mlir::inlineRegion(inliner, config.getCloneCallback(),
325 &module.getBody(), inst,
326 inst.getOperands(), inst.getResults(),
327 std::nullopt, !isLastModuleUse))) {
328 inst.emitError(
"failed to inline '")
329 <<
module.getModuleName() << "' into instance '"
330 << inst.getInstanceName() << "'";
331 return signalPassFailure();
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static void updateName(PatternRewriter &rewriter, Operation *op, StringAttr name)
Set the name of an op based on the best of two names: The current name, and the name passed in.
DenseMap< hw::InnerRefAttr, SmallVector< hw::HierPathOp > > HierPathTable
static StringRef getInnerSymbolAttrName()
Return the name of the attribute used for inner symbol names.
This is a Node in the InstanceGraph.
size_t getNumUses()
Get the number of direct instantiations of this module.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.