403 DenseMap<Value, Operation *> nodeCache;
406 auto getOrCreateNodeOp = [&](Value operand,
407 ImplicitLocOpBuilder &builder) -> Operation * {
409 auto *nodeOp = nodeCache.lookup(operand);
414 OpBuilder::InsertionGuard guard(builder);
415 builder.setInsertionPointAfterValue(operand);
416 SmallString<16> nameHint;
418 if (
auto *definingOp = operand.getDefiningOp()) {
419 if (
auto instanceOp = dyn_cast<InstanceOp>(definingOp)) {
420 nameHint.append(instanceOp.getName());
421 nameHint.push_back(
'_');
423 instanceOp.getPortName(cast<OpResult>(operand).getResultNumber()));
424 }
else if (
auto opName = definingOp->getAttrOfType<StringAttr>(
"name")) {
425 nameHint.append(opName);
428 return nodeOp = NodeOp::create(builder, operand.getLoc(), operand,
429 nameHint.empty() ?
"_layer_probe"
430 : StringRef(nameHint));
436 DenseMap<Value, Value> replacements;
437 auto getReplacement = [&](Operation *user, Value value) -> Value {
438 auto it = replacements.find(value);
439 if (it != replacements.end())
440 return it->getSecond();
442 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
445 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
446 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
453 if (type_isa<FStringType>(value.getType())) {
454 localBuilder.setInsertionPoint(user);
455 replacement = localBuilder.clone(*value.getDefiningOp())->getResult(0);
456 replacements.insert({value, replacement});
461 auto *definingOp = value.getDefiningOp();
462 if (isa_and_present<XMRRefOp>(definingOp)) {
463 replacement = localBuilder.clone(*definingOp)->getResult(0);
464 replacements.insert({value, replacement});
477 auto baseType = type_cast<FIRRTLBaseType>(value.getType());
478 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
479 OpBuilder::InsertionGuard guard(localBuilder);
480 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
481 replacement = localBuilder.createOrFold<BitCastOp>(
482 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
485 auto *definingOp = value.getDefiningOp();
486 hw::InnerRefAttr innerRef;
494 definingOp = getOrCreateNodeOp(value, localBuilder);
498 auto portIdx = cast<BlockArgument>(value).getArgNumber();
500 cast<FModuleLike>(*moduleOp), portIdx,
504 hw::HierPathOp hierPathOp;
507 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
508 Block::iterator(moduleOp));
509 llvm::sys::SmartScopedLock<true> circuitLock(*
circuitMutex);
511 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
513 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
516 replacement = XMRDerefOp::create(localBuilder, value.getType(),
517 hierPathOp.getSymNameAttr());
520 replacements.insert({value, replacement});
528 DenseMap<InstanceOp, FModuleOp> createdInstances;
532 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
534 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
536 return op->emitOpError()
537 <<
"cannot be handled by the lower-layers pass. This should have "
538 "already been removed by the lower-xmr pass.";
562 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
563 if (failed(opPreconditionCheck(op)))
564 return WalkResult::interrupt();
567 for (
auto result : op->getResults())
571 if (
auto instance = dyn_cast<InstanceOp>(op))
572 instance.setLayers({});
574 auto layerBlock = dyn_cast<LayerBlockOp>(op);
576 return WalkResult::advance();
579 auto layer =
symbolToLayer.lookup(layerBlock.getLayerName());
581 if (layer.getConvention() == LayerConvention::Inline) {
583 return WalkResult::advance();
587 assert(layer.getConvention() == LayerConvention::Bind);
590 replacements.clear();
591 OpBuilder builder(moduleOp);
592 SmallVector<hw::InnerSymAttr> innerSyms;
593 SmallVector<sv::VerbatimOp> verbatims;
594 DenseSet<Operation *> spilledSubOps;
595 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
597 if (failed(opPreconditionCheck(op)))
598 return WalkResult::interrupt();
611 if (isa<SubfieldOp, SubindexOp>(op)) {
612 auto input = op->getOperand(0);
613 if (!firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive() &&
615 op->moveBefore(layerBlock);
616 spilledSubOps.insert(op);
618 return WalkResult::advance();
620 if (
auto subOp = dyn_cast<SubaccessOp>(op)) {
621 auto input = subOp.getInput();
622 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive())
623 return WalkResult::advance();
627 subOp->moveBefore(layerBlock);
628 spilledSubOps.insert(op);
629 return WalkResult::advance();
631 auto diag = op->emitOpError()
632 <<
"has a non-passive operand and captures a value defined "
633 "outside its enclosing bind-convention layerblock. The "
634 "'LowerLayers' pass cannot lower this as it would "
635 "create an output port on the resulting module.";
636 diag.attachNote(layerBlock.getLoc())
637 <<
"the layerblock is defined here";
638 return WalkResult::interrupt();
640 if (
auto nodeOp = dyn_cast<NodeOp>(op)) {
641 auto *definingOp = nodeOp.getInput().getDefiningOp();
643 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
644 op->moveBefore(layerBlock);
645 return WalkResult::advance();
653 if (
auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
654 if (
auto innerSym = symOp.getInnerSymAttr())
655 innerSyms.push_back(innerSym);
667 if (
auto instOp = dyn_cast<InstanceOp>(op)) {
669 if (!createdInstances.contains(instOp))
670 return WalkResult::advance();
674 <<
" Found instance created from nested layer block:\n"
675 <<
" module: " << instOp.getModuleName() <<
"\n"
676 <<
" instance: " << instOp.getName() <<
"\n";
678 instOp->moveBefore(layerBlock);
679 return WalkResult::advance();
685 for (
size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
686 auto operand = op->getOperand(i);
694 op->setOperand(i, getReplacement(op, operand));
697 if (
auto verbatim = dyn_cast<sv::VerbatimOp>(op))
698 verbatims.push_back(verbatim);
700 return WalkResult::advance();
703 if (layerBlockWalkResult.wasInterrupted())
704 return WalkResult::interrupt();
708 SymbolTable::setSymbolVisibility(newModule,
709 SymbolTable::Visibility::Private);
710 newModule.getBody().takeBody(layerBlock.getRegion());
713 llvm::dbgs() <<
" New Module: "
723 builder.setInsertionPointAfter(layerBlock);
726 hw::InnerSymAttr::get(builder.getStringAttr(ns.
newName(instanceName)));
728 auto instanceOp = InstanceOp::create(
729 builder, layerBlock.getLoc(), newModule,
731 instanceName, NameKindEnum::DroppableName,
732 ArrayRef<Attribute>{},
733 ArrayRef<Attribute>{},
false,
737 layerBlock.getLayerName());
738 instanceOp->setAttr(
"output_file", outputFile);
740 createdInstances.try_emplace(instanceOp, newModule);
744 auto builder = OpBuilder::atBlockEnd(
bindFiles[moduleOp][layer].body);
745 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
746 instanceOp.getInnerSymAttr().getSymName());
749 LLVM_DEBUG(llvm::dbgs() <<
" moved inner refs:\n");
750 for (hw::InnerSymAttr innerSym : innerSyms) {
751 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
752 innerSym.getSymName());
753 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
754 newModule.getModuleNameAttr());
755 innerRefMap.insert({oldInnerRef, splice});
756 LLVM_DEBUG(llvm::dbgs() <<
" - ref: " << oldInnerRef <<
"\n"
757 <<
" splice: " << splice.first <<
", "
758 << splice.second <<
"\n";);
762 if (!verbatims.empty()) {
763 mlir::AttrTypeReplacer replacer;
764 replacer.addReplacement(
765 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
766 auto it = innerRefMap.find(ref);
767 if (it != innerRefMap.end())
768 return hw::InnerRefAttr::get(it->second.second, ref.getName());
771 for (
auto verbatim : verbatims)
772 replacer.replaceElementsIn(verbatim);
777 return WalkResult::advance();
779 return success(!result.wasInterrupted());
821 SymbolRefAttr layerName, LayerOp layer) {
822 assert(layer.getConvention() == LayerConvention::Bind);
823 auto module = node->getModule<FModuleOp>();
824 auto loc =
module.getLoc();
828 auto macroSymbol = ns.
newName(macroName);
829 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
830 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
831 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
838 auto dir = layer->getAttrOfType<hw::OutputFileAttr>(
"output_file");
839 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
842 path = StringAttr::get(&getContext(),
843 Twine(dir.getDirectory()) + bindFileName);
848 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, ArrayAttr{}, macroNameAttr);
851 auto bindFile = emit::FileOp::create(b, loc, path);
852 OpBuilder::InsertionGuard _(b);
853 b.setInsertionPointToEnd(bindFile.getBody());
856 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
857 b.createBlock(&includeGuard.getElseRegion());
860 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
863 auto parent = layer->getParentOfType<LayerOp>();
867 if (parent.getConvention() == LayerConvention::Bind) {
868 auto target =
bindFiles[module][parent].filename;
869 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
875 if (parent.getConvention() == LayerConvention::Inline) {
876 auto parentMacroSymbolRefAttr =
macroNames[parent];
877 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
878 OpBuilder::InsertionGuard guard(b);
879 b.createBlock(&parentGuard.getElseRegion());
880 auto message = StringAttr::get(&getContext(),
881 Twine(parent.getName()) +
" not enabled");
882 sv::MacroErrorOp::create(b, loc, message);
883 parent = parent->getParentOfType<LayerOp>();
888 llvm_unreachable(
"unknown layer convention");
893 SmallPtrSet<Operation *, 8> seen;
894 for (
auto *record : *node) {
895 auto *child = record->getTarget()->getModule().getOperation();
896 if (!std::get<bool>(seen.insert(child)))
899 auto lookup = files.find(layer);
900 if (lookup != files.end())
901 sv::IncludeOp::create(b, loc, IncludeStyle::Local,
902 lookup->second.filename);
907 info.filename = filename;
908 info.body = includeGuard.getElseBlock();
1029 llvm::dbgs() <<
"==----- Running LowerLayers "
1030 "-------------------------------------------------===\n");
1031 CircuitOp circuitOp = getOperation();
1034 llvm::sys::SmartMutex<true> mutex;
1037 auto *ig = &getAnalysis<InstanceGraph>();
1040 &ns, OpBuilder::InsertPoint(getOperation().
getBodyBlock(),
1047 auto mergeMaps = [](
auto &&a,
auto &&b) {
1049 return std::forward<
decltype(a)>(a);
1051 return std::forward<
decltype(b)>(b);
1055 return std::forward<decltype(a)>(a);
1059 SmallVector<FModuleLike> modules(
1060 circuitOp.getBodyBlock()->getOps<FModuleLike>());
1062 circuitOp.getContext(), modules, FailureOr<InnerRefMap>(
InnerRefMap{}),
1063 mergeMaps, [
this](FModuleLike mod) -> FailureOr<InnerRefMap> {
1064 return runOnModuleLike(mod);
1066 if (failed(failureOrInnerRefMap))
1067 return signalPassFailure();
1068 auto &innerRefMap = *failureOrInnerRefMap;
1077 for (hw::HierPathOp hierPathOp : circuitOp.getOps<hw::HierPathOp>()) {
1078 SmallVector<Attribute> newNamepath;
1079 bool modified =
false;
1080 for (
auto attr : hierPathOp.getNamepath()) {
1081 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(attr);
1083 newNamepath.push_back(attr);
1086 auto it = innerRefMap.find(innerRef);
1087 if (it == innerRefMap.end()) {
1088 newNamepath.push_back(attr);
1092 auto &[inst, mod] = it->getSecond();
1093 newNamepath.push_back(
1094 hw::InnerRefAttr::get(innerRef.getModule(), inst.getSymName()));
1095 newNamepath.push_back(hw::InnerRefAttr::get(mod, innerRef.getName()));
1099 hierPathOp.setNamepathAttr(
1100 ArrayAttr::get(circuitOp.getContext(), newNamepath));
1105 llvm::make_early_inc_range(circuitOp.getBodyBlock()->getOps<LayerOp>()))