15#include "mlir/Transforms/DialectConversion.h"
16#include "llvm/Support/JSON.h"
19using namespace firrtl;
31 auto numOps =
op.getNumOperands();
33 if (numOps < n || numOps > m) {
34 auto err =
emitError() <<
" has " << numOps <<
" inputs instead of ";
38 err <<
" between " << n <<
" and " << m;
50 return emitError() <<
" missing output bundle";
51 if (b.getType().getNumElements() != n)
52 return emitError() <<
" has " << b.getType().getNumElements()
53 <<
" output elements instead of " << n;
59 if (
op.getParameters())
60 num =
op.getParameters().size();
61 if (num < n || num > n + c) {
62 auto d =
emitError() <<
" has " << num <<
" parameters instead of ";
66 d <<
" between " << n <<
" and " << (n + c);
73 for (
auto a :
op.getParameters()) {
74 auto param = cast<ParamDeclAttr>(a);
75 if (param.getName().getValue() == paramName) {
76 if (isa<StringAttr>(param.getValue()))
79 return emitError() <<
" has parameter '" << param.getName()
80 <<
"' which should be a string but is not";
85 return emitError() <<
" is missing parameter " << paramName;
90 for (
auto a :
op.getParameters()) {
91 auto param = cast<ParamDeclAttr>(a);
92 if (param.getName().getValue() == paramName) {
93 if (isa<IntegerAttr>(param.getValue()))
96 return emitError() <<
" has parameter '" << param.getName()
97 <<
"' which should be an integer but is not";
102 return emitError() <<
" is missing parameter " << paramName;
111class IntrinsicOpConversion final
116 IntrinsicOpConversion(TypeConverter &typeConverter, MLIRContext *
context,
117 const ConversionMapTy &conversions,
118 size_t &numConversions,
119 bool allowUnknownIntrinsics =
false)
121 numConversions(numConversions),
122 allowUnknownIntrinsics(allowUnknownIntrinsics) {}
125 matchAndRewrite(GenericIntrinsicOp op, OpAdaptor adaptor,
126 ConversionPatternRewriter &rewriter)
const override {
128 auto it = conversions.find(op.getIntrinsicAttr());
129 if (it == conversions.end()) {
130 if (!allowUnknownIntrinsics)
131 return op.emitError(
"unknown intrinsic ") << op.getIntrinsicAttr();
135 auto &conv = *it->second;
136 auto result = conv.checkAndConvert(
GenericIntrinsic(op), adaptor, rewriter);
137 if (succeeded(result))
143 const ConversionMapTy &conversions;
144 size_t &numConversions;
145 const bool allowUnknownIntrinsics;
154 bool allowUnknownIntrinsics) {
156 ConversionTarget target(*
context);
158 target.markUnknownOpDynamicallyLegal([](Operation *op) {
return true; });
159 if (allowUnknownIntrinsics)
160 target.addDynamicallyLegalOp<GenericIntrinsicOp>(
161 [
this](GenericIntrinsicOp op) {
162 return !
conversions.contains(op.getIntrinsicAttr());
165 target.addIllegalOp<GenericIntrinsicOp>();
169 TypeConverter typeConverter;
170 typeConverter.addConversion([](Type type) {
return type; });
171 auto firrtlBaseTypeMaterialization =
172 [](OpBuilder &builder,
FIRRTLBaseType resultType, ValueRange inputs,
173 Location loc) -> Value {
174 if (inputs.size() != 1)
176 auto inputType = type_dyn_cast<FIRRTLBaseType>(inputs.front().getType());
184 auto w = WireOp::create(builder, loc, resultType).getResult();
189 typeConverter.addSourceMaterialization(firrtlBaseTypeMaterialization);
191 typeConverter.addTargetMaterialization(firrtlBaseTypeMaterialization);
196 count, allowUnknownIntrinsics);
198 if (failed(mlir::applyPartialConversion(mod, target, std::move(
patterns))))
211 interface.populateIntrinsicLowerings(lowering);
222 using IntrinsicOpConverter::IntrinsicOpConverter;
231 using IntrinsicOpConverter::IntrinsicOpConverter;
240 using IntrinsicConverter::IntrinsicConverter;
248 PatternRewriter &rewriter)
override {
249 rewriter.replaceOpWithNewOp<PlusArgsTestIntrinsicOp>(
256 using IntrinsicConverter::IntrinsicConverter;
266 PatternRewriter &rewriter)
override {
268 auto newop = PlusArgsValueIntrinsicOp::create(
269 rewriter, gi.
op.getLoc(), bty.getElementTypePreservingConst(0),
270 bty.getElementTypePreservingConst(1),
272 rewriter.replaceOpWithNewOp<BundleCreateOp>(
273 gi.
op, bty, ValueRange({newop.getFound(), newop.getResult()}));
277class CirctClockGateConverter
280 using IntrinsicOpConverter::IntrinsicOpConverter;
283 if (gi.
op.getNumOperands() == 3) {
288 if (gi.
op.getNumOperands() == 2) {
292 gi.
emitError() <<
" has " << gi.
op.getNumOperands()
293 <<
" ports instead of 3 or 4";
298class CirctClockInverterConverter
301 using IntrinsicOpConverter::IntrinsicOpConverter;
311 using IntrinsicConverter::IntrinsicConverter;
320 PatternRewriter &rewriter)
override {
322 gi.
getParamValue<IntegerAttr>(
"POW_2").getValue().getZExtValue();
324 auto pow2Attr = rewriter.getI64IntegerAttr(pow2);
326 rewriter.replaceOpWithNewOp<ClockDividerIntrinsicOp>(
327 gi.
op, adaptor.getOperands()[0], pow2Attr);
331template <
typename OpTy>
343template <
typename OpTy>
356 using IntrinsicConverter::IntrinsicConverter;
365 PatternRewriter &rewriter)
override {
366 auto getI64Attr = [&](IntegerAttr val) {
368 return IntegerAttr();
369 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
371 auto delay = getI64Attr(gi.
getParamValue<IntegerAttr>(
"delay"));
372 auto length = getI64Attr(gi.
getParamValue<IntegerAttr>(
"length"));
373 rewriter.replaceOpWithNewOp<LTLDelayIntrinsicOp>(
374 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], delay, length);
380 using IntrinsicConverter::IntrinsicConverter;
393 PatternRewriter &rewriter)
override {
394 auto delay = rewriter.getI64IntegerAttr(
395 gi.
getParamValue<IntegerAttr>(
"delay").getValue().getZExtValue());
396 auto operands = adaptor.getOperands();
397 Value clock = operands[1];
398 rewriter.replaceOpWithNewOp<LTLPastIntrinsicOp>(
399 gi.
op, gi.
op.getResultTypes(), operands[0], delay, clock);
403class CirctLTLClockConverter
406 using IntrinsicOpConverter::IntrinsicOpConverter;
417 using IntrinsicConverter::IntrinsicConverter;
426 PatternRewriter &rewriter)
override {
427 auto getI64Attr = [&](IntegerAttr val) {
429 return IntegerAttr();
430 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
432 auto base = getI64Attr(gi.
getParamValue<IntegerAttr>(
"base"));
433 auto more = getI64Attr(gi.
getParamValue<IntegerAttr>(
"more"));
434 rewriter.replaceOpWithNewOp<LTLRepeatIntrinsicOp>(
435 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], base, more);
441 using IntrinsicConverter::IntrinsicConverter;
450 PatternRewriter &rewriter)
override {
451 auto getI64Attr = [&](IntegerAttr val) {
453 return IntegerAttr();
454 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
456 auto base = getI64Attr(gi.
getParamValue<IntegerAttr>(
"base"));
457 auto more = getI64Attr(gi.
getParamValue<IntegerAttr>(
"more"));
458 rewriter.replaceOpWithNewOp<LTLGoToRepeatIntrinsicOp>(
459 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], base, more);
465 using IntrinsicConverter::IntrinsicConverter;
474 PatternRewriter &rewriter)
override {
475 auto getI64Attr = [&](IntegerAttr val) {
477 return IntegerAttr();
478 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
480 auto base = getI64Attr(gi.
getParamValue<IntegerAttr>(
"base"));
481 auto more = getI64Attr(gi.
getParamValue<IntegerAttr>(
"more"));
482 rewriter.replaceOpWithNewOp<LTLNonConsecutiveRepeatIntrinsicOp>(
483 gi.
op, gi.
op.getResultTypes(), adaptor.getOperands()[0], base, more);
490 using IntrinsicConverter::IntrinsicConverter;
499 PatternRewriter &rewriter)
override {
501 auto operands = adaptor.getOperands();
506 enable = operands[1];
508 rewriter.replaceOpWithNewOp<Op>(gi.
op, operands[0], enable, label);
513 using IntrinsicConverter::IntrinsicConverter;
521 PatternRewriter &rewriter)
override {
522 auto operands = adaptor.getOperands();
523 rewriter.replaceOpWithNewOp<Mux2CellIntrinsicOp>(gi.
op, operands[0],
524 operands[1], operands[2]);
529 using IntrinsicConverter::IntrinsicConverter;
537 PatternRewriter &rewriter)
override {
538 auto operands = adaptor.getOperands();
539 rewriter.replaceOpWithNewOp<Mux4CellIntrinsicOp>(
540 gi.
op, operands[0], operands[1], operands[2], operands[3], operands[4]);
544class CirctHasBeenResetConverter
547 using IntrinsicOpConverter::IntrinsicOpConverter;
558 using IntrinsicOpConverter::IntrinsicOpConverter;
566template <
class OpTy,
bool ifElseFatal = false>
569 using IntrinsicConverter::IntrinsicConverter;
572 GenericIntrinsicOpAdaptor adaptor,
573 PatternRewriter &rewriter)
override {
587 auto clock = adaptor.getOperands()[0];
588 auto predicate = adaptor.getOperands()[1];
589 auto enable = adaptor.getOperands()[2];
591 auto substitutions = adaptor.getOperands().drop_front(3);
592 auto name = label ? label.strref() :
"";
597 SmallVector<Value> allOperands;
599 SmallVector<Value> substitutionVec(substitutions.begin(),
600 substitutions.end());
602 substitutionVec, message, allOperands)))
606 message = rewriter.getStringAttr(
"");
607 allOperands.append(substitutions.begin(), substitutions.end());
610 auto op = rewriter.template replaceOpWithNewOp<OpTy>(
611 gi.
op, clock, predicate, enable, message, allOperands, name,
614 SmallVector<StringRef> guardStrings;
615 guards.strref().split(guardStrings,
';', -1,
617 rewriter.startOpModification(op);
618 op->setAttr(
"guards", rewriter.getStrArrayAttr(guardStrings));
619 rewriter.finalizeOpModification(op);
622 if constexpr (ifElseFatal) {
623 rewriter.startOpModification(op);
624 op->setAttr(
"format", rewriter.getStringAttr(
"ifElseFatal"));
625 rewriter.finalizeOpModification(op);
634 using IntrinsicConverter::IntrinsicConverter;
645 PatternRewriter &rewriter)
override {
649 auto clock = adaptor.getOperands()[0];
650 auto predicate = adaptor.getOperands()[1];
651 auto enable = adaptor.getOperands()[2];
653 auto name = label ? label.strref() :
"";
655 auto message = rewriter.getStringAttr(
"");
656 auto op = rewriter.replaceOpWithNewOp<CoverOp>(
657 gi.
op, clock, predicate, enable, message, ValueRange{}, name,
660 SmallVector<StringRef> guardStrings;
661 guards.strref().split(guardStrings,
';', -1,
663 rewriter.startOpModification(op);
664 op->setAttr(
"guards", rewriter.getStrArrayAttr(guardStrings));
665 rewriter.finalizeOpModification(op);
672 using IntrinsicConverter::IntrinsicConverter;
683 PatternRewriter &rewriter)
override {
688 auto predicate = adaptor.getOperands()[0];
689 auto enable = adaptor.getOperands()[1];
691 auto substitutions = adaptor.getOperands().drop_front(2);
692 auto name = label ? label.strref() :
"";
694 auto message = format ? format : rewriter.getStringAttr(
"");
695 auto op = rewriter.template replaceOpWithNewOp<UnclockedAssumeIntrinsicOp>(
696 gi.
op, predicate, enable, message, substitutions, name);
698 SmallVector<StringRef> guardStrings;
699 guards.strref().split(guardStrings,
';', -1,
701 rewriter.startOpModification(op);
702 op->setAttr(
"guards", rewriter.getStrArrayAttr(guardStrings));
703 rewriter.finalizeOpModification(op);
710 return !gi.
getParamValue<IntegerAttr>(
"isClocked").getValue().isZero();
714 using IntrinsicConverter::IntrinsicConverter;
722 auto isClocked = getIsClocked(gi);
734 PatternRewriter &rewriter)
override {
735 auto isClocked = getIsClocked(gi);
736 auto functionName = gi.
getParamValue<StringAttr>(
"functionName");
737 ArrayAttr inputNamesStrArray;
738 StringAttr outputStr = gi.
getParamValue<StringAttr>(
"outputName");
739 if (
auto inputNames = gi.
getParamValue<StringAttr>(
"inputNames")) {
740 SmallVector<StringRef> inputNamesTemporary;
741 inputNames.strref().split(inputNamesTemporary,
';', -1,
743 inputNamesStrArray = rewriter.getStrArrayAttr(inputNamesTemporary);
746 Value clock = isClocked ? adaptor.getOperands()[0] : Value();
747 Value enable = adaptor.getOperands()[
static_cast<size_t>(isClocked)];
750 adaptor.getOperands().drop_front(
static_cast<size_t>(isClocked) + 1);
752 rewriter.replaceOpWithNewOp<DPICallIntrinsicOp>(
753 gi.
op, gi.
op.getResultTypes(), functionName, inputNamesStrArray,
754 outputStr, clock, enable, inputs);
763A
tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc,
764 Twine path = Twine()) {
765 return tryGetAsBase<A>(dict, root, key, loc,
"View 'info'",
766 "'info' attribute", path);
771std::optional<DictionaryAttr>
773 DictionaryAttr augmentedType, DictionaryAttr root,
774 StringAttr name, StringAttr defName,
775 std::optional<StringAttr> description, Twine path = {}) {
777 tryGetAs<StringAttr>(augmentedType, root,
"class", loc, path);
780 StringRef classBase = classAttr.getValue();
781 if (!classBase.consume_front(
"sifive.enterprise.grandcentral.Augmented")) {
783 "the 'class' was expected to start with "
784 "'sifive.enterprise.grandCentral.Augmented*', but was '" +
785 classAttr.getValue() +
"' (Did you misspell it?)")
787 <<
"see attribute: " << augmentedType;
794 if (classBase ==
"BundleType") {
795 defName = tryGetAs<StringAttr>(augmentedType, root,
"defName", loc, path);
803 SmallVector<Attribute> elements;
805 tryGetAs<ArrayAttr>(augmentedType, root,
"elements", loc, path);
808 for (
size_t i = 0, e = elementsAttr.size(); i != e; ++i) {
809 auto field = dyn_cast_or_null<DictionaryAttr>(elementsAttr[i]);
813 "View 'info' attribute with path '.elements[" + Twine(i) +
814 "]' contained an unexpected type (expected a DictionaryAttr).")
816 <<
"The received element was: " << elementsAttr[i];
819 auto ePath = (path +
".elements[" + Twine(i) +
"]").str();
820 auto name = tryGetAs<StringAttr>(field, root,
"name", loc, ePath);
823 auto tpe = tryGetAs<DictionaryAttr>(field, root,
"tpe", loc, ePath);
826 std::optional<StringAttr> description;
827 if (
auto maybeDescription = field.get(
"description"))
828 description = cast<StringAttr>(maybeDescription);
831 description, path +
"_" + name.getValue());
838 if (
auto maybeDescription = field.get(
"description"))
839 attrs.append(
"description", cast<StringAttr>(maybeDescription));
840 attrs.append(
"name", name);
841 auto tpeClass = tpe.getAs<StringAttr>(
"class");
843 mlir::emitError(loc,
"missing 'class' key in") << tpe;
846 attrs.append(
"tpe", tpeClass);
847 elements.push_back(*eltAttr);
853 attrs.append(
"class", classAttr);
854 attrs.append(
"defName", defName);
856 attrs.append(
"description", *description);
857 attrs.append(
"elements", ArrayAttr::get(
context, elements));
858 attrs.append(
"name", name);
859 return DictionaryAttr::getWithSorted(
context, attrs);
863 if (classBase ==
"GroundType") {
864 NamedAttrList elementIface;
867 elementIface.append(
"class", classAttr);
869 elementIface.append(
"description", *description);
870 elementIface.append(
"name", name);
872 return DictionaryAttr::getWithSorted(
context, elementIface);
877 if (classBase ==
"VectorType") {
879 tryGetAs<ArrayAttr>(augmentedType, root,
"elements", loc, path);
882 SmallVector<Attribute> elements;
883 for (
auto [i, elt] :
llvm::enumerate(elementsAttr)) {
885 context, loc, cast<DictionaryAttr>(elt), root, name,
886 StringAttr::get(
context,
""), std::nullopt, path +
"_" + Twine(i));
889 elements.push_back(*eltAttr);
892 attrs.append(
"class", classAttr);
894 attrs.append(
"description", *description);
895 attrs.append(
"elements", ArrayAttr::get(
context, elements));
896 attrs.append(
"name", name);
897 return DictionaryAttr::getWithSorted(
context, attrs);
902 mlir::emitError(loc,
"found unknown AugmentedType '" + classAttr.getValue() +
903 "' (Did you misspell it?)")
905 <<
"see attribute: " << augmentedType;
912 GenericIntrinsicOpAdaptor adaptor,
913 PatternRewriter &rewriter)
override {
920 for (
auto idx :
llvm::
seq(gi.getNumInputs()))
921 if (gi.checkInputType(idx,
"must be ground type", [](auto ty) {
922 auto base = type_dyn_cast<FIRRTLBaseType>(ty);
923 return base && base.isGround();
929 llvm::json::parse(gi.
getParamValue<StringAttr>(
"info").getValue());
930 if (
auto err = view.takeError()) {
931 handleAllErrors(std::move(err), [&](
const llvm::json::ParseError &a) {
932 gi.
emitError() <<
": error parsing view JSON: " <<
a.message();
938 llvm::json::Path::Root root;
940 assert(value &&
"JSON to attribute failed but should not ever fail");
944 auto dict = dyn_cast<DictionaryAttr>(value);
946 return gi.
emitError() <<
": 'info' parameter must be a dictionary";
950 gi.
op.getContext(), gi.
op.getLoc(), dict, dict, nameAttr,
958 AugmentedBundleTypeAttr::get(gi.
op.getContext(), *result);
959 if (augmentedType.getClass() != augmentedBundleTypeAnnoClass)
960 return gi.
emitError() <<
": 'info' must be augmented bundle";
963 SmallVector<DictionaryAttr> worklist;
964 worklist.push_back(augmentedType.getUnderlying());
965 size_t numLeaves = 0;
967 StringAttr::get(gi.
op.getContext(), augmentedGroundTypeAnnoClass);
968 [[maybe_unused]]
auto augBundleAttr =
969 StringAttr::get(gi.
op.getContext(), augmentedBundleTypeAnnoClass);
970 [[maybe_unused]]
auto augVectorAttr =
971 StringAttr::get(gi.
op.getContext(), augmentedVectorTypeAnnoClass);
972 while (!worklist.empty()) {
973 auto dict = worklist.pop_back_val();
974 auto clazz = dict.getAs<StringAttr>(
"class");
975 if (clazz == augGroundAttr) {
979 assert(clazz == augBundleAttr || clazz == augVectorAttr);
982 dict.getAs<ArrayAttr>(
"elements").getAsRange<DictionaryAttr>());
987 <<
" has " << gi.
getNumInputs() <<
" operands but view 'info' has "
988 << numLeaves <<
" leaf elements";
992 rewriter.replaceOpWithNewOp<ViewIntrinsicOp>(
993 gi.
op, nameAttr.getValue(),
yaml, augmentedType, adaptor.getOperands());
1004#include "FIRRTLIntrinsics.cpp.inc"
1008 populateLowerings(lowering);
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static std::optional< DictionaryAttr > parseAugmentedType(ApplyState &state, DictionaryAttr augmentedType, DictionaryAttr root, StringAttr name, StringAttr defName, std::optional< IntegerAttr > id, std::optional< StringAttr > description, Twine clazz, StringAttr companionAttr, Twine path={})
Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract any annotations it may con...
static LogicalResult convert(arc::ExecuteOp op, arc::ExecuteOp::Adaptor adaptor, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
Base class for Intrinsic Converters.
Lowering helper which collects all intrinsic converters.
FailureOr< size_t > lower(FModuleOp mod, bool allowUnknownIntrinsics=false)
Lowers all intrinsics in a module. Returns number converted or failure.
llvm::DenseMap< StringAttr, std::unique_ptr< IntrinsicConverter > > ConversionMapTy
MLIRContext * context
Reference to the MLIR context.
ConversionMapTy conversions
Mapping from intrinsic names to converters.
A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc, Twine clazz, Twine path=Twine())
Implements the same behavior as DictionaryAttr::getAs<A> to return the value of a specific type assoc...
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
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)
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Attribute convertJSONToAttribute(MLIRContext *context, llvm::json::Value &value, llvm::json::Path p)
Convert arbitrary JSON to an MLIR Attribute.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const override
Helper class for checking and extracting information from the generic instrinsic op.
ParseResult sizedInput(unsigned n, int32_t size)
mlir::TypedValue< BundleType > getOutputBundle()
T getParamValue(StringRef name)
Get parameter value by name, if present, as requested type.
ParseResult typedOutput()
ParseResult hasResetInput(unsigned n)
ParseResult typedInput(unsigned n)
ParseResult hasNOutputElements(unsigned n)
InFlightDiagnostic emitError()
ParseResult namedIntParam(StringRef paramName, bool optional=false)
ParseResult namedParam(StringRef paramName, bool optional=false)
ParseResult sizedOutput(int32_t size)
ParseResult sizedOutputElement(unsigned n, StringRef name, int32_t size)
ParseResult hasNParam(unsigned n, unsigned c=0)
ParseResult hasOutputElement(unsigned n, StringRef name)
ParseResult hasNInputs(unsigned n, unsigned c=0)
ParseResult hasNoOutput()
A dialect interface to provide lowering conversions.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const