13 #include "../PassDetails.h"
24 #include "mlir/Transforms/DialectConversion.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/TypeSwitch.h"
28 #include "llvm/Support/JSON.h"
32 #define GEN_PASS_DEF_LOWERESITOHW
33 #include "circt/Dialect/ESI/ESIPasses.h.inc"
37 using namespace circt;
51 using OpConversionPattern::OpConversionPattern;
54 matchAndRewrite(PipelineStageOp stage, OpAdaptor adaptor,
55 ConversionPatternRewriter &rewriter)
const final;
62 LogicalResult PipelineStageLowering::matchAndRewrite(
63 PipelineStageOp stage, OpAdaptor adaptor,
64 ConversionPatternRewriter &rewriter)
const {
65 auto loc = stage.getLoc();
66 auto chPort = dyn_cast<ChannelType>(stage.getInput().getType());
68 return rewriter.notifyMatchFailure(stage,
"stage had wrong type");
69 Operation *symTable = stage->getParentWithTrait<OpTrait::SymbolTable>();
70 auto stageModule = builder.declareStage(symTable, stage);
74 ArrayAttr stageParams =
75 builder.getStageParameterList(rewriter.getUI32IntegerAttr(width));
83 rewriter.create<UnwrapValidReadyOp>(loc, stage.getInput(), wrapReady);
85 StringRef pipeStageName =
"pipelineStage";
86 if (
auto name = stage->getAttrOfType<StringAttr>(
"name"))
87 pipeStageName = name.getValue();
91 llvm::SmallVector<Value> operands = {stage.getClk(), stage.getRst()};
92 operands.push_back(
unwrap.getRawOutput());
93 operands.push_back(
unwrap.getValid());
94 operands.push_back(stageReady);
95 auto stageInst = rewriter.create<hw::InstanceOp>(
96 loc, stageModule, pipeStageName, operands, stageParams);
97 auto stageInstResults = stageInst.getResults();
101 wrapReady.
setValue(stageInstResults[0]);
103 x = stageInstResults[1];
104 xValid = stageInstResults[2];
107 auto wrap = rewriter.create<WrapValidReadyOp>(
108 loc, chPort, rewriter.getI1Type(), x, xValid);
112 rewriter.replaceOp(stage,
wrap.getChanOutput());
120 using OpConversionPattern::OpConversionPattern;
123 matchAndRewrite(NullSourceOp nullop, OpAdaptor adaptor,
124 ConversionPatternRewriter &rewriter)
const final;
128 LogicalResult NullSourceOpLowering::matchAndRewrite(
129 NullSourceOp nullop, OpAdaptor adaptor,
130 ConversionPatternRewriter &rewriter)
const {
131 auto innerType = cast<ChannelType>(nullop.getOut().getType()).getInner();
132 Location loc = nullop.getLoc();
135 return rewriter.notifyMatchFailure(
136 nullop,
"NullOp lowering only supports hw types");
138 rewriter.create<
hw::ConstantOp>(nullop.getLoc(), rewriter.getI1Type(), 0);
142 auto wrap = rewriter.create<WrapValidReadyOp>(loc, typedZero, valid);
143 wrap->setAttr(
"name", rewriter.getStringAttr(
"nullsource"));
144 rewriter.replaceOp(nullop, {
wrap.getChanOutput()});
150 struct RemoveWrapUnwrap :
public ConversionPattern {
152 RemoveWrapUnwrap(MLIRContext *context)
153 : ConversionPattern(MatchAnyOpTypeTag(), 1, context) {}
156 matchAndRewrite(Operation *op, ArrayRef<Value> operands,
157 ConversionPatternRewriter &rewriter)
const override {
158 Value valid, ready,
data;
159 WrapValidReadyOp
wrap = dyn_cast<WrapValidReadyOp>(op);
160 UnwrapValidReadyOp
unwrap = dyn_cast<UnwrapValidReadyOp>(op);
162 if (
wrap.getChanOutput().getUsers().empty()) {
164 rewriter.getI1Type(), 1);
165 rewriter.replaceOp(
wrap, {
nullptr, c1});
169 if (!
wrap.getChanOutput().hasOneUse())
170 return rewriter.notifyMatchFailure(
171 wrap,
"This conversion only supports wrap-unwrap back-to-back. "
172 "Wrap didn't have exactly one use.");
173 if (!(
unwrap = dyn_cast<UnwrapValidReadyOp>(
174 wrap.getChanOutput().use_begin()->getOwner())))
175 return rewriter.notifyMatchFailure(
176 wrap,
"This conversion only supports wrap-unwrap back-to-back. "
177 "Could not find 'unwrap'.");
181 ready =
unwrap.getReady();
183 wrap = dyn_cast<WrapValidReadyOp>(operands[0].getDefiningOp());
185 return rewriter.notifyMatchFailure(
186 operands[0].getDefiningOp(),
187 "This conversion only supports wrap-unwrap back-to-back. "
188 "Could not find 'wrap'.");
189 valid =
wrap.getValid();
196 if (!
wrap.getChanOutput().hasOneUse())
197 return rewriter.notifyMatchFailure(
wrap, [](Diagnostic &d) {
198 d <<
"This conversion only supports wrap-unwrap back-to-back. "
199 "Wrap didn't have exactly one use.";
201 rewriter.replaceOp(
wrap, {
nullptr, ready});
211 template <
typename Op>
217 matchAndRewrite(Op op,
typename Op::Adaptor adaptor,
218 ConversionPatternRewriter &rewriter)
const final {
220 return rewriter.notifyMatchFailure(op->getLoc(),
"canonicalizer failed");
227 struct ESItoHWPass :
public circt::esi::impl::LowerESItoHWBase<ESItoHWPass> {
228 void runOnOperation()
override;
237 using OpConversionPattern::OpConversionPattern;
240 matchAndRewrite(WrapSVInterfaceOp
wrap, OpAdaptor adaptor,
241 ConversionPatternRewriter &rewriter)
const final;
246 WrapInterfaceLower::matchAndRewrite(WrapSVInterfaceOp
wrap, OpAdaptor adaptor,
247 ConversionPatternRewriter &rewriter)
const {
248 auto operands = adaptor.getOperands();
249 if (operands.size() != 1)
250 return rewriter.notifyMatchFailure(
wrap, [&operands](Diagnostic &d) {
251 d <<
"wrap.iface has 1 argument. Got " << operands.size() <<
"operands";
253 auto sinkModport = dyn_cast<GetModportOp>(operands[0].getDefiningOp());
257 dyn_cast<InterfaceInstanceOp>(sinkModport.getIface().getDefiningOp());
261 auto loc =
wrap.getLoc();
262 auto validSignal = rewriter.create<ReadInterfaceSignalOp>(
265 dataSignal = rewriter.create<ReadInterfaceSignalOp>(loc, ifaceInstance,
267 auto wrapVR = rewriter.create<WrapValidReadyOp>(loc, dataSignal, validSignal);
268 rewriter.create<AssignInterfaceSignalOp>(
270 rewriter.replaceOp(
wrap, {wrapVR.getChanOutput()});
280 using OpConversionPattern::OpConversionPattern;
283 matchAndRewrite(UnwrapSVInterfaceOp
wrap, OpAdaptor adaptor,
284 ConversionPatternRewriter &rewriter)
const final;
288 LogicalResult UnwrapInterfaceLower::matchAndRewrite(
289 UnwrapSVInterfaceOp
unwrap, OpAdaptor adaptor,
290 ConversionPatternRewriter &rewriter)
const {
291 auto operands = adaptor.getOperands();
292 if (operands.size() != 2)
293 return rewriter.notifyMatchFailure(
unwrap, [&operands](Diagnostic &d) {
294 d <<
"Unwrap.iface has 2 arguments. Got " << operands.size()
298 auto sourceModport = dyn_cast<GetModportOp>(operands[1].getDefiningOp());
302 dyn_cast<InterfaceInstanceOp>(sourceModport.getIface().getDefiningOp());
306 auto loc =
unwrap.getLoc();
307 auto readySignal = rewriter.create<ReadInterfaceSignalOp>(
310 rewriter.create<UnwrapValidReadyOp>(loc, operands[0], readySignal);
311 rewriter.create<AssignInterfaceSignalOp>(
314 rewriter.create<AssignInterfaceSignalOp>(
328 using OpConversionPattern::OpConversionPattern;
331 matchAndRewrite(CosimToHostEndpointOp, OpAdaptor adaptor,
332 ConversionPatternRewriter &rewriter)
const final;
339 LogicalResult CosimToHostLowering::matchAndRewrite(
340 CosimToHostEndpointOp ep, OpAdaptor adaptor,
341 ConversionPatternRewriter &rewriter)
const {
342 auto loc = ep.getLoc();
343 auto *
ctxt = rewriter.getContext();
346 Value toHost = adaptor.getToHost();
347 Type type = toHost.getType();
351 SmallVector<Attribute, 8> params;
355 "TO_HOST_SIZE_BITS", rewriter.getI32IntegerAttr(width > 0 ? width : 1)));
358 auto sendReady = bb.get(rewriter.getI1Type());
359 UnwrapValidReadyOp unwrapSend =
360 rewriter.create<UnwrapValidReadyOp>(loc, toHost, sendReady);
361 Value castedSendData;
364 loc, rewriter.getIntegerType(width), unwrapSend.getRawOutput());
367 loc, rewriter.getIntegerType(1), rewriter.getBoolAttr(
false));
370 Operation *symTable = ep->getParentWithTrait<OpTrait::SymbolTable>();
371 HWModuleExternOp endpoint =
372 builder.declareCosimEndpointToHostModule(symTable);
378 unwrapSend.getValid(),
381 auto cosimEpModule = rewriter.
create<hw::InstanceOp>(
383 sendReady.setValue(cosimEpModule.getResult(0));
386 rewriter.eraseOp(ep);
394 struct CosimFromHostLowering
400 using OpConversionPattern::OpConversionPattern;
403 matchAndRewrite(CosimFromHostEndpointOp, OpAdaptor adaptor,
404 ConversionPatternRewriter &rewriter)
const final;
411 LogicalResult CosimFromHostLowering::matchAndRewrite(
412 CosimFromHostEndpointOp ep, OpAdaptor adaptor,
413 ConversionPatternRewriter &rewriter)
const {
414 auto loc = ep.getLoc();
415 auto *
ctxt = rewriter.getContext();
418 ChannelType type = ep.getFromHost().getType();
422 SmallVector<Attribute, 8> params;
427 rewriter.getI32IntegerAttr(width > 0 ? width : 1)));
430 auto recvReady = bb.get(rewriter.getI1Type());
433 Operation *symTable = ep->getParentWithTrait<OpTrait::SymbolTable>();
434 HWModuleExternOp endpoint =
435 builder.declareCosimEndpointFromHostModule(symTable);
438 Value operands[] = {adaptor.getClk(), adaptor.getRst(), recvReady};
439 auto cosimEpModule = rewriter.create<hw::InstanceOp>(
443 Value recvDataFromCosim = cosimEpModule.getResult(1);
444 Value recvValidFromCosim = cosimEpModule.getResult(0);
445 Value castedRecvData;
448 rewriter.create<
hw::BitcastOp>(loc, type.getInner(), recvDataFromCosim);
451 loc, rewriter.getIntegerType(0),
452 rewriter.getIntegerAttr(rewriter.getIntegerType(0), 0));
453 WrapValidReadyOp wrapRecv = rewriter.create<WrapValidReadyOp>(
454 loc, castedRecvData, recvValidFromCosim);
455 recvReady.setValue(wrapRecv.getReady());
458 rewriter.replaceOp(ep, wrapRecv.getChanOutput());
469 using OpConversionPattern::OpConversionPattern;
470 constexpr
static StringRef manifestRomName =
"__ESI_Manifest_ROM";
473 matchAndRewrite(CompressedManifestOp, OpAdaptor adaptor,
474 ConversionPatternRewriter &rewriter)
const override;
477 LogicalResult createRomModule(CompressedManifestOp op,
478 ConversionPatternRewriter &rewriter)
const;
482 LogicalResult ManifestRomLowering::createRomModule(
483 CompressedManifestOp op, ConversionPatternRewriter &rewriter)
const {
484 Location loc = op.getLoc();
485 auto mlirModBody = op->getParentOfType<mlir::ModuleOp>();
486 rewriter.setInsertionPointToStart(mlirModBody.getBody());
490 if (Operation *existingExtern = mlirModBody.lookupSymbol(manifestRomName)) {
491 if (!isa<hw::HWModuleExternOp>(existingExtern))
492 return rewriter.notifyMatchFailure(
494 "Found " + manifestRomName +
" but it wasn't an HWModuleExternOp");
495 rewriter.eraseOp(existingExtern);
500 {{rewriter.getStringAttr(
"clk"), rewriter.getType<seq::ClockType>(),
502 {{rewriter.getStringAttr(
"address"), rewriter.getIntegerType(29),
504 {{rewriter.getStringAttr(
"data"), rewriter.getI64Type(),
507 auto rom = rewriter.create<HWModuleOp>(
508 loc, rewriter.getStringAttr(manifestRomName), ports);
509 Block *romBody = rom.getBodyBlock();
510 rewriter.setInsertionPointToStart(romBody);
511 Value
clk = romBody->getArgument(0);
512 Value inputAddress = romBody->getArgument(1);
515 ArrayRef<uint8_t> maniBytes = op.getCompressedManifest().getData();
516 SmallVector<uint64_t> words;
517 words.push_back(maniBytes.size());
519 for (
size_t i = 0; i < maniBytes.size() - 7; i += 8) {
521 for (
size_t b = 0; b < 8; ++b)
522 word |=
static_cast<uint64_t
>(maniBytes[i + b]) << (8 * b);
523 words.push_back(word);
525 size_t overHang = maniBytes.size() % 8;
528 for (
size_t i = 0; i < overHang; ++i)
529 word |=
static_cast<uint64_t
>(maniBytes[maniBytes.size() - overHang + i])
531 words.push_back(word);
536 SmallVector<Attribute> wordAttrs;
537 for (uint64_t word : words)
538 wordAttrs.push_back(rewriter.getI64IntegerAttr(word));
539 auto manifestConstant = rewriter.create<hw::AggregateConstantOp>(
541 rewriter.getArrayAttr(wordAttrs));
543 rewriter.create<
sv::RegOp>(loc, manifestConstant.getType());
544 rewriter.create<
sv::AssignOp>(loc, manifestReg, manifestConstant);
547 size_t addrBits = llvm::Log2_64_Ceil(words.size());
552 rewriter.
create<sv::ArrayIndexInOutOp>(loc, manifestReg, inputAddresReg);
555 if (
auto *term = romBody->getTerminator())
556 rewriter.eraseOp(term);
557 rewriter.
create<hw::OutputOp>(loc, ValueRange{readDataReg});
561 LogicalResult ManifestRomLowering::matchAndRewrite(
562 CompressedManifestOp op, OpAdaptor adaptor,
563 ConversionPatternRewriter &rewriter)
const {
564 LogicalResult ret = createRomModule(op, rewriter);
565 rewriter.eraseOp(op);
572 struct CosimManifestLowering :
public ManifestRomLowering {
574 using ManifestRomLowering::ManifestRomLowering;
577 matchAndRewrite(CompressedManifestOp, OpAdaptor adaptor,
578 ConversionPatternRewriter &rewriter)
const final;
582 LogicalResult CosimManifestLowering::matchAndRewrite(
583 CompressedManifestOp op, OpAdaptor adaptor,
584 ConversionPatternRewriter &rewriter)
const {
585 MLIRContext *
ctxt = rewriter.getContext();
586 Location loc = op.getLoc();
590 LogicalResult ret = createRomModule(op, rewriter);
595 Attribute params[] = {
598 {{rewriter.getStringAttr(
"compressed_manifest"),
599 rewriter.getType<hw::ArrayType>(
600 rewriter.getI8Type(),
602 rewriter.getStringAttr(
"COMPRESSED_MANIFEST_SIZE"),
603 rewriter.getI32Type())),
607 rewriter.setInsertionPointToEnd(
608 op->getParentOfType<mlir::ModuleOp>().getBody());
609 auto cosimManifestExternModule = rewriter.create<HWModuleExternOp>(
610 loc, rewriter.getStringAttr(
"Cosim_Manifest"), ports,
"Cosim_Manifest",
613 hw::ModulePortInfo portInfo({});
615 loc, rewriter.getStringAttr(
"__ESIManifest"), portInfo,
616 [&](OpBuilder &rewriter,
const hw::HWModulePortAccessor &) {
618 SmallVector<Attribute> bytes;
619 for (uint8_t b : op.getCompressedManifest().getData())
620 bytes.push_back(rewriter.getI8IntegerAttr(b));
621 auto manifestConstant = rewriter.create<hw::AggregateConstantOp>(
623 rewriter.getArrayAttr(bytes));
625 rewriter.create<sv::LogicOp>(loc, manifestConstant.getType());
626 rewriter.create<
sv::AssignOp>(loc, manifestLogic, manifestConstant);
630 rewriter.
create<hw::InstanceOp>(
631 loc, cosimManifestExternModule,
"__manifest",
632 ArrayRef<Value>({manifest}),
633 rewriter.getArrayAttr({ParamDeclAttr::get(
634 "COMPRESSED_MANIFEST_SIZE",
635 rewriter.getI32IntegerAttr(bytes.size()))}));
638 rewriter.setInsertionPoint(op);
639 rewriter.create<hw::InstanceOp>(loc, manifestMod,
"__manifest",
640 ArrayRef<Value>({}));
642 rewriter.eraseOp(op);
645 void ESItoHWPass::runOnOperation() {
646 auto top = getOperation();
647 auto *
ctxt = &getContext();
649 ConversionTarget noBundlesTarget(*
ctxt);
650 noBundlesTarget.markUnknownOpDynamicallyLegal(
651 [](Operation *) {
return true; });
652 noBundlesTarget.addIllegalOp<PackBundleOp>();
653 noBundlesTarget.addIllegalOp<UnpackBundleOp>();
654 RewritePatternSet bundlePatterns(&getContext());
655 bundlePatterns.add<CanonicalizerOpLowering<PackBundleOp>>(&getContext());
656 bundlePatterns.add<CanonicalizerOpLowering<UnpackBundleOp>>(&getContext());
657 if (failed(applyPartialConversion(getOperation(), noBundlesTarget,
658 std::move(bundlePatterns))))
662 ConversionTarget pass1Target(*
ctxt);
663 pass1Target.addLegalDialect<comb::CombDialect>();
664 pass1Target.addLegalDialect<HWDialect>();
665 pass1Target.addLegalDialect<SVDialect>();
666 pass1Target.addLegalDialect<seq::SeqDialect>();
667 pass1Target.addLegalOp<WrapValidReadyOp, UnwrapValidReadyOp>();
669 pass1Target.addIllegalOp<WrapSVInterfaceOp, UnwrapSVInterfaceOp>();
670 pass1Target.addIllegalOp<PipelineStageOp>();
671 pass1Target.addIllegalOp<CompressedManifestOp>();
675 RewritePatternSet pass1Patterns(
ctxt);
676 pass1Patterns.insert<PipelineStageLowering>(esiBuilder,
ctxt);
677 pass1Patterns.insert<WrapInterfaceLower>(
ctxt);
678 pass1Patterns.insert<UnwrapInterfaceLower>(
ctxt);
679 pass1Patterns.insert<CosimToHostLowering>(esiBuilder);
680 pass1Patterns.insert<CosimFromHostLowering>(esiBuilder);
681 pass1Patterns.insert<NullSourceOpLowering>(
ctxt);
684 pass1Patterns.insert<CosimManifestLowering>(
ctxt);
686 pass1Patterns.insert<ManifestRomLowering>(
ctxt);
692 applyPartialConversion(top, pass1Target, std::move(pass1Patterns))))
695 ConversionTarget pass2Target(*
ctxt);
696 pass2Target.addLegalDialect<comb::CombDialect>();
697 pass2Target.addLegalDialect<HWDialect>();
698 pass2Target.addLegalDialect<SVDialect>();
699 pass2Target.addIllegalDialect<ESIDialect>();
701 RewritePatternSet pass2Patterns(
ctxt);
702 pass2Patterns.insert<CanonicalizerOpLowering<UnwrapFIFOOp>>(
ctxt);
703 pass2Patterns.insert<CanonicalizerOpLowering<WrapFIFOOp>>(
ctxt);
704 pass2Patterns.insert<RemoveWrapUnwrap>(
ctxt);
706 applyPartialConversion(top, pass2Target, std::move(pass2Patterns))))
711 return std::make_unique<ESItoHWPass>();
return wrap(CMemoryType::get(unwrap(ctx), baseType, numElements))
static EvaluatorValuePtr unwrap(OMEvaluatorValue c)
Instantiate one of these and use it to build typed backedges.
Backedge is a wrapper class around a Value.
void setValue(mlir::Value)
Assist the lowering steps for conversions which need to create auxiliary IR.
static constexpr char validStr[]
static constexpr char readyStr[]
static constexpr char dataStr[]
def create(data_type, value)
def create(data_type, value)
def create(cls, result_type, reset=None, reset_value=None, name=None, sym_name=None, **kwargs)
static LogicalResult canonicalize(Op op, PatternRewriter &rewriter)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
uint64_t getWidth(Type t)
StringAttr getTypeID(Type t)
std::unique_ptr< OperationPass< ModuleOp > > createESItoHWPass()
mlir::Type innerType(mlir::Type type)
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Generic pattern for removing an op during pattern conversion.
This holds the name, type, direction of a module's ports.