CIRCT 22.0.0git
Loading...
Searching...
No Matches
ESILowerToHW.cpp
Go to the documentation of this file.
1//===- ESILowerToHW.cpp - Lower ESI to HW -----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Lower to HW/SV conversions and pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "../PassDetails.h"
14
21#include "circt/Support/LLVM.h"
23
24#include "mlir/Transforms/DialectConversion.h"
25
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/TypeSwitch.h"
28#include "llvm/Support/JSON.h"
29
30namespace circt {
31namespace esi {
32#define GEN_PASS_DEF_LOWERESITOHW
33#include "circt/Dialect/ESI/ESIPasses.h.inc"
34} // namespace esi
35} // namespace circt
36
37using namespace circt;
38using namespace circt::esi;
39using namespace circt::esi::detail;
40using namespace circt::hw;
41using namespace circt::sv;
42
43namespace {
44/// Lower PipelineStageOp ops to an HW implementation. Unwrap and re-wrap
45/// appropriately. Another conversion will take care merging the resulting
46/// adjacent wrap/unwrap ops.
47struct PipelineStageLowering : public OpConversionPattern<PipelineStageOp> {
48public:
49 PipelineStageLowering(ESIHWBuilder &builder, MLIRContext *ctxt)
50 : OpConversionPattern(ctxt), builder(builder) {}
51 using OpConversionPattern::OpConversionPattern;
52
53 LogicalResult
54 matchAndRewrite(PipelineStageOp stage, OpAdaptor adaptor,
55 ConversionPatternRewriter &rewriter) const final;
56
57private:
58 ESIHWBuilder &builder;
59};
60} // anonymous namespace
61
62LogicalResult 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());
67 if (!chPort)
68 return rewriter.notifyMatchFailure(stage, "stage had wrong type");
69 Operation *symTable = stage->getParentWithTrait<OpTrait::SymbolTable>();
70 auto stageModule = builder.declareStage(symTable, stage);
71
72 size_t width = circt::hw::getBitWidth(chPort.getInner());
73
74 ArrayAttr stageParams =
75 builder.getStageParameterList(rewriter.getUI32IntegerAttr(width));
76
77 // Unwrap the channel. The ready signal is a Value we haven't created yet,
78 // so create a temp value and replace it later. Give this constant an
79 // odd-looking type to make debugging easier.
80 circt::BackedgeBuilder back(rewriter, loc);
81 circt::Backedge wrapReady = back.get(rewriter.getI1Type());
82 auto unwrap =
83 UnwrapValidReadyOp::create(rewriter, loc, stage.getInput(), wrapReady);
84
85 StringRef pipeStageName = "pipelineStage";
86 if (auto name = stage->getAttrOfType<StringAttr>("name"))
87 pipeStageName = name.getValue();
88
89 // Instantiate the "ESI_PipelineStage" external module.
90 circt::Backedge stageReady = back.get(rewriter.getI1Type());
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 = hw::InstanceOp::create(rewriter, loc, stageModule,
96 pipeStageName, operands, stageParams);
97 auto stageInstResults = stageInst.getResults();
98
99 // Set a_ready (from the unwrap) back edge correctly to its output from
100 // stage.
101 wrapReady.setValue(stageInstResults[0]);
102 Value x, xValid;
103 x = stageInstResults[1];
104 xValid = stageInstResults[2];
105
106 // Wrap up the output of the HW stage module.
107 auto wrap = WrapValidReadyOp::create(rewriter, loc, chPort,
108 rewriter.getI1Type(), x, xValid);
109 // Set the stages x_ready backedge correctly.
110 stageReady.setValue(wrap.getReady());
111
112 rewriter.replaceOp(stage, wrap.getChanOutput());
113 return success();
114}
115
116namespace {
117struct NullSourceOpLowering : public OpConversionPattern<NullSourceOp> {
118public:
119 NullSourceOpLowering(MLIRContext *ctxt) : OpConversionPattern(ctxt) {}
120 using OpConversionPattern::OpConversionPattern;
121
122 LogicalResult
123 matchAndRewrite(NullSourceOp nullop, OpAdaptor adaptor,
124 ConversionPatternRewriter &rewriter) const final;
125};
126} // anonymous namespace
127
128LogicalResult 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();
133 int64_t width = hw::getBitWidth(innerType);
134 if (width == -1)
135 return rewriter.notifyMatchFailure(
136 nullop, "NullOp lowering only supports hw types");
137 auto valid = hw::ConstantOp::create(rewriter, nullop.getLoc(),
138 rewriter.getI1Type(), 0);
139 auto zero =
140 hw::ConstantOp::create(rewriter, loc, rewriter.getIntegerType(width), 0);
141 auto typedZero = hw::BitcastOp::create(rewriter, loc, innerType, zero);
142 auto wrap = WrapValidReadyOp::create(rewriter, loc, typedZero, valid);
143 wrap->setAttr("name", rewriter.getStringAttr("nullsource"));
144 rewriter.replaceOp(nullop, {wrap.getChanOutput()});
145 return success();
146}
147
148namespace {
149/// Eliminate back-to-back wrap-unwraps to reduce the number of ESI channels.
150struct RemoveWrapUnwrap : public ConversionPattern {
151public:
152 RemoveWrapUnwrap(MLIRContext *context)
153 : ConversionPattern(MatchAnyOpTypeTag(), /*benefit=*/1, context) {}
154
155 LogicalResult
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);
161 if (wrap) {
162 if (ChannelType::hasNoConsumers(wrap.getChanOutput())) {
163 auto c1 = hw::ConstantOp::create(rewriter, wrap.getLoc(),
164 rewriter.getI1Type(), 1);
165 rewriter.replaceOp(wrap, {nullptr, c1});
166 return success();
167 }
168
169 if (!ChannelType::hasOneConsumer(wrap.getChanOutput()))
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 ChannelType::getSingleConsumer(wrap.getChanOutput())
175 ->getOwner())))
176 return rewriter.notifyMatchFailure(
177 wrap, "This conversion only supports wrap-unwrap back-to-back. "
178 "Could not find 'unwrap'.");
179
180 data = operands[0];
181 valid = operands[1];
182 ready = unwrap.getReady();
183 } else if (unwrap) {
184 Operation *defOp = operands[0].getDefiningOp();
185 if (!defOp)
186 return rewriter.notifyMatchFailure(
187 unwrap, "unwrap input is not defined by an op");
188 wrap = dyn_cast<WrapValidReadyOp>(defOp);
189 if (!wrap)
190 return rewriter.notifyMatchFailure(
191 operands[0].getDefiningOp(),
192 "This conversion only supports wrap-unwrap back-to-back. "
193 "Could not find 'wrap'.");
194 valid = wrap.getValid();
195 data = wrap.getRawInput();
196 ready = operands[1];
197 } else {
198 return failure();
199 }
200
201 if (!ChannelType::hasOneConsumer(wrap.getChanOutput()))
202 return rewriter.notifyMatchFailure(wrap, [](Diagnostic &d) {
203 d << "This conversion only supports wrap-unwrap back-to-back. "
204 "Wrap didn't have exactly one use.";
205 });
206 rewriter.replaceOp(wrap, {nullptr, ready});
207 rewriter.replaceOp(unwrap, {data, valid});
208 return success();
209 }
210};
211} // anonymous namespace
212
213namespace {
214/// Eliminate snoop operations in wrap-unwrap pairs.
215struct RemoveSnoopOp : public OpConversionPattern<SnoopValidReadyOp> {
216public:
217 using OpConversionPattern::OpConversionPattern;
218
219 LogicalResult
220 matchAndRewrite(SnoopValidReadyOp op, SnoopValidReadyOpAdaptor operands,
221 ConversionPatternRewriter &rewriter) const override {
222 Operation *defOp = op.getInput().getDefiningOp();
223 if (!defOp)
224 return rewriter.notifyMatchFailure(op,
225 "snoop input is not defined by an op");
226 auto wrap = dyn_cast<WrapValidReadyOp>(defOp);
227 if (!wrap)
228 return rewriter.notifyMatchFailure(
229 defOp, "This conversion only supports wrap-unwrap back-to-back. "
230 "Could not find 'wrap'.");
231 auto *unwrapOpOperand =
232 ChannelType::getSingleConsumer(wrap.getChanOutput());
233 if (!unwrapOpOperand)
234 return rewriter.notifyMatchFailure(
235 defOp, "This conversion only supports wrap-unwrap back-to-back. "
236 "Could sole consumer.");
237 auto unwrap = dyn_cast<UnwrapValidReadyOp>(unwrapOpOperand->getOwner());
238 if (!unwrap)
239 return rewriter.notifyMatchFailure(
240 defOp, "This conversion only supports wrap-unwrap back-to-back. "
241 "Could not find 'unwrap'.");
242 rewriter.replaceOp(
243 op, {wrap.getValid(), unwrap.getReady(), wrap.getRawInput()});
244 return success();
245 }
246};
247} // anonymous namespace
248
249namespace {
250/// Eliminate snoop transaction operations in wrap-unwrap pairs.
251struct RemoveSnoopTransactionOp
252 : public OpConversionPattern<SnoopTransactionOp> {
253public:
254 using OpConversionPattern::OpConversionPattern;
255
256 LogicalResult
257 matchAndRewrite(SnoopTransactionOp op, SnoopTransactionOpAdaptor operands,
258 ConversionPatternRewriter &rewriter) const override {
259 Operation *defOp = op.getInput().getDefiningOp();
260 if (!defOp)
261 return rewriter.notifyMatchFailure(op,
262 "snoop input is not defined by an op");
263
264 // Handle ValidReady signaling
265 if (auto wrapVR = dyn_cast<WrapValidReadyOp>(defOp)) {
266 auto *unwrapOpOperand =
267 ChannelType::getSingleConsumer(wrapVR.getChanOutput());
268 if (!unwrapOpOperand)
269 return rewriter.notifyMatchFailure(
270 defOp, "This conversion only supports wrap-unwrap back-to-back. "
271 "Could not find sole consumer.");
272 auto unwrapVR = dyn_cast<UnwrapValidReadyOp>(unwrapOpOperand->getOwner());
273 if (!unwrapVR)
274 return rewriter.notifyMatchFailure(
275 defOp, "This conversion only supports wrap-unwrap back-to-back. "
276 "Could not find 'unwrap'.");
277
278 // Create transaction signal as valid AND ready
279 auto validAndReady = comb::AndOp::create(
280 rewriter, op.getLoc(), wrapVR.getValid(), unwrapVR.getReady());
281
282 rewriter.replaceOp(op, {validAndReady, wrapVR.getRawInput()});
283 return success();
284 }
285
286 // Handle FIFO signaling
287 if (auto wrapFIFO = dyn_cast<WrapFIFOOp>(defOp)) {
288 auto *unwrapOpOperand =
289 ChannelType::getSingleConsumer(wrapFIFO.getChanOutput());
290 if (!unwrapOpOperand)
291 return rewriter.notifyMatchFailure(
292 defOp, "This conversion only supports wrap-unwrap back-to-back. "
293 "Could not find sole consumer.");
294 auto unwrapFIFO = dyn_cast<UnwrapFIFOOp>(unwrapOpOperand->getOwner());
295 if (!unwrapFIFO)
296 return rewriter.notifyMatchFailure(
297 defOp, "This conversion only supports wrap-unwrap back-to-back. "
298 "Could not find 'unwrap'.");
299
300 // Create transaction signal as !empty AND rden
301 auto notEmpty = comb::XorOp::create(
302 rewriter, op.getLoc(), wrapFIFO.getEmpty(),
303 hw::ConstantOp::create(rewriter, op.getLoc(),
304 rewriter.getBoolAttr(true)));
305 auto transaction = comb::AndOp::create(rewriter, op.getLoc(), notEmpty,
306 unwrapFIFO.getRden());
307
308 rewriter.replaceOp(op, {transaction, wrapFIFO.getData()});
309 return success();
310 }
311
312 return rewriter.notifyMatchFailure(
313 defOp, "This conversion only supports wrap-unwrap back-to-back for "
314 "ValidReady and FIFO signaling.");
315 }
316};
317} // anonymous namespace
318
319namespace {
320/// Use the op canonicalizer to lower away the op. Assumes the canonicalizer
321/// deletes the op.
322template <typename Op>
323struct CanonicalizerOpLowering : public OpConversionPattern<Op> {
324public:
325 CanonicalizerOpLowering(MLIRContext *ctxt) : OpConversionPattern<Op>(ctxt) {}
326
327 LogicalResult
328 matchAndRewrite(Op op, typename Op::Adaptor adaptor,
329 ConversionPatternRewriter &rewriter) const final {
330 if (failed(Op::canonicalize(op, rewriter)))
331 return rewriter.notifyMatchFailure(op->getLoc(), "canonicalizer failed");
332 return success();
333 }
334};
335} // anonymous namespace
336
337namespace {
338struct ESItoHWPass : public circt::esi::impl::LowerESItoHWBase<ESItoHWPass> {
339 void runOnOperation() override;
340};
341} // anonymous namespace
342
343namespace {
344/// Lower a `wrap.iface` to `wrap.vr` by extracting the wires then feeding the
345/// new `wrap.vr`.
346struct WrapInterfaceLower : public OpConversionPattern<WrapSVInterfaceOp> {
347public:
348 using OpConversionPattern::OpConversionPattern;
349
350 LogicalResult
351 matchAndRewrite(WrapSVInterfaceOp wrap, OpAdaptor adaptor,
352 ConversionPatternRewriter &rewriter) const final;
353};
354} // anonymous namespace
355
356LogicalResult
357WrapInterfaceLower::matchAndRewrite(WrapSVInterfaceOp wrap, OpAdaptor adaptor,
358 ConversionPatternRewriter &rewriter) const {
359 auto operands = adaptor.getOperands();
360 if (operands.size() != 1)
361 return rewriter.notifyMatchFailure(wrap, [&operands](Diagnostic &d) {
362 d << "wrap.iface has 1 argument. Got " << operands.size() << "operands";
363 });
364 auto sinkModport = dyn_cast<GetModportOp>(operands[0].getDefiningOp());
365 if (!sinkModport)
366 return failure();
367 auto ifaceInstance =
368 dyn_cast<InterfaceInstanceOp>(sinkModport.getIface().getDefiningOp());
369 if (!ifaceInstance)
370 return failure();
371
372 auto loc = wrap.getLoc();
373 auto validSignal = ReadInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
375 Value dataSignal;
376 dataSignal = ReadInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
378 auto wrapVR =
379 WrapValidReadyOp::create(rewriter, loc, dataSignal, validSignal);
380 AssignInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
381 ESIHWBuilder::readyStr, wrapVR.getReady());
382 rewriter.replaceOp(wrap, {wrapVR.getChanOutput()});
383 return success();
384}
385
386namespace {
387/// Lower an unwrap interface to just extract the wires and feed them into an
388/// `unwrap.vr`.
389struct UnwrapInterfaceLower : public OpConversionPattern<UnwrapSVInterfaceOp> {
390public:
391 UnwrapInterfaceLower(MLIRContext *ctxt) : OpConversionPattern(ctxt) {}
392 using OpConversionPattern::OpConversionPattern;
393
394 LogicalResult
395 matchAndRewrite(UnwrapSVInterfaceOp wrap, OpAdaptor adaptor,
396 ConversionPatternRewriter &rewriter) const final;
397};
398} // anonymous namespace
399
400LogicalResult UnwrapInterfaceLower::matchAndRewrite(
401 UnwrapSVInterfaceOp unwrap, OpAdaptor adaptor,
402 ConversionPatternRewriter &rewriter) const {
403 auto operands = adaptor.getOperands();
404 if (operands.size() != 2)
405 return rewriter.notifyMatchFailure(unwrap, [&operands](Diagnostic &d) {
406 d << "Unwrap.iface has 2 arguments. Got " << operands.size()
407 << "operands";
408 });
409
410 auto sourceModport = dyn_cast<GetModportOp>(operands[1].getDefiningOp());
411 if (!sourceModport)
412 return failure();
413 auto ifaceInstance =
414 dyn_cast<InterfaceInstanceOp>(sourceModport.getIface().getDefiningOp());
415 if (!ifaceInstance)
416 return failure();
417
418 auto loc = unwrap.getLoc();
419 auto readySignal = ReadInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
421 auto unwrapVR =
422 UnwrapValidReadyOp::create(rewriter, loc, operands[0], readySignal);
423 AssignInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
424 ESIHWBuilder::validStr, unwrapVR.getValid());
425
426 AssignInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
428 unwrapVR.getRawOutput());
429 rewriter.eraseOp(unwrap);
430 return success();
431}
432
433namespace {
434/// Lower `CosimEndpointOp` ops to a SystemVerilog extern module and a Capnp
435/// gasket op.
436struct CosimToHostLowering : public OpConversionPattern<CosimToHostEndpointOp> {
437public:
438 CosimToHostLowering(ESIHWBuilder &b)
439 : OpConversionPattern(b.getContext(), 1), builder(b) {}
440
441 using OpConversionPattern::OpConversionPattern;
442
443 LogicalResult
444 matchAndRewrite(CosimToHostEndpointOp, OpAdaptor adaptor,
445 ConversionPatternRewriter &rewriter) const final;
446
447private:
448 ESIHWBuilder &builder;
449};
450} // anonymous namespace
451
452LogicalResult CosimToHostLowering::matchAndRewrite(
453 CosimToHostEndpointOp ep, OpAdaptor adaptor,
454 ConversionPatternRewriter &rewriter) const {
455 auto loc = ep.getLoc();
456 auto *ctxt = rewriter.getContext();
457 circt::BackedgeBuilder bb(rewriter, loc);
458
459 Value toHost = adaptor.getToHost();
460 Type type = toHost.getType();
461 auto chanTy = dyn_cast<ChannelType>(type);
462 uint64_t width = getWidth(type);
463
464 // Set all the parameters.
465 SmallVector<Attribute, 8> params;
466 params.push_back(ParamDeclAttr::get("ENDPOINT_ID", ep.getIdAttr()));
467 params.push_back(ParamDeclAttr::get("TO_HOST_TYPE_ID", getTypeID(type)));
468 params.push_back(ParamDeclAttr::get(
469 "TO_HOST_SIZE_BITS", rewriter.getI32IntegerAttr(width > 0 ? width : 1)));
470
471 // Set up the egest route to drive the EP's toHost ports.
472 auto sendReady = bb.get(rewriter.getI1Type());
473 UnwrapValidReadyOp unwrapSend =
474 UnwrapValidReadyOp::create(rewriter, loc, toHost, sendReady);
475
476 Value rawSendData = unwrapSend.getRawOutput();
477 // For windows, we need to extract the lowered data from the window type.
478 if (chanTy)
479 if (WindowType windowType = dyn_cast_or_null<WindowType>(chanTy.getInner()))
480 rawSendData = UnwrapWindow::create(rewriter, loc, rawSendData);
481
482 Value castedSendData;
483 if (width > 0)
484 castedSendData = hw::BitcastOp::create(
485 rewriter, loc, rewriter.getIntegerType(width), rawSendData);
486 else
487 castedSendData = hw::ConstantOp::create(
488 rewriter, loc, rewriter.getIntegerType(1), rewriter.getBoolAttr(false));
489
490 // Build or get the cached Cosim Endpoint module parameterization.
491 Operation *symTable = ep->getParentWithTrait<OpTrait::SymbolTable>();
492 HWModuleExternOp endpoint =
493 builder.declareCosimEndpointToHostModule(symTable);
494
495 // Create replacement Cosim_Endpoint instance.
496 Value operands[] = {
497 adaptor.getClk(),
498 adaptor.getRst(),
499 unwrapSend.getValid(),
500 castedSendData,
501 };
502 auto cosimEpModule =
503 hw::InstanceOp::create(rewriter, loc, endpoint, ep.getIdAttr(), operands,
504 ArrayAttr::get(ctxt, params));
505 sendReady.setValue(cosimEpModule.getResult(0));
506
507 // Replace the CosimEndpointOp op.
508 rewriter.eraseOp(ep);
509
510 return success();
511}
512
513namespace {
514/// Lower `CosimEndpointOp` ops to a SystemVerilog extern module and a Capnp
515/// gasket op.
516struct CosimFromHostLowering
517 : public OpConversionPattern<CosimFromHostEndpointOp> {
518public:
519 CosimFromHostLowering(ESIHWBuilder &b)
520 : OpConversionPattern(b.getContext(), 1), builder(b) {}
521
522 using OpConversionPattern::OpConversionPattern;
523
524 LogicalResult
525 matchAndRewrite(CosimFromHostEndpointOp, OpAdaptor adaptor,
526 ConversionPatternRewriter &rewriter) const final;
527
528private:
529 ESIHWBuilder &builder;
530};
531} // anonymous namespace
532
533LogicalResult CosimFromHostLowering::matchAndRewrite(
534 CosimFromHostEndpointOp ep, OpAdaptor adaptor,
535 ConversionPatternRewriter &rewriter) const {
536 auto loc = ep.getLoc();
537 auto *ctxt = rewriter.getContext();
538 circt::BackedgeBuilder bb(rewriter, loc);
539
540 ChannelType type = ep.getFromHost().getType();
541 WindowType windowType = dyn_cast<WindowType>(type.getInner());
542 uint64_t width = getWidth(type);
543
544 // Set all the parameters.
545 SmallVector<Attribute, 8> params;
546 params.push_back(ParamDeclAttr::get("ENDPOINT_ID", ep.getIdAttr()));
547 params.push_back(ParamDeclAttr::get("FROM_HOST_TYPE_ID", getTypeID(type)));
548 params.push_back(
549 ParamDeclAttr::get("FROM_HOST_SIZE_BITS",
550 rewriter.getI32IntegerAttr(width > 0 ? width : 1)));
551
552 // Get information necessary for injest path.
553 auto recvReady = bb.get(rewriter.getI1Type());
554
555 // Build or get the cached Cosim Endpoint module parameterization.
556 Operation *symTable = ep->getParentWithTrait<OpTrait::SymbolTable>();
557 HWModuleExternOp endpoint =
558 builder.declareCosimEndpointFromHostModule(symTable);
559
560 // Create replacement Cosim_Endpoint instance.
561 Value operands[] = {adaptor.getClk(), adaptor.getRst(), recvReady};
562 auto cosimEpModule =
563 hw::InstanceOp::create(rewriter, loc, endpoint, ep.getIdAttr(), operands,
564 ArrayAttr::get(ctxt, params));
565
566 // Set up the injest path.
567 Value recvDataFromCosim = cosimEpModule.getResult(1);
568 Value recvValidFromCosim = cosimEpModule.getResult(0);
569 Value castedRecvData;
570 Type castToType = windowType ? windowType.getLoweredType() : type.getInner();
571 if (width > 0)
572 castedRecvData =
573 hw::BitcastOp::create(rewriter, loc, castToType, recvDataFromCosim);
574 else
575 castedRecvData = hw::ConstantOp::create(
576 rewriter, loc, rewriter.getIntegerType(0),
577 rewriter.getIntegerAttr(rewriter.getIntegerType(0), 0));
578 if (windowType) {
579 // For windows, we need to reconstruct the window type from the lowered
580 // data.
581 castedRecvData =
582 WrapWindow::create(rewriter, loc, windowType, castedRecvData);
583 }
584 WrapValidReadyOp wrapRecv = WrapValidReadyOp::create(
585 rewriter, loc, castedRecvData, recvValidFromCosim);
586 recvReady.setValue(wrapRecv.getReady());
587
588 // Replace the CosimEndpointOp op.
589 rewriter.replaceOp(ep, wrapRecv.getChanOutput());
590
591 return success();
592}
593
594namespace {
595/// Lower `CompressedManifestOps` ops to a module containing an on-chip ROM.
596/// Said module has registered input and outputs, so it has two cycles latency
597/// between changing the address and the data being reflected on the output.
598struct ManifestRomLowering : public OpConversionPattern<CompressedManifestOp> {
599public:
600 using OpConversionPattern::OpConversionPattern;
601 constexpr static StringRef manifestRomName = "__ESI_Manifest_ROM";
602
603 LogicalResult
604 matchAndRewrite(CompressedManifestOp, OpAdaptor adaptor,
605 ConversionPatternRewriter &rewriter) const override;
606
607protected:
608 LogicalResult createRomModule(CompressedManifestOp op,
609 ConversionPatternRewriter &rewriter) const;
610};
611} // anonymous namespace
612
613LogicalResult ManifestRomLowering::createRomModule(
614 CompressedManifestOp op, ConversionPatternRewriter &rewriter) const {
615 Location loc = op.getLoc();
616 auto mlirModBody = op->getParentOfType<mlir::ModuleOp>();
617 rewriter.setInsertionPointToStart(mlirModBody.getBody());
618
619 // Find possible existing module (which may have been created as a dummy
620 // module) and erase it.
621 if (Operation *existingExtern = mlirModBody.lookupSymbol(manifestRomName)) {
622 if (!isa<hw::HWModuleExternOp>(existingExtern))
623 return rewriter.notifyMatchFailure(
624 op,
625 "Found " + manifestRomName + " but it wasn't an HWModuleExternOp");
626 rewriter.eraseOp(existingExtern);
627 }
628
629 // Create the real module.
630 PortInfo ports[] = {
631 {{rewriter.getStringAttr("clk"), rewriter.getType<seq::ClockType>(),
632 ModulePort::Direction::Input}},
633 {{rewriter.getStringAttr("address"), rewriter.getIntegerType(29),
634 ModulePort::Direction::Input}},
635 {{rewriter.getStringAttr("data"), rewriter.getI64Type(),
636 ModulePort::Direction::Output}},
637 };
638 auto rom = HWModuleOp::create(rewriter, loc,
639 rewriter.getStringAttr(manifestRomName), ports);
640 Block *romBody = rom.getBodyBlock();
641 rewriter.setInsertionPointToStart(romBody);
642 Value clk = romBody->getArgument(0);
643 Value inputAddress = romBody->getArgument(1);
644
645 // Manifest the compressed manifest into 64-bit words.
646 ArrayRef<uint8_t> maniBytes = op.getCompressedManifest().getData();
647 SmallVector<uint64_t> words;
648 words.push_back(maniBytes.size());
649
650 for (size_t i = 0; i < maniBytes.size() - 7; i += 8) {
651 uint64_t word = 0;
652 for (size_t b = 0; b < 8; ++b)
653 word |= static_cast<uint64_t>(maniBytes[i + b]) << (8 * b);
654 words.push_back(word);
655 }
656 size_t overHang = maniBytes.size() % 8;
657 if (overHang != 0) {
658 uint64_t word = 0;
659 for (size_t i = 0; i < overHang; ++i)
660 word |= static_cast<uint64_t>(maniBytes[maniBytes.size() - overHang + i])
661 << (i * 8);
662 words.push_back(word);
663 }
664
665 // From the words, create an the register which will hold the manifest (and
666 // hopefully synthized to a ROM).
667 SmallVector<Attribute> wordAttrs;
668 for (uint64_t word : words)
669 wordAttrs.push_back(rewriter.getI64IntegerAttr(word));
670 auto manifestConstant = hw::AggregateConstantOp::create(
671 rewriter, loc,
672 hw::UnpackedArrayType::get(rewriter.getI64Type(), words.size()),
673 rewriter.getArrayAttr(wordAttrs));
674 auto manifestReg =
675 sv::RegOp::create(rewriter, loc, manifestConstant.getType());
676 sv::AssignOp::create(rewriter, loc, manifestReg, manifestConstant);
677
678 // Slim down the address, register it, do the lookup, and register the output.
679 size_t addrBits = llvm::Log2_64_Ceil(words.size());
680 auto slimmedIdx =
681 comb::ExtractOp::create(rewriter, loc, inputAddress, 0, addrBits);
682 Value inputAddresReg = seq::CompRegOp::create(rewriter, loc, slimmedIdx, clk);
683 auto readIdx =
684 sv::ArrayIndexInOutOp::create(rewriter, loc, manifestReg, inputAddresReg);
685 auto readData = sv::ReadInOutOp::create(rewriter, loc, readIdx);
686 Value readDataReg = seq::CompRegOp::create(rewriter, loc, readData, clk);
687 if (auto *term = romBody->getTerminator())
688 rewriter.eraseOp(term);
689 hw::OutputOp::create(rewriter, loc, ValueRange{readDataReg});
690 return success();
691}
692
693LogicalResult ManifestRomLowering::matchAndRewrite(
694 CompressedManifestOp op, OpAdaptor adaptor,
695 ConversionPatternRewriter &rewriter) const {
696 LogicalResult ret = createRomModule(op, rewriter);
697 rewriter.eraseOp(op);
698 return ret;
699}
700
701namespace {
702/// Lower `CompressedManifestOps` ops to a SystemVerilog module which sets the
703/// Cosim manifest using a DPI support module.
704struct CosimManifestLowering : public ManifestRomLowering {
705public:
706 using ManifestRomLowering::ManifestRomLowering;
707
708 LogicalResult
709 matchAndRewrite(CompressedManifestOp, OpAdaptor adaptor,
710 ConversionPatternRewriter &rewriter) const final;
711};
712} // anonymous namespace
713
714LogicalResult CosimManifestLowering::matchAndRewrite(
715 CompressedManifestOp op, OpAdaptor adaptor,
716 ConversionPatternRewriter &rewriter) const {
717 MLIRContext *ctxt = rewriter.getContext();
718 Location loc = op.getLoc();
719
720 // Cosim can optionally include a manifest simulation, so produce it in case
721 // the Cosim BSP wants it.
722 LogicalResult ret = createRomModule(op, rewriter);
723 if (failed(ret))
724 return ret;
725
726 // Declare external module.
727 Attribute params[] = {
728 ParamDeclAttr::get("COMPRESSED_MANIFEST_SIZE", rewriter.getI32Type())};
729 PortInfo ports[] = {
730 {{rewriter.getStringAttr("compressed_manifest"),
731 rewriter.getType<hw::ArrayType>(
732 rewriter.getI8Type(),
733 ParamDeclRefAttr::get(
734 rewriter.getStringAttr("COMPRESSED_MANIFEST_SIZE"),
735 rewriter.getI32Type())),
736 ModulePort::Direction::Input},
737 0},
738 };
739 rewriter.setInsertionPointToEnd(
740 op->getParentOfType<mlir::ModuleOp>().getBody());
741 auto cosimManifestExternModule = HWModuleExternOp::create(
742 rewriter, loc, rewriter.getStringAttr("Cosim_Manifest"), ports,
743 "Cosim_Manifest", ArrayAttr::get(ctxt, params));
744
745 hw::ModulePortInfo portInfo({});
746 auto manifestMod = hw::HWModuleOp::create(
747 rewriter, loc, rewriter.getStringAttr("__ESIManifest"), portInfo,
748 [&](OpBuilder &rewriter, const hw::HWModulePortAccessor &) {
749 // Assemble the manifest data into a constant.
750 SmallVector<Attribute> bytes;
751 for (uint8_t b : op.getCompressedManifest().getData())
752 bytes.push_back(rewriter.getI8IntegerAttr(b));
753 auto manifestConstant = hw::AggregateConstantOp::create(
754 rewriter, loc,
755 hw::ArrayType::get(rewriter.getI8Type(), bytes.size()),
756 rewriter.getArrayAttr(bytes));
757 auto manifestLogic =
758 sv::LogicOp::create(rewriter, loc, manifestConstant.getType());
759 sv::AssignOp::create(rewriter, loc, manifestLogic, manifestConstant);
760 auto manifest = sv::ReadInOutOp::create(rewriter, loc, manifestLogic);
761
762 // Then instantiate the external module.
763 hw::InstanceOp::create(rewriter, loc, cosimManifestExternModule,
764 "__manifest", ArrayRef<Value>({manifest}),
765 rewriter.getArrayAttr({ParamDeclAttr::get(
766 "COMPRESSED_MANIFEST_SIZE",
767 rewriter.getI32IntegerAttr(bytes.size()))}));
768 });
769
770 rewriter.setInsertionPoint(op);
771 hw::InstanceOp::create(rewriter, loc, manifestMod, "__manifest",
772 ArrayRef<Value>({}));
773
774 rewriter.eraseOp(op);
775 return success();
776}
777void ESItoHWPass::runOnOperation() {
778 auto top = getOperation();
779 auto *ctxt = &getContext();
780
781 // Lower all the bundles.
782 ConversionTarget noBundlesTarget(*ctxt);
783 noBundlesTarget.markUnknownOpDynamicallyLegal(
784 [](Operation *) { return true; });
785 noBundlesTarget.addIllegalOp<PackBundleOp>();
786 noBundlesTarget.addIllegalOp<UnpackBundleOp>();
787 RewritePatternSet bundlePatterns(&getContext());
788 bundlePatterns.add<CanonicalizerOpLowering<PackBundleOp>>(&getContext());
789 bundlePatterns.add<CanonicalizerOpLowering<UnpackBundleOp>>(&getContext());
790 if (failed(applyPartialConversion(getOperation(), noBundlesTarget,
791 std::move(bundlePatterns)))) {
792 signalPassFailure();
793 return;
794 }
795
796 // Set up a conversion and give it a set of laws.
797 ConversionTarget pass1Target(*ctxt);
798 pass1Target.addLegalDialect<comb::CombDialect>();
799 pass1Target.addLegalDialect<HWDialect>();
800 pass1Target.addLegalDialect<SVDialect>();
801 pass1Target.addLegalDialect<seq::SeqDialect>();
802 pass1Target.addLegalOp<WrapValidReadyOp, UnwrapValidReadyOp, WrapFIFOOp,
803 UnwrapFIFOOp, WrapWindow, UnwrapWindow>();
804 pass1Target.addLegalOp<SnoopTransactionOp, SnoopValidReadyOp>();
805
806 pass1Target.addIllegalOp<WrapSVInterfaceOp, UnwrapSVInterfaceOp>();
807 pass1Target.addIllegalOp<PipelineStageOp>();
808 pass1Target.addIllegalOp<CompressedManifestOp>();
809
810 // Add all the conversion patterns.
811 ESIHWBuilder esiBuilder(top);
812 RewritePatternSet pass1Patterns(ctxt);
813 pass1Patterns.insert<PipelineStageLowering>(esiBuilder, ctxt);
814 pass1Patterns.insert<WrapInterfaceLower>(ctxt);
815 pass1Patterns.insert<UnwrapInterfaceLower>(ctxt);
816 pass1Patterns.insert<CosimToHostLowering>(esiBuilder);
817 pass1Patterns.insert<CosimFromHostLowering>(esiBuilder);
818 pass1Patterns.insert<NullSourceOpLowering>(ctxt);
819
820 if (platform == Platform::cosim)
821 pass1Patterns.insert<CosimManifestLowering>(ctxt);
822 else if (platform == Platform::fpga)
823 pass1Patterns.insert<ManifestRomLowering>(ctxt);
824 else
825 pass1Patterns.insert<RemoveOpLowering<CompressedManifestOp>>(ctxt);
826
827 // Run the conversion.
828 if (failed(
829 applyPartialConversion(top, pass1Target, std::move(pass1Patterns)))) {
830 signalPassFailure();
831 return;
832 }
833
834 // Lower all the snoop operations.
835 ConversionTarget pass2Target(*ctxt);
836 pass2Target.addLegalDialect<comb::CombDialect>();
837 pass2Target.addLegalDialect<HWDialect>();
838 pass2Target.addLegalDialect<SVDialect>();
839 pass2Target.addIllegalOp<SnoopTransactionOp, SnoopValidReadyOp>();
840 pass2Target.addLegalOp<WrapValidReadyOp, UnwrapValidReadyOp, WrapFIFOOp,
841 UnwrapFIFOOp>();
842 RewritePatternSet pass2Patterns(ctxt);
843 pass2Patterns.insert<RemoveSnoopOp>(ctxt);
844 pass2Patterns.insert<RemoveSnoopTransactionOp>(ctxt);
845 if (failed(
846 applyPartialConversion(top, pass2Target, std::move(pass2Patterns)))) {
847 signalPassFailure();
848 return;
849 }
850
851 // Lower the channel operations.
852 ConversionTarget pass3Target(*ctxt);
853 pass3Target.addLegalDialect<comb::CombDialect>();
854 pass3Target.addLegalDialect<HWDialect>();
855 pass3Target.addLegalDialect<SVDialect>();
856 pass3Target.addIllegalDialect<ESIDialect>();
857 pass3Target.addLegalOp<WrapWindow, UnwrapWindow>();
858
859 RewritePatternSet pass3Patterns(ctxt);
860 pass3Patterns.insert<CanonicalizerOpLowering<UnwrapFIFOOp>>(ctxt);
861 pass3Patterns.insert<CanonicalizerOpLowering<WrapFIFOOp>>(ctxt);
862 pass3Patterns.insert<RemoveWrapUnwrap>(ctxt);
863 if (failed(
864 applyPartialConversion(top, pass3Target, std::move(pass3Patterns))))
865 signalPassFailure();
866}
867
868std::unique_ptr<OperationPass<ModuleOp>> circt::esi::createESItoHWPass() {
869 return std::make_unique<ESItoHWPass>();
870}
return wrap(CMemoryType::get(unwrap(ctx), baseType, numElements))
static std::unique_ptr< Context > context
static EvaluatorValuePtr unwrap(OMEvaluatorValue c)
Definition OM.cpp:111
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.
Definition PassDetails.h:56
static constexpr char validStr[]
Definition PassDetails.h:76
static constexpr char readyStr[]
Definition PassDetails.h:77
static constexpr char dataStr[]
Definition PassDetails.h:76
create(low_bit, result_type, input=None)
Definition comb.py:187
create(data_type, value)
Definition hw.py:441
create(data_type, value)
Definition hw.py:433
create(cls, result_type, reset=None, reset_value=None, name=None, sym_name=None, **kwargs)
Definition seq.py:157
create(dest, src)
Definition sv.py:100
create(value)
Definition sv.py:108
uint64_t getWidth(Type t)
Definition ESIPasses.cpp:32
StringAttr getTypeID(Type t)
Definition ESIPasses.cpp:26
std::unique_ptr< OperationPass< ModuleOp > > createESItoHWPass()
mlir::Type innerType(mlir::Type type)
Definition ESITypes.cpp:420
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:110
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition esi.py:1
static constexpr char fpga[]
Definition ESIPasses.h:29
static constexpr char cosim[]
Definition ESIPasses.h:28
Generic pattern for removing an op during pattern conversion.
Definition PassDetails.h:40
This holds a decoded list of input/inout and output ports for a module or instance.
This holds the name, type, direction of a module's ports.