24#include "mlir/IR/Builders.h"
25#include "mlir/IR/PatternMatch.h"
26#include "mlir/Interfaces/FunctionImplementation.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringSet.h"
38 case ModulePort::Direction::Input:
39 return ModulePort::Direction::Output;
40 case ModulePort::Direction::Output:
41 return ModulePort::Direction::Input;
42 case ModulePort::Direction::InOut:
43 return ModulePort::Direction::InOut;
45 llvm_unreachable(
"unknown PortDirection");
48bool hw::isValidIndexBitWidth(Value index, Value array) {
49 hw::ArrayType arrayType =
50 dyn_cast<hw::ArrayType>(hw::getCanonicalType(array.getType()));
51 assert(arrayType &&
"expected array type");
52 unsigned indexWidth = index.getType().getIntOrFloatBitWidth();
53 auto requiredWidth = llvm::Log2_64_Ceil(arrayType.getNumElements());
54 return requiredWidth == 0 ? (indexWidth == 0 || indexWidth == 1)
55 : indexWidth == requiredWidth;
59bool hw::isCombinational(Operation *op) {
60 struct IsCombClassifier :
public TypeOpVisitor<IsCombClassifier, bool> {
65 return (op->getDialect() && op->getDialect()->getNamespace() ==
"comb") ||
71 if (
auto structCreate = dyn_cast_or_null<StructCreateOp>(inputOp)) {
72 return structCreate.getOperand(fieldIndex);
76 if (
auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
77 if (structInject.getFieldIndex() != fieldIndex)
79 return structInject.getNewValue();
85 ArrayRef<Attribute> attrs) {
87 return ArrayAttr::get(context, {});
90 if (a && !cast<DictionaryAttr>(a).empty()) {
95 return ArrayAttr::get(context, {});
96 return ArrayAttr::get(context, attrs);
102 OpAsmSetValueNameFn setNameFn) {
106 auto module = cast<HWModuleOp>(region.getParentOp());
108 auto *block = ®ion.front();
109 for (
size_t i = 0, e = block->getNumArguments(); i != e; ++i) {
110 auto name =
module.getInputName(i);
112 setNameFn(block->getArgument(i), name);
128LogicalResult hw::checkParameterInContext(
129 Attribute value, ArrayAttr moduleParameters,
131 bool disallowParamRefs) {
134 if (isa<IntegerAttr>(value) || isa<FloatAttr>(value) ||
135 isa<StringAttr>(value) || isa<ParamVerbatimAttr>(value))
139 if (
auto expr = dyn_cast<ParamExprAttr>(value)) {
140 for (
auto op : expr.getOperands())
149 if (
auto parameterRef = dyn_cast<ParamDeclRefAttr>(value)) {
150 auto nameAttr = parameterRef.getName();
154 if (disallowParamRefs) {
155 instanceError([&](
auto &diag) {
156 diag <<
"parameter " << nameAttr
157 <<
" cannot be used as a default value for a parameter";
164 for (
auto param : moduleParameters) {
165 auto paramAttr = cast<ParamDeclAttr>(param);
166 if (paramAttr.getName() != nameAttr)
170 if (paramAttr.getType() == parameterRef.getType())
173 instanceError([&](
auto &diag) {
174 diag <<
"parameter " << nameAttr <<
" used with type "
175 << parameterRef.getType() <<
"; should have type "
176 << paramAttr.getType();
182 instanceError([&](
auto &diag) {
183 diag <<
"use of unknown parameter " << nameAttr;
189 instanceError([&](
auto &diag) {
190 diag <<
"invalid parameter value " << value;
202LogicalResult hw::checkParameterInContext(Attribute value, Operation *module,
204 bool disallowParamRefs) {
206 [&](
const std::function<bool(InFlightDiagnostic &)> &fn) {
208 auto diag = usingOp->emitOpError();
210 diag.attachNote(module->getLoc()) <<
"module declared here";
215 module->getAttrOfType<ArrayAttr>(
"parameters"),
216 emitError, disallowParamRefs);
221bool hw::isValidParameterExpression(Attribute attr, Operation *module) {
230 for (
auto [i, barg] : llvm::enumerate(bodyRegion.getArguments())) {
262void ConstantOp::print(OpAsmPrinter &p) {
264 p.printAttribute(getValueAttr());
265 p.printOptionalAttrDict((*this)->getAttrs(), {
"value"});
268ParseResult ConstantOp::parse(OpAsmParser &parser, OperationState &result) {
269 IntegerAttr valueAttr;
271 if (parser.parseAttribute(valueAttr,
"value", result.attributes) ||
272 parser.parseOptionalAttrDict(result.attributes))
275 result.addTypes(valueAttr.getType());
279LogicalResult ConstantOp::verify() {
281 if (getValue().
getBitWidth() != cast<IntegerType>(getType()).getWidth())
283 "hw.constant attribute bitwidth doesn't match return type");
290void ConstantOp::build(OpBuilder &builder, OperationState &result,
291 const APInt &value) {
293 auto type = IntegerType::get(builder.getContext(), value.getBitWidth());
294 auto attr = builder.getIntegerAttr(type, value);
295 return build(builder, result, type, attr);
300void ConstantOp::build(OpBuilder &builder, OperationState &result,
302 return build(builder, result, value.getType(), value);
309void ConstantOp::build(OpBuilder &builder, OperationState &result, Type type,
311 auto numBits = cast<IntegerType>(type).getWidth();
312 build(builder, result,
313 APInt(numBits, (uint64_t)value,
true,
317void ConstantOp::getAsmResultNames(
318 function_ref<
void(Value, StringRef)> setNameFn) {
319 auto intTy = getType();
320 auto intCst = getValue();
323 if (cast<IntegerType>(intTy).
getWidth() == 1)
324 return setNameFn(getResult(), intCst.isZero() ?
"false" :
"true");
327 SmallVector<char, 32> specialNameBuffer;
328 llvm::raw_svector_ostream specialName(specialNameBuffer);
329 specialName <<
'c' << intCst <<
'_' << intTy;
330 setNameFn(getResult(), specialName.str());
333OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) {
334 assert(adaptor.getOperands().empty() &&
"constant has no operands");
335 return getValueAttr();
346 ArrayRef<StringRef> ignoredAttrs = {}) {
347 auto names = op.getAttributeNames();
348 llvm::SmallDenseSet<StringRef> nameSet;
349 nameSet.reserve(names.size() + ignoredAttrs.size());
350 nameSet.insert(names.begin(), names.end());
351 nameSet.insert(ignoredAttrs.begin(), ignoredAttrs.end());
352 return llvm::any_of(op->getAttrs(), [&](
auto namedAttr) {
353 return !nameSet.contains(namedAttr.getName());
357void WireOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
359 auto nameAttr = (*this)->getAttrOfType<StringAttr>(
"name");
360 if (nameAttr && !nameAttr.getValue().empty())
361 setNameFn(getResult(), nameAttr.getValue());
364std::optional<size_t> WireOp::getTargetResultIndex() {
return 0; }
366OpFoldResult WireOp::fold(FoldAdaptor adaptor) {
375LogicalResult WireOp::canonicalize(WireOp wire, PatternRewriter &rewriter) {
381 if (wire.getInnerSymAttr())
386 if (
auto *inputOp = wire.getInput().getDefiningOp())
388 rewriter.modifyOpInPlace(inputOp,
389 [&] { inputOp->setAttr(
"sv.namehint", name); });
391 rewriter.replaceOp(wire, wire.getInput());
401 if (
auto typeAlias = dyn_cast<TypeAliasType>(type))
402 type = typeAlias.getCanonicalType();
404 if (
auto structType = dyn_cast<StructType>(type)) {
405 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
407 return op->emitOpError(
"expected array attribute for constant of type ")
409 if (structType.getElements().size() != arrayAttr.size())
410 return op->emitOpError(
"array attribute (")
411 << arrayAttr.size() <<
") has wrong size for struct constant ("
412 << structType.getElements().size() <<
")";
414 for (
auto [attr, fieldInfo] :
415 llvm::zip(arrayAttr.getValue(), structType.getElements())) {
419 }
else if (
auto arrayType = dyn_cast<ArrayType>(type)) {
420 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
422 return op->emitOpError(
"expected array attribute for constant of type ")
424 if (arrayType.getNumElements() != arrayAttr.size())
425 return op->emitOpError(
"array attribute (")
426 << arrayAttr.size() <<
") has wrong size for array constant ("
427 << arrayType.getNumElements() <<
")";
430 for (
auto attr : arrayAttr.getValue()) {
434 }
else if (
auto arrayType = dyn_cast<UnpackedArrayType>(type)) {
435 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
437 return op->emitOpError(
"expected array attribute for constant of type ")
440 if (arrayType.getNumElements() != arrayAttr.size())
441 return op->emitOpError(
"array attribute (")
443 <<
") has wrong size for unpacked array constant ("
444 << arrayType.getNumElements() <<
")";
446 for (
auto attr : arrayAttr.getValue()) {
450 }
else if (
auto enumType = dyn_cast<EnumType>(type)) {
451 auto stringAttr = dyn_cast<StringAttr>(attr);
453 return op->emitOpError(
"expected string attribute for constant of type ")
455 }
else if (
auto intType = dyn_cast<IntegerType>(type)) {
457 auto intAttr = dyn_cast<IntegerAttr>(attr);
459 return op->emitOpError(
"expected integer attribute for constant of type ")
462 if (intAttr.getValue().getBitWidth() != intType.getWidth())
463 return op->emitOpError(
"hw.constant attribute bitwidth "
464 "doesn't match return type");
465 }
else if (
auto typedAttr = dyn_cast<TypedAttr>(attr)) {
466 if (typedAttr.getType() != type)
467 return op->emitOpError(
"typed attr doesn't match the return type ")
470 return op->emitOpError(
"unknown element type ") << type;
475LogicalResult AggregateConstantOp::verify() {
479OpFoldResult AggregateConstantOp::fold(FoldAdaptor) {
return getFieldsAttr(); }
487 if (p.parseType(resultType) || p.parseEqual() ||
488 p.parseAttribute(value, resultType))
495 p << resultType <<
" = ";
496 p.printAttributeWithoutType(value);
499LogicalResult ParamValueOp::verify() {
505OpFoldResult ParamValueOp::fold(FoldAdaptor adaptor) {
506 assert(adaptor.getOperands().empty() &&
"hw.param.value has no operands");
507 return getValueAttr();
516 return isa<HWModuleLike, InstanceOp>(moduleOrInstance);
522 return TypeSwitch<Operation *, FunctionType>(moduleOrInstance)
523 .Case<InstanceOp, InstanceChoiceOp>([](
auto instance) {
524 SmallVector<Type> inputs(instance->getOperandTypes());
525 SmallVector<Type> results(instance->getResultTypes());
526 return FunctionType::get(instance->getContext(), inputs, results);
529 [](
auto mod) {
return mod.getHWModuleType().getFuncType(); })
530 .Default([](Operation *op) {
531 return cast<FunctionType>(
532 cast<mlir::FunctionOpInterface>(op).getFunctionType());
540 auto nameAttr =
module->getAttrOfType<StringAttr>("verilogName");
544 return module->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
547template <
typename ModuleTy>
549buildModule(OpBuilder &builder, OperationState &result, StringAttr name,
551 ArrayRef<NamedAttribute> attributes, StringAttr comment) {
552 using namespace mlir::function_interface_impl;
555 result.addAttribute(SymbolTable::getSymbolAttrName(), name);
557 SmallVector<Attribute> perPortAttrs;
558 SmallVector<ModulePort> portTypes;
560 for (
auto elt : ports) {
561 portTypes.push_back(elt);
562 llvm::SmallVector<NamedAttribute> portAttrs;
564 llvm::copy(elt.attrs, std::back_inserter(portAttrs));
565 perPortAttrs.push_back(builder.getDictionaryAttr(portAttrs));
570 parameters = builder.getArrayAttr({});
573 auto type = ModuleType::get(builder.getContext(), portTypes);
574 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name),
575 TypeAttr::get(type));
576 result.addAttribute(
"per_port_attrs",
578 result.addAttribute(
"parameters", parameters);
580 comment = builder.getStringAttr(
"");
581 result.addAttribute(
"comment", comment);
582 result.addAttributes(attributes);
588 MLIRContext *context, ArrayRef<std::pair<unsigned, PortInfo>> insertArgs,
589 ArrayRef<unsigned> removeArgs, ArrayRef<Attribute> oldArgNames,
590 ArrayRef<Type> oldArgTypes, ArrayRef<Attribute> oldArgAttrs,
591 ArrayRef<Location> oldArgLocs, SmallVector<Attribute> &newArgNames,
592 SmallVector<Type> &newArgTypes, SmallVector<Attribute> &newArgAttrs,
593 SmallVector<Location> &newArgLocs, Block *body =
nullptr) {
598 assert(llvm::is_sorted(insertArgs,
599 [](
auto &a,
auto &b) {
return a.first < b.first; }) &&
600 "insertArgs must be in ascending order");
601 assert(llvm::is_sorted(removeArgs, [](
auto &a,
auto &b) {
return a < b; }) &&
602 "removeArgs must be in ascending order");
605 auto oldArgCount = oldArgTypes.size();
606 auto newArgCount = oldArgCount + insertArgs.size() - removeArgs.size();
607 assert((
int)newArgCount >= 0);
609 newArgNames.reserve(newArgCount);
610 newArgTypes.reserve(newArgCount);
611 newArgAttrs.reserve(newArgCount);
612 newArgLocs.reserve(newArgCount);
614 auto exportPortAttrName = StringAttr::get(context,
"hw.exportPort");
615 auto emptyDictAttr = DictionaryAttr::get(context, {});
616 auto unknownLoc = UnknownLoc::get(context);
618 BitVector erasedIndices;
620 erasedIndices.resize(oldArgCount + insertArgs.size());
622 for (
unsigned argIdx = 0, idx = 0; argIdx <= oldArgCount; ++argIdx, ++idx) {
624 while (!insertArgs.empty() && insertArgs[0].first == argIdx) {
625 auto port = insertArgs[0].second;
627 !isa<InOutType>(port.type))
628 port.type = InOutType::get(port.type);
629 auto sym = port.getSym();
631 (sym && !sym.empty())
632 ? DictionaryAttr::get(context, {{exportPortAttrName, sym}})
634 newArgNames.push_back(port.name);
635 newArgTypes.push_back(port.type);
636 newArgAttrs.push_back(attr);
637 insertArgs = insertArgs.drop_front();
638 LocationAttr loc = port.loc ? port.loc : unknownLoc;
639 newArgLocs.push_back(loc);
641 body->insertArgument(idx++, port.type, loc);
643 if (argIdx == oldArgCount)
647 bool removed =
false;
648 while (!removeArgs.empty() && removeArgs[0] == argIdx) {
649 removeArgs = removeArgs.drop_front();
655 erasedIndices.set(idx);
657 newArgNames.push_back(oldArgNames[argIdx]);
658 newArgTypes.push_back(oldArgTypes[argIdx]);
659 newArgAttrs.push_back(oldArgAttrs.empty() ? emptyDictAttr
660 : oldArgAttrs[argIdx]);
661 newArgLocs.push_back(oldArgLocs[argIdx]);
666 body->eraseArguments(erasedIndices);
668 assert(newArgNames.size() == newArgCount);
669 assert(newArgTypes.size() == newArgCount);
670 assert(newArgAttrs.size() == newArgCount);
671 assert(newArgLocs.size() == newArgCount);
685[[deprecated]]
static void
687 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
688 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
689 ArrayRef<unsigned> removeInputs,
690 ArrayRef<unsigned> removeOutputs, Block *body =
nullptr) {
691 auto moduleOp = cast<HWModuleLike>(op);
692 auto *context = moduleOp.getContext();
695 auto oldArgNames = moduleOp.getInputNames();
696 auto oldArgTypes = moduleOp.getInputTypes();
697 auto oldArgAttrs = moduleOp.getAllInputAttrs();
698 auto oldArgLocs = moduleOp.getInputLocs();
700 auto oldResultNames = moduleOp.getOutputNames();
701 auto oldResultTypes = moduleOp.getOutputTypes();
702 auto oldResultAttrs = moduleOp.getAllOutputAttrs();
703 auto oldResultLocs = moduleOp.getOutputLocs();
706 SmallVector<Attribute> newArgNames, newResultNames;
707 SmallVector<Type> newArgTypes, newResultTypes;
708 SmallVector<Attribute> newArgAttrs, newResultAttrs;
709 SmallVector<Location> newArgLocs, newResultLocs;
712 oldArgTypes, oldArgAttrs, oldArgLocs, newArgNames,
713 newArgTypes, newArgAttrs, newArgLocs, body);
716 oldResultTypes, oldResultAttrs, oldResultLocs,
717 newResultNames, newResultTypes, newResultAttrs,
721 auto fnty = FunctionType::get(context, newArgTypes, newResultTypes);
723 moduleOp.setHWModuleType(modty);
724 moduleOp.setAllInputAttrs(newArgAttrs);
725 moduleOp.setAllOutputAttrs(newResultAttrs);
727 newArgLocs.append(newResultLocs.begin(), newResultLocs.end());
728 moduleOp.setAllPortLocs(newArgLocs);
731void HWModuleOp::build(OpBuilder &builder, OperationState &result,
733 ArrayAttr parameters,
734 ArrayRef<NamedAttribute> attributes, StringAttr comment,
735 bool shouldEnsureTerminator) {
736 buildModule<HWModuleOp>(builder, result, name, ports, parameters, attributes,
740 auto *bodyRegion = result.regions[0].get();
742 bodyRegion->push_back(body);
745 auto unknownLoc = builder.getUnknownLoc();
746 for (
auto port : ports.getInputs()) {
747 auto loc = port.loc ? Location(port.loc) : unknownLoc;
748 auto type = port.type;
749 if (port.isInOut() && !isa<InOutType>(type))
750 type = InOutType::get(type);
751 body->addArgument(type, loc);
755 auto unknownLocAttr = cast<LocationAttr>(unknownLoc);
756 SmallVector<Attribute> resultLocs;
757 for (
auto port : ports.getOutputs())
758 resultLocs.push_back(port.loc ? port.loc : unknownLocAttr);
759 result.addAttribute(
"result_locs", builder.getArrayAttr(resultLocs));
761 if (shouldEnsureTerminator)
762 HWModuleOp::ensureTerminator(*bodyRegion, builder, result.location);
765void HWModuleOp::build(OpBuilder &builder, OperationState &result,
766 StringAttr name, ArrayRef<PortInfo> ports,
767 ArrayAttr parameters,
768 ArrayRef<NamedAttribute> attributes,
769 StringAttr comment) {
770 build(builder, result, name,
ModulePortInfo(ports), parameters, attributes,
774void HWModuleOp::build(OpBuilder &builder, OperationState &odsState,
777 ArrayRef<NamedAttribute> attributes,
778 StringAttr comment) {
779 build(builder, odsState, name, ports, parameters, attributes, comment,
781 auto *bodyRegion = odsState.regions[0].get();
782 OpBuilder::InsertionGuard guard(builder);
784 builder.setInsertionPointToEnd(&bodyRegion->front());
785 modBuilder(builder, accessor);
787 llvm::SmallVector<Value> outputOperands = accessor.getOutputOperands();
788 builder.create<hw::OutputOp>(odsState.location, outputOperands);
791void HWModuleOp::modifyPorts(
792 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
793 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
794 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
802StringAttr HWModuleExternOp::getVerilogModuleNameAttr() {
803 if (
auto vName = getVerilogNameAttr())
806 return (*this)->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
809StringAttr HWModuleGeneratedOp::getVerilogModuleNameAttr() {
810 if (
auto vName = getVerilogNameAttr()) {
813 return (*this)->getAttrOfType<StringAttr>(
814 ::mlir::SymbolTable::getSymbolAttrName());
817void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
819 StringRef verilogName, ArrayAttr parameters,
820 ArrayRef<NamedAttribute> attributes) {
821 buildModule<HWModuleExternOp>(builder, result, name, ports, parameters,
825 LocationAttr unknownLoc = builder.getUnknownLoc();
826 SmallVector<Attribute> portLocs;
827 for (
auto elt : ports)
828 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
829 result.addAttribute(
"port_locs", builder.getArrayAttr(portLocs));
831 if (!verilogName.empty())
832 result.addAttribute(
"verilogName", builder.getStringAttr(verilogName));
835void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
836 StringAttr name, ArrayRef<PortInfo> ports,
837 StringRef verilogName, ArrayAttr parameters,
838 ArrayRef<NamedAttribute> attributes) {
839 build(builder, result, name,
ModulePortInfo(ports), verilogName, parameters,
843void HWModuleExternOp::modifyPorts(
844 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
845 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
846 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
851void HWModuleExternOp::appendOutputs(
852 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
854void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
855 FlatSymbolRefAttr genKind, StringAttr name,
857 StringRef verilogName, ArrayAttr parameters,
858 ArrayRef<NamedAttribute> attributes) {
859 buildModule<HWModuleGeneratedOp>(builder, result, name, ports, parameters,
862 LocationAttr unknownLoc = builder.getUnknownLoc();
863 SmallVector<Attribute> portLocs;
864 for (
auto elt : ports)
865 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
866 result.addAttribute(
"port_locs", builder.getArrayAttr(portLocs));
868 result.addAttribute(
"generatorKind", genKind);
869 if (!verilogName.empty())
870 result.addAttribute(
"verilogName", builder.getStringAttr(verilogName));
873void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
874 FlatSymbolRefAttr genKind, StringAttr name,
875 ArrayRef<PortInfo> ports, StringRef verilogName,
876 ArrayAttr parameters,
877 ArrayRef<NamedAttribute> attributes) {
878 build(builder, result, genKind, name,
ModulePortInfo(ports), verilogName,
879 parameters, attributes);
882void HWModuleGeneratedOp::modifyPorts(
883 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
884 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
885 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
890void HWModuleGeneratedOp::appendOutputs(
891 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
893static bool hasAttribute(StringRef name, ArrayRef<NamedAttribute> attrs) {
894 for (
auto &argAttr : attrs)
895 if (argAttr.getName() == name)
900template <
typename ModuleTy>
902 OperationState &result) {
904 using namespace mlir::function_interface_impl;
905 auto builder = parser.getBuilder();
906 auto loc = parser.getCurrentLocation();
909 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
913 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
918 FlatSymbolRefAttr kindAttr;
919 if constexpr (std::is_same_v<ModuleTy, HWModuleGeneratedOp>) {
920 if (parser.parseComma() ||
921 parser.parseAttribute(kindAttr,
"generatorKind", result.attributes)) {
927 ArrayAttr parameters;
931 SmallVector<module_like_impl::PortParse> ports;
937 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
941 parser.emitError(loc,
"explicit `parameters` attributes not allowed");
945 result.addAttribute(
"parameters", parameters);
946 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name), modType);
950 SmallVector<Attribute> attrs;
951 for (
auto &port : ports)
952 attrs.push_back(port.attrs ? port.attrs : builder.getDictionaryAttr({}));
954 auto nonEmptyAttrsFn = [](Attribute attr) {
955 return attr && !cast<DictionaryAttr>(attr).empty();
957 if (llvm::any_of(attrs, nonEmptyAttrsFn))
958 result.addAttribute(ModuleTy::getPerPortAttrsAttrName(result.name),
959 builder.getArrayAttr(attrs));
962 auto unknownLoc = builder.getUnknownLoc();
963 auto nonEmptyLocsFn = [unknownLoc](Attribute attr) {
964 return attr && cast<Location>(attr) != unknownLoc;
966 SmallVector<Attribute> locs;
967 StringAttr portLocsAttrName;
968 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>) {
971 portLocsAttrName = ModuleTy::getResultLocsAttrName(result.name);
972 for (
auto &port : ports)
974 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
977 portLocsAttrName = ModuleTy::getPortLocsAttrName(result.name);
978 for (
auto &port : ports)
979 locs.push_back(port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc);
981 if (llvm::any_of(locs, nonEmptyLocsFn))
982 result.addAttribute(portLocsAttrName, builder.getArrayAttr(locs));
985 SmallVector<OpAsmParser::Argument, 4> entryArgs;
986 for (
auto &port : ports)
988 entryArgs.push_back(port);
991 auto *body = result.addRegion();
992 if (std::is_same_v<ModuleTy, HWModuleOp>) {
993 if (parser.parseRegion(*body, entryArgs))
996 HWModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1001ParseResult HWModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1002 return parseHWModuleOp<HWModuleOp>(parser, result);
1005ParseResult HWModuleExternOp::parse(OpAsmParser &parser,
1006 OperationState &result) {
1007 return parseHWModuleOp<HWModuleExternOp>(parser, result);
1010ParseResult HWModuleGeneratedOp::parse(OpAsmParser &parser,
1011 OperationState &result) {
1012 return parseHWModuleOp<HWModuleGeneratedOp>(parser, result);
1016 if (
auto mod = dyn_cast<HWModuleLike>(op))
1017 return mod.getHWModuleType().getFuncType();
1018 return cast<FunctionType>(
1019 cast<mlir::FunctionOpInterface>(op).getFunctionType());
1022template <
typename ModuleTy>
1026 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
1027 if (
auto visibility = mod.getOperation()->template getAttrOfType<StringAttr>(
1028 visibilityAttrName))
1029 p << visibility.getValue() <<
' ';
1032 p.printSymbolName(SymbolTable::getSymbolName(mod.getOperation()).getValue());
1033 if (
auto gen = dyn_cast<HWModuleGeneratedOp>(mod.getOperation())) {
1035 p.printSymbolName(gen.getGeneratorKind());
1043 SmallVector<StringRef, 3> omittedAttrs;
1044 if (isa<HWModuleGeneratedOp>(mod.getOperation()))
1045 omittedAttrs.push_back(
"generatorKind");
1046 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>)
1047 omittedAttrs.push_back(mod.getResultLocsAttrName());
1049 omittedAttrs.push_back(mod.getPortLocsAttrName());
1050 omittedAttrs.push_back(mod.getModuleTypeAttrName());
1051 omittedAttrs.push_back(mod.getPerPortAttrsAttrName());
1052 omittedAttrs.push_back(mod.getParametersAttrName());
1053 omittedAttrs.push_back(visibilityAttrName);
1055 mod.getOperation()->template getAttrOfType<StringAttr>(
"comment"))
1056 if (cmt.getValue().empty())
1057 omittedAttrs.push_back(
"comment");
1059 mlir::function_interface_impl::printFunctionAttributes(p, mod.getOperation(),
1063void HWModuleExternOp::print(OpAsmPrinter &p) {
printModuleOp(p, *
this); }
1064void HWModuleGeneratedOp::print(OpAsmPrinter &p) {
printModuleOp(p, *
this); }
1066void HWModuleOp::print(OpAsmPrinter &p) {
1070 Region &body = getBody();
1071 if (!body.empty()) {
1073 p.printRegion(body,
false,
1079 assert(isa<HWModuleLike>(module) &&
1080 "verifier hook should only be called on modules");
1082 SmallPtrSet<Attribute, 4> paramNames;
1085 for (
auto param :
module->getAttrOfType<ArrayAttr>("parameters")) {
1086 auto paramAttr = cast<ParamDeclAttr>(param);
1090 if (!paramNames.insert(paramAttr.getName()).second)
1091 return module->emitOpError("parameter ")
1092 << paramAttr << " has the same name as a previous parameter";
1095 auto value = paramAttr.getValue();
1099 auto typedValue = dyn_cast<TypedAttr>(value);
1101 return module->emitOpError("parameter ")
1102 << paramAttr << " should have a typed value; has value
" << value;
1104 if (typedValue.getType() != paramAttr.getType())
1105 return module->emitOpError("parameter
")
1106 << paramAttr << " should have type
" << paramAttr.getType()
1107 << "; has type
" << typedValue.getType();
1109 // Verify that this is a valid parameter value, disallowing parameter
1110 // references. We could allow parameters to refer to each other in the
1111 // future with lexical ordering if there is a need.
1112 if (failed(checkParameterInContext(value, module, module,
1113 /*disallowParamRefs=*/true)))
1119LogicalResult HWModuleOp::verify() {
1120 if (failed(verifyModuleCommon(*this)))
1123 auto type = getModuleType();
1124 auto *body = getBodyBlock();
1126 // Verify the number of block arguments.
1127 auto numInputs = type.getNumInputs();
1128 if (body->getNumArguments() != numInputs)
1129 return emitOpError("entry block must have
")
1130 << numInputs << " arguments to match
module signature";
1137std::pair<StringAttr, BlockArgument>
1138HWModuleOp::insertInput(
unsigned index, StringAttr name, Type ty) {
1142 for (
auto port : ports)
1143 ns.newName(port.name.getValue());
1144 auto nameAttr = StringAttr::get(getContext(), ns.
newName(name.getValue()));
1150 port.
name = nameAttr;
1157 return {nameAttr, body->getArgument(index)};
1160void HWModuleOp::insertOutputs(
unsigned index,
1161 ArrayRef<std::pair<StringAttr, Value>> outputs) {
1163 auto output = cast<OutputOp>(
getBodyBlock()->getTerminator());
1164 assert(index <= output->getNumOperands() &&
"invalid output index");
1167 SmallVector<std::pair<unsigned, PortInfo>> indexedNewPorts;
1168 for (
auto &[name, value] : outputs) {
1172 port.
type = value.getType();
1173 indexedNewPorts.emplace_back(index, port);
1179 for (
auto &[name, value] : outputs)
1180 output->insertOperands(index++, value);
1183void HWModuleOp::appendOutputs(ArrayRef<std::pair<StringAttr, Value>> outputs) {
1184 return insertOutputs(getNumOutputPorts(), outputs);
1187void HWModuleOp::getAsmBlockArgumentNames(mlir::Region ®ion,
1192void HWModuleExternOp::getAsmBlockArgumentNames(
1197template <
typename ModTy>
1199 auto locs =
module.getPortLocs();
1201 SmallVector<Location> retval;
1202 retval.reserve(locs->size());
1203 for (
auto l : *locs)
1204 retval.push_back(cast<Location>(l));
1206 assert(!locs->size() || locs->size() == module.getNumPorts());
1209 return SmallVector<Location>(module.getNumPorts(),
1210 UnknownLoc::get(module.getContext()));
1213SmallVector<Location> HWModuleOp::getAllPortLocs() {
1214 SmallVector<Location> portLocs;
1216 auto resultLocs = getResultLocsAttr();
1217 unsigned inputCount = 0;
1219 auto unknownLoc = UnknownLoc::get(getContext());
1221 for (
unsigned i = 0, e =
getNumPorts(); i < e; ++i) {
1222 if (modType.isOutput(i)) {
1223 auto loc = resultLocs
1225 resultLocs.getValue()[portLocs.size() - inputCount])
1227 portLocs.push_back(loc);
1229 auto loc = body ? body->getArgument(inputCount).getLoc() : unknownLoc;
1230 portLocs.push_back(loc);
1237SmallVector<Location> HWModuleExternOp::getAllPortLocs() {
1238 return ::getAllPortLocs(*
this);
1241SmallVector<Location> HWModuleGeneratedOp::getAllPortLocs() {
1242 return ::getAllPortLocs(*
this);
1245void HWModuleOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1246 SmallVector<Attribute> resultLocs;
1247 unsigned inputCount = 0;
1250 for (
unsigned i = 0, e =
getNumPorts(); i < e; ++i) {
1251 if (modType.isOutput(i))
1252 resultLocs.push_back(locs[i]);
1254 body->getArgument(inputCount++).setLoc(cast<Location>(locs[i]));
1256 setResultLocsAttr(ArrayAttr::get(getContext(), resultLocs));
1259void HWModuleExternOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1260 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1263void HWModuleGeneratedOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1264 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1267template <
typename ModTy>
1269 auto numInputs =
module.getNumInputPorts();
1270 SmallVector<Attribute> argNames(names.begin(), names.begin() + numInputs);
1271 SmallVector<Attribute> resNames(names.begin() + numInputs, names.end());
1272 auto oldType =
module.getModuleType();
1273 SmallVector<ModulePort> newPorts(oldType.getPorts().begin(),
1274 oldType.getPorts().end());
1275 for (
size_t i = 0UL, e = newPorts.size(); i != e; ++i)
1276 newPorts[i].name = cast<StringAttr>(names[i]);
1277 auto newType = ModuleType::get(module.getContext(), newPorts);
1278 module.setModuleType(newType);
1281void HWModuleOp::setAllPortNames(ArrayRef<Attribute> names) {
1285void HWModuleExternOp::setAllPortNames(ArrayRef<Attribute> names) {
1289void HWModuleGeneratedOp::setAllPortNames(ArrayRef<Attribute> names) {
1293ArrayRef<Attribute> HWModuleOp::getAllPortAttrs() {
1294 auto attrs = getPerPortAttrs();
1295 if (attrs && !attrs->empty())
1296 return attrs->getValue();
1300ArrayRef<Attribute> HWModuleExternOp::getAllPortAttrs() {
1301 auto attrs = getPerPortAttrs();
1302 if (attrs && !attrs->empty())
1303 return attrs->getValue();
1307ArrayRef<Attribute> HWModuleGeneratedOp::getAllPortAttrs() {
1308 auto attrs = getPerPortAttrs();
1309 if (attrs && !attrs->empty())
1310 return attrs->getValue();
1314void HWModuleOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1315 setPerPortAttrsAttr(
arrayOrEmpty(getContext(), attrs));
1318void HWModuleExternOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1319 setPerPortAttrsAttr(
arrayOrEmpty(getContext(), attrs));
1322void HWModuleGeneratedOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1323 setPerPortAttrsAttr(
arrayOrEmpty(getContext(), attrs));
1326void HWModuleOp::removeAllPortAttrs() {
1327 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1330void HWModuleExternOp::removeAllPortAttrs() {
1331 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1334void HWModuleGeneratedOp::removeAllPortAttrs() {
1335 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1340template <
typename ModTy>
1342 auto argAttrs = mod.getAllInputAttrs();
1343 auto resAttrs = mod.getAllOutputAttrs();
1344 mod.setModuleTypeAttr(TypeAttr::get(type));
1345 unsigned newNumArgs = type.getNumInputs();
1346 unsigned newNumResults = type.getNumOutputs();
1348 auto emptyDict = DictionaryAttr::get(mod.getContext());
1349 argAttrs.resize(newNumArgs, emptyDict);
1350 resAttrs.resize(newNumResults, emptyDict);
1352 SmallVector<Attribute> attrs;
1353 attrs.append(argAttrs.begin(), argAttrs.end());
1354 attrs.append(resAttrs.begin(), resAttrs.end());
1357 return mod.removeAllPortAttrs();
1358 mod.setAllPortAttrs(attrs);
1361void HWModuleOp::setHWModuleType(ModuleType type) {
1362 return ::setHWModuleType(*
this, type);
1365void HWModuleExternOp::setHWModuleType(ModuleType type) {
1366 return ::setHWModuleType(*
this, type);
1369void HWModuleGeneratedOp::setHWModuleType(ModuleType type) {
1370 return ::setHWModuleType(*
this, type);
1375Operation *HWModuleGeneratedOp::getGeneratorKindOp() {
1376 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
1377 return topLevelModuleOp.lookupSymbol(getGeneratorKind());
1381HWModuleGeneratedOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1382 auto *referencedKind =
1383 symbolTable.lookupNearestSymbolFrom(*
this, getGeneratorKindAttr());
1385 if (referencedKind ==
nullptr)
1386 return emitError(
"Cannot find generator definition '")
1387 << getGeneratorKind() <<
"'";
1389 if (!isa<HWGeneratorSchemaOp>(referencedKind))
1390 return emitError(
"Symbol resolved to '")
1391 << referencedKind->getName()
1392 <<
"' which is not a HWGeneratorSchemaOp";
1394 auto referencedKindOp = dyn_cast<HWGeneratorSchemaOp>(referencedKind);
1395 auto paramRef = referencedKindOp.getRequiredAttrs();
1396 auto dict = (*this)->getAttrDictionary();
1397 for (
auto str : paramRef) {
1398 auto strAttr = dyn_cast<StringAttr>(str);
1400 return emitError(
"Unknown attribute type, expected a string");
1401 if (!dict.get(strAttr.getValue()))
1402 return emitError(
"Missing attribute '") << strAttr.getValue() <<
"'";
1408LogicalResult HWModuleGeneratedOp::verify() {
1412void HWModuleGeneratedOp::getAsmBlockArgumentNames(
1417LogicalResult HWModuleOp::verifyBody() {
return success(); }
1419template <
typename ModuleTy>
1421 auto modTy = mod.getHWModuleType();
1422 auto emptyDict = DictionaryAttr::get(mod.getContext());
1423 SmallVector<PortInfo> retval;
1424 auto locs = mod.getAllPortLocs();
1425 for (
unsigned i = 0, e = modTy.getNumPorts(); i < e; ++i) {
1426 LocationAttr loc = locs[i];
1427 DictionaryAttr attrs =
1428 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(i));
1431 retval.push_back({modTy.getPorts()[i],
1432 modTy.isOutput(i) ? modTy.getOutputIdForPortId(i)
1433 : modTy.getInputIdForPortId(i),
1439template <
typename ModuleTy>
1441 auto modTy = mod.getHWModuleType();
1442 auto emptyDict = DictionaryAttr::get(mod.getContext());
1443 LocationAttr loc = mod.getPortLoc(idx);
1444 DictionaryAttr attrs =
1445 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(idx));
1448 return {modTy.getPorts()[idx],
1449 modTy.isOutput(idx) ? modTy.getOutputIdForPortId(idx)
1450 : modTy.getInputIdForPortId(idx),
1459void InstanceOp::build(OpBuilder &builder, OperationState &result,
1460 Operation *module, StringAttr name,
1461 ArrayRef<Value> inputs, ArrayAttr parameters,
1462 InnerSymAttr innerSym) {
1464 parameters = builder.getArrayAttr({});
1466 auto mod = cast<hw::HWModuleLike>(module);
1467 auto argNames = builder.getArrayAttr(mod.getInputNames());
1468 auto resultNames = builder.getArrayAttr(mod.getOutputNames());
1473 ModuleType modType = mod.getHWModuleType();
1474 FailureOr<ModuleType> resolvedModType = modType.resolveParametricTypes(
1475 parameters, result.location,
false);
1476 if (succeeded(resolvedModType))
1477 modType = *resolvedModType;
1478 FunctionType funcType = resolvedModType->getFuncType();
1479 build(builder, result, funcType.getResults(), name,
1480 FlatSymbolRefAttr::get(SymbolTable::getSymbolName(module)), inputs,
1481 argNames, resultNames, parameters, innerSym, {});
1484std::optional<size_t> InstanceOp::getTargetResultIndex() {
1486 return std::nullopt;
1489LogicalResult InstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1491 *
this, getModuleNameAttr(), getInputs(), getResultTypes(), getArgNames(),
1492 getResultNames(), getParameters(), symbolTable);
1495LogicalResult InstanceOp::verify() {
1496 auto module = (*this)->getParentOfType<HWModuleOp>();
1500 auto moduleParameters =
module->getAttrOfType<ArrayAttr>("parameters");
1502 [&](
const std::function<bool(InFlightDiagnostic &)> &fn) {
1503 auto diag = emitOpError();
1505 diag.attachNote(module->getLoc()) <<
"module declared here";
1508 getParameters(), moduleParameters, emitError);
1511ParseResult InstanceOp::parse(OpAsmParser &parser, OperationState &result) {
1512 StringAttr instanceNameAttr;
1513 InnerSymAttr innerSym;
1514 FlatSymbolRefAttr moduleNameAttr;
1515 SmallVector<OpAsmParser::UnresolvedOperand, 4> inputsOperands;
1516 SmallVector<Type, 1> inputsTypes, allResultTypes;
1517 ArrayAttr argNames, resultNames, parameters;
1518 auto noneType = parser.getBuilder().getType<NoneType>();
1520 if (parser.parseAttribute(instanceNameAttr, noneType,
"instanceName",
1524 if (succeeded(parser.parseOptionalKeyword(
"sym"))) {
1527 if (parser.parseCustomAttributeWithFallback(innerSym))
1532 llvm::SMLoc parametersLoc, inputsOperandsLoc;
1533 if (parser.parseAttribute(moduleNameAttr, noneType,
"moduleName",
1534 result.attributes) ||
1535 parser.getCurrentLocation(¶metersLoc) ||
1538 parser.resolveOperands(inputsOperands, inputsTypes, inputsOperandsLoc,
1540 parser.parseArrow() ||
1542 parser.parseOptionalAttrDict(result.attributes)) {
1546 result.addAttribute(
"argNames", argNames);
1547 result.addAttribute(
"resultNames", resultNames);
1548 result.addAttribute(
"parameters", parameters);
1549 result.addTypes(allResultTypes);
1553void InstanceOp::print(OpAsmPrinter &p) {
1555 p.printAttributeWithoutType(getInstanceNameAttr());
1556 if (
auto attr = getInnerSymAttr()) {
1561 p.printAttributeWithoutType(getModuleNameAttr());
1568 p.printOptionalAttrDict(
1569 (*this)->getAttrs(),
1571 InnerSymbolTable::getInnerSymbolAttrName(),
"moduleName",
1572 "argNames",
"resultNames",
"parameters"});
1579std::optional<size_t> InstanceChoiceOp::getTargetResultIndex() {
1581 return std::nullopt;
1585InstanceChoiceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1586 for (Attribute name : getModuleNamesAttr()) {
1588 *
this, cast<FlatSymbolRefAttr>(name), getInputs(), getResultTypes(),
1589 getArgNames(), getResultNames(), getParameters(), symbolTable))) {
1596LogicalResult InstanceChoiceOp::verify() {
1597 auto module = (*this)->getParentOfType<HWModuleOp>();
1601 auto moduleParameters =
module->getAttrOfType<ArrayAttr>("parameters");
1603 [&](
const std::function<bool(InFlightDiagnostic &)> &fn) {
1604 auto diag = emitOpError();
1606 diag.attachNote(module->getLoc()) <<
"module declared here";
1609 getParameters(), moduleParameters, emitError);
1612ParseResult InstanceChoiceOp::parse(OpAsmParser &parser,
1613 OperationState &result) {
1614 StringAttr optionNameAttr;
1615 StringAttr instanceNameAttr;
1616 InnerSymAttr innerSym;
1617 SmallVector<Attribute> moduleNames;
1618 SmallVector<Attribute> caseNames;
1619 SmallVector<OpAsmParser::UnresolvedOperand, 4> inputsOperands;
1620 SmallVector<Type, 1> inputsTypes, allResultTypes;
1621 ArrayAttr argNames, resultNames, parameters;
1622 auto noneType = parser.getBuilder().getType<NoneType>();
1624 if (parser.parseAttribute(instanceNameAttr, noneType,
"instanceName",
1628 if (succeeded(parser.parseOptionalKeyword(
"sym"))) {
1631 if (parser.parseCustomAttributeWithFallback(innerSym))
1636 if (parser.parseKeyword(
"option") ||
1637 parser.parseAttribute(optionNameAttr, noneType,
"optionName",
1641 FlatSymbolRefAttr defaultModuleName;
1642 if (parser.parseAttribute(defaultModuleName))
1644 moduleNames.push_back(defaultModuleName);
1646 while (succeeded(parser.parseOptionalKeyword(
"or"))) {
1647 FlatSymbolRefAttr moduleName;
1648 StringAttr targetName;
1649 if (parser.parseAttribute(moduleName) ||
1650 parser.parseOptionalKeyword(
"if") || parser.parseAttribute(targetName))
1652 moduleNames.push_back(moduleName);
1653 caseNames.push_back(targetName);
1656 llvm::SMLoc parametersLoc, inputsOperandsLoc;
1657 if (parser.getCurrentLocation(¶metersLoc) ||
1660 parser.resolveOperands(inputsOperands, inputsTypes, inputsOperandsLoc,
1662 parser.parseArrow() ||
1664 parser.parseOptionalAttrDict(result.attributes)) {
1668 result.addAttribute(
"moduleNames",
1669 ArrayAttr::get(parser.getContext(), moduleNames));
1670 result.addAttribute(
"caseNames",
1671 ArrayAttr::get(parser.getContext(), caseNames));
1672 result.addAttribute(
"argNames", argNames);
1673 result.addAttribute(
"resultNames", resultNames);
1674 result.addAttribute(
"parameters", parameters);
1675 result.addTypes(allResultTypes);
1679void InstanceChoiceOp::print(OpAsmPrinter &p) {
1681 p.printAttributeWithoutType(getInstanceNameAttr());
1682 if (
auto attr = getInnerSymAttr()) {
1686 p <<
" option " << getOptionNameAttr() <<
' ';
1688 auto moduleNames = getModuleNamesAttr();
1689 auto caseNames = getCaseNamesAttr();
1690 assert(moduleNames.size() == caseNames.size() + 1);
1692 p.printAttributeWithoutType(moduleNames[0]);
1693 for (
size_t i = 0, n = caseNames.size(); i < n; ++i) {
1695 p.printAttributeWithoutType(moduleNames[i + 1]);
1697 p.printAttributeWithoutType(caseNames[i]);
1706 p.printOptionalAttrDict(
1707 (*this)->getAttrs(),
1709 InnerSymbolTable::getInnerSymbolAttrName(),
1710 "moduleNames",
"caseNames",
"argNames",
"resultNames",
1711 "parameters",
"optionName"});
1714ArrayAttr InstanceChoiceOp::getReferencedModuleNamesAttr() {
1715 SmallVector<Attribute> moduleNames;
1716 for (Attribute attr : getModuleNamesAttr()) {
1717 moduleNames.push_back(cast<FlatSymbolRefAttr>(attr).getAttr());
1719 return ArrayAttr::get(getContext(), moduleNames);
1727LogicalResult OutputOp::verify() {
1731 if (
auto mod = dyn_cast<HWModuleOp>((*this)->getParentOp()))
1732 modType = mod.getHWModuleType();
1734 emitOpError(
"must have a module parent");
1737 auto modResults = modType.getOutputTypes();
1738 OperandRange outputValues = getOperands();
1739 if (modResults.size() != outputValues.size()) {
1740 emitOpError(
"must have same number of operands as region results.");
1745 for (
size_t i = 0, e = modResults.size(); i < e; ++i) {
1746 if (modResults[i] != outputValues[i].getType()) {
1747 emitOpError(
"output types must match module. In "
1749 << i <<
", expected " << modResults[i] <<
", but got "
1750 << outputValues[i].getType() <<
".";
1765 if (p.parseType(type))
1766 return p.emitError(p.getCurrentLocation(),
"Expected type");
1767 auto arrType = type_dyn_cast<ArrayType>(type);
1769 return p.emitError(p.getCurrentLocation(),
"Expected !hw.array type");
1771 unsigned idxWidth = llvm::Log2_64_Ceil(arrType.getNumElements());
1772 idxType = IntegerType::get(p.getBuilder().getContext(), idxWidth);
1778 p.printType(srcType);
1781ParseResult ArrayCreateOp::parse(OpAsmParser &parser, OperationState &result) {
1782 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
1783 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
1786 if (parser.parseOperandList(operands) ||
1787 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
1788 parser.parseType(elemType))
1791 if (operands.size() == 0)
1792 return parser.emitError(inputOperandsLoc,
1793 "Cannot construct an array of length 0");
1794 result.addTypes({ArrayType::get(elemType, operands.size())});
1796 for (
auto operand : operands)
1797 if (parser.resolveOperand(operand, elemType, result.operands))
1802void ArrayCreateOp::print(OpAsmPrinter &p) {
1804 p.printOperands(getInputs());
1805 p.printOptionalAttrDict((*this)->getAttrs());
1806 p <<
" : " << getInputs()[0].getType();
1809void ArrayCreateOp::build(OpBuilder &b, OperationState &state,
1810 ValueRange values) {
1811 assert(values.size() > 0 &&
"Cannot build array of zero elements");
1812 Type elemType = values[0].getType();
1815 [elemType](Value v) ->
bool {
return v.getType() == elemType; }) &&
1816 "All values must have same type.");
1817 build(b, state, ArrayType::get(elemType, values.size()), values);
1820LogicalResult ArrayCreateOp::verify() {
1821 unsigned returnSize = cast<ArrayType>(getType()).getNumElements();
1822 if (getInputs().size() != returnSize)
1827OpFoldResult ArrayCreateOp::fold(FoldAdaptor adaptor) {
1828 if (llvm::any_of(adaptor.getInputs(), [](Attribute attr) { return !attr; }))
1830 return ArrayAttr::get(getContext(), adaptor.getInputs());
1840 auto baseValue = constBase.getValue();
1841 auto indexValue = constIndex.getValue();
1843 unsigned bits = baseValue.getBitWidth();
1844 assert(bits == indexValue.getBitWidth() &&
"mismatched widths");
1846 if (bits < 64 && offset >= (1ull << bits))
1849 APInt baseExt = baseValue.zextOrTrunc(bits + 1);
1850 APInt indexExt = indexValue.zextOrTrunc(bits + 1);
1851 return baseExt + offset == indexExt;
1859 PatternRewriter &rewriter) {
1861 auto arrayTy = hw::type_cast<ArrayType>(op.getType());
1862 if (arrayTy.getNumElements() <= 1)
1864 auto elemTy = arrayTy.getElementType();
1873 SmallVector<Chunk> chunks;
1874 for (Value value : llvm::reverse(op.getInputs())) {
1875 auto get = value.getDefiningOp<
ArrayGetOp>();
1879 Value input = get.getInput();
1880 Value index = get.getIndex();
1881 if (!chunks.empty()) {
1882 auto &c = *chunks.rbegin();
1883 if (c.input == get.getInput() &&
isOffset(c.index, index, c.size)) {
1889 chunks.push_back(Chunk{input, index, 1});
1893 if (chunks.size() == 1) {
1894 auto &chunk = chunks[0];
1895 rewriter.replaceOp(op, rewriter.createOrFold<
ArraySliceOp>(
1896 op.getLoc(), arrayTy, chunk.input, chunk.index));
1902 if (chunks.size() * 2 < arrayTy.getNumElements()) {
1903 SmallVector<Value> slices;
1904 for (
auto &chunk : llvm::reverse(chunks)) {
1905 auto sliceTy = ArrayType::get(elemTy, chunk.size);
1907 op.getLoc(), sliceTy, chunk.input, chunk.index));
1909 rewriter.replaceOpWithNewOp<
ArrayConcatOp>(op, arrayTy, slices);
1917 PatternRewriter &rewriter) {
1923Value ArrayCreateOp::getUniformElement() {
1924 if (!getInputs().
empty() && llvm::all_equal(getInputs()))
1925 return getInputs()[0];
1930 auto idxOp = dyn_cast_or_null<ConstantOp>(value.getDefiningOp());
1932 return std::nullopt;
1933 APInt idxAttr = idxOp.getValue();
1934 if (idxAttr.getBitWidth() > 64)
1935 return std::nullopt;
1936 return idxAttr.getLimitedValue();
1939LogicalResult ArraySliceOp::verify() {
1940 unsigned inputSize =
1941 type_cast<ArrayType>(getInput().getType()).getNumElements();
1942 if (llvm::Log2_64_Ceil(inputSize) !=
1943 getLowIndex().getType().getIntOrFloatBitWidth())
1945 "ArraySlice: index width must match clog2 of array size");
1949OpFoldResult ArraySliceOp::fold(FoldAdaptor adaptor) {
1951 if (getType() == getInput().getType())
1956LogicalResult ArraySliceOp::canonicalize(
ArraySliceOp op,
1957 PatternRewriter &rewriter) {
1958 auto sliceTy = hw::type_cast<ArrayType>(op.getType());
1959 auto elemTy = sliceTy.getElementType();
1960 uint64_t sliceSize = sliceTy.getNumElements();
1964 if (sliceSize == 1) {
1966 auto get = rewriter.create<
ArrayGetOp>(op.getLoc(), op.getInput(),
1968 rewriter.replaceOpWithNewOp<
ArrayCreateOp>(op, op.getType(),
1977 auto inputOp = op.getInput().getDefiningOp();
1978 if (
auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
1980 if (inputSlice == op)
1983 auto inputIndex = inputSlice.getLowIndex();
1985 if (!inputOffsetOpt)
1988 uint64_t offset = *offsetOpt + *inputOffsetOpt;
1990 rewriter.create<
ConstantOp>(op.getLoc(), inputIndex.getType(), offset);
1991 rewriter.replaceOpWithNewOp<
ArraySliceOp>(op, op.getType(),
1992 inputSlice.getInput(), lowIndex);
1996 if (
auto inputCreate = dyn_cast_or_null<ArrayCreateOp>(inputOp)) {
1998 auto inputs = inputCreate.getInputs();
2000 uint64_t begin = inputs.size() - *offsetOpt - sliceSize;
2001 rewriter.replaceOpWithNewOp<
ArrayCreateOp>(op, op.getType(),
2002 inputs.slice(begin, sliceSize));
2006 if (
auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
2008 SmallVector<Value> chunks;
2009 uint64_t sliceStart = *offsetOpt;
2010 for (
auto input :
llvm::reverse(inputConcat.getInputs())) {
2012 uint64_t inputSize =
2013 hw::type_cast<ArrayType>(input.getType()).getNumElements();
2014 if (inputSize == 0 || inputSize <= sliceStart) {
2015 sliceStart -= inputSize;
2020 uint64_t cutEnd = std::min(inputSize, sliceStart + sliceSize);
2021 uint64_t cutSize = cutEnd - sliceStart;
2022 assert(cutSize != 0 &&
"slice cannot be empty");
2024 if (cutSize == inputSize) {
2026 assert(sliceStart == 0 &&
"invalid cut size");
2027 chunks.push_back(input);
2030 unsigned width = inputSize == 1 ? 1 : llvm::Log2_64_Ceil(inputSize);
2032 op.getLoc(), rewriter.getIntegerType(width), sliceStart);
2034 op.getLoc(), hw::ArrayType::get(elemTy, cutSize), input, lowIndex));
2038 sliceSize -= cutSize;
2043 assert(chunks.size() > 0 &&
"missing sliced items");
2044 if (chunks.size() == 1)
2045 rewriter.replaceOp(op, chunks[0]);
2048 op, llvm::to_vector(llvm::reverse(chunks)));
2059 SmallVectorImpl<Type> &inputTypes,
2062 uint64_t resultSize = 0;
2064 auto parseElement = [&]() -> ParseResult {
2066 if (p.parseType(ty))
2068 auto arrTy = type_dyn_cast<ArrayType>(ty);
2070 return p.emitError(p.getCurrentLocation(),
"Expected !hw.array type");
2071 if (elemType && elemType != arrTy.getElementType())
2072 return p.emitError(p.getCurrentLocation(),
"Expected array element type ")
2075 elemType = arrTy.getElementType();
2076 inputTypes.push_back(ty);
2077 resultSize += arrTy.getNumElements();
2081 if (p.parseCommaSeparatedList(parseElement))
2084 resultType = ArrayType::get(elemType, resultSize);
2089 TypeRange inputTypes, Type resultType) {
2090 llvm::interleaveComma(inputTypes, p, [&p](Type t) { p << t; });
2093void ArrayConcatOp::build(OpBuilder &b, OperationState &state,
2094 ValueRange values) {
2095 assert(!values.empty() &&
"Cannot build array of zero elements");
2096 ArrayType arrayTy = cast<ArrayType>(values[0].getType());
2097 Type elemTy = arrayTy.getElementType();
2098 assert(llvm::all_of(values,
2099 [elemTy](Value v) ->
bool {
2100 return isa<ArrayType>(v.getType()) &&
2101 cast<ArrayType>(v.getType()).getElementType() ==
2104 "All values must be of ArrayType with the same element type.");
2106 uint64_t resultSize = 0;
2107 for (Value val : values)
2108 resultSize += cast<ArrayType>(val.getType()).getNumElements();
2109 build(b, state, ArrayType::get(elemTy, resultSize), values);
2112OpFoldResult ArrayConcatOp::fold(FoldAdaptor adaptor) {
2113 auto inputs = adaptor.getInputs();
2114 SmallVector<Attribute> array;
2115 for (
size_t i = 0, e = getNumOperands(); i < e; ++i) {
2118 llvm::copy(cast<ArrayAttr>(inputs[i]), std::back_inserter(array));
2120 return ArrayAttr::get(getContext(), array);
2125 for (
auto input : op.getInputs())
2129 SmallVector<Value> items;
2130 for (
auto input : op.getInputs()) {
2131 auto create = cast<ArrayCreateOp>(input.getDefiningOp());
2132 for (
auto item : create.getInputs())
2133 items.push_back(item);
2147 SmallVector<Location> locs;
2150 SmallVector<Value> items;
2151 std::optional<Slice> last;
2152 bool changed =
false;
2154 auto concatenate = [&] {
2159 items.push_back(last->op);
2167 auto loc = FusedLoc::get(op.getContext(), last->locs);
2168 auto origTy = hw::type_cast<ArrayType>(last->input.getType());
2169 auto arrayTy = ArrayType::get(origTy.getElementType(), last->size);
2171 loc, arrayTy, last->input, last->index));
2176 auto append = [&](Value op, Value input, Value index,
size_t size) {
2181 if (last->input == input &&
isOffset(last->index, index, last->size)) {
2184 last->locs.push_back(op.getLoc());
2189 last.emplace(Slice{input, index, size, op, {op.getLoc()}});
2192 for (
auto item : llvm::reverse(op.getInputs())) {
2194 auto size = hw::type_cast<ArrayType>(slice.getType()).getNumElements();
2195 append(item, slice.getInput(), slice.getLowIndex(), size);
2200 if (create.getInputs().size() == 1) {
2201 if (
auto get = create.getInputs()[0].getDefiningOp<
ArrayGetOp>()) {
2202 append(item, get.getInput(), get.getIndex(), 1);
2209 items.push_back(item);
2216 if (items.size() == 1) {
2217 rewriter.replaceOp(op, items[0]);
2219 std::reverse(items.begin(), items.end());
2226 PatternRewriter &rewriter) {
2242ParseResult EnumConstantOp::parse(OpAsmParser &parser, OperationState &result) {
2249 auto loc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
2250 if (parser.parseKeyword(&field) || parser.parseColonType(type))
2253 auto fieldAttr = EnumFieldAttr::get(
2254 loc, StringAttr::get(parser.getContext(), field), type);
2259 result.addAttribute(
"field", fieldAttr);
2260 result.addTypes(type);
2265void EnumConstantOp::print(OpAsmPrinter &p) {
2266 p <<
" " << getField().getField().getValue() <<
" : "
2267 << getField().getType().getValue();
2270void EnumConstantOp::getAsmResultNames(
2271 function_ref<
void(Value, StringRef)> setNameFn) {
2272 setNameFn(getResult(), getField().getField().str());
2275void EnumConstantOp::build(OpBuilder &builder, OperationState &odsState,
2276 EnumFieldAttr field) {
2277 return build(builder, odsState, field.getType().getValue(), field);
2280OpFoldResult EnumConstantOp::fold(FoldAdaptor adaptor) {
2281 assert(adaptor.getOperands().empty() &&
"constant has no operands");
2282 return getFieldAttr();
2285LogicalResult EnumConstantOp::verify() {
2286 auto fieldAttr = getFieldAttr();
2287 auto fieldType = fieldAttr.getType().getValue();
2290 if (fieldType != getType())
2291 emitOpError(
"return type ")
2292 << getType() <<
" does not match attribute type " << fieldAttr;
2300LogicalResult EnumCmpOp::verify() {
2302 auto lhsType = type_cast<EnumType>(getLhs().getType());
2303 auto rhsType = type_cast<EnumType>(getRhs().getType());
2304 if (rhsType != lhsType)
2305 emitOpError(
"types do not match");
2313ParseResult StructCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2314 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2315 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
2316 Type declOrAliasType;
2318 if (parser.parseLParen() || parser.parseOperandList(operands) ||
2319 parser.parseRParen() || parser.parseOptionalAttrDict(result.attributes) ||
2320 parser.parseColonType(declOrAliasType))
2323 auto declType = type_dyn_cast<StructType>(declOrAliasType);
2325 return parser.emitError(parser.getNameLoc(),
2326 "expected !hw.struct type or alias");
2328 llvm::SmallVector<Type, 4> structInnerTypes;
2329 declType.getInnerTypes(structInnerTypes);
2330 result.addTypes(declOrAliasType);
2332 if (parser.resolveOperands(operands, structInnerTypes, inputOperandsLoc,
2338void StructCreateOp::print(OpAsmPrinter &printer) {
2340 printer.printOperands(getInput());
2342 printer.printOptionalAttrDict((*this)->getAttrs());
2343 printer <<
" : " << getType();
2346LogicalResult StructCreateOp::verify() {
2347 auto elements = hw::type_cast<StructType>(getType()).getElements();
2349 if (elements.size() != getInput().size())
2350 return emitOpError(
"structure field count mismatch");
2352 for (
const auto &[field, value] :
llvm::zip(elements, getInput()))
2353 if (field.type != value.getType())
2354 return emitOpError(
"structure field `")
2355 << field.name <<
"` type does not match";
2360OpFoldResult StructCreateOp::fold(FoldAdaptor adaptor) {
2362 if (!getInput().
empty())
2363 if (
auto explodeOp = getInput()[0].getDefiningOp<StructExplodeOp>();
2364 explodeOp && getInput() == explodeOp.getResults() &&
2365 getResult().getType() == explodeOp.getInput().getType())
2366 return explodeOp.getInput();
2368 auto inputs = adaptor.getInput();
2369 if (llvm::any_of(inputs, [](Attribute attr) {
return !attr; }))
2371 return ArrayAttr::get(getContext(), inputs);
2378ParseResult StructExplodeOp::parse(OpAsmParser &parser,
2379 OperationState &result) {
2380 OpAsmParser::UnresolvedOperand operand;
2383 if (parser.parseOperand(operand) ||
2384 parser.parseOptionalAttrDict(result.attributes) ||
2385 parser.parseColonType(declType))
2387 auto structType = type_dyn_cast<StructType>(declType);
2389 return parser.emitError(parser.getNameLoc(),
2390 "invalid kind of type specified");
2392 llvm::SmallVector<Type, 4> structInnerTypes;
2393 structType.getInnerTypes(structInnerTypes);
2394 result.addTypes(structInnerTypes);
2396 if (parser.resolveOperand(operand, declType, result.operands))
2401void StructExplodeOp::print(OpAsmPrinter &printer) {
2403 printer.printOperand(getInput());
2404 printer.printOptionalAttrDict((*this)->getAttrs());
2405 printer <<
" : " << getInput().getType();
2408LogicalResult StructExplodeOp::fold(FoldAdaptor adaptor,
2409 SmallVectorImpl<OpFoldResult> &results) {
2410 auto input = adaptor.getInput();
2413 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(results));
2417LogicalResult StructExplodeOp::canonicalize(StructExplodeOp op,
2418 PatternRewriter &rewriter) {
2419 auto *inputOp = op.getInput().getDefiningOp();
2420 auto elements = type_cast<StructType>(op.getInput().getType()).getElements();
2421 auto result = failure();
2422 auto opResults = op.getResults();
2423 for (uint32_t index = 0; index < elements.size(); index++) {
2425 rewriter.replaceAllUsesWith(opResults[index], foldResult);
2432void StructExplodeOp::getAsmResultNames(
2433 function_ref<
void(Value, StringRef)> setNameFn) {
2434 auto structType = type_cast<StructType>(getInput().getType());
2435 for (
auto [res, field] :
llvm::zip(getResults(), structType.getElements()))
2436 setNameFn(res, field.name.str());
2439void StructExplodeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2441 StructType inputType = dyn_cast<StructType>(input.getType());
2443 SmallVector<Type, 16> fieldTypes;
2444 for (
auto field : inputType.getElements())
2445 fieldTypes.push_back(field.type);
2446 build(odsBuilder, odsState, fieldTypes, input);
2455template <
typename AggregateOp,
typename AggregateType>
2457 AggregateType aggType,
2459 auto index = op.getFieldIndex();
2460 if (index >= aggType.getElements().size())
2461 return op.emitOpError() <<
"field index " << index
2462 <<
" exceeds element count of aggregate type";
2466 return op.emitOpError()
2467 <<
"type " << aggType.getElements()[index].type
2468 <<
" of accessed field in aggregate at index " << index
2469 <<
" does not match expected type " <<
elementType;
2474LogicalResult StructExtractOp::verify() {
2475 return verifyAggregateFieldIndexAndType<StructExtractOp, StructType>(
2476 *
this, getInput().getType(), getType());
2481template <
typename AggregateType>
2483 OpAsmParser::UnresolvedOperand operand;
2484 StringAttr fieldName;
2487 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2488 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2489 parser.parseOptionalAttrDict(result.attributes) ||
2490 parser.parseColonType(declType))
2492 auto aggType = type_dyn_cast<AggregateType>(declType);
2494 return parser.emitError(parser.getNameLoc(),
2495 "invalid kind of type specified");
2497 auto fieldIndex = aggType.getFieldIndex(fieldName);
2499 parser.emitError(parser.getNameLoc(),
"field name '" +
2500 fieldName.getValue() +
2501 "' not found in aggregate type");
2506 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2507 result.addAttribute(
"fieldIndex", indexAttr);
2508 Type resultType = aggType.getElements()[*fieldIndex].type;
2509 result.addTypes(resultType);
2511 if (parser.resolveOperand(operand, declType, result.operands))
2518template <
typename AggType>
2521 printer.printOperand(op.getInput());
2522 printer <<
"[\"" << op.getFieldName() <<
"\"]";
2523 printer.printOptionalAttrDict(op->getAttrs(), {
"fieldIndex"});
2524 printer <<
" : " << op.getInput().getType();
2527ParseResult StructExtractOp::parse(OpAsmParser &parser,
2528 OperationState &result) {
2529 return parseExtractOp<StructType>(parser, result);
2532void StructExtractOp::print(OpAsmPrinter &printer) {
2536void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2537 Value input, StructType::FieldInfo field) {
2539 type_cast<StructType>(input.getType()).getFieldIndex(field.name);
2540 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2541 build(builder, odsState, field.type, input, *fieldIndex);
2544void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2545 Value input, StringAttr fieldName) {
2546 auto structType = type_cast<StructType>(input.getType());
2547 auto fieldIndex = structType.getFieldIndex(fieldName);
2548 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2549 auto resultType = structType.getElements()[*fieldIndex].type;
2550 build(builder, odsState, resultType, input, *fieldIndex);
2553OpFoldResult StructExtractOp::fold(FoldAdaptor adaptor) {
2554 if (
auto constOperand = adaptor.getInput()) {
2556 auto operandAttr = llvm::cast<ArrayAttr>(constOperand);
2557 return operandAttr.getValue()[getFieldIndex()];
2560 if (
auto foldResult =
2567 PatternRewriter &rewriter) {
2568 auto inputOp = op.getInput().getDefiningOp();
2571 if (
auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
2572 if (structInject.getFieldIndex() != op.getFieldIndex()) {
2574 op, op.getType(), structInject.getInput(), op.getFieldIndexAttr());
2582void StructExtractOp::getAsmResultNames(
2583 function_ref<
void(Value, StringRef)> setNameFn) {
2591void StructInjectOp::build(OpBuilder &builder, OperationState &odsState,
2592 Value input, StringAttr fieldName, Value newValue) {
2593 auto structType = type_cast<StructType>(input.getType());
2594 auto fieldIndex = structType.getFieldIndex(fieldName);
2595 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2596 build(builder, odsState, input, *fieldIndex, newValue);
2599LogicalResult StructInjectOp::verify() {
2600 return verifyAggregateFieldIndexAndType<StructInjectOp, StructType>(
2601 *
this, getInput().getType(), getNewValue().getType());
2604ParseResult StructInjectOp::parse(OpAsmParser &parser, OperationState &result) {
2605 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2606 OpAsmParser::UnresolvedOperand operand, val;
2607 StringAttr fieldName;
2610 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2611 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2612 parser.parseComma() || parser.parseOperand(val) ||
2613 parser.parseOptionalAttrDict(result.attributes) ||
2614 parser.parseColonType(declType))
2616 auto structType = type_dyn_cast<StructType>(declType);
2618 return parser.emitError(inputOperandsLoc,
"invalid kind of type specified");
2620 auto fieldIndex = structType.getFieldIndex(fieldName);
2622 parser.emitError(parser.getNameLoc(),
"field name '" +
2623 fieldName.getValue() +
2624 "' not found in aggregate type");
2629 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2630 result.addAttribute(
"fieldIndex", indexAttr);
2631 result.addTypes(declType);
2633 Type resultType = structType.getElements()[*fieldIndex].type;
2634 if (parser.resolveOperands({operand, val}, {declType, resultType},
2635 inputOperandsLoc, result.operands))
2640void StructInjectOp::print(OpAsmPrinter &printer) {
2642 printer.printOperand(getInput());
2644 printer.printOperand(getNewValue());
2645 printer.printOptionalAttrDict((*this)->getAttrs(), {
"fieldIndex"});
2646 printer <<
" : " << getInput().getType();
2649OpFoldResult StructInjectOp::fold(FoldAdaptor adaptor) {
2650 auto input = adaptor.getInput();
2651 auto newValue = adaptor.getNewValue();
2652 if (!input || !newValue)
2654 SmallVector<Attribute> array;
2655 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(array));
2656 array[getFieldIndex()] = newValue;
2657 return ArrayAttr::get(getContext(), array);
2660LogicalResult StructInjectOp::canonicalize(StructInjectOp op,
2661 PatternRewriter &rewriter) {
2663 SmallPtrSet<Operation *, 4> injects;
2664 DenseMap<StringAttr, Value> fields;
2667 StructInjectOp inject = op;
2670 if (!injects.insert(inject).second)
2673 fields.try_emplace(inject.getFieldNameAttr(), inject.getNewValue());
2674 input = inject.getInput();
2675 inject = dyn_cast_or_null<StructInjectOp>(input.getDefiningOp());
2677 assert(input &&
"missing input to inject chain");
2679 auto ty = hw::type_cast<StructType>(op.getType());
2680 auto elements = ty.getElements();
2683 if (fields.size() == elements.size()) {
2684 SmallVector<Value> createFields;
2685 for (
const auto &field : elements) {
2686 auto it = fields.find(field.name);
2687 assert(it != fields.end() &&
"missing field");
2688 createFields.push_back(it->second);
2690 rewriter.replaceOpWithNewOp<
StructCreateOp>(op, ty, createFields);
2695 if (injects.size() == fields.size())
2699 for (uint32_t fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
2700 auto it = fields.find(elements[fieldIndex].name);
2701 if (it == fields.end())
2703 input = rewriter.create<StructInjectOp>(op.getLoc(), ty, input, fieldIndex,
2707 rewriter.replaceOp(op, input);
2715LogicalResult UnionCreateOp::verify() {
2716 return verifyAggregateFieldIndexAndType<UnionCreateOp, UnionType>(
2717 *
this, getType(), getInput().getType());
2720void UnionCreateOp::build(OpBuilder &builder, OperationState &odsState,
2721 Type unionType, StringAttr fieldName, Value input) {
2722 auto fieldIndex = type_cast<UnionType>(unionType).getFieldIndex(fieldName);
2723 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2724 build(builder, odsState, unionType, *fieldIndex, input);
2727ParseResult UnionCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2728 Type declOrAliasType;
2729 StringAttr fieldName;
2730 OpAsmParser::UnresolvedOperand input;
2731 llvm::SMLoc fieldLoc = parser.getCurrentLocation();
2733 if (parser.parseAttribute(fieldName) || parser.parseComma() ||
2734 parser.parseOperand(input) ||
2735 parser.parseOptionalAttrDict(result.attributes) ||
2736 parser.parseColonType(declOrAliasType))
2739 auto declType = type_dyn_cast<UnionType>(declOrAliasType);
2741 return parser.emitError(parser.getNameLoc(),
2742 "expected !hw.union type or alias");
2744 auto fieldIndex = declType.getFieldIndex(fieldName);
2746 parser.emitError(fieldLoc,
"cannot find union field '")
2747 << fieldName.getValue() <<
'\'';
2752 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2753 result.addAttribute(
"fieldIndex", indexAttr);
2754 Type inputType = declType.getElements()[*fieldIndex].type;
2756 if (parser.resolveOperand(input, inputType, result.operands))
2758 result.addTypes({declOrAliasType});
2762void UnionCreateOp::print(OpAsmPrinter &printer) {
2764 printer.printOperand(getInput());
2765 printer.printOptionalAttrDict((*this)->getAttrs(), {
"fieldIndex"});
2766 printer <<
" : " << getType();
2773ParseResult UnionExtractOp::parse(OpAsmParser &parser, OperationState &result) {
2774 return parseExtractOp<UnionType>(parser, result);
2777void UnionExtractOp::print(OpAsmPrinter &printer) {
2781LogicalResult UnionExtractOp::inferReturnTypes(
2782 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
2783 DictionaryAttr attrs, mlir::OpaqueProperties properties,
2784 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
2785 Adaptor adaptor(operands, attrs, properties, regions);
2786 auto unionElements =
2787 hw::type_cast<UnionType>((adaptor.getInput().getType())).getElements();
2788 unsigned fieldIndex = adaptor.getFieldIndexAttr().getValue().getZExtValue();
2789 if (fieldIndex >= unionElements.size()) {
2791 mlir::emitError(*loc,
"field index " + Twine(fieldIndex) +
2792 " exceeds element count of aggregate type");
2795 results.push_back(unionElements[fieldIndex].type);
2799void UnionExtractOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2800 Value input, StringAttr fieldName) {
2801 auto unionType = type_cast<UnionType>(input.getType());
2802 auto fieldIndex = unionType.getFieldIndex(fieldName);
2803 assert(fieldIndex.has_value() &&
"field name not found in aggregate type");
2804 auto resultType = unionType.getElements()[*fieldIndex].type;
2805 build(odsBuilder, odsState, resultType, input, *fieldIndex);
2817OpFoldResult ArrayGetOp::fold(FoldAdaptor adaptor) {
2818 auto inputCst = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2819 auto indexCst = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2824 auto indexVal = indexCst.getValue();
2825 if (indexVal.getBitWidth() < 64) {
2826 auto index = indexVal.getZExtValue();
2827 return inputCst[inputCst.size() - 1 - index];
2832 if (!inputCst.empty() && llvm::all_equal(inputCst))
2837 if (
auto bitcast = getInput().getDefiningOp<hw::BitcastOp>()) {
2838 auto intTy = dyn_cast<IntegerType>(getType());
2841 auto bitcastInputOp = bitcast.getInput().getDefiningOp<
hw::ConstantOp>();
2842 if (!bitcastInputOp)
2846 auto bitcastInputCst = bitcastInputOp.getValue();
2849 auto startIdx = indexCst.getValue().zext(bitcastInputCst.getBitWidth()) *
2850 getType().getIntOrFloatBitWidth();
2852 return IntegerAttr::get(intTy, bitcastInputCst.lshr(startIdx).trunc(
2853 intTy.getIntOrFloatBitWidth()));
2856 auto inputCreate = getInput().getDefiningOp<
ArrayCreateOp>();
2860 if (
auto uniformValue = inputCreate.getUniformElement())
2861 return uniformValue;
2863 if (!indexCst || indexCst.getValue().getBitWidth() > 64)
2866 uint64_t index = indexCst.getValue().getLimitedValue();
2867 auto createInputs = inputCreate.getInputs();
2868 if (index >= createInputs.size())
2870 return createInputs[createInputs.size() - index - 1];
2873LogicalResult ArrayGetOp::canonicalize(
ArrayGetOp op,
2874 PatternRewriter &rewriter) {
2879 auto *inputOp = op.getInput().getDefiningOp();
2880 if (
auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
2882 auto offsetOp = inputSlice.getLowIndex();
2887 uint64_t offset = *offsetOpt + *idxOpt;
2889 rewriter.create<
ConstantOp>(op.getLoc(), offsetOp.getType(), offset);
2890 rewriter.replaceOpWithNewOp<
ArrayGetOp>(op, inputSlice.getInput(),
2895 if (
auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
2897 uint64_t elemIndex = *idxOpt;
2898 for (
auto input :
llvm::reverse(inputConcat.getInputs())) {
2899 size_t size = hw::type_cast<ArrayType>(input.getType()).getNumElements();
2900 if (elemIndex >= size) {
2905 unsigned indexWidth = size == 1 ? 1 : llvm::Log2_64_Ceil(size);
2907 op.getLoc(), rewriter.getIntegerType(indexWidth), elemIndex);
2909 rewriter.replaceOpWithNewOp<
ArrayGetOp>(op, input, newIdxOp);
2918 if (
auto innerGet = dyn_cast_or_null<hw::ArrayGetOp>(inputOp)) {
2923 SmallVector<Value> newValues;
2924 for (
auto operand : create.getOperands())
2925 newValues.push_back(rewriter.createOrFold<
hw::
ArrayGetOp>(
2926 op.getLoc(), operand, op.getIndex()));
2931 innerGet.getIndex());
2944StringRef TypedeclOp::getPreferredName() {
2945 return getVerilogName().value_or(
getName());
2948Type TypedeclOp::getAliasType() {
2949 auto parentScope = cast<hw::TypeScopeOp>(getOperation()->getParentOp());
2950 return hw::TypeAliasType::get(
2951 SymbolRefAttr::get(parentScope.getSymNameAttr(),
2952 {FlatSymbolRefAttr::get(*this)}),
2960OpFoldResult BitcastOp::fold(FoldAdaptor) {
2963 if (getOperand().getType() == getType())
2964 return getOperand();
2969LogicalResult BitcastOp::canonicalize(
BitcastOp op, PatternRewriter &rewriter) {
2975 dyn_cast_or_null<BitcastOp>(op.getInput().getDefiningOp());
2978 auto bitcast = rewriter.createOrFold<
BitcastOp>(op.getLoc(), op.getType(),
2979 inputBitcast.getInput());
2980 rewriter.replaceOp(op, bitcast);
2984LogicalResult BitcastOp::verify() {
2986 return this->emitOpError(
"Bitwidth of input must match result");
2994bool HierPathOp::dropModule(StringAttr moduleToDrop) {
2995 SmallVector<Attribute, 4> newPath;
2996 bool updateMade =
false;
2997 for (
auto nameRef : getNamepath()) {
2999 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3000 if (ref.getModule() == moduleToDrop)
3003 newPath.push_back(ref);
3005 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3008 newPath.push_back(nameRef);
3012 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3016bool HierPathOp::inlineModule(StringAttr moduleToDrop) {
3017 SmallVector<Attribute, 4> newPath;
3018 bool updateMade =
false;
3019 StringRef inlinedInstanceName =
"";
3020 for (
auto nameRef : getNamepath()) {
3022 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3023 if (ref.getModule() == moduleToDrop) {
3024 inlinedInstanceName = ref.getName().getValue();
3026 }
else if (!inlinedInstanceName.empty()) {
3027 newPath.push_back(hw::InnerRefAttr::get(
3029 StringAttr::get(getContext(), inlinedInstanceName +
"_" +
3030 ref.getName().getValue())));
3031 inlinedInstanceName =
"";
3033 newPath.push_back(ref);
3035 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3038 newPath.push_back(nameRef);
3042 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3046bool HierPathOp::updateModule(StringAttr oldMod, StringAttr newMod) {
3047 SmallVector<Attribute, 4> newPath;
3048 bool updateMade =
false;
3049 for (
auto nameRef : getNamepath()) {
3051 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3052 if (ref.getModule() == oldMod) {
3053 newPath.push_back(hw::InnerRefAttr::get(newMod, ref.getName()));
3056 newPath.push_back(ref);
3058 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == oldMod) {
3059 newPath.push_back(FlatSymbolRefAttr::get(newMod));
3062 newPath.push_back(nameRef);
3066 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3070bool HierPathOp::updateModuleAndInnerRef(
3071 StringAttr oldMod, StringAttr newMod,
3072 const llvm::DenseMap<StringAttr, StringAttr> &innerSymRenameMap) {
3073 auto fromRef = FlatSymbolRefAttr::get(oldMod);
3074 if (oldMod == newMod)
3077 auto namepathNew = getNamepath().getValue().vec();
3078 bool updateMade =
false;
3080 for (
auto &element : namepathNew) {
3081 if (
auto innerRef = dyn_cast<hw::InnerRefAttr>(element)) {
3082 if (innerRef.getModule() != oldMod)
3084 auto symName = innerRef.getName();
3087 auto to = innerSymRenameMap.find(symName);
3088 if (to != innerSymRenameMap.end())
3089 symName = to->second;
3091 element = hw::InnerRefAttr::get(newMod, symName);
3094 if (element != fromRef)
3098 element = FlatSymbolRefAttr::get(newMod);
3102 setNamepathAttr(ArrayAttr::get(getContext(), namepathNew));
3106bool HierPathOp::truncateAtModule(StringAttr atMod,
bool includeMod) {
3107 SmallVector<Attribute, 4> newPath;
3108 bool updateMade =
false;
3109 for (
auto nameRef : getNamepath()) {
3111 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3112 if (ref.getModule() == atMod) {
3115 newPath.push_back(ref);
3117 newPath.push_back(ref);
3119 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == atMod && !includeMod)
3122 newPath.push_back(nameRef);
3128 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3133StringAttr HierPathOp::modPart(
unsigned i) {
3134 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3135 .Case<FlatSymbolRefAttr>([](
auto a) {
return a.getAttr(); })
3136 .Case<hw::InnerRefAttr>([](
auto a) {
return a.getModule(); });
3140StringAttr HierPathOp::root() {
3146bool HierPathOp::hasModule(StringAttr modName) {
3147 for (
auto nameRef : getNamepath()) {
3149 if (
auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3150 if (ref.getModule() == modName)
3153 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == modName)
3161bool HierPathOp::hasInnerSym(StringAttr modName, StringAttr symName)
const {
3162 for (
auto nameRef : const_cast<HierPathOp *>(this)->getNamepath())
3163 if (auto ref = dyn_cast<
hw::InnerRefAttr>(nameRef))
3164 if (ref.
getName() == symName && ref.getModule() == modName)
3172StringAttr HierPathOp::refPart(
unsigned i) {
3173 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3174 .Case<FlatSymbolRefAttr>([](
auto a) {
return StringAttr({}); })
3175 .Case<hw::InnerRefAttr>([](
auto a) {
return a.getName(); });
3180StringAttr HierPathOp::ref() {
3182 return refPart(getNamepath().size() - 1);
3186StringAttr HierPathOp::leafMod() {
3188 return modPart(getNamepath().size() - 1);
3193bool HierPathOp::isModule() {
return !ref(); }
3197bool HierPathOp::isComponent() {
return (
bool)ref(); }
3213 ArrayAttr expectedModuleNames = {};
3214 auto checkExpectedModule = [&](Attribute name) -> LogicalResult {
3215 if (!expectedModuleNames)
3217 if (llvm::any_of(expectedModuleNames,
3218 [name](Attribute attr) {
return attr == name; }))
3220 auto diag = emitOpError() <<
"instance path is incorrect. Expected ";
3221 size_t n = expectedModuleNames.size();
3225 for (
size_t i = 0; i < n; ++i) {
3227 diag << ((i + 1 == n) ?
" or " :
", ");
3228 diag << cast<StringAttr>(expectedModuleNames[i]);
3230 diag <<
". Instead found: " << name;
3234 if (!getNamepath() || getNamepath().
empty())
3235 return emitOpError() <<
"the instance path cannot be empty";
3236 for (
unsigned i = 0, s = getNamepath().size() - 1; i < s; ++i) {
3237 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(getNamepath()[i]);
3239 return emitOpError()
3240 <<
"the instance path can only contain inner sym reference"
3241 <<
", only the leaf can refer to a module symbol";
3243 if (failed(checkExpectedModule(innerRef.getModule())))
3246 auto instOp = ns.
lookupOp<igraph::InstanceOpInterface>(innerRef);
3248 return emitOpError() <<
" module: " << innerRef.getModule()
3249 <<
" does not contain any instance with symbol: "
3250 << innerRef.getName();
3251 expectedModuleNames = instOp.getReferencedModuleNamesAttr();
3255 auto leafRef = getNamepath()[getNamepath().size() - 1];
3256 if (
auto innerRef = dyn_cast<hw::InnerRefAttr>(leafRef)) {
3257 if (!ns.
lookup(innerRef)) {
3258 return emitOpError() <<
" operation with symbol: " << innerRef
3259 <<
" was not found ";
3261 if (failed(checkExpectedModule(innerRef.getModule())))
3263 }
else if (failed(checkExpectedModule(
3264 cast<FlatSymbolRefAttr>(leafRef).getAttr()))) {
3270void HierPathOp::print(OpAsmPrinter &p) {
3274 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
3275 if (
auto visibility =
3276 getOperation()->getAttrOfType<StringAttr>(visibilityAttrName))
3277 p << visibility.getValue() <<
' ';
3279 p.printSymbolName(getSymName());
3281 llvm::interleaveComma(getNamepath().getValue(), p, [&](Attribute attr) {
3282 if (
auto ref = dyn_cast<hw::InnerRefAttr>(attr)) {
3283 p.printSymbolName(ref.getModule().getValue());
3285 p.printSymbolName(ref.getName().getValue());
3287 p.printSymbolName(cast<FlatSymbolRefAttr>(attr).getValue());
3291 p.printOptionalAttrDict(
3292 (*this)->getAttrs(),
3293 {SymbolTable::getSymbolAttrName(),
"namepath", visibilityAttrName});
3296ParseResult HierPathOp::parse(OpAsmParser &parser, OperationState &result) {
3298 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
3302 if (parser.parseSymbolName(symName, SymbolTable::getSymbolAttrName(),
3307 SmallVector<Attribute> namepath;
3308 if (parser.parseCommaSeparatedList(
3309 OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
3310 auto loc = parser.getCurrentLocation();
3312 if (parser.parseAttribute(ref))
3316 auto pathLength = ref.getNestedReferences().size();
3317 if (pathLength == 0)
3319 FlatSymbolRefAttr::get(ref.getRootReference()));
3320 else if (pathLength == 1)
3321 namepath.push_back(hw::InnerRefAttr::get(ref.getRootReference(),
3322 ref.getLeafReference()));
3324 return parser.emitError(loc,
3325 "only one nested reference is allowed");
3329 result.addAttribute(
"namepath",
3330 ArrayAttr::get(parser.getContext(), namepath));
3332 if (parser.parseOptionalAttrDict(result.attributes))
3342void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
3343 EventControlAttr event, Value trigger,
3344 ValueRange inputs) {
3345 odsState.addOperands(trigger);
3346 odsState.addOperands(inputs);
3347 odsState.addAttribute(getEventAttrName(odsState.name), event);
3348 auto *r = odsState.addRegion();
3352 llvm::SmallVector<Location> argLocs;
3353 llvm::transform(inputs, std::back_inserter(argLocs),
3354 [&](Value v) {
return v.getLoc(); });
3355 b->addArguments(inputs.getTypes(), argLocs);
3363#define GET_OP_CLASSES
3364#include "circt/Dialect/HW/HW.cpp.inc"
assert(baseType &&"element must be base type")
static void buildModule(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports, ArrayAttr annotations, ArrayAttr layers)
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 LogicalResult verifyModuleCommon(HWModuleLike module)
static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value, Type resultType)
static void printModuleOp(OpAsmPrinter &p, ModuleTy mod)
static bool flattenConcatOp(ArrayConcatOp op, PatternRewriter &rewriter)
static LogicalResult foldCreateToSlice(ArrayCreateOp op, PatternRewriter &rewriter)
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
static ArrayAttr arrayOrEmpty(mlir::MLIRContext *context, ArrayRef< Attribute > attrs)
FunctionType getHWModuleOpType(Operation *op)
static void printExtractOp(OpAsmPrinter &printer, AggType op)
Use the same printer for both struct_extract and union_extract since the syntax is identical.
static void printArrayConcatTypes(OpAsmPrinter &p, Operation *, TypeRange inputTypes, Type resultType)
static ParseResult parseSliceTypes(OpAsmParser &p, Type &srcType, Type &idxType)
static void modifyModulePorts(Operation *op, ArrayRef< std::pair< unsigned, PortInfo > > insertInputs, ArrayRef< std::pair< unsigned, PortInfo > > insertOutputs, ArrayRef< unsigned > removeInputs, ArrayRef< unsigned > removeOutputs, Block *body=nullptr)
Insert and remove ports of a module.
static Value foldStructExtract(Operation *inputOp, uint32_t fieldIndex)
static bool hasAttribute(StringRef name, ArrayRef< NamedAttribute > attrs)
static void modifyModuleArgs(MLIRContext *context, ArrayRef< std::pair< unsigned, PortInfo > > insertArgs, ArrayRef< unsigned > removeArgs, ArrayRef< Attribute > oldArgNames, ArrayRef< Type > oldArgTypes, ArrayRef< Attribute > oldArgAttrs, ArrayRef< Location > oldArgLocs, SmallVector< Attribute > &newArgNames, SmallVector< Type > &newArgTypes, SmallVector< Attribute > &newArgAttrs, SmallVector< Location > &newArgLocs, Block *body=nullptr)
Internal implementation of argument/result insertion and removal on modules.
static bool mergeConcatSlices(ArrayConcatOp op, PatternRewriter &rewriter)
static SmallVector< Location > getAllPortLocs(ModTy module)
static ParseResult parseExtractOp(OpAsmParser &parser, OperationState &result)
Use the same parser for both struct_extract and union_extract since the syntax is identical.
static void setAllPortNames(ArrayRef< Attribute > names, ModTy module)
static void getAsmBlockArgumentNamesImpl(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 setHWModuleType(ModTy &mod, ModuleType type)
static ParseResult parseParamValue(OpAsmParser &p, Attribute &value, Type &resultType)
static LogicalResult checkAttributes(Operation *op, Attribute attr, Type type)
static std::optional< uint64_t > getUIntFromValue(Value value)
static ParseResult parseHWModuleOp(OpAsmParser &parser, OperationState &result)
static LogicalResult verifyAggregateFieldIndexAndType(AggregateOp &op, AggregateType aggType, Type elementType)
Ensure an aggregate op's field index is within the bounds of the aggregate type and the accessed fiel...
static PortInfo getPort(ModuleTy &mod, size_t idx)
static void printSliceTypes(OpAsmPrinter &p, Operation *, Type srcType, Type idxType)
static bool hasAdditionalAttributes(Op op, ArrayRef< StringRef > ignoredAttrs={})
Check whether an operation has any additional attributes set beyond its standard list of attributes r...
static ParseResult parseArrayConcatTypes(OpAsmParser &p, SmallVectorImpl< Type > &inputTypes, Type &resultType)
static bool getFieldName(const FieldRef &fieldRef, SmallString< 32 > &string)
static InstancePath empty
static StringAttr append(StringAttr base, const Twine &suffix)
Return a attribute with the specified suffix appended.
static Block * getBodyBlock(FModuleLike mod)
A namespace that is used to store existing names and generate new names in some scope within the IR.
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
void setOutput(unsigned i, Value v)
Value getInput(unsigned i)
llvm::SmallVector< Value > outputOperands
llvm::SmallVector< Value > inputArgs
llvm::StringMap< unsigned > outputIdx
llvm::StringMap< unsigned > inputIdx
HWModulePortAccessor(Location loc, const ModulePortInfo &info, Region &bodyRegion)
static StringRef getInnerSymbolAttrName()
Return the name of the attribute used for inner symbol names.
This helps visit TypeOp nodes.
ResultType dispatchTypeOpVisitor(Operation *op, ExtraArgs... args)
ResultType visitUnhandledTypeOp(Operation *op, ExtraArgs... args)
This callback is invoked on any combinational operations that are not handled by the concrete visitor...
ResultType visitInvalidTypeOp(Operation *op, ExtraArgs... args)
This callback is invoked on any non-expression operations.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
uint64_t getWidth(Type t)
size_t getNumPorts(Operation *op)
Return the number of ports in a module-like thing (modules, memories, etc)
ModuleType fnToMod(Operation *op, ArrayRef< Attribute > inputNames, ArrayRef< Attribute > outputNames)
LogicalResult verifyParameterStructure(ArrayAttr parameters, ArrayAttr moduleParameters, const EmitErrorFn &emitError)
Check that all the parameter values specified to the instance are structurally valid.
std::function< void(std::function< bool(InFlightDiagnostic &)>)> EmitErrorFn
Whenever the nested function returns true, a note referring to the referenced module is attached to t...
LogicalResult verifyInstanceOfHWModule(Operation *instance, FlatSymbolRefAttr moduleRef, OperandRange inputs, TypeRange results, ArrayAttr argNames, ArrayAttr resultNames, ArrayAttr parameters, SymbolTableCollection &symbolTable)
Combines verifyReferencedModule, verifyInputs, verifyOutputs, and verifyParameters.
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
ParseResult parseModuleSignature(OpAsmParser &parser, SmallVectorImpl< PortParse > &args, TypeAttr &modType)
New Style parsing.
void printModuleSignatureNew(OpAsmPrinter &p, Region &body, hw::ModuleType modType, ArrayRef< Attribute > portAttrs, ArrayRef< Location > locAttrs)
bool isOffset(Value base, Value index, uint64_t offset)
llvm::function_ref< void(OpBuilder &, HWModulePortAccessor &)> HWModuleBuilder
FunctionType getModuleType(Operation *module)
Return the signature for the specified module as a function type.
LogicalResult checkParameterInContext(Attribute value, Operation *module, Operation *usingOp, bool disallowParamRefs=false)
Check parameter specified by value to see if it is valid within the scope of the specified module mod...
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
bool isAnyModuleOrInstance(Operation *module)
TODO: Move all these functions to a hw::ModuleLike interface.
StringAttr getVerilogModuleNameAttr(Operation *module)
Returns the verilog module name attribute or symbol name of any module-like operations.
mlir::Type getCanonicalType(mlir::Type type)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
ParseResult parseInputPortList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inputs, SmallVectorImpl< Type > &inputTypes, ArrayAttr &inputNames)
Parse a list of instance input ports.
void printOutputPortList(OpAsmPrinter &p, Operation *op, TypeRange resultTypes, ArrayAttr resultNames)
Print a list of instance output ports.
ParseResult parseOptionalParameterList(OpAsmParser &parser, ArrayAttr ¶meters)
Parse an parameter list if present.
void printOptionalParameterList(OpAsmPrinter &p, Operation *op, ArrayAttr parameters)
Print a parameter list for a module or instance.
StringRef chooseName(StringRef a, StringRef b)
Choose a good name for an item from two options.
void printInputPortList(OpAsmPrinter &p, Operation *op, OperandRange inputs, TypeRange inputTypes, ArrayAttr inputNames)
Print a list of instance input ports.
ParseResult parseOutputPortList(OpAsmParser &parser, SmallVectorImpl< Type > &resultTypes, ArrayAttr &resultNames)
Parse a list of instance output ports.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
This class represents the namespace in which InnerRef's can be resolved.
InnerSymTarget lookup(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
Operation * lookupOp(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...
This holds a decoded list of input/inout and output ports for a module or instance.
PortInfo & at(size_t idx)
size_t sizeOutputs() const
size_t sizeInputs() const
PortDirectionRange getOutputs()
This holds the name, type, direction of a module's ports.