29#include "mlir/IR/BuiltinTypes.h"
30#include "mlir/IR/Diagnostics.h"
31#include "mlir/IR/DialectImplementation.h"
32#include "mlir/IR/PatternMatch.h"
33#include "mlir/IR/SymbolTable.h"
34#include "mlir/Interfaces/FunctionImplementation.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/ADT/TypeSwitch.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/FormatVariadic.h"
45using llvm::SmallDenseSet;
46using mlir::RegionRange;
56template <
typename RetTy =
FIRRTLType,
typename... Args>
58 const Twine &message, Args &&...args) {
60 (mlir::emitError(*loc, message) << ... << std::forward<Args>(args));
66 while (Operation *op = val.getDefiningOp()) {
68 TypeSwitch<Operation *, std::optional<bool>>(op)
69 .Case<SubfieldOp, SubindexOp, SubaccessOp>([&val](
auto op) {
73 .Case<RegOp, RegResetOp, WireOp>([](
auto) {
return true; })
74 .Default([](
auto) {
return false; });
81SmallVector<std::pair<circt::FieldRef, circt::FieldRef>>
82MemOp::computeDataFlow() {
85 if (getReadLatency() > 0)
87 SmallVector<std::pair<circt::FieldRef, circt::FieldRef>> deps;
89 for (
auto memPort : getResults())
91 auto enableFieldId = type.getFieldID((
unsigned)ReadPortSubfield::en);
92 auto addressFieldId = type.getFieldID((
unsigned)ReadPortSubfield::addr);
93 auto dataFieldId = type.getFieldID((
unsigned)ReadPortSubfield::data);
95 FieldRef(memPort,
static_cast<unsigned>(dataFieldId)),
96 FieldRef(memPort,
static_cast<unsigned>(enableFieldId)));
98 FieldRef(memPort,
static_cast<unsigned>(dataFieldId)),
99 FieldRef(memPort,
static_cast<unsigned>(addressFieldId)));
106 constexpr unsigned int addr = 1 << 0;
107 constexpr unsigned int en = 1 << 1;
108 constexpr unsigned int clk = 1 << 2;
109 constexpr unsigned int data = 1 << 3;
110 constexpr unsigned int mask = 1 << 4;
111 constexpr unsigned int rdata = 1 << 5;
112 constexpr unsigned int wdata = 1 << 6;
113 constexpr unsigned int wmask = 1 << 7;
114 constexpr unsigned int wmode = 1 << 8;
115 constexpr unsigned int def = 1 << 9;
119 return MemOp::PortKind::Debug;
122 for (
auto elem : portType.getElements()) {
123 fields |= llvm::StringSwitch<unsigned>(elem.name.getValue())
129 .Case(
"rdata",
rdata)
130 .Case(
"wdata",
wdata)
131 .Case(
"wmask",
wmask)
132 .Case(
"wmode",
wmode)
136 return MemOp::PortKind::Read;
138 return MemOp::PortKind::Write;
140 return MemOp::PortKind::ReadWrite;
141 return MemOp::PortKind::Debug;
156 llvm_unreachable(
"Unsupported Flow type.");
164 return "source flow";
168 return "duplex flow";
171 llvm_unreachable(
"Unsupported Flow type.");
176 if (
auto blockArg = dyn_cast<BlockArgument>(val)) {
177 auto *op = val.getParentBlock()->getParentOp();
178 if (
auto moduleLike = dyn_cast<FModuleLike>(op)) {
179 auto direction = moduleLike.getPortDirection(blockArg.getArgNumber());
183 return accumulatedFlow;
186 Operation *op = val.getDefiningOp();
188 return TypeSwitch<Operation *, Flow>(op)
189 .Case<SubfieldOp, OpenSubfieldOp>([&](
auto op) {
190 return foldFlow(op.getInput(), op.isFieldFlipped()
194 .Case<SubindexOp, SubaccessOp, OpenSubindexOp, RefSubOp>(
195 [&](
auto op) {
return foldFlow(op.getInput(), accumulatedFlow); })
197 .Case<RegOp, RegResetOp, WireOp, MemoryPortOp>(
199 .Case<InstanceOp, InstanceChoiceOp>([&](
auto inst) {
200 auto resultNo = cast<OpResult>(val).getResultNumber();
202 return accumulatedFlow;
205 .Case<MemOp>([&](
auto op) {
211 .Case<ObjectSubfieldOp>([&](ObjectSubfieldOp op) {
212 auto input = op.getInput();
213 auto *inputOp = input.getDefiningOp();
216 if (
auto objectOp = dyn_cast_or_null<ObjectOp>(inputOp)) {
217 auto classType = input.getType();
218 auto direction = classType.getElement(op.getIndex()).direction;
230 auto classType = input.getType();
231 auto direction = classType.getElement(op.getIndex()).direction;
235 op = dyn_cast_or_null<ObjectSubfieldOp>(inputOp);
237 input = op.getInput();
238 inputOp = input.getDefiningOp();
242 return accumulatedFlow;
246 .Default([&](
auto) {
return accumulatedFlow; });
252 Operation *op = val.getDefiningOp();
256 return TypeSwitch<Operation *, DeclKind>(op)
258 .Case<SubfieldOp, SubindexOp, SubaccessOp, OpenSubfieldOp, OpenSubindexOp,
264 if (
auto module = dyn_cast<FModuleLike>(op))
265 return module.getNumPorts();
266 return op->getNumResults();
280 if (
auto *op = value.getDefiningOp())
282 auto arg = dyn_cast<BlockArgument>(value);
283 auto module = dyn_cast<FModuleOp>(arg.getOwner()->getParentOp());
286 return (module.getPortSymbolAttr(arg.getArgNumber())) ||
297 auto *block = ®ion.front();
300 auto argAttr = parentOp->getAttrOfType<ArrayAttr>(
"portNames");
302 if (!argAttr || argAttr.size() != block->getNumArguments())
305 for (
size_t i = 0, e = block->getNumArguments(); i != e; ++i) {
306 auto str = cast<StringAttr>(argAttr[i]).getValue();
308 setNameFn(block->getArgument(i), str);
314 firrtl::NameKindEnumAttr &result);
325 for (; op !=
nullptr; op = op->getParentOp()) {
326 if (
auto module = dyn_cast<FModuleLike>(op)) {
327 auto layers =
module.getLayersAttr().getAsRange<SymbolRefAttr>();
328 result.insert(layers.begin(), layers.end());
331 if (
auto layerblock = dyn_cast<LayerBlockOp>(op)) {
332 result.insert(layerblock.getLayerName());
350 if (
auto type = dyn_cast<RefType>(value.getType()))
351 if (
auto layer = type.getLayer())
352 result.insert(type.getLayer());
361 mlir::SymbolRefAttr dstLayer) {
371 if (srcLayer.getRootReference() != dstLayer.getRootReference())
374 auto srcNames = srcLayer.getNestedReferences();
375 auto dstNames = dstLayer.getNestedReferences();
376 if (dstNames.size() < srcNames.size())
379 return llvm::all_of(llvm::zip_first(srcNames, dstNames),
380 [](
auto x) {
return std::get<0>(x) == std::get<1>(x); });
387 if (dstLayers.contains(srcLayer))
392 return any_of(dstLayers, [=](SymbolRefAttr dstLayer) {
401 SmallVectorImpl<SymbolRefAttr> &missing) {
402 for (
auto srcLayer : src)
404 missing.push_back(srcLayer);
407 return missing.empty();
412 const Twine &errorMsg,
413 const Twine ¬eMsg = Twine(
"missing layer requirements")) {
414 SmallVector<SymbolRefAttr> missing;
417 interleaveComma(missing, op->emitOpError(errorMsg).attachNote()
426void CircuitOp::build(OpBuilder &builder, OperationState &result,
427 StringAttr name, ArrayAttr annotations) {
429 result.getOrAddProperties<Properties>().setName(name);
432 annotations = builder.getArrayAttr({});
433 result.getOrAddProperties<Properties>().setAnnotations(annotations);
436 Region *bodyRegion = result.addRegion();
438 bodyRegion->push_back(body);
442 NamedAttrList &resultAttrs) {
443 auto result = parser.parseOptionalAttrDictWithKeyword(resultAttrs);
444 if (!resultAttrs.get(
"annotations"))
445 resultAttrs.append(
"annotations", parser.getBuilder().getArrayAttr({}));
451 DictionaryAttr attr) {
453 SmallVector<StringRef> elidedAttrs = {
"name"};
455 auto annotationsAttr = op->getAttrOfType<ArrayAttr>(
"annotations");
456 if (annotationsAttr.empty())
457 elidedAttrs.push_back(
"annotations");
459 p.printOptionalAttrDictWithKeyword(op->getAttrs(), elidedAttrs);
462LogicalResult CircuitOp::verifyRegions() {
467 emitOpError(
"must have a non-empty name");
471 mlir::SymbolTable symtbl(getOperation());
473 auto *mainModule = symtbl.lookup(
main);
475 return emitOpError().append(
476 "does not contain module with same name as circuit");
477 if (!isa<FModuleLike>(mainModule))
478 return mainModule->emitError(
479 "entity with name of circuit must be a module");
480 if (symtbl.getSymbolVisibility(mainModule) !=
481 mlir::SymbolTable::Visibility::Public)
482 return mainModule->emitError(
"main module must be public");
487 llvm::DenseMap<Attribute, FExtModuleOp> defnameMap;
489 auto verifyExtModule = [&](FExtModuleOp extModule) -> LogicalResult {
493 auto defname = extModule.getDefnameAttr();
499 if (
auto collidingModule = symtbl.lookup<FModuleOp>(defname.getValue()))
500 return extModule.emitOpError()
501 .append(
"attribute 'defname' with value ", defname,
502 " conflicts with the name of another module in the circuit")
503 .attachNote(collidingModule.getLoc())
504 .append(
"previous module declared here");
512 FExtModuleOp collidingExtModule;
513 if (
auto &value = defnameMap[defname]) {
514 collidingExtModule = value;
515 if (!value.getParameters().empty() && extModule.getParameters().empty())
525 SmallVector<PortInfo> ports = extModule.getPorts();
526 SmallVector<PortInfo> collidingPorts = collidingExtModule.getPorts();
528 if (ports.size() != collidingPorts.size())
529 return extModule.emitOpError()
530 .append(
"with 'defname' attribute ", defname,
" has ", ports.size(),
531 " ports which is different from a previously defined "
532 "extmodule with the same 'defname' which has ",
533 collidingPorts.size(),
" ports")
534 .attachNote(collidingExtModule.getLoc())
535 .append(
"previous extmodule definition occurred here");
541 for (
auto p : llvm::zip(ports, collidingPorts)) {
542 StringAttr aName = std::get<0>(p).name, bName = std::get<1>(p).name;
543 Type aType = std::get<0>(p).type, bType = std::get<1>(p).type;
546 return extModule.emitOpError()
547 .append(
"with 'defname' attribute ", defname,
548 " has a port with name ", aName,
549 " which does not match the name of the port in the same "
550 "position of a previously defined extmodule with the same "
551 "'defname', expected port to have name ",
553 .attachNote(collidingExtModule.getLoc())
554 .append(
"previous extmodule definition occurred here");
556 if (!extModule.getParameters().empty() ||
557 !collidingExtModule.getParameters().empty()) {
560 aType = base.getWidthlessType();
562 bType = base.getWidthlessType();
565 return extModule.emitOpError()
566 .append(
"with 'defname' attribute ", defname,
567 " has a port with name ", aName,
568 " which has a different type ", aType,
569 " which does not match the type of the port in the same "
570 "position of a previously defined extmodule with the same "
571 "'defname', expected port to have type ",
573 .attachNote(collidingExtModule.getLoc())
574 .append(
"previous extmodule definition occurred here");
579 SmallVector<FModuleOp, 1> dutModules;
582 if (
auto moduleOp = dyn_cast<FModuleOp>(op)) {
583 if (AnnotationSet(moduleOp).hasAnnotation(markDUTAnnoClass))
584 dutModules.push_back(moduleOp);
589 if (
auto extModule = dyn_cast<FExtModuleOp>(op)) {
590 if (verifyExtModule(extModule).failed())
596 if (dutModules.size() > 1) {
597 auto diag = dutModules[0]->emitOpError()
598 <<
"is annotated as the design-under-test (DUT), but other "
599 "modules are also annotated";
600 for (
auto moduleOp : ArrayRef(dutModules).drop_front())
601 diag.attachNote(moduleOp.getLoc()) <<
"is also annotated as the DUT";
608Block *CircuitOp::getBodyBlock() {
return &getBody().front(); }
615 SmallVector<PortInfo> results;
616 results.reserve(module.getNumPorts());
617 ArrayRef<Attribute> domains =
module.getDomainInfo();
618 for (
unsigned i = 0, e = module.getNumPorts(); i < e; ++i) {
619 results.push_back({
module.getPortNameAttr(i), module.getPortType(i),
620 module.getPortDirection(i), module.getPortSymbolAttr(i),
621 module.getPortLocation(i),
622 AnnotationSet::forPort(module, i),
623 domains.empty() ? Attribute{} : domains[i]});
628SmallVector<PortInfo> FModuleOp::getPorts() { return ::getPortImpl(*
this); }
630SmallVector<PortInfo> FExtModuleOp::getPorts() { return ::getPortImpl(*
this); }
632SmallVector<PortInfo> FIntModuleOp::getPorts() { return ::getPortImpl(*
this); }
634SmallVector<PortInfo> FMemModuleOp::getPorts() { return ::getPortImpl(*
this); }
637 if (dir == Direction::In)
639 if (dir == Direction::Out)
641 assert(0 &&
"invalid direction");
646 SmallVector<hw::PortInfo> results;
647 auto aname = StringAttr::get(module.getContext(),
648 hw::HWModuleLike::getPortSymbolAttrName());
649 auto emptyDict = DictionaryAttr::get(module.getContext());
650 for (
unsigned i = 0, e =
getNumPorts(module); i < e; ++i) {
651 auto sym =
module.getPortSymbolAttr(i);
653 {{
module.getPortNameAttr(i), module.getPortType(i),
654 dirFtoH(module.getPortDirection(i))},
656 sym ? DictionaryAttr::get(
658 ArrayRef<mlir::NamedAttribute>{NamedAttribute{aname, sym}})
660 module.getPortLocation(i)});
665SmallVector<::circt::hw::PortInfo> FModuleOp::getPortList() {
666 return ::getPortListImpl(*
this);
669SmallVector<::circt::hw::PortInfo> FExtModuleOp::getPortList() {
670 return ::getPortListImpl(*
this);
673SmallVector<::circt::hw::PortInfo> FIntModuleOp::getPortList() {
674 return ::getPortListImpl(*
this);
677SmallVector<::circt::hw::PortInfo> FMemModuleOp::getPortList() {
678 return ::getPortListImpl(*
this);
682 auto sym =
module.getPortSymbolAttr(idx);
683 auto attrs = sym ? DictionaryAttr::getWithSorted(
685 ArrayRef(mlir::NamedAttribute(
686 hw::HWModuleLike::getPortSymbolAttrName(), sym)))
687 : DictionaryAttr::get(module.getContext());
688 return {{
module.getPortNameAttr(idx), module.getPortType(idx),
689 dirFtoH(module.getPortDirection(idx))},
692 module.getPortLocation(idx)};
696 return ::getPortImpl(*
this, idx);
700 return ::getPortImpl(*
this, idx);
704 return ::getPortImpl(*
this, idx);
708 return ::getPortImpl(*
this, idx);
712BlockArgument FModuleOp::getArgument(
size_t portNumber) {
719 Attribute domainInfoAttr,
720 ArrayRef<unsigned> indexMap) {
722 auto di = dyn_cast_or_null<ArrayAttr>(domainInfoAttr);
723 if (!di || di.empty())
724 return domainInfoAttr;
727 SmallVector<Attribute> domainInfo;
728 for (
auto attr : di) {
729 auto oldIdx = cast<IntegerAttr>(attr).getUInt();
730 auto newIdx = indexMap[oldIdx];
731 if (oldIdx == newIdx)
732 domainInfo.push_back(attr);
734 domainInfo.push_back(IntegerAttr::get(
735 IntegerType::get(
context, 32, IntegerType::Unsigned), newIdx));
737 return ArrayAttr::get(
context, domainInfo);
744 ArrayRef<std::pair<unsigned, PortInfo>> ports) {
747 unsigned oldNumArgs = op.getNumPorts();
748 unsigned newNumArgs = oldNumArgs + ports.size();
751 SmallVector<unsigned> indexMap(oldNumArgs);
753 for (
size_t i = 0; i < oldNumArgs; ++i) {
754 while (inserted < ports.size() && ports[inserted].first == i)
756 indexMap[i] = i + inserted;
760 auto existingDirections = op.getPortDirectionsAttr();
761 ArrayRef<Attribute> existingNames = op.getPortNames();
762 ArrayRef<Attribute> existingTypes = op.getPortTypes();
763 ArrayRef<Attribute> existingLocs = op.getPortLocations();
764 assert(existingDirections.size() == oldNumArgs);
765 assert(existingNames.size() == oldNumArgs);
766 assert(existingTypes.size() == oldNumArgs);
767 assert(existingLocs.size() == oldNumArgs);
769 SmallVector<bool> newDirections;
770 SmallVector<Attribute> newNames, newTypes, newDomains, newAnnos, newSyms,
772 newDirections.reserve(newNumArgs);
773 newNames.reserve(newNumArgs);
774 newTypes.reserve(newNumArgs);
775 newDomains.reserve(newNumArgs);
776 newAnnos.reserve(newNumArgs);
777 newSyms.reserve(newNumArgs);
778 newLocs.reserve(newNumArgs);
780 auto emptyArray = ArrayAttr::get(op.getContext(), {});
783 auto migrateOldPorts = [&](
unsigned untilOldIdx) {
784 while (oldIdx < oldNumArgs && oldIdx < untilOldIdx) {
785 newDirections.push_back(existingDirections[oldIdx]);
786 newNames.push_back(existingNames[oldIdx]);
787 newTypes.push_back(existingTypes[oldIdx]);
789 op.getContext(), op.getDomainInfoAttrForPort(oldIdx), indexMap));
790 newAnnos.push_back(op.getAnnotationsAttrForPort(oldIdx));
791 newSyms.push_back(op.getPortSymbolAttr(oldIdx));
792 newLocs.push_back(existingLocs[oldIdx]);
797 for (
auto [idx, port] : ports) {
798 migrateOldPorts(idx);
800 newNames.push_back(port.name);
801 newTypes.push_back(TypeAttr::get(port.type));
804 port.domains ? port.domains : ArrayAttr::get(op.getContext(), {}),
806 auto annos = port.annotations.getArrayAttr();
807 newAnnos.push_back(annos ? annos : emptyArray);
808 newSyms.push_back(port.sym);
809 newLocs.push_back(port.loc);
812 migrateOldPorts(oldNumArgs);
816 if (llvm::all_of(newAnnos, [](Attribute attr) {
817 return cast<ArrayAttr>(attr).empty();
823 if (llvm::all_of(newDomains, [](Attribute attr) {
826 if (
auto arrayAttr = dyn_cast<ArrayAttr>(attr))
827 return arrayAttr.empty();
833 op->setAttr(
"portDirections",
835 op->setAttr(
"portNames", ArrayAttr::get(op.getContext(), newNames));
836 op->setAttr(
"portTypes", ArrayAttr::get(op.getContext(), newTypes));
837 op->setAttr(
"domainInfo", ArrayAttr::get(op.getContext(), newDomains));
838 op->setAttr(
"portAnnotations", ArrayAttr::get(op.getContext(), newAnnos));
839 FModuleLike::fixupPortSymsArray(newSyms, op.getContext());
840 op.setPortSymbols(newSyms);
841 op->setAttr(
"portLocations", ArrayAttr::get(op.getContext(), newLocs));
852 ArrayAttr domainInfoAttr,
853 const llvm::BitVector &portIndices,
854 bool supportsEmptyAttr) {
855 if (supportsEmptyAttr && domainInfoAttr.empty())
856 return domainInfoAttr;
859 SmallVector<unsigned> indexMap(portIndices.size());
861 for (
size_t i = 0, e = portIndices.size(); i != e; ++i) {
862 indexMap[i] = i - deleted;
869 auto getEmpty = [&]() {
871 eEmpty = ArrayAttr::get(
context, {});
876 SmallVector<Attribute> newDomainInfo;
877 newDomainInfo.reserve(portIndices.size() - portIndices.count());
878 for (
size_t i = 0, e = portIndices.size(); i != e; ++i) {
880 if (portIndices.test(i))
883 if (domainInfoAttr.empty()) {
884 newDomainInfo.push_back(getEmpty());
887 auto attr = domainInfoAttr[i];
889 auto domains = dyn_cast<ArrayAttr>(attr);
890 if (!domains || domains.empty()) {
891 newDomainInfo.push_back(attr);
895 SmallVector<Attribute> newDomains;
896 for (
auto domain : domains) {
898 auto oldIdx = cast<IntegerAttr>(domain).getUInt();
899 if (portIndices.test(oldIdx))
902 auto newIdx = indexMap[oldIdx];
903 if (oldIdx == newIdx) {
904 newDomains.push_back(domain);
908 newDomains.push_back(IntegerAttr::get(
909 IntegerType::get(
context, 32, IntegerType::Unsigned), newIdx));
911 newDomainInfo.push_back(ArrayAttr::get(
context, newDomains));
914 return ArrayAttr::get(
context, newDomainInfo);
918static void erasePorts(FModuleLike op,
const llvm::BitVector &portIndices) {
919 if (portIndices.none())
923 ArrayRef<bool> portDirections = op.getPortDirectionsAttr().asArrayRef();
924 ArrayRef<Attribute> portNames = op.getPortNames();
925 ArrayRef<Attribute> portTypes = op.getPortTypes();
926 ArrayRef<Attribute> portAnnos = op.getPortAnnotations();
927 ArrayRef<Attribute> portSyms = op.getPortSymbols();
928 ArrayRef<Attribute> portLocs = op.getPortLocations();
929 ArrayRef<Attribute> portDomains = op.getDomainInfo();
931 auto numPorts = op.getNumPorts();
933 assert(portDirections.size() == numPorts);
934 assert(portNames.size() == numPorts);
935 assert(portAnnos.size() == numPorts || portAnnos.empty());
936 assert(portTypes.size() == numPorts);
937 assert(portSyms.size() == numPorts || portSyms.empty());
938 assert(portLocs.size() == numPorts);
939 assert(portDomains.size() == numPorts || portDomains.empty());
941 SmallVector<bool> newPortDirections =
943 SmallVector<Attribute> newPortNames, newPortTypes, newPortAnnos, newPortSyms,
951 op->setAttr(
"portDirections",
953 op->setAttr(
"portNames", ArrayAttr::get(op.getContext(), newPortNames));
954 op->setAttr(
"portAnnotations", ArrayAttr::get(op.getContext(), newPortAnnos));
955 op->setAttr(
"portTypes", ArrayAttr::get(op.getContext(), newPortTypes));
956 FModuleLike::fixupPortSymsArray(newPortSyms, op.getContext());
957 op->setAttr(
"portSymbols", ArrayAttr::get(op.getContext(), newPortSyms));
958 op->setAttr(
"portLocations", ArrayAttr::get(op.getContext(), newPortLocs));
959 op->setAttr(
"domainInfo",
964void FExtModuleOp::erasePorts(
const llvm::BitVector &portIndices) {
965 ::erasePorts(cast<FModuleLike>((Operation *)*
this), portIndices);
968void FIntModuleOp::erasePorts(
const llvm::BitVector &portIndices) {
969 ::erasePorts(cast<FModuleLike>((Operation *)*
this), portIndices);
972void FMemModuleOp::erasePorts(
const llvm::BitVector &portIndices) {
973 ::erasePorts(cast<FModuleLike>((Operation *)*
this), portIndices);
976void FModuleOp::erasePorts(
const llvm::BitVector &portIndices) {
977 ::erasePorts(cast<FModuleLike>((Operation *)*
this), portIndices);
984void FModuleOp::insertPorts(ArrayRef<std::pair<unsigned, PortInfo>> ports) {
989 for (
size_t i = 0, e = ports.size(); i < e; ++i) {
992 auto &[index, port] = ports[i];
993 body->insertArgument(index + i, port.type, port.loc);
997void FExtModuleOp::insertPorts(ArrayRef<std::pair<unsigned, PortInfo>> ports) {
1001void FIntModuleOp::insertPorts(ArrayRef<std::pair<unsigned, PortInfo>> ports) {
1002 ::insertPorts(cast<FModuleLike>((Operation *)*
this), ports);
1008void FMemModuleOp::insertPorts(ArrayRef<std::pair<unsigned, PortInfo>> ports) {
1009 ::insertPorts(cast<FModuleLike>((Operation *)*
this), ports);
1012template <
typename OpTy>
1014 StringAttr name, ArrayRef<PortInfo> ports) {
1016 auto &properties = result.getOrAddProperties<
typename OpTy::Properties>();
1017 properties.setSymName(name);
1020 SmallVector<Direction, 4> portDirections;
1021 SmallVector<Attribute, 4> portNames, portTypes, portSyms, portLocs,
1023 portDirections.reserve(ports.size());
1024 portNames.reserve(ports.size());
1025 portTypes.reserve(ports.size());
1026 portSyms.reserve(ports.size());
1027 portLocs.reserve(ports.size());
1028 portDomains.reserve(ports.size());
1030 for (
const auto &port : ports) {
1031 portDirections.push_back(port.direction);
1032 portNames.push_back(port.name);
1033 portTypes.push_back(TypeAttr::get(port.type));
1034 portSyms.push_back(port.sym);
1035 portLocs.push_back(port.loc);
1036 portDomains.push_back(port.domains);
1038 if (llvm::all_of(portDomains, [](Attribute attr) {
1041 if (
auto arrayAttr = dyn_cast<ArrayAttr>(attr))
1042 return arrayAttr.empty();
1045 portDomains.clear();
1047 FModuleLike::fixupPortSymsArray(portSyms, builder.getContext());
1050 properties.setPortDirections(
1052 properties.setPortNames(builder.getArrayAttr(portNames));
1053 properties.setPortTypes(builder.getArrayAttr(portTypes));
1054 properties.setPortSymbols(builder.getArrayAttr(portSyms));
1055 properties.setPortLocations(builder.getArrayAttr(portLocs));
1056 properties.setDomainInfo(builder.getArrayAttr(portDomains));
1061template <
typename OpTy>
1063 StringAttr name, ArrayRef<PortInfo> ports,
1064 ArrayAttr annotations, ArrayAttr layers) {
1066 auto &properties = result.getOrAddProperties<
typename OpTy::Properties>();
1069 annotations = builder.getArrayAttr({});
1070 properties.setAnnotations(annotations);
1074 SmallVector<Attribute, 4> portAnnotations;
1075 for (
const auto &port : ports)
1076 portAnnotations.push_back(port.annotations.getArrayAttr());
1077 if (llvm::all_of(portAnnotations, [](Attribute attr) {
1078 return cast<ArrayAttr>(attr).empty();
1080 portAnnotations.clear();
1081 properties.setPortAnnotations(builder.getArrayAttr(portAnnotations));
1085 layers = builder.getArrayAttr({});
1086 properties.setLayers(layers);
1089template <
typename OpTy>
1090static void buildClass(OpBuilder &builder, OperationState &result,
1091 StringAttr name, ArrayRef<PortInfo> ports) {
1095void FModuleOp::build(OpBuilder &builder, OperationState &result,
1096 StringAttr name, ConventionAttr convention,
1097 ArrayRef<PortInfo> ports, ArrayAttr annotations,
1100 auto &properties = result.getOrAddProperties<Properties>();
1101 properties.setConvention(convention);
1104 auto *bodyRegion = result.regions[0].get();
1106 bodyRegion->push_back(body);
1109 for (
auto &elt : ports)
1110 body->addArgument(elt.type, elt.loc);
1113void FExtModuleOp::build(OpBuilder &builder, OperationState &result,
1114 StringAttr name, ConventionAttr convention,
1115 ArrayRef<PortInfo> ports, ArrayAttr knownLayers,
1116 StringRef defnameAttr, ArrayAttr annotations,
1117 ArrayAttr parameters, ArrayAttr layers,
1118 ArrayAttr externalRequirements) {
1120 auto &properties = result.getOrAddProperties<Properties>();
1121 properties.setConvention(convention);
1123 knownLayers = builder.getArrayAttr({});
1124 properties.setKnownLayers(knownLayers);
1125 if (!defnameAttr.empty())
1126 properties.setDefname(builder.getStringAttr(defnameAttr));
1128 parameters = builder.getArrayAttr({});
1129 properties.setParameters(parameters);
1130 if (externalRequirements)
1131 properties.setExternalRequirements(externalRequirements);
1134void FIntModuleOp::build(OpBuilder &builder, OperationState &result,
1135 StringAttr name, ArrayRef<PortInfo> ports,
1136 StringRef intrinsicNameStr, ArrayAttr annotations,
1137 ArrayAttr parameters, ArrayAttr layers) {
1139 auto &properties = result.getOrAddProperties<Properties>();
1140 properties.setIntrinsic(builder.getStringAttr(intrinsicNameStr));
1142 parameters = builder.getArrayAttr({});
1143 properties.setParameters(parameters);
1146void FMemModuleOp::build(OpBuilder &builder, OperationState &result,
1147 StringAttr name, ArrayRef<PortInfo> ports,
1148 uint32_t numReadPorts, uint32_t numWritePorts,
1149 uint32_t numReadWritePorts, uint32_t dataWidth,
1150 uint32_t maskBits, uint32_t readLatency,
1151 uint32_t writeLatency, uint64_t depth, RUWBehavior ruw,
1152 ArrayAttr annotations, ArrayAttr layers) {
1153 auto *
context = builder.getContext();
1155 auto ui32Type = IntegerType::get(
context, 32, IntegerType::Unsigned);
1156 auto ui64Type = IntegerType::get(
context, 64, IntegerType::Unsigned);
1157 auto &properties = result.getOrAddProperties<Properties>();
1158 properties.setNumReadPorts(IntegerAttr::get(ui32Type, numReadPorts));
1159 properties.setNumWritePorts(IntegerAttr::get(ui32Type, numWritePorts));
1160 properties.setNumReadWritePorts(
1161 IntegerAttr::get(ui32Type, numReadWritePorts));
1162 properties.setDataWidth(IntegerAttr::get(ui32Type, dataWidth));
1163 properties.setMaskBits(IntegerAttr::get(ui32Type, maskBits));
1164 properties.setReadLatency(IntegerAttr::get(ui32Type, readLatency));
1165 properties.setWriteLatency(IntegerAttr::get(ui32Type, writeLatency));
1166 properties.setDepth(IntegerAttr::get(ui64Type, depth));
1167 properties.setExtraPorts(ArrayAttr::get(
context, {}));
1168 properties.setRuw(RUWBehaviorAttr::get(
context, ruw));
1185 ArrayRef<Attribute> portNames, ArrayRef<Attribute> portTypes,
1186 ArrayRef<Attribute> portAnnotations,
1187 ArrayRef<Attribute> portSyms, ArrayRef<Attribute> portLocs,
1188 ArrayRef<Attribute> domainInfo) {
1191 bool printedNamesDontMatch =
false;
1193 mlir::OpPrintingFlags flags;
1196 DenseMap<unsigned, std::string> ssaNames;
1197 auto getSsaName = [&](
unsigned idx) -> StringRef {
1199 auto itr = ssaNames.find(idx);
1200 if (itr != ssaNames.end())
1201 return itr->getSecond();
1205 SmallString<32> resultNameStr;
1207 llvm::raw_svector_ostream tmpStream(resultNameStr);
1208 p.printOperand(block->getArgument(idx), tmpStream);
1211 auto portName = cast<StringAttr>(portNames[idx]).getValue();
1212 if (tmpStream.str().drop_front() != portName)
1213 printedNamesDontMatch =
true;
1214 return ssaNames.insert({idx, tmpStream.str().str()}).first->getSecond();
1217 auto name = cast<StringAttr>(portNames[idx]).getValue();
1218 return ssaNames.insert({idx, name.str()}).first->getSecond();
1224 for (
unsigned i = 0, e = portTypes.size(); i < e; ++i) {
1233 auto portType = cast<TypeAttr>(portTypes[i]).getValue();
1237 p.printKeywordOrString(getSsaName(i));
1242 p.printType(portType);
1245 if (!portSyms.empty()) {
1246 if (!cast<hw::InnerSymAttr>(portSyms[i]).
empty()) {
1248 cast<hw::InnerSymAttr>(portSyms[i]).print(p);
1256 if (!domainInfo.empty()) {
1257 auto domains = cast<ArrayAttr>(domainInfo[i]);
1258 if (!domains.empty()) {
1260 llvm::interleaveComma(domains, p, [&](Attribute attr) {
1261 p << getSsaName(cast<IntegerAttr>(attr).getUInt());
1269 if (!portAnnotations.empty() &&
1270 !cast<ArrayAttr>(portAnnotations[i]).empty()) {
1272 p.printAttribute(portAnnotations[i]);
1279 if (flags.shouldPrintDebugInfo() && !portLocs.empty())
1280 p.printOptionalLocationSpecifier(cast<LocationAttr>(portLocs[i]));
1284 return printedNamesDontMatch;
1290 OpAsmParser &parser,
bool hasSSAIdentifiers,
bool supportsSymbols,
1291 bool supportsDomains, SmallVectorImpl<OpAsmParser::Argument> &entryArgs,
1292 SmallVectorImpl<Direction> &portDirections,
1293 SmallVectorImpl<Attribute> &portNames,
1294 SmallVectorImpl<Attribute> &portTypes,
1295 SmallVectorImpl<Attribute> &portAnnotations,
1296 SmallVectorImpl<Attribute> &portSyms, SmallVectorImpl<Attribute> &portLocs,
1297 SmallVectorImpl<Attribute> &domains) {
1298 auto *
context = parser.getContext();
1301 DenseMap<Attribute, size_t> domainIndex;
1304 using DomainAndLoc = std::pair<Attribute, llvm::SMLoc>;
1305 DenseMap<size_t, SmallVector<DomainAndLoc>> domainStrings;
1307 auto parseArgument = [&]() -> ParseResult {
1309 if (succeeded(parser.parseOptionalKeyword(
"out")))
1310 portDirections.push_back(Direction::Out);
1311 else if (succeeded(parser.parseKeyword(
"in",
" or 'out'")))
1312 portDirections.push_back(Direction::In);
1319 auto portIdx = portNames.size();
1321 if (hasSSAIdentifiers) {
1322 OpAsmParser::Argument arg;
1323 if (parser.parseArgument(arg))
1325 entryArgs.push_back(arg);
1329 assert(arg.ssaName.name.size() > 1 && arg.ssaName.name[0] ==
'%' &&
1330 "Unknown MLIR name");
1331 if (
isdigit(arg.ssaName.name[1]))
1332 portNames.push_back(StringAttr::get(
context,
""));
1334 portNames.push_back(
1335 StringAttr::get(
context, arg.ssaName.name.drop_front()));
1338 irLoc = arg.ssaName.location;
1342 irLoc = parser.getCurrentLocation();
1343 std::string portName;
1344 if (parser.parseKeywordOrString(&portName))
1346 portNames.push_back(StringAttr::get(
context, portName));
1351 if (parser.parseColonType(portType))
1353 portTypes.push_back(TypeAttr::get(portType));
1354 if (isa<DomainType>(portType))
1355 domainIndex[portNames.back()] = portIdx;
1357 if (hasSSAIdentifiers)
1358 entryArgs.back().type = portType;
1361 if (supportsSymbols) {
1362 hw::InnerSymAttr innerSymAttr;
1363 if (succeeded(parser.parseOptionalKeyword(
"sym"))) {
1364 NamedAttrList dummyAttrs;
1365 if (parser.parseCustomAttributeWithFallback(
1366 innerSymAttr, ::mlir::Type{},
1368 return ::mlir::failure();
1371 portSyms.push_back(innerSymAttr);
1377 Attribute domainInfo = ArrayAttr::get(
context, {});
1378 if (supportsDomains) {
1379 if (
auto domainType = dyn_cast<DomainType>(portType)) {
1381 domainInfo = ArrayAttr::get(
context, {});
1382 }
else if (succeeded(parser.parseOptionalKeyword(
"domains"))) {
1383 auto result = parser.parseCommaSeparatedList(
1384 OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
1386 if (hasSSAIdentifiers) {
1387 OpAsmParser::Argument arg;
1388 if (parser.parseArgument(arg))
1391 StringAttr::get(
context, arg.ssaName.name.drop_front());
1393 std::string portName;
1394 if (parser.parseKeywordOrString(&portName))
1396 argName = StringAttr::get(
context, portName);
1398 domainStrings[portIdx].push_back({argName, irLoc});
1405 domainInfo =
nullptr;
1408 domains.push_back(domainInfo);
1412 auto parseResult = parser.parseOptionalAttribute(annos);
1413 if (!parseResult.has_value())
1414 annos = parser.getBuilder().getArrayAttr({});
1415 else if (failed(*parseResult))
1417 portAnnotations.push_back(annos);
1420 std::optional<Location> maybeLoc;
1421 if (failed(parser.parseOptionalLocationSpecifier(maybeLoc)))
1423 Location loc = maybeLoc ? *maybeLoc : parser.getEncodedSourceLoc(irLoc);
1424 portLocs.push_back(loc);
1425 if (hasSSAIdentifiers)
1426 entryArgs.back().sourceLoc = loc;
1435 if (failed(parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
1441 for (
auto [portIdx, domainInfo] : llvm::enumerate(domains)) {
1446 SmallVector<Attribute> portDomains;
1447 for (
auto [domainName, loc] : domainStrings[portIdx]) {
1448 auto index = domainIndex.find(domainName);
1449 if (index == domainIndex.end()) {
1450 parser.emitError(loc) <<
"domain name '" << domainName <<
"' not found";
1453 portDomains.push_back(IntegerAttr::get(
1454 IntegerType::get(
context, 32, IntegerType::Unsigned), index->second));
1456 domains[portIdx] = parser.getBuilder().getArrayAttr(portDomains);
1464 ArrayAttr parameters) {
1465 if (!parameters || parameters.empty())
1469 llvm::interleaveComma(parameters, p, [&](Attribute param) {
1470 auto paramAttr = cast<ParamDeclAttr>(param);
1471 p << paramAttr.getName().getValue() <<
": " << paramAttr.getType();
1472 if (
auto value = paramAttr.getValue()) {
1474 p.printAttributeWithoutType(value);
1480template <
typename ModuleTy>
1485 StringRef visibilityAttrName =
1486 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
1487 if (
auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
1488 p << visibility.getValue() <<
' ';
1491 p.printSymbolName(cast<mlir::SymbolOpInterface>(op.getOperation()).getName());
1498 Block *body =
nullptr;
1499 if (!op->getRegion(0).empty())
1500 body = &op->getRegion(0).front();
1503 p, body, op.getPortDirectionsAttr(), op.getPortNames(), op.getPortTypes(),
1504 op.getPortAnnotations(), op.getPortSymbols(), op.getPortLocations(),
1505 op.getDomainInfo());
1507 SmallVector<StringRef, 13> omittedAttrs = {
1508 ModuleTy::getSymNameAttrName(op->getName()),
1518 if (op.getConvention() == Convention::Internal)
1519 omittedAttrs.push_back(
"convention");
1523 if (!needPortNamesAttr)
1524 omittedAttrs.push_back(
"portNames");
1527 if (op->getAttrOfType<ArrayAttr>(
"annotations").empty())
1528 omittedAttrs.push_back(
"annotations");
1531 if (
auto knownLayers = op->getAttrOfType<ArrayAttr>(
"knownLayers"))
1532 if (knownLayers.empty())
1533 omittedAttrs.push_back(
"knownLayers");
1536 if (
auto layers = op->getAttrOfType<ArrayAttr>(
"layers"))
1538 omittedAttrs.push_back(
"layers");
1541 if (
auto extReqs = op->getAttrOfType<ArrayAttr>(
"externalRequirements"))
1542 if (extReqs.empty())
1543 omittedAttrs.push_back(
"externalRequirements");
1545 p.printOptionalAttrDictWithKeyword(op->getAttrs(), omittedAttrs);
1548void FExtModuleOp::print(OpAsmPrinter &p) {
1552void FIntModuleOp::print(OpAsmPrinter &p) {
1556void FMemModuleOp::print(OpAsmPrinter &p) {
1560void FModuleOp::print(OpAsmPrinter &p) {
1566 Region &fbody = getBody();
1567 if (!fbody.empty()) {
1569 p.printRegion(fbody,
false,
1581 SmallVectorImpl<Attribute> ¶meters) {
1583 return parser.parseCommaSeparatedList(
1584 OpAsmParser::Delimiter::OptionalLessGreater, [&]() {
1589 if (parser.parseKeywordOrString(&name) || parser.parseColonType(type))
1593 if (succeeded(parser.parseOptionalEqual())) {
1594 if (parser.parseAttribute(value, type))
1598 auto &builder = parser.getBuilder();
1599 parameters.push_back(ParamDeclAttr::get(
1600 builder.getContext(), builder.getStringAttr(name), type, value));
1607 ArrayAttr ¶meters) {
1608 SmallVector<Attribute> parseParameters;
1612 parameters = ArrayAttr::get(parser.getContext(), parseParameters);
1617template <
typename Properties,
typename =
void>
1620template <
typename Properties>
1622 Properties, std::void_t<decltype(std::declval<Properties>().parameters)>>
1623 : std::true_type {};
1625template <
typename OpTy>
1627 OperationState &result,
1628 bool hasSSAIdentifiers) {
1629 auto *
context = result.getContext();
1630 auto &builder = parser.getBuilder();
1631 using Properties =
typename OpTy::Properties;
1632 auto &properties = result.getOrAddProperties<Properties>();
1636 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
1639 StringAttr nameAttr;
1640 if (parser.parseSymbolName(nameAttr))
1642 properties.setSymName(nameAttr);
1646 SmallVector<Attribute, 4> parameters;
1649 properties.setParameters(builder.getArrayAttr(parameters));
1653 SmallVector<OpAsmParser::Argument> entryArgs;
1654 SmallVector<Direction, 4> portDirections;
1655 SmallVector<Attribute, 4> portNames;
1656 SmallVector<Attribute, 4> portTypes;
1657 SmallVector<Attribute, 4> portAnnotations;
1658 SmallVector<Attribute, 4> portSyms;
1659 SmallVector<Attribute, 4> portLocs;
1660 SmallVector<Attribute, 4> domains;
1662 true, entryArgs, portDirections,
1663 portNames, portTypes, portAnnotations, portSyms,
1668 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1671 assert(portNames.size() == portTypes.size());
1677 properties.setPortDirections(
1681 properties.setPortNames(builder.getArrayAttr(portNames));
1684 properties.setPortTypes(ArrayAttr::get(
context, portTypes));
1688 if (llvm::any_of(portAnnotations, [&](Attribute anno) {
1689 return !cast<ArrayAttr>(anno).empty();
1691 properties.setPortAnnotations(ArrayAttr::get(
context, portAnnotations));
1693 properties.setPortAnnotations(builder.getArrayAttr({}));
1696 FModuleLike::fixupPortSymsArray(portSyms, builder.getContext());
1697 properties.setPortSymbols(builder.getArrayAttr(portSyms));
1700 properties.setPortLocations(ArrayAttr::get(
context, portLocs));
1703 properties.setAnnotations(builder.getArrayAttr({}));
1706 if (llvm::all_of(domains, [&](Attribute attr) {
1707 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
1708 return arrayAttr && arrayAttr.empty();
1710 properties.setDomainInfo(ArrayAttr::get(
context, {}));
1712 properties.setDomainInfo(ArrayAttr::get(
context, domains));
1715 auto *body = result.addRegion();
1717 if (hasSSAIdentifiers) {
1718 if (parser.parseRegion(*body, entryArgs))
1721 body->push_back(
new Block());
1726ParseResult FModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1730 auto &properties = result.getOrAddProperties<Properties>();
1731 properties.setConvention(
1732 ConventionAttr::get(result.getContext(), Convention::Internal));
1733 properties.setLayers(ArrayAttr::get(parser.getContext(), {}));
1737ParseResult FExtModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1741 auto &properties = result.getOrAddProperties<Properties>();
1742 properties.setConvention(
1743 ConventionAttr::get(result.getContext(), Convention::Internal));
1744 properties.setKnownLayers(ArrayAttr::get(result.getContext(), {}));
1748ParseResult FIntModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1753ParseResult FMemModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1758LogicalResult FModuleOp::verify() {
1761 auto portTypes = getPortTypes();
1762 auto portLocs = getPortLocations();
1763 auto numPorts = portTypes.size();
1766 if (body->getNumArguments() != numPorts)
1767 return emitOpError(
"entry block must have ")
1768 << numPorts <<
" arguments to match module signature";
1771 for (
auto [arg, type, loc] : zip(body->getArguments(), portTypes, portLocs)) {
1772 if (arg.getType() != cast<TypeAttr>(type).getValue())
1773 return emitOpError(
"block argument types should match signature types");
1774 if (arg.getLoc() != cast<LocationAttr>(loc))
1776 "block argument locations should match signature locations");
1782LogicalResult FExtModuleOp::verify() {
1783 auto params = getParameters();
1785 auto checkParmValue = [&](Attribute elt) ->
bool {
1786 auto param = cast<ParamDeclAttr>(elt);
1787 auto value = param.getValue();
1788 if (isa<IntegerAttr, StringAttr, FloatAttr, hw::ParamVerbatimAttr>(value))
1790 emitError() <<
"has unknown extmodule parameter value '"
1791 << param.getName().getValue() <<
"' = " << value;
1795 if (!llvm::all_of(params, checkParmValue))
1800 known.insert_range(getKnownLayersAttr().getAsRange<SymbolRefAttr>());
1803 referenced.insert_range(getLayersAttr().getAsRange<SymbolRefAttr>());
1804 for (
auto attr : getPortTypes()) {
1805 auto type = cast<TypeAttr>(attr).getValue();
1807 if (
auto layer = refType.getLayer())
1808 referenced.insert(layer);
1812 "references unknown layers",
"unknown layers");
1815LogicalResult FIntModuleOp::verify() {
1816 auto params = getParameters();
1820 auto checkParmValue = [&](Attribute elt) ->
bool {
1821 auto param = cast<ParamDeclAttr>(elt);
1822 auto value = param.getValue();
1823 if (isa<IntegerAttr, StringAttr, FloatAttr>(value))
1825 emitError() <<
"has unknown intmodule parameter value '"
1826 << param.getName().getValue() <<
"' = " << value;
1830 if (!llvm::all_of(params, checkParmValue))
1837 CircuitOp circuitOp,
1838 SymbolTableCollection &symbolTable,
1840 auto layer = refType.getLayer();
1843 auto *layerOp = symbolTable.lookupSymbolIn(circuitOp, layer);
1845 return emitError(loc) << start <<
" associated with layer '" << layer
1846 <<
"', but this layer was not defined";
1847 if (!isa<LayerOp>(layerOp)) {
1848 auto diag = emitError(loc)
1849 << start <<
" associated with layer '" << layer
1850 <<
"', but symbol '" << layer <<
"' does not refer to a '"
1851 << LayerOp::getOperationName() <<
"' op";
1852 return diag.attachNote(layerOp->getLoc()) <<
"symbol refers to this op";
1858 SymbolTableCollection &symbolTable) {
1860 auto circuitOp =
module->getParentOfType<CircuitOp>();
1861 for (
size_t i = 0, e = module.getNumPorts(); i < e; ++i) {
1862 auto type =
module.getPortType(i);
1866 refType, module.getPortLocation(i), circuitOp, symbolTable,
1867 Twine(
"probe port '") + module.getPortName(i) +
"' is")))
1872 if (
auto classType = dyn_cast<ClassType>(type)) {
1873 auto className = classType.getNameAttr();
1874 auto classOp = dyn_cast_or_null<ClassLike>(
1875 symbolTable.lookupSymbolIn(circuitOp, className));
1877 return module.emitOpError() << "references unknown class " << className;
1880 if (failed(classOp.verifyType(classType,
1881 [&]() { return module.emitOpError(); })))
1886 if (
auto domainType = dyn_cast<DomainType>(type)) {
1888 domainType.verifySymbolUses(module.getOperation(), symbolTable)))
1897LogicalResult FModuleOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1901 auto circuitOp = getOperation()->getParentOfType<CircuitOp>();
1902 for (
auto layer : getLayers()) {
1903 if (!symbolTable.lookupSymbolIn(circuitOp, cast<SymbolRefAttr>(layer)))
1904 return emitOpError() <<
"enables undefined layer '" << layer <<
"'";
1911FExtModuleOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1915 auto circuitOp = getOperation()->getParentOfType<CircuitOp>();
1916 for (
auto layer : getKnownLayersAttr().getAsRange<SymbolRefAttr>()) {
1917 if (!symbolTable.lookupSymbolIn(circuitOp, layer))
1918 return emitOpError() <<
"knows undefined layer '" << layer <<
"'";
1920 for (
auto layer : getLayersAttr().getAsRange<SymbolRefAttr>()) {
1921 if (!symbolTable.lookupSymbolIn(circuitOp, layer))
1922 return emitOpError() <<
"enables undefined layer '" << layer <<
"'";
1929FIntModuleOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1934FMemModuleOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1938void FModuleOp::getAsmBlockArgumentNames(mlir::Region ®ion,
1943void FExtModuleOp::getAsmBlockArgumentNames(
1948StringAttr FExtModuleOp::getExtModuleNameAttr() {
1949 if (
auto defnameAttr = getDefnameAttr(); defnameAttr && !defnameAttr.empty())
1951 return getNameAttr();
1954StringRef FExtModuleOp::getExtModuleName() {
1955 if (
auto defname = getDefname(); defname && !defname->empty())
1960void FIntModuleOp::getAsmBlockArgumentNames(
1965void FMemModuleOp::getAsmBlockArgumentNames(
1970ArrayAttr FMemModuleOp::getParameters() {
return {}; }
1972ArrayAttr FModuleOp::getParameters() {
return {}; }
1974Convention FIntModuleOp::getConvention() {
return Convention::Internal; }
1976ConventionAttr FIntModuleOp::getConventionAttr() {
1977 return ConventionAttr::get(getContext(), getConvention());
1980Convention FMemModuleOp::getConvention() {
return Convention::Internal; }
1982ConventionAttr FMemModuleOp::getConventionAttr() {
1983 return ConventionAttr::get(getContext(), getConvention());
1991 ClassLike classOp, ClassType type,
1992 function_ref<InFlightDiagnostic()> emitError) {
1994 auto name = type.getNameAttr().getAttr();
1995 auto expectedName = classOp.getModuleNameAttr();
1996 if (name != expectedName)
1997 return emitError() <<
"type has wrong name, got " << name <<
", expected "
2000 auto elements = type.getElements();
2002 auto expectedNumElements = classOp.getNumPorts();
2004 return emitError() <<
"has wrong number of ports, got " <<
numElements
2005 <<
", expected " << expectedNumElements;
2007 auto portNames = classOp.getPortNames();
2008 auto portDirections = classOp.getPortDirections();
2009 auto portTypes = classOp.getPortTypes();
2012 auto element = elements[i];
2014 auto name = element.name;
2015 auto expectedName = portNames[i];
2016 if (name != expectedName)
2017 return emitError() <<
"port #" << i <<
" has wrong name, got " << name
2018 <<
", expected " << expectedName;
2021 auto expectedDirection =
Direction(portDirections[i]);
2023 return emitError() <<
"port " << name <<
" has wrong direction, got "
2027 auto type = element.type;
2028 auto expectedType = cast<TypeAttr>(portTypes[i]).getValue();
2029 if (type != expectedType)
2030 return emitError() <<
"port " << name <<
" has wrong type, got " << type
2031 <<
", expected " << expectedType;
2038 auto n = classOp.getNumPorts();
2039 SmallVector<ClassElement> elements;
2040 elements.reserve(n);
2041 for (
size_t i = 0; i < n; ++i)
2042 elements.push_back({classOp.getPortNameAttr(i), classOp.getPortType(i),
2043 classOp.getPortDirection(i)});
2044 auto name = FlatSymbolRefAttr::get(classOp.getModuleNameAttr());
2045 return ClassType::get(name, elements);
2048template <
typename OpTy>
2050 bool hasSSAIdentifiers) {
2051 auto *
context = result.getContext();
2052 auto &builder = parser.getBuilder();
2053 auto &properties = result.getOrAddProperties<
typename OpTy::Properties>();
2057 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
2060 StringAttr nameAttr;
2061 if (parser.parseSymbolName(nameAttr))
2063 properties.setSymName(nameAttr);
2066 SmallVector<OpAsmParser::Argument> entryArgs;
2067 SmallVector<Direction, 4> portDirections;
2068 SmallVector<Attribute, 4> portNames;
2069 SmallVector<Attribute, 4> portTypes;
2070 SmallVector<Attribute, 4> portAnnotations;
2071 SmallVector<Attribute, 4> portSyms;
2072 SmallVector<Attribute, 4> portLocs;
2073 SmallVector<Attribute, 4> domains;
2076 entryArgs, portDirections, portNames, portTypes,
2077 portAnnotations, portSyms, portLocs, domains))
2081 for (
auto annos : portAnnotations)
2082 if (!cast<ArrayAttr>(annos).
empty())
2086 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
2089 assert(portNames.size() == portTypes.size());
2095 properties.setPortDirections(
2099 properties.setPortNames(builder.getArrayAttr(portNames));
2102 properties.setPortTypes(builder.getArrayAttr(portTypes));
2105 FModuleLike::fixupPortSymsArray(portSyms, builder.getContext());
2106 properties.setPortSymbols(builder.getArrayAttr(portSyms));
2109 properties.setPortLocations(ArrayAttr::get(
context, portLocs));
2115 auto *bodyRegion = result.addRegion();
2117 if (hasSSAIdentifiers) {
2118 if (parser.parseRegion(*bodyRegion, entryArgs))
2120 if (bodyRegion->empty())
2121 bodyRegion->push_back(
new Block());
2127template <
typename ClassTy>
2132 StringRef visibilityAttrName =
2133 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
2134 if (
auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
2135 p << visibility.getValue() <<
' ';
2138 p.printSymbolName(cast<mlir::SymbolOpInterface>(op.getOperation()).getName());
2142 Region ®ion = op->getRegion(0);
2143 Block *body =
nullptr;
2144 if (!region.empty())
2145 body = ®ion.front();
2148 p, body, op.getPortDirectionsAttr(), op.getPortNames(), op.getPortTypes(),
2149 {}, op.getPortSymbols(), op.getPortLocations(), {});
2152 SmallVector<StringRef, 8> omittedAttrs = {
2153 ClassTy::getSymNameAttrName(op->getName()),
2164 if (!needPortNamesAttr)
2165 omittedAttrs.push_back(
"portNames");
2167 p.printOptionalAttrDictWithKeyword(op->getAttrs(), omittedAttrs);
2170 if (!region.empty()) {
2172 auto printEntryBlockArgs =
false;
2173 auto printBlockTerminators =
false;
2174 p.printRegion(region, printEntryBlockArgs, printBlockTerminators);
2182void ClassOp::build(OpBuilder &builder, OperationState &result, StringAttr name,
2183 ArrayRef<PortInfo> ports) {
2186 [](
const auto &port) {
return port.annotations.empty(); }) &&
2187 "class ports may not have annotations");
2192 auto *bodyRegion = result.regions[0].get();
2194 bodyRegion->push_back(body);
2197 for (
auto &elt : ports)
2198 body->addArgument(elt.type, elt.loc);
2201void ClassOp::build(::mlir::OpBuilder &odsBuilder,
2202 ::mlir::OperationState &odsState, Twine name,
2203 mlir::ArrayRef<mlir::StringRef> fieldNames,
2204 mlir::ArrayRef<mlir::Type> fieldTypes) {
2206 SmallVector<PortInfo, 10> ports;
2207 ports.reserve(fieldNames.size() * 2);
2208 for (
auto [fieldName, fieldType] : llvm::zip(fieldNames, fieldTypes)) {
2209 ports.emplace_back(odsBuilder.getStringAttr(fieldName +
"_in"), fieldType,
2211 ports.emplace_back(odsBuilder.getStringAttr(fieldName), fieldType,
2214 build(odsBuilder, odsState, odsBuilder.getStringAttr(name), ports);
2216 auto &body = odsState.regions[0]->getBlocks().front();
2217 auto prevLoc = odsBuilder.saveInsertionPoint();
2218 odsBuilder.setInsertionPointToEnd(&body);
2219 auto args = body.getArguments();
2220 auto loc = odsState.location;
2221 for (
unsigned i = 0, e = ports.size(); i != e; i += 2)
2222 PropAssignOp::create(odsBuilder, loc, args[i + 1], args[i]);
2224 odsBuilder.restoreInsertionPoint(prevLoc);
2226void ClassOp::print(OpAsmPrinter &p) {
2230ParseResult ClassOp::parse(OpAsmParser &parser, OperationState &result) {
2231 auto hasSSAIdentifiers =
true;
2235LogicalResult ClassOp::verify() {
2237 auto type = operand.getType();
2238 if (!isa<PropertyType>(type)) {
2239 emitOpError(
"ports on a class must be properties");
2248ClassOp::verifySymbolUses(::mlir::SymbolTableCollection &symbolTable) {
2252void ClassOp::getAsmBlockArgumentNames(mlir::Region ®ion,
2257SmallVector<PortInfo> ClassOp::getPorts() {
2258 return ::getPortImpl(cast<FModuleLike>((Operation *)*
this));
2261void ClassOp::erasePorts(
const llvm::BitVector &portIndices) {
2262 ::erasePorts(cast<FModuleLike>((Operation *)*
this), portIndices);
2266void ClassOp::insertPorts(ArrayRef<std::pair<unsigned, PortInfo>> ports) {
2267 ::insertPorts(cast<FModuleLike>((Operation *)*
this), ports);
2270Convention ClassOp::getConvention() {
return Convention::Internal; }
2272ConventionAttr ClassOp::getConventionAttr() {
2273 return ConventionAttr::get(getContext(), getConvention());
2276ArrayAttr ClassOp::getParameters() {
return {}; }
2278ArrayAttr ClassOp::getPortAnnotationsAttr() {
2279 return ArrayAttr::get(getContext(), {});
2282ArrayRef<Attribute> ClassOp::getPortAnnotations() {
return {}; }
2284void ClassOp::setPortAnnotationsAttr(ArrayAttr annotations) {
2285 llvm_unreachable(
"classes do not support annotations");
2288ArrayAttr ClassOp::getLayersAttr() {
return ArrayAttr::get(getContext(), {}); }
2290ArrayRef<Attribute> ClassOp::getLayers() {
return {}; }
2292SmallVector<::circt::hw::PortInfo> ClassOp::getPortList() {
2293 return ::getPortListImpl(*
this);
2297 return ::getPortImpl(*
this, idx);
2300BlockArgument ClassOp::getArgument(
size_t portNumber) {
2304bool ClassOp::canDiscardOnUseEmpty() {
2315void ExtClassOp::build(OpBuilder &builder, OperationState &result,
2316 StringAttr name, ArrayRef<PortInfo> ports) {
2319 [](
const auto &port) {
return port.annotations.empty(); }) &&
2320 "class ports may not have annotations");
2324void ExtClassOp::print(OpAsmPrinter &p) {
2328ParseResult ExtClassOp::parse(OpAsmParser &parser, OperationState &result) {
2329 auto hasSSAIdentifiers =
false;
2334ExtClassOp::verifySymbolUses(::mlir::SymbolTableCollection &symbolTable) {
2338void ExtClassOp::getAsmBlockArgumentNames(mlir::Region ®ion,
2343SmallVector<PortInfo> ExtClassOp::getPorts() {
2344 return ::getPortImpl(cast<FModuleLike>((Operation *)*
this));
2347void ExtClassOp::erasePorts(
const llvm::BitVector &portIndices) {
2348 ::erasePorts(cast<FModuleLike>((Operation *)*
this), portIndices);
2351void ExtClassOp::insertPorts(ArrayRef<std::pair<unsigned, PortInfo>> ports) {
2352 ::insertPorts(cast<FModuleLike>((Operation *)*
this), ports);
2355Convention ExtClassOp::getConvention() {
return Convention::Internal; }
2357ConventionAttr ExtClassOp::getConventionAttr() {
2358 return ConventionAttr::get(getContext(), getConvention());
2361ArrayAttr ExtClassOp::getLayersAttr() {
2362 return ArrayAttr::get(getContext(), {});
2365ArrayRef<Attribute> ExtClassOp::getLayers() {
return {}; }
2367ArrayAttr ExtClassOp::getParameters() {
return {}; }
2369ArrayAttr ExtClassOp::getPortAnnotationsAttr() {
2370 return ArrayAttr::get(getContext(), {});
2373ArrayRef<Attribute> ExtClassOp::getPortAnnotations() {
return {}; }
2375void ExtClassOp::setPortAnnotationsAttr(ArrayAttr annotations) {
2376 llvm_unreachable(
"classes do not support annotations");
2379SmallVector<::circt::hw::PortInfo> ExtClassOp::getPortList() {
2380 return ::getPortListImpl(*
this);
2384 return ::getPortImpl(*
this, idx);
2387bool ExtClassOp::canDiscardOnUseEmpty() {
2398void InstanceOp::build(
2399 OpBuilder &builder, OperationState &result, TypeRange resultTypes,
2400 StringRef moduleName, StringRef name, NameKindEnum nameKind,
2401 ArrayRef<Direction> portDirections, ArrayRef<Attribute> portNames,
2402 ArrayRef<Attribute> domainInfo, ArrayRef<Attribute> annotations,
2403 ArrayRef<Attribute> portAnnotations, ArrayRef<Attribute> layers,
2404 bool lowerToBind,
bool doNotPrint, StringAttr innerSym) {
2405 build(builder, result, resultTypes, moduleName, name, nameKind,
2406 portDirections, portNames, domainInfo, annotations, portAnnotations,
2407 layers, lowerToBind, doNotPrint,
2408 innerSym ? hw::InnerSymAttr::get(innerSym) : hw::InnerSymAttr());
2411void InstanceOp::build(
2412 OpBuilder &builder, OperationState &result, TypeRange resultTypes,
2413 StringRef moduleName, StringRef name, NameKindEnum nameKind,
2414 ArrayRef<Direction> portDirections, ArrayRef<Attribute> portNames,
2415 ArrayRef<Attribute> domainInfo, ArrayRef<Attribute> annotations,
2416 ArrayRef<Attribute> portAnnotations, ArrayRef<Attribute> layers,
2417 bool lowerToBind,
bool doNotPrint, hw::InnerSymAttr innerSym) {
2418 result.addTypes(resultTypes);
2419 result.getOrAddProperties<Properties>().setModuleName(
2420 SymbolRefAttr::get(builder.getContext(), moduleName));
2421 result.getOrAddProperties<Properties>().setName(builder.getStringAttr(name));
2422 result.getOrAddProperties<Properties>().setPortDirections(
2424 result.getOrAddProperties<Properties>().setPortNames(
2425 builder.getArrayAttr(portNames));
2427 if (domainInfo.empty()) {
2428 SmallVector<Attribute, 16> domainInfoVec(resultTypes.size(),
2429 builder.getArrayAttr({}));
2430 result.getOrAddProperties<Properties>().setDomainInfo(
2431 builder.getArrayAttr(domainInfoVec));
2433 assert(domainInfo.size() == resultTypes.size());
2434 result.getOrAddProperties<Properties>().setDomainInfo(
2435 builder.getArrayAttr(domainInfo));
2438 result.getOrAddProperties<Properties>().setAnnotations(
2439 builder.getArrayAttr(annotations));
2440 result.getOrAddProperties<Properties>().setLayers(
2441 builder.getArrayAttr(layers));
2443 result.getOrAddProperties<Properties>().setLowerToBind(
2444 builder.getUnitAttr());
2446 result.getOrAddProperties<Properties>().setDoNotPrint(
2447 builder.getUnitAttr());
2449 result.getOrAddProperties<Properties>().setInnerSym(innerSym);
2451 result.getOrAddProperties<Properties>().setNameKind(
2452 NameKindEnumAttr::get(builder.getContext(), nameKind));
2454 if (portAnnotations.empty()) {
2455 SmallVector<Attribute, 16> portAnnotationsVec(resultTypes.size(),
2456 builder.getArrayAttr({}));
2457 result.getOrAddProperties<Properties>().setPortAnnotations(
2458 builder.getArrayAttr(portAnnotationsVec));
2460 assert(portAnnotations.size() == resultTypes.size());
2461 result.getOrAddProperties<Properties>().setPortAnnotations(
2462 builder.getArrayAttr(portAnnotations));
2466void InstanceOp::build(OpBuilder &builder, OperationState &result,
2467 FModuleLike module, StringRef name,
2468 NameKindEnum nameKind, ArrayRef<Attribute> annotations,
2469 ArrayRef<Attribute> portAnnotations,
bool lowerToBind,
2470 bool doNotPrint, hw::InnerSymAttr innerSym) {
2473 SmallVector<Type> resultTypes;
2474 resultTypes.reserve(module.getNumPorts());
2476 module.getPortTypes(), std::back_inserter(resultTypes),
2477 [](Attribute typeAttr) { return cast<TypeAttr>(typeAttr).getValue(); });
2482 ArrayAttr portAnnotationsAttr;
2483 if (portAnnotations.empty()) {
2484 portAnnotationsAttr = builder.getArrayAttr(SmallVector<Attribute, 16>(
2485 resultTypes.size(), builder.getArrayAttr({})));
2487 portAnnotationsAttr = builder.getArrayAttr(portAnnotations);
2489 ArrayAttr domainInfoAttr =
module.getDomainInfoAttr();
2490 if (domainInfoAttr.empty()) {
2491 domainInfoAttr = builder.getArrayAttr(SmallVector<Attribute, 16>(
2492 resultTypes.size(), builder.getArrayAttr({})));
2496 builder, result, resultTypes,
2497 SymbolRefAttr::get(builder.getContext(), module.getModuleNameAttr()),
2498 builder.getStringAttr(name),
2499 NameKindEnumAttr::get(builder.getContext(), nameKind),
2500 module.getPortDirectionsAttr(), module.getPortNamesAttr(), domainInfoAttr,
2501 builder.getArrayAttr(annotations), portAnnotationsAttr,
2502 module.getLayersAttr(), lowerToBind ? builder.getUnitAttr() : UnitAttr(),
2503 doNotPrint ? builder.getUnitAttr() : UnitAttr(), innerSym);
2506void InstanceOp::build(OpBuilder &builder, OperationState &odsState,
2507 ArrayRef<PortInfo> ports, StringRef moduleName,
2508 StringRef name, NameKindEnum nameKind,
2509 ArrayRef<Attribute> annotations,
2510 ArrayRef<Attribute> layers,
bool lowerToBind,
2511 bool doNotPrint, hw::InnerSymAttr innerSym) {
2513 SmallVector<Type> newResultTypes;
2514 SmallVector<Direction> newPortDirections;
2515 SmallVector<Attribute> newPortNames, newPortAnnotations, newDomainInfo;
2516 newResultTypes.reserve(ports.size());
2517 newPortDirections.reserve(ports.size());
2518 newPortNames.reserve(ports.size());
2519 newPortAnnotations.reserve(ports.size());
2520 newDomainInfo.reserve(ports.size());
2522 for (
auto &p : ports) {
2523 newResultTypes.push_back(p.type);
2524 newPortDirections.push_back(p.direction);
2525 newPortNames.push_back(p.name);
2526 newPortAnnotations.push_back(p.annotations.getArrayAttr());
2528 newDomainInfo.push_back(p.domains);
2530 newDomainInfo.push_back(builder.getArrayAttr({}));
2533 return build(builder, odsState, newResultTypes, moduleName, name, nameKind,
2534 newPortDirections, newPortNames, newDomainInfo, annotations,
2535 newPortAnnotations, layers, lowerToBind, doNotPrint, innerSym);
2538LogicalResult InstanceOp::verify() {
2541 SmallVector<SymbolRefAttr> missingLayers;
2542 for (
auto layer : getLayersAttr().getAsRange<SymbolRefAttr>())
2544 missingLayers.push_back(layer);
2546 if (missingLayers.empty())
2550 emitOpError(
"ambient layers are insufficient to instantiate module");
2551 auto ¬e = diag.attachNote();
2552 note <<
"missing layer requirements: ";
2553 interleaveComma(missingLayers, note);
2558 Operation *op1, Operation *op2,
2559 ArrayRef<std::pair<unsigned, PortInfo>> insertions) {
2561 size_t n = insertions.size();
2562 size_t inserted = 0;
2563 for (
size_t i = 0, e = op1->getNumResults(); i < e; ++i) {
2564 while (inserted < n) {
2565 auto &[index, portInfo] = insertions[inserted];
2570 auto r1 = op1->getResult(i);
2571 auto r2 = op2->getResult(i + inserted);
2572 r1.replaceAllUsesWith(r2);
2577 const llvm::BitVector &erasures) {
2580 for (
size_t i = 0, e = op1->getNumResults(); i < e; ++i) {
2581 auto r1 = op1->getResult(i);
2583 assert(r1.use_empty() &&
"removed instance port has uses");
2587 auto r2 = op2->getResult(i - erased);
2588 r1.replaceAllUsesWith(r2);
2593InstanceOp::cloneWithErasedPorts(
const llvm::BitVector &erasures) {
2594 assert(erasures.size() >= getNumResults() &&
2595 "erasures is not at least as large as getNumResults()");
2598 SmallVector<Type>(result_type_begin(), result_type_end()), erasures);
2601 SmallVector<Attribute> newPortNames =
2603 SmallVector<Attribute> newPortAnnotations =
2605 ArrayAttr newDomainInfo =
2609 OpBuilder builder(*
this);
2610 auto clone = InstanceOp::create(
2611 builder,
getLoc(), newResultTypes, getModuleName(),
getName(),
2612 getNameKind(), newPortDirections, newPortNames, newDomainInfo.getValue(),
2613 getAnnotations().getValue(), newPortAnnotations, getLayers(),
2614 getLowerToBind(), getDoNotPrint(), getInnerSymAttr());
2616 if (
auto outputFile = (*this)->getAttr(
"output_file"))
2617 clone->setAttr(
"output_file", outputFile);
2622FInstanceLike InstanceOp::cloneWithErasedPortsAndReplaceUses(
2623 const llvm::BitVector &erasures) {
2629ArrayAttr InstanceOp::getPortAnnotation(
unsigned portIdx) {
2630 assert(portIdx < getNumResults() &&
2631 "index should be smaller than result number");
2632 return cast<ArrayAttr>(getPortAnnotations()[portIdx]);
2635void InstanceOp::setAllPortAnnotations(ArrayRef<Attribute> annotations) {
2636 assert(annotations.size() == getNumResults() &&
2637 "number of annotations is not equal to result number");
2638 (*this)->setAttr(
"portAnnotations",
2639 ArrayAttr::get(getContext(), annotations));
2642FInstanceLike InstanceOp::cloneWithInsertedPorts(
2643 ArrayRef<std::pair<unsigned, PortInfo>> insertions) {
2647 auto oldPortCount = getNumResults();
2648 auto numInsertions = insertions.size();
2649 auto newPortCount = oldPortCount + numInsertions;
2651 SmallVector<Direction> newPortDirections;
2652 SmallVector<Attribute> newPortNames;
2653 SmallVector<Type> newPortTypes;
2654 SmallVector<Attribute> newPortAnnos;
2655 SmallVector<Attribute> newDomainInfo;
2657 newPortDirections.reserve(newPortCount);
2658 newPortNames.reserve(newPortCount);
2659 newPortTypes.reserve(newPortCount);
2660 newPortAnnos.reserve(newPortCount);
2661 newDomainInfo.reserve(newPortCount);
2667 SmallVector<unsigned> indexMap(oldPortCount);
2668 size_t inserted = 0;
2669 for (
size_t i = 0; i < oldPortCount; ++i) {
2670 while (inserted < numInsertions && insertions[inserted].first <= i)
2672 indexMap[i] = i + inserted;
2677 for (
size_t i = 0; i < oldPortCount; ++i) {
2678 while (inserted < numInsertions) {
2679 auto &[index,
info] = insertions[inserted];
2685 newPortDirections.push_back(
info.direction);
2686 newPortNames.push_back(
info.name);
2687 newPortTypes.push_back(
info.type);
2688 newPortAnnos.push_back(
info.annotations.getArrayAttr());
2689 newDomainInfo.push_back(domains);
2693 newPortDirections.push_back(getPortDirection(i));
2694 newPortNames.push_back(getPortNameAttr(i));
2695 newPortTypes.push_back(getType(i));
2696 newPortAnnos.push_back(getPortAnnotation(i));
2699 newDomainInfo.push_back(domains);
2702 while (inserted < numInsertions) {
2703 auto &[index,
info] = insertions[inserted];
2706 newPortDirections.push_back(
info.direction);
2707 newPortNames.push_back(
info.name);
2708 newPortTypes.push_back(
info.type);
2709 newPortAnnos.push_back(
info.annotations.getArrayAttr());
2710 newDomainInfo.push_back(domains);
2714 OpBuilder builder(*
this);
2715 auto clone = InstanceOp::create(
2716 builder,
getLoc(), newPortTypes, getModuleName(),
getName(),
2717 getNameKind(), newPortDirections, newPortNames, newDomainInfo,
2718 getAnnotations().getValue(), newPortAnnos, getLayers(), getLowerToBind(),
2719 getDoNotPrint(), getInnerSymAttr());
2721 if (
auto outputFile = (*this)->getAttr(
"output_file"))
2722 clone->setAttr(
"output_file", outputFile);
2727FInstanceLike InstanceOp::cloneWithInsertedPortsAndReplaceUses(
2728 ArrayRef<std::pair<unsigned, PortInfo>> insertions) {
2729 auto clone = cloneWithInsertedPorts(insertions);
2734LogicalResult InstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2736 getModuleNameAttr());
2739StringRef InstanceOp::getInstanceName() {
return getName(); }
2741StringAttr InstanceOp::getInstanceNameAttr() {
return getNameAttr(); }
2743void InstanceOp::print(OpAsmPrinter &p) {
2746 p.printKeywordOrString(
getName());
2747 if (
auto attr = getInnerSymAttr()) {
2749 p.printSymbolName(attr.getSymName());
2751 if (getNameKindAttr().getValue() != NameKindEnum::DroppableName)
2752 p <<
' ' << stringifyNameKindEnum(getNameKindAttr().getValue());
2755 SmallVector<StringRef, 10> omittedAttrs = {
2756 "moduleName",
"name",
"portDirections",
2757 "portNames",
"portTypes",
"portAnnotations",
2758 "inner_sym",
"nameKind",
"domainInfo"};
2759 if (getAnnotations().
empty())
2760 omittedAttrs.push_back(
"annotations");
2761 if (getLayers().
empty())
2762 omittedAttrs.push_back(
"layers");
2763 p.printOptionalAttrDict((*this)->getAttrs(), omittedAttrs);
2767 p.printSymbolName(getModuleName());
2770 SmallVector<Attribute> portTypes;
2771 portTypes.reserve(getNumResults());
2772 llvm::transform(getResultTypes(), std::back_inserter(portTypes),
2776 getPortNames().getValue(), portTypes,
2777 getPortAnnotations().getValue(), {}, {},
2778 getDomainInfo().getValue());
2781ParseResult InstanceOp::parse(OpAsmParser &parser, OperationState &result) {
2782 auto *
context = parser.getContext();
2783 auto &properties = result.getOrAddProperties<Properties>();
2786 hw::InnerSymAttr innerSymAttr;
2787 FlatSymbolRefAttr moduleName;
2788 SmallVector<OpAsmParser::Argument> entryArgs;
2789 SmallVector<Direction, 4> portDirections;
2790 SmallVector<Attribute, 4> portNames;
2791 SmallVector<Attribute, 4> portTypes;
2792 SmallVector<Attribute, 4> portAnnotations;
2793 SmallVector<Attribute, 4> portSyms;
2794 SmallVector<Attribute, 4> portLocs;
2795 SmallVector<Attribute, 4> domains;
2796 NameKindEnumAttr nameKind;
2798 if (parser.parseKeywordOrString(&name))
2800 if (succeeded(parser.parseOptionalKeyword(
"sym"))) {
2801 if (parser.parseCustomAttributeWithFallback(
2802 innerSymAttr, ::mlir::Type{},
2804 result.attributes)) {
2805 return ::mlir::failure();
2809 parser.parseOptionalAttrDict(result.attributes) ||
2810 parser.parseAttribute(moduleName) ||
2813 entryArgs, portDirections, portNames, portTypes,
2814 portAnnotations, portSyms, portLocs, domains))
2820 properties.setModuleName(moduleName);
2821 properties.setName(StringAttr::get(
context, name));
2822 properties.setNameKind(nameKind);
2823 properties.setPortDirections(
2825 properties.setPortNames(ArrayAttr::get(
context, portNames));
2826 properties.setPortAnnotations(ArrayAttr::get(
context, portAnnotations));
2830 properties.setAnnotations(parser.getBuilder().getArrayAttr({}));
2831 properties.setLayers(parser.getBuilder().getArrayAttr({}));
2834 properties.setDomainInfo(ArrayAttr::get(
context, domains));
2837 result.types.reserve(portTypes.size());
2839 portTypes, std::back_inserter(result.types),
2840 [](Attribute typeAttr) { return cast<TypeAttr>(typeAttr).getValue(); });
2850 for (
size_t i = 0, e = (*this)->getNumResults(); i != e; ++i) {
2851 setNameFn(getResult(i), (base +
"_" + getPortName(i)).str());
2855std::optional<size_t> InstanceOp::getTargetResultIndex() {
2857 return std::nullopt;
2864void InstanceChoiceOp::build(
2865 OpBuilder &builder, OperationState &result, FModuleLike defaultModule,
2866 ArrayRef<std::pair<OptionCaseOp, FModuleLike>> cases, StringRef name,
2867 NameKindEnum nameKind, ArrayRef<Attribute> annotations,
2868 ArrayRef<Attribute> portAnnotations, StringAttr innerSym,
2869 FlatSymbolRefAttr instanceMacro) {
2871 SmallVector<Type> resultTypes;
2872 for (Attribute portType : defaultModule.getPortTypes())
2873 resultTypes.push_back(cast<TypeAttr>(portType).getValue());
2876 ArrayAttr portAnnotationsAttr;
2877 if (portAnnotations.empty()) {
2878 portAnnotationsAttr = builder.getArrayAttr(SmallVector<Attribute, 16>(
2879 resultTypes.size(), builder.getArrayAttr({})));
2881 portAnnotationsAttr = builder.getArrayAttr(portAnnotations);
2885 ArrayAttr domainInfoAttr = defaultModule.getDomainInfoAttr();
2886 if (domainInfoAttr.empty()) {
2887 domainInfoAttr = builder.getArrayAttr(SmallVector<Attribute, 16>(
2888 resultTypes.size(), builder.getArrayAttr({})));
2892 SmallVector<Attribute> moduleNames, caseNames;
2893 moduleNames.push_back(SymbolRefAttr::get(defaultModule.getModuleNameAttr()));
2894 for (
auto [caseOption, caseModule] : cases) {
2895 auto caseGroup = caseOption->getParentOfType<OptionOp>();
2896 caseNames.push_back(SymbolRefAttr::get(caseGroup.getSymNameAttr(),
2897 {SymbolRefAttr::get(caseOption)}));
2898 moduleNames.push_back(SymbolRefAttr::get(caseModule.getModuleNameAttr()));
2901 return build(builder, result, resultTypes, builder.getArrayAttr(moduleNames),
2902 builder.getArrayAttr(caseNames), builder.getStringAttr(name),
2903 NameKindEnumAttr::get(builder.getContext(), nameKind),
2904 defaultModule.getPortDirectionsAttr(),
2905 defaultModule.getPortNamesAttr(), domainInfoAttr,
2906 builder.getArrayAttr(annotations), portAnnotationsAttr,
2907 defaultModule.getLayersAttr(),
2908 innerSym ? hw::InnerSymAttr::get(innerSym) : hw::InnerSymAttr(),
2912void InstanceChoiceOp::build(OpBuilder &builder, OperationState &odsState,
2913 ArrayRef<PortInfo> ports, ArrayAttr moduleNames,
2914 ArrayAttr caseNames, StringRef name,
2915 NameKindEnum nameKind, ArrayAttr annotations,
2916 ArrayAttr layers, hw::InnerSymAttr innerSym,
2917 FlatSymbolRefAttr instanceMacro) {
2919 SmallVector<Type> newResultTypes;
2920 SmallVector<bool> newPortDirections;
2921 SmallVector<Attribute> newPortNames, newPortAnnotations, newDomainInfo;
2922 newPortDirections.reserve(ports.size());
2923 newResultTypes.reserve(ports.size());
2924 newPortAnnotations.reserve(ports.size());
2925 newDomainInfo.reserve(ports.size());
2926 newPortNames.reserve(ports.size());
2927 for (
auto &p : ports) {
2928 newResultTypes.push_back(p.type);
2930 newPortDirections.push_back(p.direction == Direction::Out);
2931 newPortNames.push_back(p.name);
2932 newPortAnnotations.push_back(p.annotations.getArrayAttr());
2934 newDomainInfo.push_back(p.domains);
2936 newDomainInfo.push_back(builder.getArrayAttr({}));
2939 return build(builder, odsState, newResultTypes, moduleNames, caseNames, name,
2940 nameKind, newPortDirections, builder.getArrayAttr(newPortNames),
2941 builder.getArrayAttr(newDomainInfo), annotations,
2942 builder.getArrayAttr(newPortAnnotations), layers.getValue(),
2943 innerSym, instanceMacro);
2946std::optional<size_t> InstanceChoiceOp::getTargetResultIndex() {
2947 return std::nullopt;
2950StringRef InstanceChoiceOp::getInstanceName() {
return getName(); }
2952StringAttr InstanceChoiceOp::getInstanceNameAttr() {
return getNameAttr(); }
2954ArrayAttr InstanceChoiceOp::getReferencedModuleNamesAttr() {
2956 auto moduleNames = getModuleNamesAttr();
2957 SmallVector<Attribute> moduleNameStrings;
2958 moduleNameStrings.reserve(moduleNames.size());
2959 for (
auto moduleName : moduleNames)
2960 moduleNameStrings.push_back(cast<FlatSymbolRefAttr>(moduleName).getAttr());
2962 return ArrayAttr::get(getContext(), moduleNameStrings);
2965void InstanceChoiceOp::print(OpAsmPrinter &p) {
2968 p.printKeywordOrString(
getName());
2969 if (
auto attr = getInnerSymAttr()) {
2971 p.printSymbolName(attr.getSymName());
2973 if (getNameKindAttr().getValue() != NameKindEnum::DroppableName)
2974 p <<
' ' << stringifyNameKindEnum(getNameKindAttr().getValue());
2977 SmallVector<StringRef, 11> omittedAttrs = {
2978 "moduleNames",
"caseNames",
"name",
2979 "portDirections",
"portNames",
"portTypes",
2980 "portAnnotations",
"inner_sym",
"nameKind",
2982 if (getAnnotations().
empty())
2983 omittedAttrs.push_back(
"annotations");
2984 if (getLayers().
empty())
2985 omittedAttrs.push_back(
"layers");
2986 p.printOptionalAttrDict((*this)->getAttrs(), omittedAttrs);
2991 auto moduleNames = getModuleNamesAttr();
2992 auto caseNames = getCaseNamesAttr();
2994 p.printSymbolName(cast<FlatSymbolRefAttr>(moduleNames[0]).getValue());
2996 p <<
" alternatives ";
2998 cast<SymbolRefAttr>(caseNames[0]).getRootReference().getValue());
3000 for (
size_t i = 0, n = caseNames.size(); i < n; ++i) {
3004 auto symbol = cast<SymbolRefAttr>(caseNames[i]);
3005 p.printSymbolName(symbol.getNestedReferences()[0].getValue());
3007 p.printSymbolName(cast<FlatSymbolRefAttr>(moduleNames[i + 1]).getValue());
3013 SmallVector<Attribute> portTypes;
3014 portTypes.reserve(getNumResults());
3015 llvm::transform(getResultTypes(), std::back_inserter(portTypes),
3018 getPortNames().getValue(), portTypes,
3019 getPortAnnotations().getValue(), {}, {},
3020 getDomainInfo().getValue());
3023ParseResult InstanceChoiceOp::parse(OpAsmParser &parser,
3024 OperationState &result) {
3025 auto *
context = parser.getContext();
3026 auto &properties = result.getOrAddProperties<Properties>();
3029 hw::InnerSymAttr innerSymAttr;
3030 SmallVector<Attribute> moduleNames;
3031 SmallVector<Attribute> caseNames;
3032 SmallVector<OpAsmParser::Argument> entryArgs;
3033 SmallVector<Direction, 4> portDirections;
3034 SmallVector<Attribute, 4> portNames;
3035 SmallVector<Attribute, 4> portTypes;
3036 SmallVector<Attribute, 4> portAnnotations;
3037 SmallVector<Attribute, 4> portSyms;
3038 SmallVector<Attribute, 4> portLocs;
3039 SmallVector<Attribute, 4> domains;
3040 NameKindEnumAttr nameKind;
3042 if (parser.parseKeywordOrString(&name))
3044 if (succeeded(parser.parseOptionalKeyword(
"sym"))) {
3045 if (parser.parseCustomAttributeWithFallback(
3046 innerSymAttr, Type{},
3048 result.attributes)) {
3053 parser.parseOptionalAttrDict(result.attributes))
3056 FlatSymbolRefAttr defaultModuleName;
3057 if (parser.parseAttribute(defaultModuleName))
3059 moduleNames.push_back(defaultModuleName);
3063 FlatSymbolRefAttr optionName;
3064 if (parser.parseKeyword(
"alternatives") ||
3065 parser.parseAttribute(optionName) || parser.parseLBrace())
3068 FlatSymbolRefAttr moduleName;
3069 StringAttr caseName;
3070 while (succeeded(parser.parseOptionalSymbolName(caseName))) {
3071 if (parser.parseArrow() || parser.parseAttribute(moduleName))
3073 moduleNames.push_back(moduleName);
3074 caseNames.push_back(SymbolRefAttr::get(
3075 optionName.getAttr(), {FlatSymbolRefAttr::get(caseName)}));
3076 if (failed(parser.parseOptionalComma()))
3079 if (parser.parseRBrace())
3085 entryArgs, portDirections, portNames, portTypes,
3086 portAnnotations, portSyms, portLocs, domains))
3091 properties.setModuleNames(ArrayAttr::get(
context, moduleNames));
3092 properties.setCaseNames(ArrayAttr::get(
context, caseNames));
3093 properties.setName(StringAttr::get(
context, name));
3094 properties.setNameKind(nameKind);
3095 properties.setPortDirections(
3097 properties.setPortNames(ArrayAttr::get(
context, portNames));
3098 properties.setDomainInfo(ArrayAttr::get(
context, domains));
3099 properties.setPortAnnotations(ArrayAttr::get(
context, portAnnotations));
3103 properties.setAnnotations(parser.getBuilder().getArrayAttr({}));
3104 properties.setLayers(parser.getBuilder().getArrayAttr({}));
3107 result.types.reserve(portTypes.size());
3109 portTypes, std::back_inserter(result.types),
3110 [](Attribute typeAttr) { return cast<TypeAttr>(typeAttr).getValue(); });
3117 for (
auto [result, name] : llvm::zip(getResults(), getPortNames()))
3118 setNameFn(result, (base +
"_" + cast<StringAttr>(name).getValue()).str());
3121LogicalResult InstanceChoiceOp::verify() {
3122 if (getCaseNamesAttr().
empty())
3123 return emitOpError() <<
"must have at least one case";
3124 if (getModuleNamesAttr().size() != getCaseNamesAttr().size() + 1)
3125 return emitOpError() <<
"number of referenced modules does not match the "
3126 "number of options";
3131 SmallVector<SymbolRefAttr> missingLayers;
3132 for (
auto layer : getLayersAttr().getAsRange<SymbolRefAttr>())
3134 missingLayers.push_back(layer);
3136 if (missingLayers.empty())
3140 emitOpError(
"ambient layers are insufficient to instantiate module");
3141 auto ¬e = diag.attachNote();
3142 note <<
"missing layer requirements: ";
3143 interleaveComma(missingLayers, note);
3148InstanceChoiceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
3149 auto caseNames = getCaseNamesAttr();
3150 for (
auto moduleName : getModuleNamesAttr()) {
3151 auto moduleNameRef = cast<FlatSymbolRefAttr>(moduleName);
3157 auto referencedModule =
3158 symbolTable.lookupNearestSymbolFrom<FModuleLike>(*
this, moduleNameRef);
3159 if (isa<FIntModuleOp>(referencedModule))
3160 return emitOpError(
"intmodule must be instantiated with instance op, "
3161 "not via 'firrtl.instance_choice'");
3164 auto root = cast<SymbolRefAttr>(caseNames[0]).getRootReference();
3165 for (
size_t i = 0, n = caseNames.size(); i < n; ++i) {
3166 auto ref = cast<SymbolRefAttr>(caseNames[i]);
3167 auto refRoot = ref.getRootReference();
3168 if (ref.getRootReference() != root)
3169 return emitOpError() <<
"case " << ref
3170 <<
" is not in the same option group as "
3173 if (!symbolTable.lookupNearestSymbolFrom<OptionOp>(*
this, refRoot))
3174 return emitOpError() <<
"option " << refRoot <<
" does not exist";
3176 if (!symbolTable.lookupNearestSymbolFrom<OptionCaseOp>(*
this, ref))
3177 return emitOpError() <<
"option " << refRoot
3178 <<
" does not contain option case " << ref;
3181 if (
auto instanceMacro = getInstanceMacroAttr())
3182 if (!symbolTable.lookupNearestSymbolFrom(*
this, instanceMacro))
3183 return emitOpError() <<
"instance_macro " << instanceMacro
3184 <<
" does not exist";
3190InstanceChoiceOp::getTargetOrDefaultAttr(OptionCaseOp option) {
3191 auto caseNames = getCaseNamesAttr();
3192 for (
size_t i = 0, n = caseNames.size(); i < n; ++i) {
3193 StringAttr caseSym = cast<SymbolRefAttr>(caseNames[i]).getLeafReference();
3194 if (caseSym == option.getSymName())
3195 return cast<FlatSymbolRefAttr>(getModuleNamesAttr()[i + 1]);
3197 return getDefaultTargetAttr();
3200SmallVector<std::pair<SymbolRefAttr, FlatSymbolRefAttr>, 1>
3201InstanceChoiceOp::getTargetChoices() {
3202 auto caseNames = getCaseNamesAttr();
3203 auto moduleNames = getModuleNamesAttr();
3204 SmallVector<std::pair<SymbolRefAttr, FlatSymbolRefAttr>, 1> choices;
3205 for (
size_t i = 0; i < caseNames.size(); ++i) {
3206 choices.emplace_back(cast<SymbolRefAttr>(caseNames[i]),
3207 cast<FlatSymbolRefAttr>(moduleNames[i + 1]));
3213FInstanceLike InstanceChoiceOp::cloneWithInsertedPorts(
3214 ArrayRef<std::pair<unsigned, PortInfo>> insertions) {
3218 auto oldPortCount = getNumResults();
3219 auto numInsertions = insertions.size();
3220 auto newPortCount = oldPortCount + numInsertions;
3222 SmallVector<Direction> newPortDirections;
3223 SmallVector<Attribute> newPortNames;
3224 SmallVector<Type> newPortTypes;
3225 SmallVector<Attribute> newPortAnnos;
3226 SmallVector<Attribute> newDomainInfo;
3228 newPortDirections.reserve(newPortCount);
3229 newPortNames.reserve(newPortCount);
3230 newPortTypes.reserve(newPortCount);
3231 newPortAnnos.reserve(newPortCount);
3232 newDomainInfo.reserve(newPortCount);
3238 SmallVector<unsigned> indexMap(oldPortCount);
3239 size_t inserted = 0;
3240 for (
size_t i = 0; i < oldPortCount; ++i) {
3241 while (inserted < numInsertions && insertions[inserted].first <= i)
3243 indexMap[i] = i + inserted;
3248 for (
size_t i = 0; i < oldPortCount; ++i) {
3249 while (inserted < numInsertions) {
3250 auto &[index,
info] = insertions[inserted];
3256 newPortDirections.push_back(
info.direction);
3257 newPortNames.push_back(
info.name);
3258 newPortTypes.push_back(
info.type);
3259 newPortAnnos.push_back(
info.annotations.getArrayAttr());
3260 newDomainInfo.push_back(domains);
3264 newPortDirections.push_back(getPortDirection(i));
3265 newPortNames.push_back(getPortNameAttr(i));
3266 newPortTypes.push_back(getType(i));
3267 newPortAnnos.push_back(getPortAnnotations()[i]);
3270 newDomainInfo.push_back(domains);
3273 while (inserted < numInsertions) {
3274 auto &[index,
info] = insertions[inserted];
3277 newPortDirections.push_back(
info.direction);
3278 newPortNames.push_back(
info.name);
3279 newPortTypes.push_back(
info.type);
3280 newPortAnnos.push_back(
info.annotations.getArrayAttr());
3281 newDomainInfo.push_back(domains);
3285 OpBuilder builder(*
this);
3286 auto clone = InstanceChoiceOp::create(
3287 builder,
getLoc(), newPortTypes, getModuleNames(), getCaseNames(),
3290 ArrayAttr::get(
context, newPortNames),
3291 ArrayAttr::get(
context, newDomainInfo), getAnnotationsAttr(),
3292 ArrayAttr::get(
context, newPortAnnos), getLayers(), getInnerSymAttr(),
3293 getInstanceMacroAttr());
3295 if (
auto outputFile = (*this)->getAttr(
"output_file"))
3296 clone->setAttr(
"output_file", outputFile);
3301FInstanceLike InstanceChoiceOp::cloneWithInsertedPortsAndReplaceUses(
3302 ArrayRef<std::pair<unsigned, PortInfo>> insertions) {
3303 auto clone = cloneWithInsertedPorts(insertions);
3309InstanceChoiceOp::cloneWithErasedPorts(
const llvm::BitVector &erasures) {
3310 assert(erasures.size() >= getNumResults() &&
3311 "erasures is not at least as large as getNumResults()");
3314 SmallVector<Type>(result_type_begin(), result_type_end()), erasures);
3317 SmallVector<Attribute> newPortNames =
3319 SmallVector<Attribute> newPortAnnotations =
3321 ArrayAttr newPortDomains =
3325 OpBuilder builder(*
this);
3326 auto clone = InstanceChoiceOp::create(
3327 builder,
getLoc(), newResultTypes, getModuleNames(), getCaseNames(),
3330 ArrayAttr::get(getContext(), newPortNames), newPortDomains,
3331 getAnnotationsAttr(), ArrayAttr::get(getContext(), newPortAnnotations),
3332 getLayers(), getInnerSymAttr(), getInstanceMacroAttr());
3334 if (
auto outputFile = (*this)->getAttr(
"output_file"))
3335 clone->setAttr(
"output_file", outputFile);
3340FInstanceLike InstanceChoiceOp::cloneWithErasedPortsAndReplaceUses(
3341 const llvm::BitVector &erasures) {
3351ArrayAttr MemOp::getPortAnnotation(
unsigned portIdx) {
3352 assert(portIdx < getNumResults() &&
3353 "index should be smaller than result number");
3354 return cast<ArrayAttr>(getPortAnnotations()[portIdx]);
3357void MemOp::setAllPortAnnotations(ArrayRef<Attribute> annotations) {
3358 assert(annotations.size() == getNumResults() &&
3359 "number of annotations is not equal to result number");
3360 (*this)->setAttr(
"portAnnotations",
3361 ArrayAttr::get(getContext(), annotations));
3365void MemOp::getNumPorts(
size_t &numReadPorts,
size_t &numWritePorts,
3366 size_t &numReadWritePorts,
size_t &numDbgsPorts) {
3369 numReadWritePorts = 0;
3371 for (
size_t i = 0, e = getNumResults(); i != e; ++i) {
3372 auto portKind = getPortKind(i);
3373 if (portKind == MemOp::PortKind::Debug)
3375 else if (portKind == MemOp::PortKind::Read)
3377 else if (portKind == MemOp::PortKind::Write) {
3380 ++numReadWritePorts;
3385LogicalResult MemOp::verify() {
3389 llvm::SmallDenseSet<Attribute, 8> portNamesSet;
3395 for (
size_t i = 0, e = getNumResults(); i != e; ++i) {
3396 auto portName = getPortNameAttr(i);
3401 BundleType portBundleType =
3405 if (!portNamesSet.insert(portName).second) {
3406 emitOpError() <<
"has non-unique port name " << portName;
3414 auto elt = getPortNamed(portName);
3416 emitOpError() <<
"could not get port with name " << portName;
3422 if (portKind == MemOp::PortKind::Debug &&
3424 return emitOpError() <<
"has an invalid type on port " << portName
3425 <<
" (expected Read/Write/ReadWrite/Debug)";
3427 return emitOpError()
3428 <<
"cannot have only one port of debug type. Debug port can only "
3429 "exist alongside other read/write/read-write port";
3434 if (portKind == MemOp::PortKind::Debug) {
3437 return emitOpError() <<
"debug ports must be a RefType of FVectorType";
3440 auto dataTypeOption = portBundleType.getElement(
"data");
3441 if (!dataTypeOption && portKind == MemOp::PortKind::ReadWrite)
3442 dataTypeOption = portBundleType.getElement(
"wdata");
3443 if (!dataTypeOption) {
3444 emitOpError() <<
"has no data field on port " << portName
3445 <<
" (expected to see \"data\" for a read or write "
3446 "port or \"rdata\" for a read/write port)";
3449 dataType = dataTypeOption->type;
3451 if (portKind == MemOp::PortKind::Read) {
3458 emitOpError() <<
"has non-passive data type on port " << portName
3459 <<
" (memory types must be passive)";
3464 if (dataType.containsAnalog()) {
3465 emitOpError() <<
"has a data type that contains an analog type on port "
3467 <<
" (memory types cannot contain analog types)";
3475 getTypeForPort(getDepth(), dataType, portKind,
3476 dataType.isGround() ? getMaskBits() : 0);
3479 auto originalType = getResult(i).getType();
3480 if (originalType != expectedType) {
3481 StringRef portKindName;
3483 case MemOp::PortKind::Read:
3484 portKindName =
"read";
3486 case MemOp::PortKind::Write:
3487 portKindName =
"write";
3489 case MemOp::PortKind::ReadWrite:
3490 portKindName =
"readwrite";
3492 case MemOp::PortKind::Debug:
3493 portKindName =
"dbg";
3496 emitOpError() <<
"has an invalid type for port " << portName
3497 <<
" of determined kind \"" << portKindName
3498 <<
"\" (expected " << expectedType <<
", but got "
3499 << originalType <<
")";
3505 if (oldDataType && oldDataType != dataType) {
3506 emitOpError() <<
"port " << getPortNameAttr(i)
3507 <<
" has a different type than port "
3508 << getPortNameAttr(i - 1) <<
" (expected " << oldDataType
3509 <<
", but got " << dataType <<
")";
3513 oldDataType = dataType;
3516 auto maskWidth = getMaskBits();
3518 auto dataWidth = getDataType().getBitWidthOrSentinel();
3519 if (dataWidth > 0 && maskWidth > (
size_t)dataWidth)
3520 return emitOpError(
"the mask width cannot be greater than "
3523 if (getPortAnnotations().size() != getNumResults())
3524 return emitOpError(
"the number of result annotations should be "
3525 "equal to the number of results");
3531 return std::max(1U, llvm::Log2_64_Ceil(depth));
3537 PortKind portKind,
size_t maskBits) {
3539 auto *
context = dataType.getContext();
3540 if (portKind == PortKind::Debug)
3541 return RefType::get(FVectorType::get(dataType, depth));
3547 maskType = UIntType::get(
context, maskBits);
3549 auto getId = [&](StringRef name) -> StringAttr {
3550 return StringAttr::get(
context, name);
3553 SmallVector<BundleType::BundleElement, 7> portFields;
3557 portFields.push_back({getId(
"addr"),
false, addressType});
3558 portFields.push_back({getId(
"en"),
false, UIntType::get(
context, 1)});
3559 portFields.push_back({getId(
"clk"),
false, ClockType::get(
context)});
3562 case PortKind::Read:
3563 portFields.push_back({getId(
"data"),
true, dataType});
3566 case PortKind::Write:
3567 portFields.push_back({getId(
"data"),
false, dataType});
3568 portFields.push_back({getId(
"mask"),
false, maskType});
3571 case PortKind::ReadWrite:
3572 portFields.push_back({getId(
"rdata"),
true, dataType});
3573 portFields.push_back({getId(
"wmode"),
false, UIntType::get(
context, 1)});
3574 portFields.push_back({getId(
"wdata"),
false, dataType});
3575 portFields.push_back({getId(
"wmask"),
false, maskType});
3578 llvm::report_fatal_error(
"memory port kind not handled");
3582 return BundleType::get(
context, portFields);
3586SmallVector<MemOp::NamedPort> MemOp::getPorts() {
3587 SmallVector<MemOp::NamedPort> result;
3589 for (
size_t i = 0, e = getNumResults(); i != e; ++i) {
3598MemOp::PortKind MemOp::getPortKind(StringRef portName) {
3604MemOp::PortKind MemOp::getPortKind(
size_t resultNo) {
3610size_t MemOp::getMaskBits() {
3612 for (
auto res : getResults()) {
3622 if (t.name.getValue().contains(
"mask"))
3635 assert(getNumResults() != 0 &&
"Mems with no read/write ports are illegal");
3641 StringRef dataFieldName =
"data";
3643 dataFieldName =
"rdata";
3646 .getElementType(dataFieldName);
3649StringAttr MemOp::getPortNameAttr(
size_t resultNo) {
3650 return cast<StringAttr>(getPortNames()[resultNo]);
3657Value MemOp::getPortNamed(StringAttr name) {
3658 auto namesArray = getPortNames();
3659 for (
size_t i = 0, e = namesArray.size(); i != e; ++i) {
3660 if (namesArray[i] == name) {
3661 assert(i < getNumResults() &&
" names array out of sync with results");
3662 return getResult(i);
3671 size_t numReadPorts = 0;
3672 size_t numWritePorts = 0;
3673 size_t numReadWritePorts = 0;
3675 SmallVector<int32_t> writeClockIDs;
3677 for (
size_t i = 0, e = op.getNumResults(); i != e; ++i) {
3678 auto portKind = op.getPortKind(i);
3679 if (portKind == MemOp::PortKind::Read)
3681 else if (portKind == MemOp::PortKind::Write) {
3682 for (
auto *a : op.getResult(i).getUsers()) {
3683 auto subfield = dyn_cast<SubfieldOp>(a);
3684 if (!subfield || subfield.getFieldIndex() != 2)
3686 auto clockPort = a->getResult(0);
3687 for (
auto *b : clockPort.getUsers()) {
3688 if (
auto connect = dyn_cast<FConnectLike>(b)) {
3689 if (
connect.getDest() == clockPort) {
3692 connect.getSrc(),
true,
true,
true),
3694 if (result.second) {
3695 writeClockIDs.push_back(numWritePorts);
3697 writeClockIDs.push_back(result.first->second);
3706 ++numReadWritePorts;
3713 op.emitError(
"'firrtl.mem' should have simple type and known width");
3714 MemoryInitAttr init = op->getAttrOfType<MemoryInitAttr>(
"init");
3716 if (op->hasAttr(
"modName"))
3717 modName = op->getAttrOfType<StringAttr>(
"modName");
3719 SmallString<8> clocks;
3720 for (
auto a : writeClockIDs)
3721 clocks.append(Twine((
char)(a +
'a')).str());
3722 SmallString<32> initStr;
3727 for (
auto c : init.getFilename().getValue())
3728 if ((c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') ||
3729 (c >=
'0' && c <=
'9'))
3730 initStr.push_back(c);
3731 initStr.push_back(
'_');
3732 initStr.push_back(init.getIsBinary() ?
't' :
'f');
3733 initStr.push_back(
'_');
3734 initStr.push_back(init.getIsInline() ?
't' :
'f');
3736 modName = StringAttr::get(
3739 "{0}FIRRTLMem_{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_{9}_{10}{11}{12}",
3740 op.getPrefix().value_or(
""), numReadPorts, numWritePorts,
3741 numReadWritePorts, (
size_t)width, op.getDepth(),
3742 op.getReadLatency(), op.getWriteLatency(), op.getMaskBits(),
3743 (
unsigned)op.getRuw(), (
unsigned)seq::WUW::PortOrder,
3744 clocks.empty() ?
"" :
"_" + clocks, init ? initStr.str() :
""));
3746 return {numReadPorts,
3751 op.getReadLatency(),
3752 op.getWriteLatency(),
3754 *seq::symbolizeRUW(
unsigned(op.getRuw())),
3755 seq::WUW::PortOrder,
3758 op.getMaskBits() > 1,
3769 for (
size_t i = 0, e = (*this)->getNumResults(); i != e; ++i) {
3770 setNameFn(getResult(i), (base +
"_" + getPortName(i)).str());
3774std::optional<size_t> MemOp::getTargetResultIndex() {
3776 return std::nullopt;
3787 setNameFn(op.getDataRaw(), name);
3788 if (op.isForceable())
3789 setNameFn(op.getDataRef(), (name +
"_ref").str());
3796LogicalResult NodeOp::inferReturnTypes(
3797 mlir::MLIRContext *
context, std::optional<mlir::Location> location,
3798 ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes,
3799 ::mlir::PropertyRef properties, ::mlir::RegionRange regions,
3800 ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes) {
3801 if (operands.empty())
3803 Adaptor adaptor(operands, attributes, properties, regions);
3804 inferredReturnTypes.push_back(adaptor.getInput().getType());
3805 if (adaptor.getForceable()) {
3807 true, adaptor.getInput().getType());
3808 if (!forceableType) {
3810 ::mlir::emitError(*location,
"cannot force a node of type ")
3811 << operands[0].getType();
3814 inferredReturnTypes.push_back(forceableType);
3819std::optional<size_t> NodeOp::getTargetResultIndex() {
return 0; }
3825std::optional<size_t> RegOp::getTargetResultIndex() {
return 0; }
3827SmallVector<std::pair<circt::FieldRef, circt::FieldRef>>
3828RegOp::computeDataFlow() {
3837 IntegerAttr initial) {
3844 return op->emitError(
3845 "'initial' value is only supported on ground-type registers");
3848 auto width = intType.getWidthOrSentinel();
3849 if (width != -1 && (
int)initial.getValue().getBitWidth() != width)
3850 return op->emitError(
"'initial' value bitwidth (")
3851 << initial.getValue().getBitWidth()
3852 <<
") doesn't match register type width (" << width <<
")";
3856 if (attrType.isSignless() || attrType.isSigned() != intType.isSigned())
3857 return op->emitError(
"'initial' value has wrong sign");
3862LogicalResult RegOp::verify() {
3866LogicalResult RegResetOp::verify() {
3867 auto reset = getResetValue();
3874 return emitError(
"type mismatch between register ")
3875 << regType <<
" and reset value " << resetType;
3880std::optional<size_t> RegResetOp::getTargetResultIndex() {
return 0; }
3891FormalOp::verifySymbolUses(mlir::SymbolTableCollection &symbolTable) {
3892 auto *op = symbolTable.lookupNearestSymbolFrom(*
this, getModuleNameAttr());
3894 return emitOpError() <<
"targets unknown module " << getModuleNameAttr();
3896 if (!isa<FModuleLike>(op)) {
3897 auto d = emitOpError() <<
"target " << getModuleNameAttr()
3898 <<
" is not a module";
3899 d.attachNote(op->getLoc()) <<
"target defined here";
3911SimulationOp::verifySymbolUses(mlir::SymbolTableCollection &symbolTable) {
3912 auto *op = symbolTable.lookupNearestSymbolFrom(*
this, getModuleNameAttr());
3914 return emitOpError() <<
"targets unknown module " << getModuleNameAttr();
3916 auto complain = [&] {
3917 auto d = emitOpError() <<
"target " << getModuleNameAttr() <<
" ";
3918 d.attachNote(op->getLoc()) <<
"target defined here";
3922 auto module = dyn_cast<FModuleLike>(op);
3924 return complain() <<
"is not a module";
3926 auto numPorts =
module.getNumPorts();
3928 return complain() <<
"must have at least 4 ports, got " << numPorts
3932 auto checkPort = [&](
unsigned idx, StringRef expName,
Direction expDir,
3933 llvm::function_ref<bool(Type)> checkType,
3934 StringRef expType) {
3935 auto name =
module.getPortNameAttr(idx);
3936 if (name != expName) {
3937 complain() <<
"port " << idx <<
" must be called \"" << expName
3938 <<
"\", got " << name <<
" instead";
3941 if (
auto dir = module.getPortDirection(idx); dir != expDir) {
3945 complain() <<
"port " << name <<
" must be " << stringify(expDir)
3946 <<
", got " << stringify(dir) <<
" instead";
3949 if (
auto type = module.getPortType(idx); !checkType(type)) {
3950 complain() <<
"port " << name <<
" must be a '!firrtl." << expType
3951 <<
"', got " << type <<
" instead";
3957 auto isClock = [](Type type) {
return isa<ClockType>(type); };
3958 auto isBool = [](Type type) {
3959 if (
auto uintType = dyn_cast<UIntType>(type))
3960 return uintType.getWidth() == 1;
3964 if (!checkPort(0,
"clock",
Direction::In, isClock,
"clock") ||
3971 for (
unsigned i = 4; i < numPorts; ++i) {
3972 auto type =
module.getPortType(i);
3975 return complain() <<
"port " << i <<
" contains hardware types: " << type;
3985LogicalResult DomainOp::verify() {
3987 SmallPtrSet<StringAttr, 4> names;
3988 for (
auto field : getFields().getAsRange<DomainFieldAttr>())
3989 if (!names.insert(field.getName()).second)
3990 return emitOpError() <<
"has duplicate field name " << field.getName();
4002SmallVector<std::pair<circt::FieldRef, circt::FieldRef>>
4003RegResetOp::computeDataFlow() {
4008std::optional<size_t> WireOp::getTargetResultIndex() {
return 0; }
4010LogicalResult WireOp::verify() {
4013 return emitOpError(
"of domain type must not have domain associations");
4016 auto domains = getDomains();
4017 if (!domains.size())
4030 using oldValueAndDiag = std::pair<Value, std::unique_ptr<InFlightDiagnostic>>;
4031 llvm::SmallMapVector<SymbolRefAttr, oldValueAndDiag, 2> domainInfo;
4032 bool hasErrors =
false;
4033 for (
auto domain : domains) {
4034 auto domainType = cast<DomainType>(domain.getType());
4035 auto domainName = domainType.getName();
4038 auto [it, inserted] =
4039 domainInfo.try_emplace(domainName, std::make_pair(domain,
nullptr));
4046 auto &[value, diag] = it->second;
4052 diag = std::make_unique<InFlightDiagnostic>(
4053 emitOpError() <<
"associated with multiple operands of '"
4054 << domainName.getValue() <<
"' kind");
4055 diag->attachNote(value.getLoc()) <<
"first domain operand here";
4060 diag->attachNote(domain.getLoc())
4061 <<
"additional colliding domain operand here";
4073 for (
auto &[_, diag] : domainInfo.values())
4079LogicalResult WireOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4082 refType,
getLoc(), getOperation()->getParentOfType<CircuitOp>(),
4083 symbolTable, Twine(
"'") + getOperationName() +
"' op is");
4086 return domainType.verifySymbolUses(getOperation(), symbolTable);
4095LogicalResult ContractOp::verify() {
4096 if (getBody().getArgumentTypes() != getInputs().getType())
4097 return emitOpError(
"result types and region argument types must match");
4106OptionCaseOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4107 auto caseMacro = getCaseMacroAttr();
4112 auto circuitOp = getOperation()->getParentOfType<CircuitOp>();
4113 auto *refOp = symbolTable.lookupSymbolIn(circuitOp, caseMacro);
4115 return emitOpError(
"case_macro references an undefined symbol: ")
4118 if (!isa<sv::MacroDeclOp>(refOp))
4119 return emitOpError(
"case_macro must reference a macro declaration");
4128void ObjectOp::build(OpBuilder &builder, OperationState &state, ClassLike klass,
4130 build(builder, state, klass.getInstanceType(),
4131 StringAttr::get(builder.getContext(), name));
4136 auto circuit =
object->getParentOfType<CircuitOp>();
4137 auto classOp = dyn_cast_or_null<ClassLike>(
4138 symbolTable.lookupSymbolIn(circuit,
object.getClassSymbolAttr()));
4140 return object->emitOpError(
"references unknown class ")
4141 <<
object.getClassSymbolAttr();
4142 return classOp.verifyType(
object.getClassType(),
4143 [&]() {
return object->emitOpError(); });
4146LogicalResult ObjectOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4150StringRef ObjectOp::getInstanceName() {
return getName(); }
4152StringAttr ObjectOp::getInstanceNameAttr() {
return getNameAttr(); }
4155 setNameFn(getResult(),
getName());
4162LogicalResult ObjectCreateOp::verify() {
4163 unsigned inputIndex = 0;
4164 for (
const auto &element : getType().getInputElements()) {
4165 if (inputIndex >= getInputs().size())
4166 return emitOpError(
"missing operand for class input ") << element.name;
4167 auto inputType = getInputs()[inputIndex].getType();
4168 if (inputType != element.type)
4169 return emitOpError(
"class input ")
4170 << element.name <<
" expects " << element.type <<
", but operand "
4171 << inputIndex <<
" has type " << inputType;
4174 if (inputIndex != getInputs().size())
4175 return emitOpError(
"expected ")
4176 << inputIndex <<
" input operands, but got " << getInputs().size();
4181ObjectCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4185StringRef ObjectCreateOp::getInstanceName() {
return getName(); }
4187StringAttr ObjectCreateOp::getInstanceNameAttr() {
return getNameAttr(); }
4190 setNameFn(getResult(),
getName());
4197LogicalResult AttachOp::verify() {
4199 std::optional<int32_t> commonWidth;
4200 for (
auto operand : getOperands()) {
4205 commonWidth = thisWidth;
4208 if (commonWidth != thisWidth)
4209 return emitOpError(
"is inavlid as not all known operand widths match");
4216 Value dst = connect->getOperand(0);
4217 Value src = connect->getOperand(1);
4226 if (isa<PropertyType>(src.getType()) ||
4230 auto diag = emitError(connect->getLoc());
4231 diag <<
"connect has invalid flow: the source expression ";
4233 diag <<
"\"" << srcName <<
"\" ";
4234 diag <<
"has " <<
toString(srcFlow) <<
", expected source or duplex flow";
4235 return diag.attachNote(srcRef.getLoc()) <<
"the source was defined here";
4243 auto diag = emitError(connect->getLoc());
4244 diag <<
"connect has invalid flow: the destination expression ";
4246 diag <<
"\"" << dstName <<
"\" ";
4247 diag <<
"has " <<
toString(dstFlow) <<
", expected sink or duplex flow";
4248 return diag.attachNote(dstRef.getLoc())
4249 <<
"the destination was defined here";
4258 bool outerTypeIsConst =
false) {
4259 auto typeIsConst = outerTypeIsConst || type.
isConst();
4265 return llvm::any_of(bundleType.getElements(), [&](
auto &element) {
4266 return isConstFieldDriven(element.type, isFlip ^ element.isFlip,
4282 auto dest = connect.getDest();
4284 auto src = connect.getSrc();
4286 if (!destType || !srcType)
4289 auto destRefinedType = destType;
4290 auto srcRefinedType = srcType;
4295 auto findFieldDeclarationRefiningFieldType =
4297 while (
auto *definingOp = value.getDefiningOp()) {
4298 bool shouldContinue =
true;
4299 TypeSwitch<Operation *>(definingOp)
4300 .Case<SubfieldOp, SubindexOp>([&](
auto op) { value = op.getInput(); })
4301 .Case<SubaccessOp>([&](SubaccessOp op) {
4305 .getElementTypePreservingConst()
4307 originalFieldType = originalFieldType.getConstType(
true);
4308 value = op.getInput();
4310 .Default([&](Operation *) { shouldContinue =
false; });
4311 if (!shouldContinue)
4317 auto destDeclaration =
4318 findFieldDeclarationRefiningFieldType(dest, destRefinedType);
4319 auto srcDeclaration =
4320 findFieldDeclarationRefiningFieldType(src, srcRefinedType);
4322 auto checkConstConditionality = [&](Value value,
FIRRTLBaseType type,
4323 Value declaration) -> LogicalResult {
4324 auto *declarationBlock = declaration.getParentBlock();
4325 auto *block = connect->getBlock();
4326 while (block && block != declarationBlock) {
4327 auto *parentOp = block->getParentOp();
4329 if (
auto whenOp = dyn_cast<WhenOp>(parentOp);
4330 whenOp && !whenOp.getCondition().getType().
isConst()) {
4332 return connect.emitOpError()
4333 <<
"assignment to 'const' type " << type
4334 <<
" is dependent on a non-'const' condition";
4335 return connect->emitOpError()
4336 <<
"assignment to nested 'const' member of type " << type
4337 <<
" is dependent on a non-'const' condition";
4340 block = parentOp->getBlock();
4345 auto emitSubaccessError = [&] {
4346 return connect.emitError(
4347 "assignment to non-'const' subaccess of 'const' type is disallowed");
4353 if (destType != destRefinedType)
4354 return emitSubaccessError();
4356 if (failed(checkConstConditionality(dest, destType, destDeclaration)))
4361 if (srcRefinedType.containsConst() &&
4364 if (srcType != srcRefinedType)
4365 return emitSubaccessError();
4366 if (failed(checkConstConditionality(src, srcType, srcDeclaration)))
4383 auto dest = connect.getDest();
4384 for (
auto *user : dest.getUsers()) {
4385 if (
auto c = dyn_cast<FConnectLike>(user);
4386 c && c.getDest() == dest && c != connect) {
4387 auto diag = connect.emitError(
"destination cannot be driven by multiple "
4389 diag.attachNote(c->getLoc()) <<
"other driver is here";
4396LogicalResult ConnectOp::verify() {
4397 auto dstType = getDest().getType();
4398 auto srcType = getSrc().getType();
4401 if (!dstBaseType || !srcBaseType) {
4402 if (dstType != srcType)
4403 return emitError(
"may not connect different non-base types");
4406 if (dstBaseType.containsAnalog() || srcBaseType.containsAnalog())
4407 return emitError(
"analog types may not be connected");
4411 return emitError(
"type mismatch between destination ")
4412 << dstBaseType <<
" and source " << srcBaseType;
4417 return emitError(
"destination ")
4418 << dstBaseType <<
" is not as wide as the source " << srcBaseType;
4431LogicalResult MatchingConnectOp::verify() {
4436 if (baseType && baseType.containsAnalog())
4437 return emitError(
"analog types may not be connected");
4442 "`SameAnonTypeOperands` trait should have already rejected "
4443 "structurally non-equivalent types");
4456LogicalResult RefDefineOp::verify() {
4463 if (
auto *op = getDest().getDefiningOp()) {
4465 if (isa<RefSubOp>(op))
4467 "destination reference cannot be a sub-element of a reference");
4468 if (isa<RefCastOp>(op))
4470 "destination reference cannot be a cast of another reference");
4478 SmallVector<SymbolRefAttr> missingLayers;
4481 "has more layer requirements than destination",
4482 "additional layers required");
4485LogicalResult PropAssignOp::verify() {
4495LogicalResult PropertyAssertOp::verify() {
4498 if (
auto *defOp = getCondition().getDefiningOp())
4499 if (
auto boolConst = dyn_cast<BoolConstantOp>(defOp))
4500 if (!boolConst.getValue())
4501 return emitOpError(
"property assertion is statically false");
4506 auto domainType = dyn_cast<DomainType>(value.getType());
4511 return domainType.getName();
4514LogicalResult DomainDefineOp::verify() {
4521 auto dst = getDest();
4522 auto src = getSrc();
4530 if (
auto *srcDefOp = src.getDefiningOp())
4531 if (isa<WireOp>(srcDefOp))
4533 if (
auto *dstDefOp = dst.getDefiningOp())
4534 if (isa<WireOp>(dstDefOp))
4539 return emitError(
"could not determine domain-type of destination");
4543 return emitError(
"could not determine domain-type of source");
4545 if (dstDomain != srcDomain) {
4546 auto diag = emitError()
4547 <<
"source domain type " << srcDomain
4548 <<
" does not match destination domain type " << dstDomain;
4555void WhenOp::createElseRegion() {
4556 assert(!hasElseRegion() &&
"already has an else region");
4557 getElseRegion().push_back(
new Block());
4560void WhenOp::build(OpBuilder &builder, OperationState &result, Value condition,
4561 bool withElseRegion, std::function<
void()> thenCtor,
4562 std::function<
void()> elseCtor) {
4563 OpBuilder::InsertionGuard guard(builder);
4564 result.addOperands(condition);
4567 builder.createBlock(result.addRegion());
4572 Region *elseRegion = result.addRegion();
4573 if (withElseRegion) {
4574 builder.createBlock(elseRegion);
4584LogicalResult MatchOp::verify() {
4585 FEnumType type = getInput().getType();
4588 auto numCases = getTags().size();
4589 auto numRegions = getNumRegions();
4590 if (numRegions != numCases)
4591 return emitOpError(
"expected ")
4592 << numRegions <<
" tags but got " << numCases;
4594 auto numTags = type.getNumElements();
4596 SmallDenseSet<int64_t> seen;
4597 for (
const auto &[tag, region] : llvm::zip(getTags(), getRegions())) {
4598 auto tagIndex = size_t(cast<IntegerAttr>(tag).
getInt());
4601 if (region.getNumArguments() != 1)
4602 return emitOpError(
"region should have exactly one argument");
4605 if (tagIndex >= numTags)
4606 return emitOpError(
"the tag index ")
4607 << tagIndex <<
" is out of the range of valid tags in " << type;
4610 auto [it, inserted] = seen.insert(tagIndex);
4612 return emitOpError(
"the tag ") << type.getElementNameAttr(tagIndex)
4613 <<
" is matched more than once";
4616 auto expectedType = type.getElementTypePreservingConst(tagIndex);
4617 auto regionType = region.getArgument(0).getType();
4618 if (regionType != expectedType)
4619 return emitOpError(
"region type ")
4620 << regionType <<
" does not match the expected type "
4625 for (
size_t i = 0, e = type.getNumElements(); i < e; ++i)
4626 if (!seen.contains(i))
4627 return emitOpError(
"missing case for tag ") << type.getElementNameAttr(i);
4632void MatchOp::print(OpAsmPrinter &p) {
4633 auto input = getInput();
4634 FEnumType type = input.getType();
4635 auto regions = getRegions();
4636 p <<
" " << input <<
" : " << type;
4637 SmallVector<StringRef> elided = {
"tags"};
4638 p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), elided);
4641 for (
const auto &[tag, region] : llvm::zip(getTags(), regions)) {
4644 p.printKeywordOrString(
4645 type.getElementName(cast<IntegerAttr>(tag).getInt()));
4647 p.printRegionArgument(region.front().getArgument(0), {},
4650 p.printRegion(region,
false);
4657ParseResult MatchOp::parse(OpAsmParser &parser, OperationState &result) {
4658 auto *
context = parser.getContext();
4659 auto &properties = result.getOrAddProperties<Properties>();
4660 OpAsmParser::UnresolvedOperand input;
4661 if (parser.parseOperand(input) || parser.parseColon())
4664 auto loc = parser.getCurrentLocation();
4666 if (parser.parseType(type))
4670 return parser.emitError(loc,
"expected enumeration type but got") << type;
4672 if (parser.resolveOperand(input, type, result.operands) ||
4673 parser.parseOptionalAttrDictWithKeyword(result.attributes) ||
4674 parser.parseLBrace())
4677 auto i32Type = IntegerType::get(
context, 32);
4678 SmallVector<Attribute> tags;
4681 if (failed(parser.parseOptionalKeyword(
"case")))
4685 auto nameLoc = parser.getCurrentLocation();
4687 OpAsmParser::Argument arg;
4688 auto *region = result.addRegion();
4689 if (parser.parseKeywordOrString(&name) || parser.parseLParen() ||
4690 parser.parseArgument(arg) || parser.parseRParen())
4694 auto index = enumType.getElementIndex(name);
4696 return parser.emitError(nameLoc,
"the tag \"")
4697 << name <<
"\" is not a member of the enumeration " << enumType;
4698 tags.push_back(IntegerAttr::get(i32Type, *index));
4701 arg.type = enumType.getElementTypePreservingConst(*index);
4702 if (parser.parseRegion(*region, arg))
4705 properties.setTags(ArrayAttr::get(
context, tags));
4707 return parser.parseRBrace();
4710void MatchOp::build(OpBuilder &builder, OperationState &result, Value input,
4712 MutableArrayRef<std::unique_ptr<Region>> regions) {
4713 auto &properties = result.getOrAddProperties<Properties>();
4714 result.addOperands(input);
4715 properties.setTags(tags);
4716 result.addRegions(regions);
4725 struct IsExprClassifier :
public ExprVisitor<IsExprClassifier, bool> {
4726 bool visitInvalidExpr(Operation *op) {
return false; }
4727 bool visitUnhandledExpr(Operation *op) {
return true; }
4737 const char *base = ty.isSigned() ?
"invalid_si" :
"invalid_ui";
4738 auto width = ty.getWidthOrSentinel();
4742 name = (Twine(base) + Twine(width)).str();
4744 auto width = ty.getWidthOrSentinel();
4746 name =
"invalid_analog";
4748 name = (
"invalid_analog" + Twine(width)).str();
4750 name =
"invalid_asyncreset";
4752 name =
"invalid_reset";
4754 name =
"invalid_clock";
4758 setNameFn(getResult(), name);
4761void ConstantOp::print(OpAsmPrinter &p) {
4763 p.printAttributeWithoutType(getValueAttr());
4765 p.printType(getType());
4766 p.printOptionalAttrDict((*this)->getAttrs(), {
"value"});
4769ParseResult ConstantOp::parse(OpAsmParser &parser, OperationState &result) {
4770 auto &properties = result.getOrAddProperties<Properties>();
4773 auto loc = parser.getCurrentLocation();
4774 auto valueResult = parser.parseOptionalInteger(value);
4775 if (!valueResult.has_value())
4776 return parser.emitError(loc,
"expected integer value");
4780 if (failed(*valueResult) || parser.parseColonType(resultType) ||
4781 parser.parseOptionalAttrDict(result.attributes))
4783 result.addTypes(resultType);
4789 if (width > value.getBitWidth()) {
4793 value = value.sext(width);
4794 }
else if (width < value.getBitWidth()) {
4797 unsigned neededBits = value.isNegative() ? value.getSignificantBits()
4798 : value.getActiveBits();
4799 if (width < neededBits)
4800 return parser.emitError(loc,
"constant out of range for result type ")
4802 value = value.trunc(width);
4806 auto intType = parser.getBuilder().getIntegerType(value.getBitWidth(),
4808 auto valueAttr = parser.getBuilder().getIntegerAttr(intType, value);
4809 properties.setValue(valueAttr);
4813LogicalResult ConstantOp::verify() {
4817 if (width != -1 && (
int)getValue().
getBitWidth() != width)
4819 "firrtl.constant attribute bitwidth doesn't match return type");
4823 if (attrType.isSignless() || attrType.isSigned() != intType.
isSigned())
4824 return emitError(
"firrtl.constant attribute has wrong sign");
4831void ConstantOp::build(OpBuilder &builder, OperationState &result,
IntType type,
4832 const APInt &value) {
4835 assert((width == -1 || (int32_t)value.getBitWidth() == width) &&
4836 "incorrect attribute bitwidth for firrtl.constant");
4839 IntegerAttr::get(type.getContext(), APSInt(value, !type.
isSigned()));
4840 return build(builder, result, type, attr);
4845void ConstantOp::build(OpBuilder &builder, OperationState &result,
4846 const APSInt &value) {
4847 auto attr = IntegerAttr::get(builder.getContext(), value);
4849 IntType::get(builder.getContext(), value.isSigned(), value.getBitWidth());
4850 return build(builder, result, type, attr);
4860 SmallString<32> specialNameBuffer;
4861 llvm::raw_svector_ostream specialName(specialNameBuffer);
4863 getValue().print(specialName, intTy.
isSigned());
4865 specialName << (intTy.
isSigned() ?
"_si" :
"_ui");
4868 specialName << width;
4869 setNameFn(getResult(), specialName.str());
4872void SpecialConstantOp::print(OpAsmPrinter &p) {
4875 p << static_cast<unsigned>(getValue());
4877 p.printType(getType());
4878 p.printOptionalAttrDict((*this)->getAttrs(), {
"value"});
4881ParseResult SpecialConstantOp::parse(OpAsmParser &parser,
4882 OperationState &result) {
4883 auto &properties = result.getOrAddProperties<Properties>();
4887 auto loc = parser.getCurrentLocation();
4888 auto valueResult = parser.parseOptionalInteger(value);
4889 if (!valueResult.has_value())
4890 return parser.emitError(loc,
"expected integer value");
4893 if (value != 0 && value != 1)
4894 return parser.emitError(loc,
"special constants can only be 0 or 1.");
4898 if (failed(*valueResult) || parser.parseColonType(resultType) ||
4899 parser.parseOptionalAttrDict(result.attributes))
4901 result.addTypes(resultType);
4904 auto valueAttr = parser.getBuilder().getBoolAttr(value == 1);
4905 properties.setValue(valueAttr);
4910 SmallString<32> specialNameBuffer;
4911 llvm::raw_svector_ostream specialName(specialNameBuffer);
4913 specialName << static_cast<unsigned>(getValue());
4914 auto type = getType();
4916 specialName <<
"_clock";
4918 specialName <<
"_reset";
4920 specialName <<
"_asyncreset";
4922 setNameFn(getResult(), specialName.str());
4929 if (type.isGround()) {
4930 if (!isa<IntegerAttr>(attr)) {
4931 op->emitOpError(
"Ground type is not an integer attribute");
4936 auto attrlist = dyn_cast<ArrayAttr>(attr);
4938 op->emitOpError(
"expected array attribute for aggregate constant");
4942 if (array.getNumElements() != attrlist.size()) {
4943 op->emitOpError(
"array attribute (")
4944 << attrlist.size() <<
") has wrong size for vector constant ("
4945 << array.getNumElements() <<
")";
4948 return llvm::all_of(attrlist, [&array, op](Attribute attr) {
4953 if (bundle.getNumElements() != attrlist.size()) {
4954 op->emitOpError(
"array attribute (")
4955 << attrlist.size() <<
") has wrong size for bundle constant ("
4956 << bundle.getNumElements() <<
")";
4959 for (
size_t i = 0; i < bundle.getNumElements(); ++i) {
4960 if (bundle.getElement(i).isFlip) {
4961 op->emitOpError(
"Cannot have constant bundle type with flip");
4969 op->emitOpError(
"Unknown aggregate type");
4973LogicalResult AggregateConstantOp::verify() {
4979Attribute AggregateConstantOp::getAttributeFromFieldID(uint64_t fieldID) {
4981 Attribute value = getFields();
4982 while (fieldID != 0) {
4984 auto index = bundle.getIndexForFieldID(fieldID);
4985 fieldID -= bundle.getFieldID(index);
4986 type = bundle.getElementType(index);
4987 value = cast<ArrayAttr>(value)[index];
4990 auto index = vector.getIndexForFieldID(fieldID);
4991 fieldID -= vector.getFieldID(index);
4992 type = vector.getElementType();
4993 value = cast<ArrayAttr>(value)[index];
4999LogicalResult FIntegerConstantOp::verify() {
5000 auto i = getValueAttr();
5001 if (!i.getType().isSignedInteger())
5002 return emitOpError(
"value must be signed");
5006void FIntegerConstantOp::print(OpAsmPrinter &p) {
5008 p.printAttributeWithoutType(getValueAttr());
5009 p.printOptionalAttrDict((*this)->getAttrs(), {
"value"});
5012ParseResult FIntegerConstantOp::parse(OpAsmParser &parser,
5013 OperationState &result) {
5014 auto *
context = parser.getContext();
5015 auto &properties = result.getOrAddProperties<Properties>();
5017 if (parser.parseInteger(value) ||
5018 parser.parseOptionalAttrDict(result.attributes))
5020 result.addTypes(FIntegerType::get(
context));
5022 IntegerType::get(
context, value.getBitWidth(), IntegerType::Signed);
5023 auto valueAttr = parser.getBuilder().getIntegerAttr(intType, value);
5024 properties.setValue(valueAttr);
5028ParseResult ListCreateOp::parse(OpAsmParser &parser, OperationState &result) {
5029 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
5032 if (parser.parseOperandList(operands) ||
5033 parser.parseOptionalAttrDict(result.attributes) ||
5034 parser.parseColonType(type))
5036 result.addTypes(type);
5038 return parser.resolveOperands(operands, type.getElementType(),
5042void ListCreateOp::print(OpAsmPrinter &p) {
5044 p.printOperands(getElements());
5045 p.printOptionalAttrDict((*this)->getAttrs());
5046 p <<
" : " << getType();
5049LogicalResult ListCreateOp::verify() {
5050 if (getElements().
empty())
5053 auto elementType = getElements().front().getType();
5054 auto listElementType = getType().getElementType();
5056 return emitOpError(
"has elements of type ")
5057 <<
elementType <<
" instead of " << listElementType;
5062LogicalResult BundleCreateOp::verify() {
5063 BundleType resultType = getType();
5064 if (resultType.getNumElements() != getFields().size())
5065 return emitOpError(
"number of fields doesn't match type");
5066 for (
size_t i = 0; i < resultType.getNumElements(); ++i)
5068 resultType.getElementTypePreservingConst(i),
5070 return emitOpError(
"type of element doesn't match bundle for field ")
5071 << resultType.getElement(i).name;
5076LogicalResult VectorCreateOp::verify() {
5077 FVectorType resultType = getType();
5078 if (resultType.getNumElements() != getFields().size())
5079 return emitOpError(
"number of fields doesn't match type");
5080 auto elemTy = resultType.getElementTypePreservingConst();
5081 for (
size_t i = 0; i < resultType.getNumElements(); ++i)
5084 return emitOpError(
"type of element doesn't match vector element");
5090UnknownValueOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
5092 auto classType = dyn_cast<ClassType>(getType());
5096 auto className = classType.getNameAttr();
5098 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, className);
5100 return emitOpError() <<
"refers to non-existent class ("
5101 << className.getAttr() <<
")";
5104 if (!isa<ClassLike>(op))
5105 return emitOpError() <<
"refers to a non-class type ("
5106 << className.getAttr() <<
")";
5115LogicalResult FEnumCreateOp::verify() {
5116 FEnumType resultType = getResult().getType();
5117 auto elementIndex = resultType.getElementIndex(
getFieldName());
5119 return emitOpError(
"label ")
5120 <<
getFieldName() <<
" is not a member of the enumeration type "
5123 resultType.getElementTypePreservingConst(*elementIndex),
5124 getInput().getType()))
5125 return emitOpError(
"type of element doesn't match enum element");
5129void FEnumCreateOp::print(OpAsmPrinter &printer) {
5132 printer <<
'(' << getInput() <<
')';
5133 SmallVector<StringRef> elidedAttrs = {
"fieldIndex"};
5134 printer.printOptionalAttrDictWithKeyword((*this)->getAttrs(), elidedAttrs);
5136 printer.printFunctionalType(ArrayRef<Type>{getInput().getType()},
5137 ArrayRef<Type>{getResult().getType()});
5140ParseResult FEnumCreateOp::parse(OpAsmParser &parser, OperationState &result) {
5141 auto *
context = parser.getContext();
5142 auto &properties = result.getOrAddProperties<Properties>();
5144 OpAsmParser::UnresolvedOperand input;
5145 std::string fieldName;
5146 mlir::FunctionType functionType;
5147 if (parser.parseKeywordOrString(&fieldName) || parser.parseLParen() ||
5148 parser.parseOperand(input) || parser.parseRParen() ||
5149 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
5150 parser.parseType(functionType))
5153 if (functionType.getNumInputs() != 1)
5154 return parser.emitError(parser.getNameLoc(),
"single input type required");
5155 if (functionType.getNumResults() != 1)
5156 return parser.emitError(parser.getNameLoc(),
"single result type required");
5158 auto inputType = functionType.getInput(0);
5159 if (parser.resolveOperand(input, inputType, result.operands))
5162 auto outputType = functionType.getResult(0);
5165 return parser.emitError(parser.getNameLoc(),
5166 "output must be enum type, got ")
5168 auto fieldIndex = enumType.getElementIndex(fieldName);
5170 return parser.emitError(parser.getNameLoc(),
5171 "unknown field " + fieldName +
" in enum type ")
5174 properties.setFieldIndex(
5175 IntegerAttr::get(IntegerType::get(
context, 32), *fieldIndex));
5177 result.addTypes(enumType);
5186LogicalResult IsTagOp::verify() {
5187 if (getFieldIndex() >= getInput().getType().base().getNumElements())
5188 return emitOpError(
"element index is greater than the number of fields in "
5193void IsTagOp::print(::mlir::OpAsmPrinter &printer) {
5194 printer <<
' ' << getInput() <<
' ';
5196 SmallVector<::llvm::StringRef, 1> elidedAttrs = {
"fieldIndex"};
5197 printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
5198 printer <<
" : " << getInput().getType();
5201ParseResult IsTagOp::parse(OpAsmParser &parser, OperationState &result) {
5202 auto *
context = parser.getContext();
5203 auto &properties = result.getOrAddProperties<Properties>();
5205 OpAsmParser::UnresolvedOperand input;
5206 std::string fieldName;
5208 if (parser.parseOperand(input) || parser.parseKeywordOrString(&fieldName) ||
5209 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
5210 parser.parseType(inputType))
5213 if (parser.resolveOperand(input, inputType, result.operands))
5218 return parser.emitError(parser.getNameLoc(),
5219 "input must be enum type, got ")
5221 auto fieldIndex = enumType.getElementIndex(fieldName);
5223 return parser.emitError(parser.getNameLoc(),
5224 "unknown field " + fieldName +
" in enum type ")
5227 properties.setFieldIndex(
5228 IntegerAttr::get(IntegerType::get(
context, 32), *fieldIndex));
5230 result.addTypes(UIntType::get(
context, 1,
false));
5235FIRRTLType IsTagOp::inferReturnType(ValueRange operands, DictionaryAttr
attrs,
5236 PropertyRef properties,
5237 mlir::RegionRange regions,
5238 std::optional<Location> loc) {
5239 Adaptor adaptor(operands,
attrs, properties, regions);
5240 return UIntType::get(
attrs.getContext(), 1,
5241 isConst(adaptor.getInput().getType()));
5244template <
typename OpTy>
5246 auto *
context = parser.getContext();
5248 OpAsmParser::UnresolvedOperand input;
5249 std::string fieldName;
5251 if (parser.parseOperand(input) || parser.parseLSquare() ||
5252 parser.parseKeywordOrString(&fieldName) || parser.parseRSquare() ||
5253 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
5254 parser.parseType(inputType))
5257 if (parser.resolveOperand(input, inputType, result.operands))
5262 return parser.emitError(parser.getNameLoc(),
5263 "input must be bundle type, got ")
5265 auto fieldIndex = bundleType.getElementIndex(fieldName);
5267 return parser.emitError(parser.getNameLoc(),
5268 "unknown field " + fieldName +
" in bundle type ")
5271 result.getOrAddProperties<
typename OpTy::Properties>().setFieldIndex(
5272 IntegerAttr::get(IntegerType::get(
context, 32), *fieldIndex));
5274 auto type = OpTy::inferReturnType(inputType, *fieldIndex, {});
5277 result.addTypes(type);
5282ParseResult SubtagOp::parse(OpAsmParser &parser, OperationState &result) {
5283 auto *
context = parser.getContext();
5285 OpAsmParser::UnresolvedOperand input;
5286 std::string fieldName;
5288 if (parser.parseOperand(input) || parser.parseLSquare() ||
5289 parser.parseKeywordOrString(&fieldName) || parser.parseRSquare() ||
5290 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
5291 parser.parseType(inputType))
5294 if (parser.resolveOperand(input, inputType, result.operands))
5299 return parser.emitError(parser.getNameLoc(),
5300 "input must be enum type, got ")
5302 auto fieldIndex = enumType.getElementIndex(fieldName);
5304 return parser.emitError(parser.getNameLoc(),
5305 "unknown field " + fieldName +
" in enum type ")
5308 result.getOrAddProperties<Properties>().setFieldIndex(
5309 IntegerAttr::get(IntegerType::get(
context, 32), *fieldIndex));
5311 SmallVector<Type> inferredReturnTypes;
5312 if (failed(SubtagOp::inferReturnTypes(
5313 context, result.location, result.operands,
5314 result.attributes.getDictionary(
context), result.getRawProperties(),
5315 result.regions, inferredReturnTypes)))
5317 result.addTypes(inferredReturnTypes);
5322ParseResult SubfieldOp::parse(OpAsmParser &parser, OperationState &result) {
5325ParseResult OpenSubfieldOp::parse(OpAsmParser &parser, OperationState &result) {
5329template <
typename OpTy>
5331 printer <<
' ' << op.getInput() <<
'[';
5332 printer.printKeywordOrString(op.getFieldName());
5334 ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs;
5335 elidedAttrs.push_back(
"fieldIndex");
5336 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
5337 printer <<
" : " << op.getInput().getType();
5339void SubfieldOp::print(::mlir::OpAsmPrinter &printer) {
5342void OpenSubfieldOp::print(::mlir::OpAsmPrinter &printer) {
5346void SubtagOp::print(::mlir::OpAsmPrinter &printer) {
5347 printer <<
' ' << getInput() <<
'[';
5350 ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs;
5351 elidedAttrs.push_back(
"fieldIndex");
5352 printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
5353 printer <<
" : " << getInput().getType();
5356template <
typename OpTy>
5358 if (op.getFieldIndex() >=
5361 return op.emitOpError(
"subfield element index is greater than the number "
5362 "of fields in the bundle type");
5365LogicalResult SubfieldOp::verify() {
5368LogicalResult OpenSubfieldOp::verify() {
5372LogicalResult SubtagOp::verify() {
5373 if (getFieldIndex() >= getInput().getType().base().getNumElements())
5374 return emitOpError(
"subfield element index is greater than the number "
5375 "of fields in the bundle type");
5385 SmallVector<Operation *, 8> worklist({op});
5389 bool constant =
true;
5395 while (constant && !(worklist.empty()))
5396 TypeSwitch<Operation *>(worklist.pop_back_val())
5397 .Case<NodeOp, AsSIntPrimOp, AsUIntPrimOp>([&](
auto op) {
5398 if (
auto definingOp = op.getInput().getDefiningOp())
5399 worklist.push_back(definingOp);
5402 .Case<WireOp, SubindexOp, SubfieldOp>([&](
auto op) {
5403 for (
auto &use : op.getResult().getUses())
5404 worklist.push_back(use.getOwner());
5406 .Case<ConstantOp, SpecialConstantOp, AggregateConstantOp>([](
auto) {})
5407 .Default([&](
auto) { constant =
false; });
5416 if (
auto *op = value.getDefiningOp())
5421LogicalResult ConstCastOp::verify() {
5423 return emitOpError() << getInput().getType()
5424 <<
" is not 'const'-castable to "
5425 << getResult().getType();
5429FIRRTLType SubfieldOp::inferReturnType(Type type, uint32_t fieldIndex,
5430 std::optional<Location> loc) {
5433 if (fieldIndex >= inType.getNumElements())
5435 "subfield element index is greater than the "
5436 "number of fields in the bundle type");
5440 return inType.getElementTypePreservingConst(fieldIndex);
5443FIRRTLType OpenSubfieldOp::inferReturnType(Type type, uint32_t fieldIndex,
5444 std::optional<Location> loc) {
5447 if (fieldIndex >= inType.getNumElements())
5449 "subfield element index is greater than the "
5450 "number of fields in the bundle type");
5454 return inType.getElementTypePreservingConst(fieldIndex);
5457bool SubfieldOp::isFieldFlipped() {
5458 BundleType bundle = getInput().getType();
5459 return bundle.getElement(getFieldIndex()).isFlip;
5461bool OpenSubfieldOp::isFieldFlipped() {
5462 auto bundle = getInput().getType();
5463 return bundle.getElement(getFieldIndex()).isFlip;
5466FIRRTLType SubindexOp::inferReturnType(Type type, uint32_t fieldIndex,
5467 std::optional<Location> loc) {
5469 if (fieldIndex < vectorType.getNumElements())
5470 return vectorType.getElementTypePreservingConst();
5472 "' in vector type ", type);
5477FIRRTLType OpenSubindexOp::inferReturnType(Type type, uint32_t fieldIndex,
5478 std::optional<Location> loc) {
5480 if (fieldIndex < vectorType.getNumElements())
5481 return vectorType.getElementTypePreservingConst();
5483 "' in vector type ", type);
5489FIRRTLType SubtagOp::inferReturnType(ValueRange operands, DictionaryAttr
attrs,
5490 PropertyRef properties,
5491 mlir::RegionRange regions,
5492 std::optional<Location> loc) {
5493 Adaptor adaptor(operands,
attrs, properties, regions);
5495 auto fieldIndex = adaptor.getFieldIndex();
5497 if (fieldIndex >= inType.getNumElements())
5499 "subtag element index is greater than the "
5500 "number of fields in the enum type");
5504 auto elementType = inType.getElement(fieldIndex).type;
5508FIRRTLType SubaccessOp::inferReturnType(Type inType, Type indexType,
5509 std::optional<Location> loc) {
5516 return vectorType.getElementTypePreservingConst();
5517 return vectorType.getElementType().getAllConstDroppedType();
5525 std::optional<Location> loc) {
5527 return UIntType::get(inType.getContext(), inType.getTagWidth());
5530ParseResult MultibitMuxOp::parse(OpAsmParser &parser, OperationState &result) {
5531 OpAsmParser::UnresolvedOperand index;
5532 SmallVector<OpAsmParser::UnresolvedOperand, 16> inputs;
5533 Type indexType, elemType;
5535 if (parser.parseOperand(index) || parser.parseComma() ||
5536 parser.parseOperandList(inputs) ||
5537 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
5538 parser.parseType(indexType) || parser.parseComma() ||
5539 parser.parseType(elemType))
5542 if (parser.resolveOperand(index, indexType, result.operands))
5545 result.addTypes(elemType);
5547 return parser.resolveOperands(inputs, elemType, result.operands);
5550void MultibitMuxOp::print(OpAsmPrinter &p) {
5551 p <<
" " << getIndex() <<
", ";
5552 p.printOperands(getInputs());
5553 p.printOptionalAttrDict((*this)->getAttrs());
5554 p <<
" : " << getIndex().getType() <<
", " << getType();
5557FIRRTLType MultibitMuxOp::inferReturnType(ValueRange operands,
5558 DictionaryAttr
attrs,
5559 PropertyRef properties,
5560 mlir::RegionRange regions,
5561 std::optional<Location> loc) {
5562 if (operands.size() < 2)
5566 if (!llvm::all_of(operands.drop_front(2), [&](
auto op) {
5567 return operands[1].getType() == op.getType();
5578LogicalResult ObjectSubfieldOp::inferReturnTypes(
5579 MLIRContext *
context, std::optional<mlir::Location> location,
5580 ValueRange operands, DictionaryAttr attributes, PropertyRef properties,
5581 RegionRange regions, llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
5583 inferReturnType(operands, attributes, properties, regions, location);
5586 inferredReturnTypes.push_back(type);
5590Type ObjectSubfieldOp::inferReturnType(Type inType, uint32_t fieldIndex,
5591 std::optional<Location> loc) {
5592 auto classType = dyn_cast<ClassType>(inType);
5596 if (classType.getNumElements() <= fieldIndex)
5598 "number of fields in the object");
5599 return classType.getElement(fieldIndex).type;
5602void ObjectSubfieldOp::print(OpAsmPrinter &p) {
5603 auto input = getInput();
5604 auto classType = input.getType();
5605 p <<
' ' << input <<
"[";
5606 p.printKeywordOrString(classType.getElement(getIndex()).name);
5608 p.printOptionalAttrDict((*this)->getAttrs(), std::array{StringRef(
"index")});
5609 p <<
" : " << classType;
5612ParseResult ObjectSubfieldOp::parse(OpAsmParser &parser,
5613 OperationState &result) {
5614 auto *
context = parser.getContext();
5616 OpAsmParser::UnresolvedOperand input;
5617 std::string fieldName;
5618 ClassType inputType;
5619 if (parser.parseOperand(input) || parser.parseLSquare() ||
5620 parser.parseKeywordOrString(&fieldName) || parser.parseRSquare() ||
5621 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
5622 parser.parseType(inputType) ||
5623 parser.resolveOperand(input, inputType, result.operands))
5626 auto index = inputType.getElementIndex(fieldName);
5628 return parser.emitError(parser.getNameLoc(),
5629 "unknown field " + fieldName +
" in class type ")
5631 result.getOrAddProperties<Properties>().setIndex(
5632 IntegerAttr::get(IntegerType::get(
context, 32), *index));
5634 SmallVector<Type> inferredReturnTypes;
5635 if (failed(inferReturnTypes(
context, result.location, result.operands,
5636 result.attributes.getDictionary(
context),
5637 result.getRawProperties(), result.regions,
5638 inferredReturnTypes)))
5640 result.addTypes(inferredReturnTypes);
5657 int32_t &rhsWidth,
bool &isConstResult,
5658 std::optional<Location> loc) {
5662 if (!lhsi || !rhsi || lhsi.isSigned() != rhsi.isSigned()) {
5665 mlir::emitError(*loc,
"second operand must be an integer type, not ")
5667 else if (!lhsi && rhsi)
5668 mlir::emitError(*loc,
"first operand must be an integer type, not ")
5670 else if (!lhsi && !rhsi)
5671 mlir::emitError(*loc,
"operands must be integer types, not ")
5672 << lhs <<
" and " << rhs;
5674 mlir::emitError(*loc,
"operand signedness must match");
5679 lhsWidth = lhsi.getWidthOrSentinel();
5680 rhsWidth = rhsi.getWidthOrSentinel();
5681 isConstResult = lhsi.isConst() && rhsi.isConst();
5686 assert(op->getNumOperands() == 2 &&
5687 "SameOperandsIntTypeKind on non-binary op");
5688 int32_t lhsWidth, rhsWidth;
5691 op->getOperand(1).getType(), lhsWidth,
5692 rhsWidth, isConstResult, op->getLoc()));
5696 std::optional<Location> loc) {
5697 int32_t lhsWidth, rhsWidth, resultWidth = -1;
5698 bool isConstResult =
false;
5702 if (lhsWidth != -1 && rhsWidth != -1)
5703 resultWidth = std::max(lhsWidth, rhsWidth) + 1;
5709 std::optional<Location> loc) {
5710 int32_t lhsWidth, rhsWidth, resultWidth = -1;
5711 bool isConstResult =
false;
5715 if (lhsWidth != -1 && rhsWidth != -1)
5716 resultWidth = lhsWidth + rhsWidth;
5723 std::optional<Location> loc) {
5724 int32_t lhsWidth, rhsWidth;
5725 bool isConstResult =
false;
5731 return UIntType::get(lhs.getContext(), lhsWidth, isConstResult);
5734 int32_t resultWidth = lhsWidth != -1 ? lhsWidth + 1 : -1;
5735 return SIntType::get(lhs.getContext(), resultWidth, isConstResult);
5739 std::optional<Location> loc) {
5740 int32_t lhsWidth, rhsWidth, resultWidth = -1;
5741 bool isConstResult =
false;
5745 if (lhsWidth != -1 && rhsWidth != -1)
5746 resultWidth = std::min(lhsWidth, rhsWidth);
5752 std::optional<Location> loc) {
5753 int32_t lhsWidth, rhsWidth, resultWidth = -1;
5754 bool isConstResult =
false;
5758 if (lhsWidth != -1 && rhsWidth != -1) {
5759 resultWidth = std::max(lhsWidth, rhsWidth);
5760 if (lhsWidth == resultWidth && lhs.
isConst() == isConstResult &&
5763 if (rhsWidth == resultWidth && rhs.
isConst() == isConstResult &&
5767 return UIntType::get(lhs.getContext(), resultWidth, isConstResult);
5771 std::optional<Location> loc) {
5778 if (lhsVec.getNumElements() != rhsVec.getNumElements())
5783 rhsVec.getElementTypePreservingConst(), loc);
5787 return FVectorType::get(elemBaseType, lhsVec.getNumElements(),
5788 lhsVec.isConst() && rhsVec.isConst() &&
5789 elemBaseType.isConst());
5793 std::optional<Location> loc) {
5794 return UIntType::get(lhs.getContext(), 1,
isConst(lhs) &&
isConst(rhs));
5797FIRRTLType CatPrimOp::inferReturnType(ValueRange operands, DictionaryAttr
attrs,
5798 PropertyRef properties,
5799 mlir::RegionRange regions,
5800 std::optional<Location> loc) {
5802 if (operands.empty())
5803 return UIntType::get(
attrs.getContext(), 0);
5807 for (
auto operand : operands) {
5811 if (type.isSigned() != isSigned)
5813 "all operands must have same signedness");
5817 int32_t resultWidth = 0;
5818 bool isConstResult =
true;
5820 for (
auto operand : operands) {
5822 int32_t width = type.getWidthOrSentinel();
5829 if (resultWidth != -1)
5830 resultWidth += width;
5833 isConstResult &= type.isConst();
5837 return UIntType::get(
attrs.getContext(), resultWidth, isConstResult);
5841 std::optional<Location> loc) {
5844 if (!rhsui || !lhsi)
5846 loc,
"first operand should be integer, second unsigned int");
5850 auto width = lhsi.getWidthOrSentinel();
5851 if (width == -1 || !rhsui.getWidth().has_value()) {
5854 auto amount = *rhsui.getWidth();
5857 "shift amount too large: second operand of "
5858 "dshl is wider than 31 bits");
5859 int64_t newWidth = (int64_t)width + ((int64_t)1 << amount) - 1;
5860 if (newWidth > INT32_MAX)
5862 loc,
"shift amount too large: first operand shifted by maximum "
5863 "amount exceeds maximum width");
5866 return IntType::get(lhs.getContext(), lhsi.isSigned(), width,
5867 lhsi.
isConst() && rhsui.isConst());
5871 std::optional<Location> loc) {
5876 loc,
"first operand should be integer, second unsigned int");
5877 return lhsi.getConstType(lhsi.isConst() && rhsu.isConst());
5881 std::optional<Location> loc) {
5886 loc,
"first operand should be integer, second unsigned int");
5887 return lhsi.getConstType(lhsi.isConst() && rhsu.isConst());
5895 std::optional<Location> loc) {
5896 return UIntType::get(input.getContext(), 32);
5900 std::optional<Location> loc) {
5904 int32_t width = base.getBitWidthOrSentinel();
5907 return SIntType::get(input.getContext(), width, base.isConst());
5911 std::optional<Location> loc) {
5915 int32_t width = base.getBitWidthOrSentinel();
5918 return UIntType::get(input.getContext(), width, base.isConst());
5922 std::optional<Location> loc) {
5926 "operand must be single bit scalar base type");
5927 int32_t width = base.getBitWidthOrSentinel();
5928 if (width == -2 || width == 0 || width > 1)
5930 return AsyncResetType::get(input.getContext(), base.isConst());
5934 std::optional<Location> loc) {
5938 return ResetType::get(input.getContext(), base.isConst());
5942 std::optional<Location> loc) {
5943 return ClockType::get(input.getContext(),
isConst(input));
5947 std::optional<Location> loc) {
5949 auto width = uiType.getWidthOrSentinel();
5952 return SIntType::get(input.getContext(), width, uiType.
isConst());
5962 std::optional<Location> loc) {
5966 int32_t width = inputi.getWidthOrSentinel();
5969 return SIntType::get(input.getContext(), width, inputi.
isConst());
5973 std::optional<Location> loc) {
5977 if (isa<UIntType>(inputi))
5979 return UIntType::get(input.getContext(), inputi.getWidthOrSentinel(),
5984 std::optional<Location> loc) {
5985 return UIntType::get(input.getContext(), 1,
isConst(input));
5994 std::optional<Location> loc) {
5998 loc,
"input type should be the int type but got ", input);
6003 loc,
"high must be equal or greater than low, but got high = ", high,
6011 int32_t width = inputi.getWidthOrSentinel();
6012 if (width != -1 && high >= width)
6015 "high must be smaller than the width of input, but got high = ", high,
6016 ", width = ", width);
6018 return UIntType::get(input.getContext(), high - low + 1, inputi.
isConst());
6022 std::optional<Location> loc) {
6025 if (amount < 0 || !inputi)
6027 loc,
"operand must have integer type and amount must be >= 0");
6029 int32_t width = inputi.getWidthOrSentinel();
6030 if (width != -1 && amount > width)
6033 return UIntType::get(input.getContext(), amount, inputi.
isConst());
6048 bool isConstCondition,
6049 std::optional<Location> loc) {
6055 if (high.getTypeID() != low.getTypeID())
6057 loc,
"incompatible mux operand types, true value type: ", high,
6058 ", false value type: ", low);
6060 bool outerTypeIsConst = isConstCondition && low.
isConst() && high.
isConst();
6070 if (highWidth == -1)
6072 return (lowWidth > highWidth ? low : high).
getConstType(outerTypeIsConst);
6079 if (lowEnum && highEnum) {
6080 if (lowEnum.getNumElements() != highEnum.getNumElements())
6082 loc,
"incompatible mux operand types, true value type: ", high,
6083 ", false value type: ", low);
6084 SmallVector<FEnumType::EnumElement> elements;
6085 for (
auto [high, low] : llvm::zip_equal(highEnum, lowEnum)) {
6087 if (high.name != low.name || high.value != low.value)
6089 loc,
"incompatible mux operand types, true value type: ", highEnum,
6090 ", false value type: ", lowEnum);
6097 elements.emplace_back(high.name, high.value, inner);
6099 return FEnumType::get(high.getContext(), elements, outerTypeIsConst);
6105 if (highVector && lowVector &&
6106 highVector.getNumElements() == lowVector.getNumElements()) {
6108 lowVector.getElementTypePreservingConst(),
6109 isConstCondition, loc);
6112 return FVectorType::get(inner, lowVector.getNumElements(),
6119 if (highBundle && lowBundle) {
6120 auto highElements = highBundle.getElements();
6121 auto lowElements = lowBundle.getElements();
6124 SmallVector<BundleType::BundleElement> newElements;
6126 bool failed =
false;
6128 if (highElements[i].name != lowElements[i].name ||
6129 highElements[i].isFlip != lowElements[i].isFlip) {
6133 auto element = highElements[i];
6135 highBundle.getElementTypePreservingConst(i),
6136 lowBundle.getElementTypePreservingConst(i), isConstCondition, loc);
6139 newElements.push_back(element);
6142 return BundleType::get(low.getContext(), newElements, outerTypeIsConst);
6145 loc,
"incompatible mux operand bundle fields, true value type: ", high,
6146 ", false value type: ", low);
6152 loc,
"invalid mux operand types, true value type: ", high,
6153 ", false value type: ", low);
6158 std::optional<Location> loc) {
6161 if (!highType || !lowType)
6166FIRRTLType Mux2CellIntrinsicOp::inferReturnType(ValueRange operands,
6167 DictionaryAttr
attrs,
6168 PropertyRef properties,
6169 mlir::RegionRange regions,
6170 std::optional<Location> loc) {
6173 if (!highType || !lowType)
6179FIRRTLType Mux4CellIntrinsicOp::inferReturnType(ValueRange operands,
6180 DictionaryAttr
attrs,
6181 PropertyRef properties,
6182 mlir::RegionRange regions,
6183 std::optional<Location> loc) {
6184 SmallVector<FIRRTLBaseType> types;
6186 for (
unsigned i = 1; i < 5; i++) {
6192 isConst(operands[0].getType()), loc);
6196 result = types.back();
6203 std::optional<Location> loc) {
6205 if (amount < 0 || !inputi)
6207 loc,
"pad input must be integer and amount must be >= 0");
6209 int32_t width = inputi.getWidthOrSentinel();
6213 width = std::max<int32_t>(width, amount);
6214 return IntType::get(input.getContext(), inputi.isSigned(), width,
6219 std::optional<Location> loc) {
6221 if (amount < 0 || !inputi)
6223 loc,
"shl input must be integer and amount must be >= 0");
6225 int32_t width = inputi.getWidthOrSentinel();
6229 return IntType::get(input.getContext(), inputi.isSigned(), width,
6234 std::optional<Location> loc) {
6236 if (amount < 0 || !inputi)
6238 loc,
"shr input must be integer and amount must be >= 0");
6240 int32_t width = inputi.getWidthOrSentinel();
6243 int32_t minWidth = inputi.isUnsigned() ? 0 : 1;
6244 width = std::max<int32_t>(minWidth, width - amount);
6247 return IntType::get(input.getContext(), inputi.isSigned(), width,
6252 std::optional<Location> loc) {
6255 if (amount < 0 || !inputi)
6257 loc,
"tail input must be integer and amount must be >= 0");
6259 int32_t width = inputi.getWidthOrSentinel();
6263 loc,
"amount must be less than or equal operand width");
6274void VerbatimExprOp::getAsmResultNames(
6275 function_ref<
void(Value, StringRef)> setNameFn) {
6279 auto isOkCharacter = [](
char c) {
return llvm::isAlnum(c) || c ==
'_'; };
6280 auto name = getText();
6282 if (name.starts_with(
"`"))
6283 name = name.drop_front();
6284 name = name.take_while(isOkCharacter);
6286 setNameFn(getResult(), name);
6293void VerbatimWireOp::getAsmResultNames(
6294 function_ref<
void(Value, StringRef)> setNameFn) {
6298 auto isOkCharacter = [](
char c) {
return llvm::isAlnum(c) || c ==
'_'; };
6299 auto name = getText();
6301 if (name.starts_with(
"`"))
6302 name = name.drop_front();
6303 name = name.take_while(isOkCharacter);
6305 setNameFn(getResult(), name);
6316 op->emitError() <<
"unknown width is not allowed for DPI";
6317 return WalkResult::interrupt();
6319 if (width == 1 || width == 8 || width == 16 || width == 32 ||
6321 return WalkResult::advance();
6323 <<
"integer types used by DPI functions must have a "
6324 "specific bit width; "
6325 "it must be equal to 1(bit), 8(byte), 16(shortint), "
6326 "32(int), 64(longint) "
6327 "or greater than 64, but got "
6329 return WalkResult::interrupt();
6334LogicalResult DPICallIntrinsicOp::verify() {
6335 if (
auto inputNames = getInputNames()) {
6336 if (getInputs().size() != inputNames->size())
6337 return emitError() <<
"inputNames has " << inputNames->size()
6338 <<
" elements but there are " << getInputs().size()
6339 <<
" input arguments";
6341 if (
auto outputName = getOutputName())
6342 if (getNumResults() == 0)
6343 return emitError() <<
"output name is given but there is no result";
6345 auto checkType = [
this](Type type) {
6348 return success(llvm::all_of(this->getResultTypes(), checkType) &&
6349 llvm::all_of(this->getOperandTypes(), checkType));
6352SmallVector<std::pair<circt::FieldRef, circt::FieldRef>>
6353DPICallIntrinsicOp::computeDataFlow() {
6357 SmallVector<std::pair<circt::FieldRef, circt::FieldRef>> deps;
6359 for (
auto operand : getOperands()) {
6362 SmallVector<circt::FieldRef> operandFields;
6365 operandFields.push_back(baseFieldRef.getSubField(dstIndex));
6369 for (
auto result : getResults())
6372 for (
auto field : operandFields)
6373 deps.emplace_back(circt::FieldRef(result, dstIndex), field);
6383LogicalResult HWStructCastOp::verify() {
6385 BundleType bundleType;
6386 hw::StructType structType;
6388 structType = dyn_cast<hw::StructType>(getType());
6390 return emitError(
"result type must be a struct");
6392 structType = dyn_cast<hw::StructType>(getOperand().getType());
6394 return emitError(
"operand type must be a struct");
6396 return emitError(
"either source or result type must be a bundle type");
6399 auto firFields = bundleType.getElements();
6400 auto hwFields = structType.getElements();
6401 if (firFields.size() != hwFields.size())
6402 return emitError(
"bundle and struct have different number of fields");
6404 for (
size_t findex = 0, fend = firFields.size(); findex < fend; ++findex) {
6405 if (firFields[findex].name.getValue() != hwFields[findex].name)
6406 return emitError(
"field names don't match '")
6407 << firFields[findex].name.getValue() <<
"', '"
6408 << hwFields[findex].name.getValue() <<
"'";
6412 if (firWidth > 0 && hwWidth > 0 && firWidth != hwWidth)
6413 return emitError(
"size of field '")
6414 << hwFields[findex].name.getValue() <<
"' don't match " << firWidth
6421LogicalResult BitCastOp::verify() {
6422 auto inTypeBits =
getBitWidth(getInput().getType(),
true);
6424 if (inTypeBits.has_value() && resTypeBits.has_value()) {
6426 if (*inTypeBits == *resTypeBits) {
6429 return emitError(
"cannot cast non-'const' input type ")
6430 << getOperand().getType() <<
" to 'const' result type "
6434 return emitError(
"the bitwidth of input (")
6435 << *inTypeBits <<
") and result (" << *resTypeBits
6438 if (!inTypeBits.has_value())
6439 return emitError(
"bitwidth cannot be determined for input operand type ")
6440 << getInput().getType();
6441 return emitError(
"bitwidth cannot be determined for result type ")
6452 NamedAttrList &resultAttrs) {
6453 auto result = parser.parseOptionalAttrDict(resultAttrs);
6454 if (!resultAttrs.get(
"annotations"))
6455 resultAttrs.append(
"annotations", parser.getBuilder().getArrayAttr({}));
6461 DictionaryAttr attr,
6462 ArrayRef<StringRef> extraElides = {}) {
6463 SmallVector<StringRef> elidedAttrs(extraElides.begin(), extraElides.end());
6465 if (op->getAttrOfType<ArrayAttr>(
"annotations").empty())
6466 elidedAttrs.push_back(
"annotations");
6468 elidedAttrs.push_back(
"nameKind");
6470 p.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
6476 NamedAttrList &resultAttrs) {
6479 if (!resultAttrs.get(
"portAnnotations")) {
6480 SmallVector<Attribute, 16> portAnnotations(
6481 parser.getNumResults(), parser.getBuilder().getArrayAttr({}));
6482 resultAttrs.append(
"portAnnotations",
6483 parser.getBuilder().getArrayAttr(portAnnotations));
6490 DictionaryAttr attr,
6491 ArrayRef<StringRef> extraElides = {}) {
6492 SmallVector<StringRef, 2> elidedAttrs(extraElides.begin(), extraElides.end());
6494 if (llvm::all_of(op->getAttrOfType<ArrayAttr>(
"portAnnotations"),
6495 [&](Attribute a) { return cast<ArrayAttr>(a).empty(); }))
6496 elidedAttrs.push_back(
"portAnnotations");
6505 firrtl::NameKindEnumAttr &result) {
6508 if (!parser.parseOptionalKeyword(&keyword,
6509 {
"interesting_name",
"droppable_name"})) {
6510 auto kind = symbolizeNameKindEnum(keyword);
6511 result = NameKindEnumAttr::get(parser.getContext(), kind.value());
6517 NameKindEnumAttr::get(parser.getContext(), NameKindEnum::DroppableName);
6522 firrtl::NameKindEnumAttr attr,
6523 ArrayRef<StringRef> extraElides = {}) {
6524 if (attr.getValue() != NameKindEnum::DroppableName)
6525 p <<
" " << stringifyNameKindEnum(attr.getValue());
6533 NamedAttrList &resultAttrs) {
6541 DictionaryAttr
attrs) {
6542 SmallVector<StringRef, 4> elides;
6544 elides.push_back(Forceable::getForceableAttrName());
6554 OpAsmParser &parser,
6555 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &fieldValues,
6556 SmallVectorImpl<Type> &fieldTypes, Type &resultType) {
6558 if (parser.parseType(resultType))
6561 auto domainType = dyn_cast<DomainType>(resultType);
6563 return parser.emitError(parser.getCurrentLocation(),
6564 "expected domain type");
6567 auto fields = domainType.getFields();
6570 if (fieldValues.size() != fields.size())
6571 return parser.emitError(parser.getCurrentLocation(),
6572 "number of field values (" +
6573 Twine(fieldValues.size()) +
6574 ") does not match domain field count (" +
6575 Twine(fields.size()) +
")");
6578 fieldTypes.reserve(fields.size());
6579 for (
auto field : fields)
6580 fieldTypes.push_back(cast<DomainFieldAttr>(field).getType());
6586 OperandRange fieldValues,
6587 TypeRange fieldTypes, Type resultType) {
6595static ParseResult
parseMemOp(OpAsmParser &parser, NamedAttrList &resultAttrs) {
6600static void printMemOp(OpAsmPrinter &p, Operation *op, DictionaryAttr attr) {
6611 if (ClassType::parseInterface(parser, type))
6618 type.printInterface(p);
6626 NamedAttrList &resultAttrs) {
6627 auto result = p.parseOptionalAttrDict(resultAttrs);
6628 if (!resultAttrs.get(
"name"))
6629 resultAttrs.append(
"name", p.getBuilder().getStringAttr(
""));
6635 DictionaryAttr attr,
6636 ArrayRef<StringRef> extraElides = {}) {
6637 SmallVector<StringRef> elides(extraElides.begin(), extraElides.end());
6638 if (op->getAttrOfType<StringAttr>(
"name").getValue().empty())
6639 elides.push_back(
"name");
6641 p.printOptionalAttrDict(op->getAttrs(), elides);
6645 NamedAttrList &resultAttrs) {
6650 DictionaryAttr attr) {
6655 NamedAttrList &resultAttrs) {
6660 DictionaryAttr attr) {
6662 {
"formatString",
"outputFile",
"operandSegmentSizes"});
6670 DictionaryAttr attr) {
6679 DictionaryAttr attr) {
6691 if (op->getNumResults() == 1)
6692 if (
auto nameAttr = op->getAttrOfType<StringAttr>(
"name"))
6693 setNameFn(op->getResult(0), nameAttr.getValue());
6798void PlusArgsValueIntrinsicOp::getAsmResultNames(
6942FIRRTLType RefResolveOp::inferReturnType(ValueRange operands,
6943 DictionaryAttr
attrs,
6944 PropertyRef properties,
6945 mlir::RegionRange regions,
6946 std::optional<Location> loc) {
6947 Type inType = operands[0].getType();
6951 loc,
"ref.resolve operand must be ref type, not ", inType);
6952 return inRefType.getType();
6955FIRRTLType RefSendOp::inferReturnType(ValueRange operands, DictionaryAttr
attrs,
6956 PropertyRef properties,
6957 mlir::RegionRange regions,
6958 std::optional<Location> loc) {
6959 Type inType = operands[0].getType();
6963 loc,
"ref.send operand must be base type, not ", inType);
6964 return RefType::get(inBaseType.getPassiveType());
6967FIRRTLType RefSubOp::inferReturnType(Type type, uint32_t fieldIndex,
6968 std::optional<Location> loc) {
6972 auto inType = refType.getType();
6979 if (fieldIndex < vectorType.getNumElements())
6980 return RefType::get(
6981 vectorType.getElementType().getConstType(
6982 vectorType.isConst() || vectorType.getElementType().isConst()),
6983 refType.getForceable(), refType.getLayer());
6985 "' in RefType of vector type ", refType);
6988 if (fieldIndex >= bundleType.getNumElements()) {
6990 "subfield element index is greater than "
6991 "the number of fields in the bundle type");
6993 return RefType::get(
6994 bundleType.getElement(fieldIndex)
6996 bundleType.isConst() ||
6997 bundleType.getElement(fieldIndex).type.isConst()),
6998 refType.getForceable(), refType.getLayer());
7002 loc,
"ref.sub op requires a RefType of vector or bundle base type");
7005LogicalResult RefCastOp::verify() {
7009 getOperation(), srcLayers, dstLayers,
7010 "cannot discard layer requirements of input reference",
7011 "discarding layer requirements");
7014LogicalResult RefResolveOp::verify() {
7018 getOperation(), srcLayers, dstLayers,
7019 "ambient layers are insufficient to resolve reference");
7022LogicalResult RWProbeOp::verifyInnerRefs(hw::InnerRefNamespace &ns) {
7023 auto targetRef = getTarget();
7024 if (targetRef.getModule() !=
7025 (*this)->getParentOfType<FModuleLike>().getModuleNameAttr())
7026 return emitOpError() <<
"has non-local target";
7028 auto target = ns.
lookup(targetRef);
7030 return emitOpError() <<
"has target that cannot be resolved: " << targetRef;
7032 auto checkFinalType = [&](
auto type, Location loc) -> LogicalResult {
7038 if (!baseType || baseType.getPassiveType() != getType().getType()) {
7039 auto diag = emitOpError(
"has type mismatch: target resolves to ")
7040 << fType <<
" instead of expected " << getType().getType();
7041 diag.attachNote(loc) <<
"target resolves here";
7046 if (target.isPort()) {
7047 auto mod = cast<FModuleLike>(target.getOp());
7048 return checkFinalType(mod.getPortType(target.getPort()),
7049 mod.getPortLocation(target.getPort()));
7051 hw::InnerSymbolOpInterface symOp =
7052 cast<hw::InnerSymbolOpInterface>(target.getOp());
7053 if (!symOp.getTargetResult())
7054 return emitOpError(
"has target that cannot be probed")
7055 .attachNote(symOp.getLoc())
7056 .append(
"target resolves here");
7058 symOp.getTargetResult().getParentBlock()->findAncestorOpInBlock(**
this);
7059 if (!ancestor || !symOp->isBeforeInBlock(ancestor))
7060 return emitOpError(
"is not dominated by target")
7061 .attachNote(symOp.getLoc())
7062 .append(
"target here");
7063 return checkFinalType(symOp.getTargetResult().getType(), symOp.getLoc());
7066LogicalResult RefForceOp::verify() {
7070 getOperation(), destLayers, ambientLayers,
7071 "has insufficient ambient layers to force its reference");
7074LogicalResult RefForceInitialOp::verify() {
7078 getOperation(), destLayers, ambientLayers,
7079 "has insufficient ambient layers to force its reference");
7082LogicalResult RefReleaseOp::verify() {
7086 getOperation(), destLayers, ambientLayers,
7087 "has insufficient ambient layers to release its reference");
7090LogicalResult RefReleaseInitialOp::verify() {
7094 getOperation(), destLayers, ambientLayers,
7095 "has insufficient ambient layers to release its reference");
7098LogicalResult XMRRefOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
7099 auto *target = symbolTable.lookupNearestSymbolFrom(*
this, getRefAttr());
7101 return emitOpError(
"has an invalid symbol reference");
7103 if (!isa<hw::HierPathOp>(target))
7104 return emitOpError(
"does not target a hierpath op");
7110LogicalResult XMRDerefOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
7111 auto *target = symbolTable.lookupNearestSymbolFrom(*
this, getRefAttr());
7113 return emitOpError(
"has an invalid symbol reference");
7115 if (!isa<hw::HierPathOp>(target))
7116 return emitOpError(
"does not target a hierpath op");
7126LogicalResult LayerBlockOp::verify() {
7127 auto layerName = getLayerName();
7128 auto *parentOp = (*this)->getParentOp();
7131 while (isa<WhenOp, MatchOp>(parentOp))
7132 parentOp = parentOp->getParentOp();
7136 auto nestedReferences = layerName.getNestedReferences();
7137 if (nestedReferences.empty()) {
7138 if (!isa<FModuleOp>(parentOp)) {
7139 auto diag = emitOpError() <<
"has an un-nested layer symbol, but does "
7140 "not have a 'firrtl.module' op as a parent";
7141 return diag.attachNote(parentOp->getLoc())
7142 <<
"illegal parent op defined here";
7145 auto parentLayerBlock = dyn_cast<LayerBlockOp>(parentOp);
7146 if (!parentLayerBlock) {
7147 auto diag = emitOpError()
7148 <<
"has a nested layer symbol, but does not have a '"
7149 << getOperationName() <<
"' op as a parent'";
7150 return diag.attachNote(parentOp->getLoc())
7151 <<
"illegal parent op defined here";
7153 auto parentLayerBlockName = parentLayerBlock.getLayerName();
7154 if (parentLayerBlockName.getRootReference() !=
7155 layerName.getRootReference() ||
7156 parentLayerBlockName.getNestedReferences() !=
7157 layerName.getNestedReferences().drop_back()) {
7158 auto diag = emitOpError() <<
"is nested under an illegal layer block";
7159 return diag.attachNote(parentLayerBlock->getLoc())
7160 <<
"illegal parent layer block defined here";
7168 auto getDeclaration = [&](Value value) {
7171 while (
auto subaccess = ref.getValue().getDefiningOp<SubaccessOp>())
7176 auto result = getBody(0)->walk<mlir::WalkOrder::PreOrder>(
7177 [&](Operation *op) -> WalkResult {
7179 if (isa<LayerBlockOp>(op))
7180 return WalkResult::skip();
7184 for (
auto operand : op->getOperands()) {
7186 if (
auto *definingOp = operand.getDefiningOp())
7190 auto type = operand.getType();
7193 if (isa<PropertyType>(type)) {
7194 auto diag = emitOpError() <<
"captures a property operand";
7195 diag.attachNote(operand.getLoc()) <<
"operand is defined here";
7196 diag.attachNote(op->getLoc()) <<
"operand is used here";
7197 return WalkResult::interrupt();
7202 if (
auto connect = dyn_cast<FConnectLike>(op)) {
7204 if (isa<RefDefineOp>(connect))
7205 return WalkResult::advance();
7217 if (!type.isPassive())
7218 return WalkResult::advance();
7220 auto dest = getDeclaration(
connect.getDest()).getValue();
7222 return WalkResult::advance();
7226 <<
"connects to a destination which is defined outside its "
7227 "enclosing layer block";
7228 diag.attachNote(
getLoc()) <<
"enclosing layer block is defined here";
7229 diag.attachNote(dest.getLoc()) <<
"destination is defined here";
7230 return WalkResult::interrupt();
7234 if (
auto attach = dyn_cast<AttachOp>(op)) {
7235 for (
auto operand : attach.getAttached()) {
7236 auto decl = getDeclaration(operand);
7240 auto diag = attach.emitOpError() <<
"attaches to ";
7243 diag <<
"\"" << name <<
"\"";
7245 diag <<
"an operand";
7246 diag <<
" which is defined outside its enclosing layer block"
7247 <<
" for layer " << getLayerName();
7248 diag.attachNote(
getLoc())
7249 <<
"enclosing layer block is defined here";
7250 diag.attachNote(decl.getLoc()) <<
"operand is defined here";
7251 return WalkResult::interrupt();
7255 return WalkResult::advance();
7258 return failure(result.wasInterrupted());
7262LayerBlockOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
7264 symbolTable.lookupNearestSymbolFrom<LayerOp>(*
this, getLayerNameAttr());
7266 return emitOpError(
"invalid symbol reference");
7277 setNameFn(getResult(),
"time");
7280void HierarchicalModuleNameOp::getAsmResultNames(
7282 setNameFn(getResult(),
"hierarchicalmodulename");
7285ParseResult FPrintFOp::parse(::mlir::OpAsmParser &parser,
7286 ::mlir::OperationState &result) {
7288 OpAsmParser::UnresolvedOperand clock, cond;
7289 if (parser.parseOperand(clock) || parser.parseComma() ||
7290 parser.parseOperand(cond) || parser.parseComma())
7294 [&parser](llvm::SMLoc &loc, StringAttr &result,
7295 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &operands)
7297 loc = parser.getCurrentLocation();
7300 std::string resultStr;
7301 if (parser.parseString(&resultStr))
7303 result = parser.getBuilder().getStringAttr(resultStr);
7306 if (parser.parseOperandList(operands, AsmParser::Delimiter::OptionalParen))
7312 SmallVector<OpAsmParser::UnresolvedOperand> outputFileSubstitutions,
7314 llvm::SMLoc outputFileLoc, formatStringLoc;
7318 result.getOrAddProperties<FPrintFOp::Properties>().outputFile,
7319 outputFileSubstitutions) ||
7320 parser.parseComma() ||
7323 result.getOrAddProperties<FPrintFOp::Properties>().formatString,
7331 Type clockType, condType;
7332 SmallVector<Type> restTypes;
7334 if (parser.parseColon() || parser.parseType(clockType) ||
7335 parser.parseComma() || parser.parseType(condType))
7338 if (succeeded(parser.parseOptionalComma())) {
7339 if (parser.parseTypeList(restTypes))
7344 result.getOrAddProperties<FPrintFOp::Properties>().operandSegmentSizes = {
7345 1, 1,
static_cast<int32_t
>(outputFileSubstitutions.size()),
7346 static_cast<int32_t
>(substitutions.size())};
7349 if (parser.resolveOperand(clock, clockType, result.operands) ||
7350 parser.resolveOperand(cond, condType, result.operands) ||
7351 parser.resolveOperands(
7352 outputFileSubstitutions,
7353 ArrayRef(restTypes).take_front(outputFileSubstitutions.size()),
7354 outputFileLoc, result.operands) ||
7355 parser.resolveOperands(
7357 ArrayRef(restTypes).drop_front(outputFileSubstitutions.size()),
7358 formatStringLoc, result.operands))
7364void FPrintFOp::print(OpAsmPrinter &p) {
7365 p <<
" " << getClock() <<
", " << getCond() <<
", ";
7366 p.printAttributeWithoutType(getOutputFileAttr());
7367 if (!getOutputFileSubstitutions().
empty()) {
7369 p.printOperands(getOutputFileSubstitutions());
7373 p.printAttributeWithoutType(getFormatStringAttr());
7374 if (!getSubstitutions().
empty()) {
7376 p.printOperands(getSubstitutions());
7380 p <<
" : " << getClock().getType() <<
", " << getCond().getType();
7381 if (!getOutputFileSubstitutions().
empty() || !getSubstitutions().
empty()) {
7382 for (
auto type : getOperands().drop_front(2).getTypes()) {
7393LogicalResult FFlushOp::verify() {
7394 if (!getOutputFileAttr() && !getOutputFileSubstitutions().
empty())
7395 return emitOpError(
"substitutions without output file are not allowed");
7403LogicalResult BindOp::verifyInnerRefs(hw::InnerRefNamespace &ns) {
7404 auto ref = getInstanceAttr();
7405 auto target = ns.
lookup(ref);
7407 return emitError() <<
"target " << ref <<
" cannot be resolved";
7409 if (!target.isOpOnly())
7410 return emitError() <<
"target " << ref <<
" is not an operation";
7412 auto instance = dyn_cast<InstanceOp>(target.getOp());
7414 return emitError() <<
"target " << ref <<
" is not an instance";
7416 if (!instance.getDoNotPrint())
7417 return emitError() <<
"target " << ref <<
" is not marked doNotPrint";
7431DomainCreateAnonOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
7432 auto circuitOp = getOperation()->getParentOfType<CircuitOp>();
7433 auto domainAttr = getDomainAttr();
7435 auto *symbol = symbolTable.lookupSymbolIn(circuitOp, domainAttr);
7437 return emitOpError() <<
"references undefined symbol '" << domainAttr
7440 if (!isa<DomainOp>(symbol))
7441 return emitOpError() <<
"references symbol '" << domainAttr
7442 <<
"' which is not a domain";
7445 auto domainType = getResult().getType();
7446 return domainType.verifySymbolUses(getOperation(), symbolTable);
7454DomainCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
7455 auto circuitOp = getOperation()->getParentOfType<CircuitOp>();
7456 auto domainAttr = getDomainAttr();
7458 auto *symbol = symbolTable.lookupSymbolIn(circuitOp, domainAttr);
7460 return emitOpError() <<
"references undefined symbol '" << domainAttr
7463 if (!isa<DomainOp>(symbol))
7464 return emitOpError() <<
"references symbol '" << domainAttr
7465 <<
"' which is not a domain";
7468 auto domainType = getResult().getType();
7469 return domainType.verifySymbolUses(getOperation(), symbolTable);
7472LogicalResult DomainCreateOp::verify() {
7474 auto domainType = getResult().getType();
7475 auto fields = domainType.getFields();
7476 auto fieldValues = getFieldValues();
7479 if (fieldValues.size() != fields.size())
7480 return emitOpError() <<
"has " << fieldValues.size()
7481 <<
" field value(s) but domain '"
7482 << domainType.getName() <<
"' expects "
7483 << fields.size() <<
" field(s)";
7486 for (
size_t i = 0; i < fields.size(); ++i) {
7487 auto fieldAttr = cast<DomainFieldAttr>(fields[i]);
7488 auto expectedType = fieldAttr.getType();
7489 auto actualType = fieldValues[i].getType();
7491 if (expectedType == actualType)
7494 return emitOpError() <<
"field value " << i <<
" has type " << actualType
7495 <<
" but domain field '" << fieldAttr.getName()
7496 <<
"' expects type " << expectedType;
7506StringAttr DomainSubfieldOp::getFieldName() {
7507 auto domainType = getInput().getType();
7508 auto fields = domainType.getFields();
7509 auto index = getFieldIndex();
7511 if (index >= fields.size())
7514 return cast<DomainFieldAttr>(fields[index]).getName();
7517Type DomainSubfieldOp::inferReturnType(Type inType, uint32_t fieldIndex,
7518 std::optional<Location> loc) {
7519 auto domainType = dyn_cast<DomainType>(inType);
7523 auto fields = domainType.getFields();
7524 if (fieldIndex >= fields.size())
7526 loc,
"field index ", fieldIndex,
7527 +
" is greater than the number of fields in the domain");
7529 return cast<DomainFieldAttr>(fields[fieldIndex]).getType();
7532Type DomainSubfieldOp::inferReturnType(ValueRange operands,
7533 mlir::DictionaryAttr
attrs,
7534 mlir::PropertyRef properties,
7535 mlir::RegionRange regions,
7536 std::optional<Location> loc) {
7537 Adaptor adaptor(operands,
attrs, properties, regions);
7538 return inferReturnType(adaptor.getInput().getType(), adaptor.getFieldIndex(),
7542DomainSubfieldOp DomainSubfieldOp::create(OpBuilder &builder, Type resultType,
7543 Value base,
unsigned fieldIndex) {
7544 OperationState state(builder.getUnknownLoc(),
7545 DomainSubfieldOp::getOperationName());
7546 state.addOperands(base);
7547 state.addAttribute(
"fieldIndex", builder.getI32IntegerAttr(fieldIndex));
7548 state.addTypes(resultType);
7549 return cast<DomainSubfieldOp>(builder.create(state));
7552LogicalResult DomainSubfieldOp::inferReturnTypes(
7553 MLIRContext *
context, std::optional<Location> location, ValueRange operands,
7554 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
7555 SmallVectorImpl<Type> &inferredReturnTypes) {
7556 Adaptor adaptor(operands, attributes, properties, regions);
7557 auto resultType = inferReturnType(adaptor.getInput().getType(),
7558 adaptor.getFieldIndex(), location);
7561 inferredReturnTypes.push_back(resultType);
7565void DomainSubfieldOp::print(OpAsmPrinter &p) {
7566 p <<
' ' << getInput() <<
"[";
7569 p.printOptionalAttrDict((*this)->getAttrs(), {
"fieldIndex"});
7570 p <<
" : " << getInput().getType();
7573ParseResult DomainSubfieldOp::parse(OpAsmParser &parser,
7574 OperationState &result) {
7575 auto *
context = parser.getContext();
7577 OpAsmParser::UnresolvedOperand input;
7578 std::string fieldName;
7579 DomainType inputType;
7581 if (parser.parseOperand(input) || parser.parseLSquare() ||
7582 parser.parseKeywordOrString(&fieldName) || parser.parseRSquare() ||
7583 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
7584 parser.parseType(inputType) ||
7585 parser.resolveOperand(input, inputType, result.operands))
7589 auto fieldIndex = inputType.getFieldIndex(fieldName);
7591 return parser.emitError(parser.getNameLoc(),
7592 "unknown field '" + fieldName +
"' in domain type");
7595 result.addAttribute(
7597 IntegerAttr::get(IntegerType::get(
context, 32), *fieldIndex));
7600 auto resultType = inferReturnType(inputType, *fieldIndex, std::nullopt);
7604 result.addTypes(resultType);
7613#define GET_OP_CLASSES
7614#include "circt/Dialect/FIRRTL/FIRRTL.cpp.inc"
static void printNameKind(OpAsmPrinter &p, Operation *op, firrtl::NameKindEnumAttr attr, ArrayRef< StringRef > extraElides={})
static ParseResult parseNameKind(OpAsmParser &parser, firrtl::NameKindEnumAttr &result)
assert(baseType &&"element must be base type")
MlirType uint64_t numElements
static std::unique_ptr< Context > context
static Attribute fixDomainInfoInsertions(MLIRContext *context, Attribute domainInfoAttr, ArrayRef< unsigned > indexMap)
Return an updated domain info Attribute with domain indices updated based on port insertions.
static LogicalResult verifyProbeType(RefType refType, Location loc, CircuitOp circuitOp, SymbolTableCollection &symbolTable, Twine start)
static ArrayAttr fixDomainInfoDeletions(MLIRContext *context, ArrayAttr domainInfoAttr, const llvm::BitVector &portIndices, bool supportsEmptyAttr)
static SmallVector< PortInfo > getPortImpl(FModuleLike module)
static void buildClass(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports)
static FlatSymbolRefAttr getDomainTypeName(Value value)
static void printStopAttrs(OpAsmPrinter &p, Operation *op, DictionaryAttr attr)
static void buildModule(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports, ArrayAttr annotations, ArrayAttr layers)
static LayerSet getLayersFor(Value value)
Get the effective layer requirements for the given value.
static SmallVector< hw::PortInfo > getPortListImpl(FModuleLike module)
ParseResult parseSubfieldLikeOp(OpAsmParser &parser, OperationState &result)
static bool isSameIntTypeKind(Type lhs, Type rhs, int32_t &lhsWidth, int32_t &rhsWidth, bool &isConstResult, std::optional< Location > loc)
If LHS and RHS are both UInt or SInt types, the return true and fill in the width of them if known.
static void printClassLike(OpAsmPrinter &p, ClassLike op)
static LogicalResult verifySubfieldLike(OpTy op)
static void printFPrintfAttrs(OpAsmPrinter &p, Operation *op, DictionaryAttr attr)
static LogicalResult checkSingleConnect(FConnectLike connect)
Returns success if the given connect is the sole driver of its dest operand.
static bool isConstFieldDriven(FIRRTLBaseType type, bool isFlip=false, bool outerTypeIsConst=false)
Checks if the type has any 'const' leaf elements .
static ParseResult parsePrintfAttrs(OpAsmParser &p, NamedAttrList &resultAttrs)
static ParseResult parseParameterList(OpAsmParser &parser, ArrayAttr ¶meters)
Shim to use with assemblyFormat, custom<ParameterList>.
static RetTy emitInferRetTypeError(std::optional< Location > loc, const Twine &message, Args &&...args)
Emit an error if optional location is non-null, return null of return type.
static LogicalResult checkLayerCompatibility(Operation *op, const LayerSet &src, const LayerSet &dst, const Twine &errorMsg, const Twine ¬eMsg=Twine("missing layer requirements"))
static ParseResult parseModulePorts(OpAsmParser &parser, bool hasSSAIdentifiers, bool supportsSymbols, bool supportsDomains, SmallVectorImpl< OpAsmParser::Argument > &entryArgs, SmallVectorImpl< Direction > &portDirections, SmallVectorImpl< Attribute > &portNames, SmallVectorImpl< Attribute > &portTypes, SmallVectorImpl< Attribute > &portAnnotations, SmallVectorImpl< Attribute > &portSyms, SmallVectorImpl< Attribute > &portLocs, SmallVectorImpl< Attribute > &domains)
Parse a list of module ports.
static LogicalResult checkConnectConditionality(FConnectLike connect)
Checks that connections to 'const' destinations are not dependent on non-'const' conditions in when b...
static void erasePorts(FModuleLike op, const llvm::BitVector &portIndices)
Erases the ports that have their corresponding bit set in portIndices.
static ParseResult parseClassInterface(OpAsmParser &parser, Type &result)
static void printElidePortAnnotations(OpAsmPrinter &p, Operation *op, DictionaryAttr attr, ArrayRef< StringRef > extraElides={})
static ParseResult parseStopAttrs(OpAsmParser &p, NamedAttrList &resultAttrs)
static ParseResult parseNameKind(OpAsmParser &parser, firrtl::NameKindEnumAttr &result)
A forward declaration for NameKind attribute parser.
static ParseResult parseFieldsFromDomain(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &fieldValues, SmallVectorImpl< Type > &fieldTypes, Type &resultType)
static size_t getAddressWidth(size_t depth)
static void forceableAsmResultNames(Forceable op, StringRef name, OpAsmSetValueNameFn setNameFn)
Helper for naming forceable declarations (and their optional ref result).
static void printFModuleLikeOp(OpAsmPrinter &p, FModuleLike op)
static void printFieldsFromDomain(OpAsmPrinter &p, Operation *op, OperandRange fieldValues, TypeRange fieldTypes, Type resultType)
static void printSubfieldLikeOp(OpTy op, ::mlir::OpAsmPrinter &printer)
static bool checkAggConstant(Operation *op, Attribute attr, FIRRTLBaseType type)
static hw::ModulePort::Direction dirFtoH(Direction dir)
static ParseResult parseOptionalParameters(OpAsmParser &parser, SmallVectorImpl< Attribute > ¶meters)
Parse an parameter list if present.
static MemOp::PortKind getMemPortKindFromType(FIRRTLType type)
Return the kind of port this is given the port type from a 'mem' decl.
static void genericAsmResultNames(Operation *op, OpAsmSetValueNameFn setNameFn)
static void printClassInterface(OpAsmPrinter &p, Operation *, ClassType type)
static void printPrintfAttrs(OpAsmPrinter &p, Operation *op, DictionaryAttr attr)
const char * toString(Flow flow)
static void replaceUsesRespectingInsertedPorts(Operation *op1, Operation *op2, ArrayRef< std::pair< unsigned, PortInfo > > insertions)
static bool isLayerSetCompatibleWith(const LayerSet &src, const LayerSet &dst, SmallVectorImpl< SymbolRefAttr > &missing)
Check that the source layers are all present in the destination layers.
static bool isLayerCompatibleWith(mlir::SymbolRefAttr srcLayer, mlir::SymbolRefAttr dstLayer)
Check that the source layer is compatible with the destination layer.
static LayerSet getAmbientLayersFor(Value value)
Get the ambient layer requirements at the definition site of the value.
void buildModuleLike(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports)
static LayerSet getAmbientLayersAt(Operation *op)
Get the ambient layers active at the given op.
static void printFIRRTLImplicitSSAName(OpAsmPrinter &p, Operation *op, DictionaryAttr attrs)
static ParseResult parseFIRRTLImplicitSSAName(OpAsmParser &parser, NamedAttrList &resultAttrs)
static FIRRTLBaseType inferMuxReturnType(FIRRTLBaseType high, FIRRTLBaseType low, bool isConstCondition, std::optional< Location > loc)
Infer the result type for a multiplexer given its two operand types, which may be aggregates.
static LogicalResult verifyInitialAttr(Operation *op, FIRRTLBaseType regType, IntegerAttr initial)
Verify that an optional initial time-zero value attribute is a constant of the correct ground type.
static ParseResult parseCircuitOpAttrs(OpAsmParser &parser, NamedAttrList &resultAttrs)
void getAsmBlockArgumentNamesImpl(Operation *op, mlir::Region ®ion, OpAsmSetValueNameFn setNameFn)
Get a special name to use when printing the entry block arguments of the region contained by an opera...
static void printElideAnnotations(OpAsmPrinter &p, Operation *op, DictionaryAttr attr, ArrayRef< StringRef > extraElides={})
static ParseResult parseElidePortAnnotations(OpAsmParser &parser, NamedAttrList &resultAttrs)
Parse an optional attribute dictionary, adding empty 'annotations' and 'portAnnotations' attributes i...
static void insertPorts(FModuleLike op, ArrayRef< std::pair< unsigned, PortInfo > > ports)
Inserts the given ports.
static ParseResult parseFPrintfAttrs(OpAsmParser &p, NamedAttrList &resultAttrs)
static ParseResult parseMemOp(OpAsmParser &parser, NamedAttrList &resultAttrs)
static void replaceUsesRespectingErasedPorts(Operation *op1, Operation *op2, const llvm::BitVector &erasures)
static LogicalResult checkConnectFlow(Operation *connect)
Check if the source and sink are of appropriate flow.
static void printParameterList(OpAsmPrinter &p, Operation *op, ArrayAttr parameters)
Print a paramter list for a module or instance.
static ParseResult parseVerifAttrs(OpAsmParser &p, NamedAttrList &resultAttrs)
static ParseResult parseElideAnnotations(OpAsmParser &parser, NamedAttrList &resultAttrs)
Parse an optional attribute dictionary, adding an empty 'annotations' attribute if not specified.
ParseResult parseClassLike(OpAsmParser &parser, OperationState &result, bool hasSSAIdentifiers)
static void printCircuitOpAttrs(OpAsmPrinter &p, Operation *op, DictionaryAttr attr)
static LogicalResult verifyObjectSymbolUses(FObjectLike object, SymbolTableCollection &symbolTable)
static LogicalResult verifyPortSymbolUses(FModuleLike module, SymbolTableCollection &symbolTable)
static void printVerifAttrs(OpAsmPrinter &p, Operation *op, DictionaryAttr attr)
static void printMemOp(OpAsmPrinter &p, Operation *op, DictionaryAttr attr)
Always elide "ruw" and elide "annotations" if it exists or if it is empty.
static bool isTypeAllowedForDPI(Operation *op, Type type)
static ParseResult parseElideEmptyName(OpAsmParser &p, NamedAttrList &resultAttrs)
static bool printModulePorts(OpAsmPrinter &p, Block *block, ArrayRef< bool > portDirections, ArrayRef< Attribute > portNames, ArrayRef< Attribute > portTypes, ArrayRef< Attribute > portAnnotations, ArrayRef< Attribute > portSyms, ArrayRef< Attribute > portLocs, ArrayRef< Attribute > domainInfo)
Print a list of module ports in the following form: in x: !firrtl.uint<1> [{class = "DontTouch}...
static void printElideEmptyName(OpAsmPrinter &p, Operation *op, DictionaryAttr attr, ArrayRef< StringRef > extraElides={})
static ParseResult parseFModuleLikeOp(OpAsmParser &parser, OperationState &result, bool hasSSAIdentifiers)
static InstanceOp cloneWithErasedPorts(InstanceOp &instance, const llvm::BitVector &inErasures, const llvm::BitVector &outErasures)
Clone instance, but with ports deleted according to the inErasures and outErasures BitVectors.
static bool isAncestor(Block *block, Block *other)
static Location getLoc(DefSlot slot)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
static std::optional< APInt > getInt(Value value)
Helper to convert a value to a constant integer if it is one.
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
This class represents a reference to a specific field or element of an aggregate value.
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
bool hasDontTouch() const
firrtl.transforms.DontTouchAnnotation
static AnnotationSet forPort(FModuleLike op, size_t portNo)
Get an annotation set for the specified port.
ExprVisitor is a visitor for FIRRTL expression nodes.
ResultType dispatchExprVisitor(Operation *op, ExtraArgs... args)
FIRRTLBaseType getConstType(bool isConst) const
Return a 'const' or non-'const' version of this type.
FIRRTLBaseType getMaskType()
Return this type with all ground types replaced with UInt<1>.
int32_t getBitWidthOrSentinel()
If this is an IntType, AnalogType, or sugar type for a single bit (Clock, Reset, etc) then return the...
FIRRTLBaseType getAllConstDroppedType()
Return this type with a 'const' modifiers dropped.
bool isPassive() const
Return true if this is a "passive" type - one that contains no "flip" types recursively within itself...
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
Caching version of getFieldRefFromValue.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Caching version of getFieldRefFromValue.
This is the common base class between SIntType and UIntType.
int32_t getWidthOrSentinel() const
Return the width of this type, or -1 if it has none specified.
static IntType get(MLIRContext *context, bool isSigned, int32_t widthOrSentinel=-1, bool isConst=false)
Return an SIntType or UIntType with the specified signedness, width, and constness.
bool hasWidth() const
Return true if this integer type has a known width.
std::optional< int32_t > getWidth() const
Return an optional containing the width, if the width is known (or empty if width is unknown).
static StringRef getInnerSymbolAttrName()
Return the name of the attribute used for inner symbol names.
connect(destination, source)
ClassType getInstanceTypeForClassLike(ClassLike classOp)
LogicalResult verifyTypeAgainstClassLike(ClassLike classOp, ClassType type, function_ref< InFlightDiagnostic()> emitError)
Assuming that the classOp is the source of truth, verify that the type accurately matches the signatu...
RefType getForceableResultType(bool forceable, Type type)
Return null or forceable reference result type.
mlir::DenseBoolArrayAttr packAttribute(MLIRContext *context, ArrayRef< Direction > directions)
Return a DenseBoolArrayAttr containing the packed representation of an array of directions.
static bool unGet(Direction dir)
Convert from Direction to bool. The opposite of get;.
SmallVector< Direction > unpackAttribute(mlir::DenseBoolArrayAttr directions)
Turn a packed representation of port attributes into a vector that can be worked with.
static Direction get(bool isOutput)
Return an output direction if isOutput is true, otherwise return an input direction.
static StringRef toString(Direction direction)
FIRRTLType inferElementwiseResult(FIRRTLType lhs, FIRRTLType rhs, std::optional< Location > loc)
FIRRTLType inferBitwiseResult(FIRRTLType lhs, FIRRTLType rhs, std::optional< Location > loc)
FIRRTLType inferAddSubResult(FIRRTLType lhs, FIRRTLType rhs, std::optional< Location > loc)
FIRRTLType inferComparisonResult(FIRRTLType lhs, FIRRTLType rhs, std::optional< Location > loc)
FIRRTLType inferReductionResult(FIRRTLType arg, std::optional< Location > loc)
LogicalResult verifySameOperandsIntTypeKind(Operation *op)
LogicalResult verifyReferencedModule(Operation *instanceOp, SymbolTableCollection &symbolTable, mlir::FlatSymbolRefAttr moduleName)
Verify that the instance refers to a valid FIRRTL module.
BaseTy type_cast(Type type)
Flow swapFlow(Flow flow)
Get a flow's reverse.
Direction
This represents the direction of a single port.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
void walkGroundTypes(FIRRTLType firrtlType, llvm::function_ref< void(uint64_t, FIRRTLBaseType, bool)> fn)
Walk leaf ground types in the firrtlType and apply the function fn.
bool isConstant(Operation *op)
Return true if the specified operation has a constant value.
bool areAnonymousTypesEquivalent(FIRRTLBaseType lhs, FIRRTLBaseType rhs)
Return true if anonymous types of given arguments are equivalent by pointer comparison.
constexpr bool isValidDst(Flow flow)
Flow foldFlow(Value val, Flow accumulatedFlow=Flow::Source)
Compute the flow for a Value, val, as determined by the FIRRTL specification.
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
size_t getNumPorts(Operation *op)
Return the number of ports in a module-like thing (modules, memories, etc).
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
bool containsConst(Type type)
Returns true if the type is or contains a 'const' type whose value is guaranteed to be unchanging at ...
bool isDuplexValue(Value val)
Returns true if the value results from an expression with duplex flow.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
constexpr bool isValidSrc(Flow flow)
SmallSet< SymbolRefAttr, 4, LayerSetCompare > LayerSet
Value getModuleScopedDriver(Value val, bool lookThroughWires, bool lookThroughNodes, bool lookThroughCasts)
Return the value that drives another FIRRTL value within module scope.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
BaseTy type_dyn_cast(Type type)
bool isConst(Type type)
Returns true if this is a 'const' type whose value is guaranteed to be unchanging at circuit executio...
bool hasHardwareElements(FIRRTLType type)
Return true if the given type contains any elements of hardware types.
bool areTypesConstCastable(FIRRTLType destType, FIRRTLType srcType, bool srcOuterTypeIsConst=false)
Returns whether the srcType can be const-casted to the destType.
bool isExpression(Operation *op)
Return true if the specified operation is a firrtl expression.
DeclKind getDeclarationKind(Value val)
std::optional< int64_t > getBitWidth(FIRRTLBaseType type, bool ignoreFlip=false)
::mlir::Type getFinalTypeByFieldID(Type type, uint64_t fieldID)
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
BaseTy type_dyn_cast(Type type)
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void elideImplicitSSAName(OpAsmPrinter &printer, Operation *op, DictionaryAttr attrs, SmallVectorImpl< StringRef > &elides)
Check if the name attribute in attrs matches the SSA name of the operation's first result.
bool isAncestorOfValueOwner(Operation *op, Value value)
Return true if a Value is created "underneath" an operation.
bool inferImplicitSSAName(OpAsmParser &parser, NamedAttrList &attrs)
Ensure that attrs contains a name attribute by inferring its value from the SSA name of the operation...
static SmallVector< T > removeElementsAtIndices(ArrayRef< T > input, const llvm::BitVector &indicesToDrop)
Remove elements from the input array corresponding to set bits in indicesToDrop, returning the elemen...
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
StringAttr getFirMemoryName() const
Compares two SymbolRefAttr lexicographically, returning true if LHS should be ordered before RHS.
InnerSymTarget lookup(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
This holds the name, type, direction of a module's ports.