22#include "mlir/IR/BuiltinTypes.h"
23#include "mlir/IR/ImplicitLocOpBuilder.h"
24#include "mlir/IR/SymbolTable.h"
31#define GEN_PASS_DEF_ESICONNECTSERVICES
32#include "circt/Dialect/ESI/ESIPasses.h.inc"
46 ServiceDeclOpInterface,
47 ServiceImplRecordOp implRecord) {
48 constexpr StringLiteral cosimCycleCountName =
"Cosim_CycleCount";
50 auto *ctxt = implReq.getContext();
52 Value clk = implReq.getOperand(0);
53 Value rst = implReq.getOperand(1);
54 Location reqLoc = implReq.getLoc();
56 if (implReq.getImplOpts()) {
57 auto opts = implReq.getImplOpts()->getValue();
58 for (
auto nameAttr : opts) {
59 return implReq.emitOpError(
"did not recognize option name ")
60 << nameAttr.getName();
64 Block &connImplBlock = implRecord.getReqDetails().front();
65 implRecord.setIsEngine(
true);
66 OpBuilder implRecords = OpBuilder::atBlockEnd(&connImplBlock);
69 auto toStringAttr = [&](ArrayAttr strArr, StringAttr channelName) {
71 llvm::raw_string_ostream os(buff);
73 strArr.getAsRange<AppIDAttr>(), os,
74 [&](AppIDAttr appid) {
75 os << appid.getName().getValue();
77 os <<
"[" << appid.getIndex() <<
"]";
80 os <<
"." << channelName.getValue();
81 return StringAttr::get(ctxt, os.str());
84 auto getAssignment = [&](StringAttr name, StringAttr channelName) {
85 DictionaryAttr assignment = b.getDictionaryAttr({
86 b.getNamedAttr(
"type", b.getStringAttr(
"cosim")),
87 b.getNamedAttr(
"name", channelName),
89 return b.getNamedAttr(name, assignment);
92 llvm::DenseMap<ServiceImplementConnReqOp, unsigned> toClientResultNum;
93 for (
auto req : implReq.getOps<ServiceImplementConnReqOp>())
94 toClientResultNum[req] = toClientResultNum.size();
101 for (
auto req : implReq.getOps<ServiceImplementConnReqOp>()) {
102 Location loc = req->getLoc();
103 ChannelBundleType bundleType = req.getToClient().getType();
104 SmallVector<NamedAttribute, 8> channelAssignments;
106 SmallVector<Value, 8> toServerValues;
108 if (ch.direction == ChannelDirection::to) {
109 ChannelType fromHostType = ch.type;
110 fromHostType = b.getType<ChannelType>(fromHostType.getInner(),
111 ChannelSignaling::ValidReady,
112 fromHostType.getDataDelay());
113 auto cosim = CosimFromHostEndpointOp::create(
114 b, loc, fromHostType, clk, rst,
115 toStringAttr(req.getRelativeAppIDPathAttr(), ch.name));
116 mlir::TypedValue<ChannelType> fromHost = cosim.getFromHost();
117 if (ch.type.getSignaling() != ChannelSignaling::ValidReady)
118 fromHost = ChannelBufferOp::create(
119 b, loc, ch.type, clk, rst, fromHost,
120 b.getIntegerAttr(b.getI64Type(), 1),
123 toServerValues.push_back(fromHost);
124 channelAssignments.push_back(getAssignment(ch.name, cosim.getIdAttr()));
129 PackBundleOp::create(b, implReq.getLoc(), bundleType, toServerValues);
130 implReq.getResult(toClientResultNum[req])
131 .replaceAllUsesWith(pack.getBundle());
135 if (ch.direction == ChannelDirection::from) {
136 Value fromChannel = pack.getFromChannels()[chanIdx++];
137 auto chType = cast<ChannelType>(fromChannel.getType());
138 if (chType.getSignaling() != ChannelSignaling::ValidReady) {
139 auto cosimType = b.getType<ChannelType>(chType.getInner(),
140 ChannelSignaling::ValidReady,
141 chType.getDataDelay());
142 fromChannel = ChannelBufferOp::create(
143 b, loc, cosimType, clk, rst, fromChannel,
144 b.getIntegerAttr(b.getI64Type(), 1),
148 auto cosim = CosimToHostEndpointOp::create(
149 b, loc, clk, rst, fromChannel,
150 toStringAttr(req.getRelativeAppIDPathAttr(), ch.name));
151 channelAssignments.push_back(getAssignment(ch.name, cosim.getIdAttr()));
155 ServiceImplClientRecordOp::create(
156 implRecords, req.getLoc(), req.getRelativeAppIDPathAttr(),
157 req.getServicePortAttr(), TypeAttr::get(bundleType),
158 b.getDictionaryAttr(channelAssignments), DictionaryAttr());
163 Attribute cycleCountParams[] = {
164 hw::ParamDeclAttr::get(
"CORE_CLOCK_FREQUENCY_HZ", b.getI64Type())};
166 {{b.getStringAttr(
"clk"), seq::ClockType::get(ctxt),
167 hw::ModulePort::Direction::Input},
169 {{b.getStringAttr(
"rst"), b.getI1Type(),
170 hw::ModulePort::Direction::Input},
173 auto parentModule = implReq->getParentOfType<mlir::ModuleOp>();
174 auto cosimCycleCountExternModule =
176 if (!cosimCycleCountExternModule) {
177 auto ip = b.saveInsertionPoint();
178 b.setInsertionPointToEnd(parentModule.getBody());
179 if (
auto existingSym = parentModule.lookupSymbol(cosimCycleCountName)) {
182 "symbol 'Cosim_CycleCount' already exists but is not a "
184 .attachNote(existingSym->getLoc())
185 <<
"existing symbol here";
187 cosimCycleCountExternModule = hw::HWModuleExternOp::create(
188 b, reqLoc, b.getStringAttr(cosimCycleCountName), cycleCountPorts,
189 cosimCycleCountName, ArrayAttr::get(ctxt, cycleCountParams));
190 b.restoreInsertionPoint(ip);
194 uint64_t coreClockFreq = 0;
195 if (
auto coreClockFreqAttr = dyn_cast_or_null<IntegerAttr>(
196 implReq->getAttr(
"esi.core_clock_frequency_hz")))
197 if (coreClockFreqAttr.getType().isUnsignedInteger(64))
198 coreClockFreq = coreClockFreqAttr.getUInt();
199 hw::InstanceOp::create(
200 b, reqLoc, cosimCycleCountExternModule,
"__cycle_counter",
201 ArrayRef<Value>({clk, rst}),
202 b.getArrayAttr({hw::ParamDeclAttr::get(
203 "CORE_CLOCK_FREQUENCY_HZ", b.getI64IntegerAttr(coreClockFreq))}));
214 ServiceDeclOpInterface decl,
215 ServiceImplRecordOp) {
217 return implReq.emitOpError(
218 "Must specify a service declaration to use 'sv_mem'.");
220 ImplicitLocOpBuilder b(implReq.getLoc(), implReq);
223 RandomAccessMemoryDeclOp ramDecl =
224 dyn_cast<RandomAccessMemoryDeclOp>(decl.getOperation());
226 return implReq.emitOpError(
227 "'sv_mem' implementation type can only be used to "
228 "implement RandomAccessMemory declarations");
230 if (implReq.getNumOperands() != 2)
231 return implReq.emitOpError(
"Implementation requires clk and rst operands");
232 auto clk = implReq.getOperand(0);
233 auto rst = implReq.getOperand(1);
234 auto write = b.getStringAttr(
"write");
235 auto read = b.getStringAttr(
"read");
237 b, APInt( 0, 0,
false));
238 auto i1 = b.getI1Type();
242 SmallVector<ServiceImplementConnReqOp, 8> toClientReqs(
243 llvm::make_filter_range(
244 implReq.getOps<ServiceImplementConnReqOp>(),
245 [](
auto req) { return req.getToClient() != nullptr; }));
248 DenseMap<Value, Value> outputMap;
249 for (
auto [bout, reqout] :
250 llvm::zip_longest(toClientReqs, implReq.getResults())) {
252 assert(reqout.has_value());
253 Value toClient = bout->getToClient();
254 outputMap[toClient] = *reqout;
258 hw::UnpackedArrayType memType =
259 hw::UnpackedArrayType::get(ramDecl.getInnerType(), ramDecl.getDepth());
261 sv::RegOp::create(b, memType, implReq.getServiceSymbolAttr().getAttr())
266 SmallVector<std::tuple<Value, Value, Value>> writeGoAddressData;
267 for (
auto req : implReq.getOps<ServiceImplementConnReqOp>()) {
268 auto port = req.getServicePort().getName();
275 auto doneValid = bb.
get(i1);
276 auto ackChannel = WrapValidReadyOp::create(b, none, doneValid);
279 PackBundleOp::create(b, implReq.getLoc(), req.getToClient().getType(),
280 ackChannel.getChanOutput());
282 pack.getFromChannels()[RandomAccessMemoryDeclOp::ReqDirChannelIdx];
283 toClientResp = pack.getBundle();
287 UnwrapValidReadyOp::create(b, toServer, ackChannel.getReady());
290 b.getStringAttr(
"address"));
292 b.getStringAttr(
"data"));
295 auto go = comb::AndOp::create(b,
unwrap.getValid(),
unwrap.getReady());
296 go->setAttr(
"sv.namehint", b.getStringAttr(
"write_go"));
301 writeGoAddressData.push_back(std::make_tuple(go, address, data));
303 }
else if (port == read) {
307 auto dataValid = bb.
get(i1);
308 auto data = bb.
get(ramDecl.getInnerType());
309 auto dataChannel = WrapValidReadyOp::create(b, data, dataValid);
312 PackBundleOp::create(b, implReq.getLoc(), req.getToClient().getType(),
313 dataChannel.getChanOutput());
315 pack.getFromChannels()[RandomAccessMemoryDeclOp::RespDirChannelIdx];
316 toClientResp = pack.getBundle();
320 UnwrapValidReadyOp::create(b, toServer, dataChannel.getReady());
321 Value unsignedAddress = addressUnwrap.getRawOutput();
323 b, b.getIntegerType(llvm::Log2_64_Ceil(ramDecl.getDepth())),
325 Value memLoc = sv::ArrayIndexInOutOp::create(b, mem, signlessAddress);
329 data.setValue(readData);
330 dataValid.setValue(addressUnwrap.getValid());
332 assert(
false &&
"Port should be either 'read' or 'write'");
335 outputMap[req.getToClient()].replaceAllUsesWith(toClientResp);
339 auto hwClk = seq::FromClockOp::create(b, clk);
340 sv::AlwaysFFOp::create(
341 b, sv::EventControl::AtPosEdge, hwClk, sv::ResetType::SyncReset,
342 sv::EventControl::AtPosEdge, rst, [&] {
343 for (
auto [go, address, data] : writeGoAddressData) {
344 Value a = address, d = data;
346 sv::IfOp::create(b, go, [&] {
348 b, b.getIntegerType(llvm::Log2_64_Ceil(ramDecl.getDepth())), a);
350 sv::ArrayIndexInOutOp::create(b, mem, signlessAddress);
351 sv::PAssignOp::create(b, memLoc, d);
366 ServiceDeclOpInterface decl) {
369 auto genF =
genLookupTable.find(req.getImplTypeAttr().getValue());
372 return req.emitOpError(
"Could not find service generator for attribute '")
373 << req.getImplTypeAttr() <<
"'";
380 auto implRecord = ServiceImplRecordOp::create(
381 b, req.getLoc(), req.getAppID(), UnitAttr(),
382 req.getServiceSymbolAttr(), req.getStdServiceAttr(),
383 req.getImplTypeAttr(), b.getDictionaryAttr({}));
384 implRecord.getReqDetails().emplaceBlock();
386 return genF->second(req, decl, implRecord);
390 DenseMap<StringRef, ServiceGeneratorDispatcher::ServiceGeneratorFunc>{
396 return ::globalDispatcher;
418 DenseMap<Operation *, SmallVector<igraph::InstanceOpInterface, 1>>
419 moduleInstantiations;
421 void getAndSortModules(ModuleOp topMod,
422 SmallVectorImpl<hw::HWModuleLike> &mods);
423 void getAndSortModulesVisitor(hw::HWModuleLike mod,
424 SmallVectorImpl<hw::HWModuleLike> &mods,
425 DenseSet<Operation *> &modsSeen);
429void ModuleSorter::getAndSortModules(ModuleOp topMod,
430 SmallVectorImpl<hw::HWModuleLike> &mods) {
432 DenseSet<Operation *> modsSeen;
434 moduleInstantiations.clear();
435 topMod.walk([&](hw::HWModuleLike mod) {
436 getAndSortModulesVisitor(mod, mods, modsSeen);
441void ModuleSorter::getAndSortModulesVisitor(
442 hw::HWModuleLike mod, SmallVectorImpl<hw::HWModuleLike> &mods,
443 DenseSet<Operation *> &modsSeen) {
444 if (modsSeen.contains(mod))
446 modsSeen.insert(mod);
448 mod.walk([&](igraph::InstanceOpInterface inst) {
449 auto targetNameAttrs = inst.getReferencedModuleNamesAttr();
450 for (
auto targetNameAttr : targetNameAttrs) {
452 topLevelSyms.getDefinition(cast<StringAttr>(targetNameAttr));
454 moduleInstantiations[modOp].push_back(inst);
455 if (
auto modLike = dyn_cast<hw::HWModuleLike>(modOp))
456 getAndSortModulesVisitor(modLike, mods, modsSeen);
466struct ESIConnectServicesPass
467 :
public circt::esi::impl::ESIConnectServicesBase<ESIConnectServicesPass>,
471 : genDispatcher(gen) {}
472 ESIConnectServicesPass()
475 void runOnOperation()
override;
480 void convertReq(RequestConnectionOp);
485 LogicalResult surfaceReqs(hw::HWMutableModuleLike,
486 ArrayRef<ServiceImplementConnReqOp>);
491 LogicalResult replaceInst(ServiceInstanceOp,
492 ArrayRef<ServiceImplementConnReqOp> portReqs);
496 LogicalResult process(hw::HWModuleLike);
499 StringAttr getStdService(FlatSymbolRefAttr serviceSym);
506void ESIConnectServicesPass::runOnOperation() {
507 ModuleOp outerMod = getOperation();
508 topLevelSyms.addDefinitions(outerMod);
510 outerMod.walk([&](RequestConnectionOp req) { convertReq(req); });
516 SmallVector<hw::HWModuleLike, 64> sortedMods;
517 getAndSortModules(outerMod, sortedMods);
520 for (
auto mod : sortedMods) {
521 hw::HWModuleLike mutableMod = dyn_cast<hw::HWModuleLike>(*mod);
522 if (mutableMod && failed(process(mutableMod))) {
530StringAttr ESIConnectServicesPass::getStdService(FlatSymbolRefAttr svcSym) {
533 Operation *svcDecl = topLevelSyms.getDefinition(svcSym);
534 if (!isa<CustomServiceDeclOp>(svcDecl))
535 return svcDecl->getName().getIdentifier();
539void ESIConnectServicesPass::convertReq(RequestConnectionOp req) {
541 auto newReq = ServiceImplementConnReqOp::create(
542 b, req.getLoc(), req.getToClient().getType(), req.getServicePortAttr(),
543 ArrayAttr::get(&getContext(), {req.getAppIDAttr()}));
544 newReq->setDialectAttrs(req->getDialectAttrs());
545 req.getToClient().replaceAllUsesWith(newReq.getToClient());
548 ServiceRequestRecordOp::create(
549 b, req.getLoc(), req.getAppID(), req.getServicePortAttr(),
550 getStdService(req.getServicePortAttr().getModuleRef()),
551 req.getToClient().getType());
555LogicalResult ESIConnectServicesPass::process(hw::HWModuleLike mod) {
557 if (mod->getNumRegions() == 0 || mod->getRegion(0).empty())
560 Block &modBlock = mod->getRegion(0).front();
563 SetVector<ServiceImplementConnReqOp> nonLocalReqs;
565 llvm::MapVector<SymbolRefAttr, llvm::SetVector<ServiceImplementConnReqOp>>
567 for (
auto instOp : modBlock.getOps<ServiceInstanceOp>())
568 localImplReqs[instOp.getServiceSymbolAttr()] = {};
572 llvm::SetVector<ServiceImplementConnReqOp> *anyServiceInst =
nullptr;
573 if (
auto *defaultService = localImplReqs.find(SymbolRefAttr());
574 defaultService != localImplReqs.end())
575 anyServiceInst = &defaultService->second;
577 auto sortConnReqs = [&]() {
579 for (
auto req :
llvm::make_early_inc_range(
580 mod.
getBodyBlock()->getOps<ServiceImplementConnReqOp>())) {
581 auto service = req.getServicePort().getModuleRef();
582 auto *reqListIter = localImplReqs.find(service);
583 if (reqListIter != localImplReqs.end())
584 reqListIter->second.insert(req);
585 else if (anyServiceInst)
586 anyServiceInst->insert(req);
588 nonLocalReqs.insert(req);
597 llvm::make_early_inc_range(modBlock.getOps<ServiceInstanceOp>())) {
598 auto portReqs = localImplReqs[instOp.getServiceSymbolAttr()];
599 if (failed(replaceInst(instOp, portReqs.getArrayRef())))
603 for (RequestConnectionOp req :
llvm::make_early_inc_range(
610 if (nonLocalReqs.empty())
613 if (
auto mutableMod = dyn_cast<hw::HWMutableModuleLike>(mod.getOperation()))
614 return surfaceReqs(mutableMod, nonLocalReqs.getArrayRef());
615 return mod.emitOpError(
616 "Cannot surface requests through module without mutable ports");
619LogicalResult ESIConnectServicesPass::replaceInst(
620 ServiceInstanceOp instOp, ArrayRef<ServiceImplementConnReqOp> portReqs) {
621 auto declSym = instOp.getServiceSymbolAttr();
622 ServiceDeclOpInterface decl;
624 decl = dyn_cast_or_null<ServiceDeclOpInterface>(
625 topLevelSyms.getDefinition(declSym));
627 return instOp.emitOpError(
"Could not find service declaration ")
633 SmallVector<Type, 8> resultTypes(instOp.getResultTypes().begin(),
634 instOp.getResultTypes().end());
635 for (
auto req : portReqs)
636 resultTypes.push_back(req.getBundleType());
640 auto implOp = ServiceImplementReqOp::create(
641 b, instOp.getLoc(), resultTypes, instOp.getAppIDAttr(),
642 instOp.getServiceSymbolAttr(), instOp.getImplTypeAttr(),
643 getStdService(declSym), instOp.getImplOptsAttr(), instOp.getOperands());
644 implOp->setDialectAttrs(instOp->getDialectAttrs());
645 Block &reqBlock = implOp.getPortReqs().emplaceBlock();
648 for (
auto [n, o] :
llvm::zip(implOp.getResults(), instOp.getResults()))
649 o.replaceAllUsesWith(n);
650 unsigned instOpNumResults = instOp.getNumResults();
651 for (
size_t idx = 0, e = portReqs.size(); idx < e; ++idx) {
652 ServiceImplementConnReqOp req = portReqs[idx];
653 req.getToClient().replaceAllUsesWith(
654 implOp.getResult(idx + instOpNumResults));
657 for (
auto req : portReqs)
658 req->moveBefore(&reqBlock, reqBlock.
end());
666 if (failed(genDispatcher.generate(implOp, decl)))
667 return implOp.emitOpError(
"failed to generate server");
673ESIConnectServicesPass::surfaceReqs(hw::HWMutableModuleLike mod,
674 ArrayRef<ServiceImplementConnReqOp> reqs) {
675 auto *ctxt = mod.getContext();
676 Block *body = &mod->getRegion(0).front();
679 unsigned origNumInputs = mod.getNumInputPorts();
680 SmallVector<std::pair<unsigned, hw::PortInfo>> newInputs;
683 auto getPortName = [&](ArrayAttr namePath) {
684 std::string portName;
685 llvm::raw_string_ostream nameOS(portName);
687 namePath.getAsRange<AppIDAttr>(), nameOS,
688 [&](AppIDAttr appid) {
689 nameOS << appid.getName().getValue();
690 if (appid.getIndex())
691 nameOS <<
"_" << appid.getIndex();
694 return StringAttr::get(ctxt, nameOS.str());
697 for (
auto req : reqs)
698 if (req->getParentWithTrait<
OpTrait::IsIsolatedFromAbove>() != mod)
699 return req.emitOpError(
700 "Cannot surface requests through isolated from above ops");
703 for (
auto req : reqs) {
704 newInputs.push_back(std::make_pair(
706 hw::PortInfo{{getPortName(req.getRelativeAppIDPathAttr()),
713 Value replValue = body->addArgument(req.getBundleType(), req->getLoc());
714 req.getToClient().replaceAllUsesWith(replValue);
716 mod.insertPorts(newInputs, {});
719 auto prependNamePart = [&](ArrayAttr appIDPath, AppIDAttr appID) {
720 SmallVector<Attribute, 8> newAppIDPath;
721 newAppIDPath.push_back(appID);
722 newAppIDPath.append(appIDPath.begin(), appIDPath.end());
723 return ArrayAttr::get(appIDPath.getContext(), newAppIDPath);
727 SmallVector<igraph::InstanceOpInterface, 1> newModuleInstantiations;
728 for (
auto inst : moduleInstantiations[mod]) {
732 SmallVector<Value, 16> newOperands;
733 for (
auto req : reqs) {
735 ArrayAttr appIDPath = req.getRelativeAppIDPathAttr();
736 if (
auto instAppID = dyn_cast_or_null<AppIDAttr>(
737 inst->getDiscardableAttr(AppIDAttr::AppIDAttrName)))
738 appIDPath = prependNamePart(appIDPath, instAppID);
741 auto clone = ServiceImplementConnReqOp::create(
742 b, req.getLoc(), req.getToClient().getType(),
743 req.getServicePortAttr(), appIDPath);
744 clone->setDialectAttrs(req->getDialectAttrs());
745 newOperands.push_back(clone.getToClient());
747 inst->insertOperands(inst->getNumOperands(), newOperands);
749 if (
auto hwInst = dyn_cast<hw::InstanceOp>(*inst))
750 hwInst.setArgNamesAttr(
b.getArrayAttr(mod.getInputNames()));
755 for (
auto req : reqs)
760std::unique_ptr<OperationPass<ModuleOp>>
762 return std::make_unique<ESIConnectServicesPass>();
assert(baseType &&"element must be base type")
static ServiceGeneratorDispatcher globalDispatcher(DenseMap< StringRef, ServiceGeneratorDispatcher::ServiceGeneratorFunc >{ {"cosim", instantiateCosimEndpointOps}, {"sv_mem", instantiateSystemVerilogMemory}}, false)
static LogicalResult instantiateCosimEndpointOps(ServiceImplementReqOp implReq, ServiceDeclOpInterface, ServiceImplRecordOp implRecord)
The generator for the "cosim" impl_type.
static LogicalResult instantiateSystemVerilogMemory(ServiceImplementReqOp implReq, ServiceDeclOpInterface decl, ServiceImplRecordOp)
static EvaluatorValuePtr unwrap(OMEvaluatorValue c)
static Block * getBodyBlock(FModuleLike mod)
Instantiate one of these and use it to build typed backedges.
Backedge get(mlir::Type resultType, mlir::LocationAttr optionalLoc={})
Create a typed backedge.
Default symbol cache implementation; stores associations between names (StringAttr's) to mlir::Operat...
Class which "dispatches" a service implementation request to its specified generator.
void registerGenerator(StringRef implType, ServiceGeneratorFunc gen)
Add a generator to this registry.
LogicalResult generate(ServiceImplementReqOp, ServiceDeclOpInterface)
Generate a service implementation if a generator exists in this registry.
static ServiceGeneratorDispatcher & globalDispatcher()
Get the global dispatcher.
DenseMap< StringRef, ServiceGeneratorFunc > genLookupTable
std::function< LogicalResult(ServiceImplementReqOp, ServiceDeclOpInterface, ServiceImplRecordOp)> ServiceGeneratorFunc
create(cls, result_type, reset=None, reset_value=None, name=None, sym_name=None, **kwargs)
std::unique_ptr< OperationPass< ModuleOp > > createESIConnectServicesPass()
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
This holds the name, type, direction of a module's ports.