12#include "slang/ast/Compilation.h"
13#include "slang/ast/symbols/ClassSymbols.h"
14#include "slang/ast/symbols/MemberSymbols.h"
15#include "slang/syntax/AllSyntax.h"
16#include "slang/syntax/SyntaxKind.h"
17#include "slang/syntax/SyntaxVisitor.h"
18#include "llvm/ADT/STLFunctionalExtras.h"
19#include "llvm/ADT/ScopeExit.h"
35 const slang::ast::Scope &scope,
36 const slang::syntax::SyntaxNode *syntax) {
40 auto visitor = slang::syntax::makeSyntaxVisitor(
41 [&](
auto &visitor,
const slang::syntax::DPIExportSyntax &exportSyntax) {
42 auto svName = exportSyntax.name.valueText();
46 const auto *symbol = scope.find(svName);
47 const auto *subroutine =
48 symbol ? symbol->as_if<slang::ast::SubroutineSymbol>() :
nullptr;
52 auto cName = exportSyntax.c_identifier.valueText();
55 context.dpiExportCNames[subroutine] = std::string(cName);
57 [](
auto &visitor,
const slang::syntax::SyntaxNode &node) {
58 visitor.visitDefault(node);
60 syntax->visit(visitor);
64 SmallString<64> &prefix) {
65 if (symbol.kind != slang::ast::SymbolKind::Package)
68 if (!symbol.name.empty()) {
69 prefix += symbol.name;
86 BaseVisitor(Context &context, Location loc)
87 : context(context), loc(loc), builder(context.builder) {}
90 LogicalResult visit(
const slang::ast::EmptyMemberSymbol &) {
96 LogicalResult visit(
const slang::ast::TransparentMemberSymbol &) {
101 LogicalResult visit(
const slang::ast::ClassType &classdecl) {
102 if (failed(context.buildClassProperties(classdecl)))
104 return context.materializeClassMethods(classdecl);
111 LogicalResult visit(
const slang::ast::GenericClassDefSymbol &) {
116 LogicalResult visit(
const slang::ast::TypeAliasType &) {
return success(); }
117 LogicalResult visit(
const slang::ast::ForwardingTypedefSymbol &) {
122 LogicalResult visit(
const slang::ast::ExplicitImportSymbol &) {
125 LogicalResult visit(
const slang::ast::WildcardImportSymbol &) {
130 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
135 LogicalResult visit(
const slang::ast::ElabSystemTaskSymbol &) {
140 LogicalResult visit(
const slang::ast::PrimitiveSymbol &primitive) {
141 return context.convertUserDefinedPrimitiveDef(primitive);
145 LogicalResult visit(
const slang::ast::ParameterSymbol ¶m) {
146 visitParameter(param);
150 LogicalResult visit(
const slang::ast::SpecparamSymbol ¶m) {
151 visitParameter(param);
155 template <
class Node>
156 void visitParameter(
const Node ¶m) {
160 if (!context.options.debugInfo)
163 context.materializeConstant(param.getValue(), param.getType(), loc);
166 if (builder.getInsertionBlock()->getParentOp() == context.intoModuleOp) {
168 context.orderedRootOps.insert({key, value.getDefiningOp()});
173 SmallString<64> paramName;
175 paramName += param.name;
177 debug::VariableOp::create(builder, loc, builder.getStringAttr(paramName),
188struct RootVisitor :
public BaseVisitor {
189 using BaseVisitor::BaseVisitor;
190 using BaseVisitor::visit;
193 LogicalResult visit(
const slang::ast::PackageSymbol &package) {
194 return context.convertPackage(package);
198 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
199 if (!
context.declareFunction(subroutine))
205 LogicalResult visit(
const slang::ast::VariableSymbol &var) {
206 return context.convertGlobalVariable(var);
210 template <
typename T>
211 LogicalResult visit(T &&node) {
212 mlir::emitError(loc,
"unsupported construct: ")
213 << slang::ast::toString(node.kind);
224struct PackageVisitor :
public BaseVisitor {
225 using BaseVisitor::BaseVisitor;
226 using BaseVisitor::visit;
229 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
230 if (!
context.declareFunction(subroutine))
236 LogicalResult visit(
const slang::ast::VariableSymbol &var) {
237 return context.convertGlobalVariable(var);
241 template <
typename T>
242 LogicalResult visit(T &&node) {
243 mlir::emitError(loc,
"unsupported package member: ")
244 << slang::ast::toString(node.kind);
254static moore::ProcedureKind
257 case slang::ast::ProceduralBlockKind::Always:
258 return moore::ProcedureKind::Always;
259 case slang::ast::ProceduralBlockKind::AlwaysComb:
260 return moore::ProcedureKind::AlwaysComb;
261 case slang::ast::ProceduralBlockKind::AlwaysLatch:
262 return moore::ProcedureKind::AlwaysLatch;
263 case slang::ast::ProceduralBlockKind::AlwaysFF:
264 return moore::ProcedureKind::AlwaysFF;
265 case slang::ast::ProceduralBlockKind::Initial:
266 return moore::ProcedureKind::Initial;
267 case slang::ast::ProceduralBlockKind::Final:
268 return moore::ProcedureKind::Final;
270 llvm_unreachable(
"all procedure kinds handled");
275 case slang::ast::NetType::Supply0:
276 return moore::NetKind::Supply0;
277 case slang::ast::NetType::Supply1:
278 return moore::NetKind::Supply1;
279 case slang::ast::NetType::Tri:
280 return moore::NetKind::Tri;
281 case slang::ast::NetType::TriAnd:
282 return moore::NetKind::TriAnd;
283 case slang::ast::NetType::TriOr:
284 return moore::NetKind::TriOr;
285 case slang::ast::NetType::TriReg:
286 return moore::NetKind::TriReg;
287 case slang::ast::NetType::Tri0:
288 return moore::NetKind::Tri0;
289 case slang::ast::NetType::Tri1:
290 return moore::NetKind::Tri1;
291 case slang::ast::NetType::UWire:
292 return moore::NetKind::UWire;
293 case slang::ast::NetType::Wire:
294 return moore::NetKind::Wire;
295 case slang::ast::NetType::WAnd:
296 return moore::NetKind::WAnd;
297 case slang::ast::NetType::WOr:
298 return moore::NetKind::WOr;
299 case slang::ast::NetType::Interconnect:
300 return moore::NetKind::Interconnect;
301 case slang::ast::NetType::UserDefined:
302 return moore::NetKind::UserDefined;
303 case slang::ast::NetType::Unknown:
304 return moore::NetKind::Unknown;
306 llvm_unreachable(
"all net kinds handled");
310struct ModuleVisitor :
public BaseVisitor {
311 using BaseVisitor::visit;
315 StringRef blockNamePrefix;
317 ModuleVisitor(Context &
context, Location loc, StringRef blockNamePrefix =
"")
318 : BaseVisitor(
context, loc), blockNamePrefix(blockNamePrefix) {}
321 LogicalResult visit(
const slang::ast::PortSymbol &) {
return success(); }
322 LogicalResult visit(
const slang::ast::MultiPortSymbol &) {
return success(); }
323 LogicalResult visit(
const slang::ast::InterfacePortSymbol &) {
328 LogicalResult visit(
const slang::ast::GenvarSymbol &genvarNode) {
333 LogicalResult visit(
const slang::ast::DefParamSymbol &) {
return success(); }
337 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
345 expandInterfaceInstance(
const slang::ast::InstanceSymbol &instNode) {
346 auto prefix = (Twine(blockNamePrefix) + instNode.name +
"_").str();
347 auto lowering = std::make_unique<InterfaceLowering>();
348 Context::ValueSymbolScope scope(
context.valueSymbols);
350 auto recordMember = [&](
const slang::ast::Symbol &sym,
351 Value value) ->
void {
352 lowering->expandedMembers[&sym] = value;
353 auto nameAttr = builder.getStringAttr(sym.name);
354 lowering->expandedMembersByName[nameAttr] = value;
355 if (
auto *valueSym = sym.as_if<slang::ast::ValueSymbol>())
356 context.valueSymbols.insert(valueSym, value);
359 for (
const auto &member : instNode.body.members()) {
361 if (
const auto *nestedInst = member.as_if<slang::ast::InstanceSymbol>()) {
362 if (nestedInst->body.getDefinition().definitionKind ==
363 slang::ast::DefinitionKind::Interface)
364 return mlir::emitError(loc)
365 <<
"nested interface instances are not supported: `"
366 << nestedInst->name <<
"` inside `" << instNode.name <<
"`";
369 if (
const auto *var = member.as_if<slang::ast::VariableSymbol>()) {
370 auto loweredType =
context.convertType(*var->getDeclaredType());
373 auto varOp = moore::VariableOp::create(
375 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
376 builder.getStringAttr(Twine(prefix) + StringRef(var->name)),
378 recordMember(*var, varOp);
382 if (
const auto *net = member.as_if<slang::ast::NetSymbol>()) {
383 auto loweredType =
context.convertType(*net->getDeclaredType());
387 if (netKind == moore::NetKind::Interconnect ||
388 netKind == moore::NetKind::UserDefined ||
389 netKind == moore::NetKind::Unknown)
390 return mlir::emitError(loc,
"unsupported net kind `")
391 << net->netType.name <<
"`";
392 auto netOp = moore::NetOp::create(
394 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
395 builder.getStringAttr(Twine(prefix) + StringRef(net->name)),
397 recordMember(*net, netOp);
406 for (
const auto *con : instNode.getPortConnections()) {
407 const auto *expr = con->getExpression();
408 const auto *port = con->port.as_if<slang::ast::PortSymbol>();
416 Value lvalue =
context.convertLvalueExpression(*expr);
420 recordMember(*port, lvalue);
421 if (port->internalSymbol) {
422 recordMember(*port->internalSymbol, lvalue);
428 for (
const auto &member : instNode.body.members()) {
429 switch (member.kind) {
430 case slang::ast::SymbolKind::ContinuousAssign:
431 case slang::ast::SymbolKind::ProceduralBlock:
432 case slang::ast::SymbolKind::StatementBlock:
437 auto memberLoc =
context.convertLocation(member.location);
438 if (failed(member.visit(ModuleVisitor(
context, memberLoc, prefix))))
440 if (failed(
context.flushPendingMonitors()))
444 context.interfaceInstanceStorage.push_back(std::move(lowering));
445 context.interfaceInstances.insert(
446 &instNode,
context.interfaceInstanceStorage.back().get());
451 LogicalResult visit(
const slang::ast::InstanceSymbol &instNode) {
452 using slang::ast::ArgumentDirection;
453 using slang::ast::AssignmentExpression;
454 using slang::ast::MultiPortSymbol;
455 using slang::ast::PortSymbol;
457 if (
context.predeclaredInstances.contains(&instNode))
468 auto defKind = body->getDefinition().definitionKind;
469 if (defKind == slang::ast::DefinitionKind::Interface) {
470 if (
context.interfaceInstances.lookup(&instNode))
472 return expandInterfaceInstance(instNode);
475 auto *moduleLowering =
context.convertModuleHeader(body);
478 auto module = moduleLowering->op;
479 auto moduleType =
module.getModuleType();
482 SymbolTable::setSymbolVisibility(module, SymbolTable::Visibility::Private);
488 SmallDenseMap<const PortSymbol *, Value> portValues;
489 portValues.reserve(moduleType.getNumPorts());
492 SmallDenseMap<
const slang::ast::InterfacePortSymbol *,
493 const slang::ast::InstanceSymbol *>
496 for (
const auto *con : instNode.getPortConnections()) {
497 const auto *expr = con->getExpression();
502 auto *port = con->port.as_if<PortSymbol>();
503 if (
auto *existingPort =
504 moduleLowering->portsBySyntaxNode.lookup(port->getSyntax()))
507 switch (port->direction) {
508 case ArgumentDirection::In: {
509 auto refType = moore::RefType::get(
510 cast<moore::UnpackedType>(
context.convertType(port->getType())));
512 if (
const auto *net =
513 port->internalSymbol->as_if<slang::ast::NetSymbol>()) {
514 auto netOp = moore::NetOp::create(
515 builder, loc, refType,
516 StringAttr::get(builder.getContext(), net->name),
518 auto readOp = moore::ReadOp::create(builder, loc, netOp);
519 portValues.insert({port, readOp});
520 }
else if (
const auto *var =
522 ->as_if<slang::ast::VariableSymbol>()) {
523 auto varOp = moore::VariableOp::create(
524 builder, loc, refType,
525 StringAttr::get(builder.getContext(), var->name),
nullptr);
526 auto readOp = moore::ReadOp::create(builder, loc, varOp);
527 portValues.insert({port, readOp});
529 return mlir::emitError(loc)
530 <<
"unsupported internal symbol for unconnected port `"
531 << port->name <<
"`";
538 case ArgumentDirection::Out:
541 case ArgumentDirection::InOut:
542 case ArgumentDirection::Ref: {
543 auto refType = moore::RefType::get(
544 cast<moore::UnpackedType>(
context.convertType(port->getType())));
546 if (
const auto *net =
547 port->internalSymbol->as_if<slang::ast::NetSymbol>()) {
548 auto netOp = moore::NetOp::create(
549 builder, loc, refType,
550 StringAttr::get(builder.getContext(), net->name),
552 portValues.insert({port, netOp});
553 }
else if (
const auto *var =
555 ->as_if<slang::ast::VariableSymbol>()) {
556 auto varOp = moore::VariableOp::create(
557 builder, loc, refType,
558 StringAttr::get(builder.getContext(), var->name),
nullptr);
559 portValues.insert({port, varOp});
561 return mlir::emitError(loc)
562 <<
"unsupported internal symbol for unconnected port `"
563 << port->name <<
"`";
572 if (
const auto *assign = expr->as_if<AssignmentExpression>())
573 expr = &assign->left();
578 if (
auto *port = con->port.as_if<PortSymbol>()) {
580 auto value = (port->direction == ArgumentDirection::In)
581 ?
context.convertRvalueExpression(*expr)
582 :
context.convertLvalueExpression(*expr);
585 if (
auto *existingPort =
586 moduleLowering->portsBySyntaxNode.lookup(con->port.getSyntax()))
591 if (port->direction == ArgumentDirection::InOut) {
592 auto portType = moore::RefType::get(
593 cast<moore::UnpackedType>(
context.convertType(port->getType())));
594 if (value.getType() != portType)
595 return mlir::emitError(loc)
596 <<
"inout port `" << port->name <<
"` expects " << portType
597 <<
" but is connected to " << value.getType();
600 portValues.insert({port, value});
607 if (
const auto *multiPort = con->port.as_if<MultiPortSymbol>()) {
609 auto value =
context.convertLvalueExpression(*expr);
613 for (
const auto *port : llvm::reverse(multiPort->ports)) {
614 if (
auto *existingPort = moduleLowering->portsBySyntaxNode.lookup(
615 con->port.getSyntax()))
617 unsigned width = port->getType().getBitWidth();
618 auto sliceType =
context.convertType(port->getType());
621 Value slice = moore::ExtractRefOp::create(
623 moore::RefType::get(cast<moore::UnpackedType>(sliceType)), value,
626 if (port->direction == ArgumentDirection::In)
627 slice = moore::ReadOp::create(builder, loc, slice);
628 portValues.insert({port, slice});
636 if (
const auto *ifacePort =
637 con->port.as_if<slang::ast::InterfacePortSymbol>()) {
638 auto ifaceConn = con->getIfaceConn();
639 const auto *connInst =
640 ifaceConn.first->as_if<slang::ast::InstanceSymbol>();
642 ifaceConnMap[ifacePort] = connInst;
646 mlir::emitError(loc) <<
"unsupported instance port `" << con->port.name
647 <<
"` (" << slang::ast::toString(con->port.kind)
655 SmallVector<Value> inputValues(moduleLowering->numExplicitInputs);
656 SmallVector<Value> outputValues(moduleLowering->numExplicitOutputs);
658 for (
auto &port : moduleLowering->ports) {
659 auto value = portValues.lookup(&port.ast);
660 if (port.ast.direction == ArgumentDirection::Out)
661 outputValues[*port.outputIdx] = value;
663 inputValues[*port.inputIdx] = value;
669 for (
auto &fp : moduleLowering->ifacePorts) {
670 if (!fp.bodySym || !fp.origin)
673 auto it = ifaceConnMap.find(fp.origin);
674 if (it == ifaceConnMap.end()) {
676 <<
"no interface connection for port `" << fp.name <<
"`";
679 const auto *connInst = it->second;
681 auto *ifaceLowering =
context.interfaceInstances.lookup(connInst);
682 if (!ifaceLowering) {
684 <<
"interface instance `" << connInst->name <<
"` was not expanded";
688 auto valIt = ifaceLowering->expandedMembers.find(fp.bodySym);
689 if (valIt == ifaceLowering->expandedMembers.end()) {
691 <<
"unresolved interface port signal `" << fp.name <<
"`";
694 Value val = valIt->second;
696 outputValues[*fp.outputIdx] = val;
700 if (isa<moore::RefType>(val.getType()) && !isa<moore::RefType>(fp.type))
701 val = moore::ReadOp::create(builder, loc, val);
702 inputValues[*fp.inputIdx] = val;
708 for (
auto [value, type] :
709 llvm::zip(inputValues, moduleType.getInputTypes())) {
713 value =
context.materializeConversion(type, value,
false, value.getLoc());
715 return mlir::emitError(loc) <<
"unsupported port";
722 for (
const auto &hierPath :
context.hierPaths[body]) {
723 assert(!hierPath.valueSyms.empty() &&
"hierPath must have valueSyms");
724 if (!hierPath.hierName || hierPath.direction != ArgumentDirection::In)
729 for (
auto &alias : hierPath.valueSyms)
730 if ((hierValue =
context.valueSymbols.lookup(alias.first)))
732 inputValues.push_back(hierValue);
736 for (
auto value : inputValues)
738 return mlir::emitError(loc) <<
"unsupported port";
746 SmallString<64> instName(blockNamePrefix);
747 if (instNode.arrayPath.empty()) {
748 instName += instNode.name;
750 instName += instNode.getArrayName();
751 slang::SmallVector<slang::ConstantRange, 4> dims;
752 instNode.getArrayDimensions(dims);
753 for (
auto [dim, index] : llvm::zip(dims, instNode.arrayPath)) {
755 Twine(dim.lower() + int32_t(index)).toVector(instName);
760 auto inputNames = builder.getArrayAttr(moduleType.getInputNames());
761 auto outputNames = builder.getArrayAttr(moduleType.getOutputNames());
762 auto inst = moore::InstanceOp::create(
763 builder, loc, moduleType.getOutputTypes(),
764 builder.getStringAttr(instName),
765 FlatSymbolRefAttr::get(module.getSymNameAttr()), inputValues,
766 inputNames, outputNames);
767 context.convertAttributes(instNode, inst);
771 auto aliasReachedThroughInstance =
772 [&](
const slang::ast::InstanceBodySymbol *aliasBody) {
773 for (
auto *b = aliasBody; b && b->parentInstance;
774 b = b->parentInstance->getParentScope()->getContainingInstance())
775 if (b->parentInstance == &instNode)
785 for (
const auto &hierPath :
context.hierPaths[body])
786 if (hierPath.idx && hierPath.direction == ArgumentDirection::Out) {
787 auto result = inst->getResult(*hierPath.idx);
788 for (
auto &alias : hierPath.valueSyms)
789 if (aliasReachedThroughInstance(alias.second))
790 context.valueSymbols.insert(alias.first, result);
791 context.hierValueSymbols[{&instNode, hierPath.hierName}] = result;
795 for (
auto [lvalue, output] : llvm::zip(outputValues, inst.getOutputs())) {
798 Value rvalue = output;
799 auto dstType = cast<moore::RefType>(lvalue.getType()).getNestedType();
801 rvalue =
context.materializeConversion(dstType, rvalue,
false, loc);
804 moore::ContinuousAssignOp::create(builder, loc, lvalue, rvalue);
811 LogicalResult visit(
const slang::ast::VariableSymbol &varNode) {
812 auto ref =
context.valueSymbols.lookup(&varNode);
814 return mlir::emitError(loc)
815 <<
"internal error: missing predeclared variable `" << varNode.name
818 auto varOp = ref.getDefiningOp<moore::VariableOp>();
820 return mlir::emitError(loc)
821 <<
"internal error: predeclared variable `" << varNode.name
822 <<
"` is not a moore.variable";
824 if (
const auto *init = varNode.getInitializer()) {
825 auto loweredType = cast<moore::RefType>(ref.getType()).getNestedType();
826 auto initial =
context.convertRvalueExpression(*init, loweredType);
829 varOp.getInitialMutable().assign(initial);
836 LogicalResult visit(
const slang::ast::NetSymbol &netNode) {
837 auto ref =
context.valueSymbols.lookup(&netNode);
839 return mlir::emitError(loc) <<
"internal error: missing predeclared net `"
840 << netNode.name <<
"`";
842 auto netOp = ref.getDefiningOp<moore::NetOp>();
844 return mlir::emitError(loc) <<
"internal error: predeclared net `"
845 << netNode.name <<
"` is not a moore.net";
847 if (
const auto *init = netNode.getInitializer()) {
848 auto loweredType = cast<moore::RefType>(ref.getType()).getNestedType();
849 auto assignment =
context.convertRvalueExpression(*init, loweredType);
852 netOp.getAssignmentMutable().assign(assignment);
858 LogicalResult visit(
const slang::ast::ContinuousAssignSymbol &assignNode) {
860 assignNode.getAssignment().as<slang::ast::AssignmentExpression>();
861 auto lhs =
context.convertLvalueExpression(expr.left());
865 auto rhs =
context.convertRvalueExpression(
866 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
871 if (
auto *timingCtrl = assignNode.getDelay()) {
872 if (
auto *ctrl = timingCtrl->as_if<slang::ast::DelayControl>()) {
873 auto delay =
context.convertRvalueExpression(
874 ctrl->expr, moore::TimeType::get(builder.getContext()));
877 moore::DelayedContinuousAssignOp::create(builder, loc, lhs, rhs, delay);
880 mlir::emitError(loc) <<
"unsupported delay with rise/fall/turn-off";
885 moore::ContinuousAssignOp::create(builder, loc, lhs, rhs);
890 LogicalResult convertProcedure(moore::ProcedureKind kind,
891 const slang::ast::Statement &body) {
892 if (body.as_if<slang::ast::ConcurrentAssertionStatement>())
893 return context.convertStatement(body);
894 auto procOp = moore::ProcedureOp::create(builder, loc, kind);
895 OpBuilder::InsertionGuard guard(builder);
896 builder.setInsertionPointToEnd(&procOp.getBody().emplaceBlock());
897 Context::ValueSymbolScope scope(
context.valueSymbols);
898 Context::VirtualInterfaceMemberScope vifMemberScope(
900 if (failed(
context.convertStatement(body)))
902 if (builder.getBlock())
903 moore::ReturnOp::create(builder, loc);
907 LogicalResult visit(
const slang::ast::ProceduralBlockSymbol &procNode) {
910 if (
auto *syntax = procNode.getSyntax();
912 syntax->kind == slang::syntax::SyntaxKind::ConcurrentAssertionMember)
913 return context.convertStatement(procNode.getBody());
917 if (
context.options.lowerAlwaysAtStarAsComb) {
918 auto *stmt = procNode.getBody().as_if<slang::ast::TimedStatement>();
919 if (procNode.procedureKind == slang::ast::ProceduralBlockKind::Always &&
921 stmt->timing.kind == slang::ast::TimingControlKind::ImplicitEvent)
922 return convertProcedure(moore::ProcedureKind::AlwaysComb, stmt->stmt);
930 LogicalResult visit(
const slang::ast::GenerateBlockSymbol &genNode) {
932 if (genNode.isUninstantiated)
936 SmallString<64> prefix = blockNamePrefix;
937 if (!genNode.name.empty() ||
938 genNode.getParentScope()->asSymbol().kind !=
939 slang::ast::SymbolKind::GenerateBlockArray) {
940 prefix += genNode.getExternalName();
945 for (
auto &member : genNode.members())
946 if (failed(member.visit(ModuleVisitor(
context, loc, prefix))))
952 LogicalResult visit(
const slang::ast::GenerateBlockArraySymbol &genArrNode) {
955 SmallString<64> prefix = blockNamePrefix;
956 prefix += genArrNode.getExternalName();
958 auto prefixBaseLen = prefix.size();
961 for (
const auto *entry : genArrNode.entries) {
963 prefix.resize(prefixBaseLen);
964 if (entry->arrayIndex)
965 prefix += entry->arrayIndex->toString();
967 Twine(entry->constructIndex).toVector(prefix);
971 if (failed(entry->asSymbol().visit(ModuleVisitor(
context, loc, prefix))))
983 LogicalResult visit(
const slang::ast::StatementBlockSymbol &) {
989 LogicalResult visit(
const slang::ast::SequenceSymbol &seqNode) {
995 LogicalResult visit(
const slang::ast::PropertySymbol &propNode) {
1001 LogicalResult visit(
const slang::ast::ClockingBlockSymbol &) {
1007 LogicalResult visit(
const slang::ast::LetDeclSymbol &) {
return success(); }
1010 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
1011 if (!
context.declareFunction(subroutine))
1017 LogicalResult visit(
const slang::ast::PrimitiveInstanceSymbol &prim) {
1018 return context.convertPrimitiveInstance(prim);
1022 LogicalResult visit(
const slang::ast::InstanceArraySymbol &arrNode) {
1024 for (
const auto *element : arrNode.elements)
1025 if (failed(element->visit(*
this)))
1031 template <
typename T>
1032 LogicalResult visit(T &&node) {
1033 mlir::emitError(loc,
"unsupported module member: ")
1034 << slang::ast::toString(node.kind);
1039struct ModulePredeclaration {
1043 ModulePredeclaration(Context &context)
1044 : context(context), builder(context.builder) {}
1046 LogicalResult declareVariable(
const slang::ast::VariableSymbol &varNode,
1047 Location loc, StringRef blockNamePrefix) {
1048 auto loweredType = context.convertType(*varNode.getDeclaredType());
1052 auto varOp = moore::VariableOp::create(
1054 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
1055 builder.getStringAttr(Twine(blockNamePrefix) + varNode.name), Value{});
1056 context.valueSymbols.insert(&varNode, varOp);
1058 const auto &canonTy = varNode.getType().getCanonicalType();
1059 if (
const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>())
1060 if (failed(context.registerVirtualInterfaceMembers(varNode, *vi, loc)))
1066 LogicalResult declareNet(
const slang::ast::NetSymbol &netNode, Location loc,
1067 StringRef blockNamePrefix) {
1068 auto loweredType = context.convertType(*netNode.getDeclaredType());
1073 if (netkind == moore::NetKind::Interconnect ||
1074 netkind == moore::NetKind::UserDefined ||
1075 netkind == moore::NetKind::Unknown)
1076 return mlir::emitError(loc,
"unsupported net kind `")
1077 << netNode.netType.name <<
"`";
1079 auto netOp = moore::NetOp::create(
1081 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
1082 builder.getStringAttr(Twine(blockNamePrefix) + netNode.name), netkind,
1084 context.valueSymbols.insert(&netNode, netOp);
1089 getGenerateBlockPrefix(
const slang::ast::GenerateBlockSymbol &genNode,
1090 StringRef blockNamePrefix) {
1091 SmallString<64> prefix = blockNamePrefix;
1092 if (!genNode.name.empty() ||
1093 genNode.getParentScope()->asSymbol().kind !=
1094 slang::ast::SymbolKind::GenerateBlockArray) {
1095 prefix += genNode.getExternalName();
1102 predeclareStorageGenerateBlock(
const slang::ast::GenerateBlockSymbol &genNode,
1103 StringRef blockNamePrefix) {
1104 if (genNode.isUninstantiated)
1106 return predeclareStorageScope(
1107 genNode, getGenerateBlockPrefix(genNode, blockNamePrefix));
1110 LogicalResult predeclareInterfaceGenerateBlock(
1111 const slang::ast::GenerateBlockSymbol &genNode,
1112 StringRef blockNamePrefix) {
1113 if (genNode.isUninstantiated)
1115 return predeclareInterfaceScope(
1116 genNode, getGenerateBlockPrefix(genNode, blockNamePrefix));
1119 LogicalResult predeclareModuleInstanceGenerateBlock(
1120 const slang::ast::GenerateBlockSymbol &genNode,
1121 StringRef blockNamePrefix) {
1122 if (genNode.isUninstantiated)
1124 return predeclareModuleInstanceScope(
1125 genNode, getGenerateBlockPrefix(genNode, blockNamePrefix));
1128 LogicalResult predeclareGenerateBlockArray(
1129 const slang::ast::GenerateBlockArraySymbol &genArrNode,
1130 StringRef blockNamePrefix,
1131 llvm::function_ref<LogicalResult(
const slang::ast::GenerateBlockSymbol &,
1134 SmallString<64> prefix = blockNamePrefix;
1135 prefix += genArrNode.getExternalName();
1137 auto prefixBaseLen = prefix.size();
1139 for (
const auto *entry : genArrNode.entries) {
1140 prefix.resize(prefixBaseLen);
1141 if (entry->arrayIndex)
1142 prefix += entry->arrayIndex->toString();
1144 Twine(entry->constructIndex).toVector(prefix);
1147 if (failed(predeclareBlock(*entry, prefix)))
1153 LogicalResult predeclareStorageMember(
const slang::ast::Symbol &member,
1154 StringRef blockNamePrefix) {
1155 auto loc = context.convertLocation(member.location);
1156 if (
const auto *varNode = member.as_if<slang::ast::VariableSymbol>())
1157 return declareVariable(*varNode, loc, blockNamePrefix);
1159 if (
const auto *netNode = member.as_if<slang::ast::NetSymbol>())
1160 return declareNet(*netNode, loc, blockNamePrefix);
1162 if (
const auto *genNode = member.as_if<slang::ast::GenerateBlockSymbol>())
1163 return predeclareStorageGenerateBlock(*genNode, blockNamePrefix);
1165 if (
const auto *genArrNode =
1166 member.as_if<slang::ast::GenerateBlockArraySymbol>())
1167 return predeclareGenerateBlockArray(
1168 *genArrNode, blockNamePrefix,
1169 [&](
const slang::ast::GenerateBlockSymbol &gen, StringRef prefix) {
1170 return predeclareStorageGenerateBlock(gen, prefix);
1176 LogicalResult predeclareInterfaceMember(
const slang::ast::Symbol &member,
1177 StringRef blockNamePrefix) {
1178 auto loc = context.convertLocation(member.location);
1179 if (
const auto *instNode = member.as_if<slang::ast::InstanceSymbol>()) {
1180 if (instNode->body.getDefinition().definitionKind ==
1181 slang::ast::DefinitionKind::Interface)
1182 return ModuleVisitor(context, loc, blockNamePrefix)
1183 .expandInterfaceInstance(*instNode);
1187 if (
const auto *genNode = member.as_if<slang::ast::GenerateBlockSymbol>())
1188 return predeclareInterfaceGenerateBlock(*genNode, blockNamePrefix);
1190 if (
const auto *genArrNode =
1191 member.as_if<slang::ast::GenerateBlockArraySymbol>())
1192 return predeclareGenerateBlockArray(
1193 *genArrNode, blockNamePrefix,
1194 [&](
const slang::ast::GenerateBlockSymbol &gen, StringRef prefix) {
1195 return predeclareInterfaceGenerateBlock(gen, prefix);
1201 LogicalResult predeclareModuleInstanceMember(
const slang::ast::Symbol &member,
1202 StringRef blockNamePrefix) {
1203 auto loc = context.convertLocation(member.location);
1204 if (
const auto *instNode = member.as_if<slang::ast::InstanceSymbol>()) {
1205 if (instNode->body.getDefinition().definitionKind !=
1206 slang::ast::DefinitionKind::Interface) {
1208 ModuleVisitor(context, loc, blockNamePrefix).visit(*instNode)))
1210 context.predeclaredInstances.insert(instNode);
1215 if (
const auto *arrNode = member.as_if<slang::ast::InstanceArraySymbol>()) {
1216 for (
const auto *element : arrNode->elements)
1217 if (failed(predeclareModuleInstanceMember(*element, blockNamePrefix)))
1222 if (
const auto *genNode = member.as_if<slang::ast::GenerateBlockSymbol>())
1223 return predeclareModuleInstanceGenerateBlock(*genNode, blockNamePrefix);
1225 if (
const auto *genArrNode =
1226 member.as_if<slang::ast::GenerateBlockArraySymbol>())
1227 return predeclareGenerateBlockArray(
1228 *genArrNode, blockNamePrefix,
1229 [&](
const slang::ast::GenerateBlockSymbol &gen, StringRef prefix) {
1230 return predeclareModuleInstanceGenerateBlock(gen, prefix);
1236 LogicalResult predeclareStorageScope(
const slang::ast::Scope &scope,
1237 StringRef blockNamePrefix) {
1238 for (
auto &member : scope.members())
1239 if (failed(predeclareStorageMember(member, blockNamePrefix)))
1244 LogicalResult predeclareInterfaceScope(
const slang::ast::Scope &scope,
1245 StringRef blockNamePrefix) {
1246 for (
auto &member : scope.members())
1247 if (failed(predeclareInterfaceMember(member, blockNamePrefix)))
1252 LogicalResult predeclareModuleInstanceScope(
const slang::ast::Scope &scope,
1253 StringRef blockNamePrefix) {
1254 for (
auto &member : scope.members())
1255 if (failed(predeclareModuleInstanceMember(member, blockNamePrefix)))
1260 LogicalResult predeclareScope(
const slang::ast::Scope &scope,
1261 StringRef blockNamePrefix) {
1265 if (failed(predeclareStorageScope(scope, blockNamePrefix)))
1271 if (failed(predeclareInterfaceScope(scope, blockNamePrefix)))
1276 return predeclareModuleInstanceScope(scope, blockNamePrefix);
1293 timeScale = root.getTimeScale().value_or(slang::TimeScale());
1294 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1298 SmallVector<AmbiguousHierCapture> ambiguousHierCaptures;
1300 for (
auto &ambiguous : ambiguousHierCaptures) {
1301 auto d = mlir::emitError(
convertLocation(ambiguous.function->location))
1302 <<
"hierarchical reference to `" << ambiguous.symbol->name
1303 <<
"` is ambiguous: this function reaches it through more than "
1304 "one instance of the same module, which is not yet supported";
1306 <<
"symbol declared here";
1308 if (!ambiguousHierCaptures.empty())
1313 for (
auto *inst : root.topInstances)
1323 for (
auto *unit : root.compilationUnits) {
1325 for (
const auto &member : unit->members()) {
1327 if (failed(member.visit(RootVisitor(*
this, loc))))
1335 SmallVector<const slang::ast::InstanceSymbol *> topInstances;
1336 for (
auto *inst : root.topInstances) {
1338 if (body->getDefinition().definitionKind !=
1339 slang::ast::DefinitionKind::Interface)
1346 auto *
module = moduleWorklist.front();
1354 SmallVector<const slang::ast::ClassType *, 16> classMethodWorklist;
1355 classMethodWorklist.reserve(
classes.size());
1357 classMethodWorklist.push_back(kv.first);
1359 for (
auto *inst : classMethodWorklist) {
1378 auto &block = varOp.getInitRegion().emplaceBlock();
1379 OpBuilder::InsertionGuard guard(
builder);
1380 builder.setInsertionPointToEnd(&block);
1385 moore::YieldOp::create(
builder, varOp.getLoc(), value);
1394 SmallVector<sv::SVAttributeAttr> svAttrs;
1395 for (
const slang::ast::AttributeSymbol *attr :
1397 StringAttr exprAttr;
1398 if (
const slang::syntax::SyntaxNode *syntax = attr->getSyntax()) {
1399 const auto &spec = syntax->as<slang::syntax::AttributeSpecSyntax>();
1401 if (spec.value->expr->kind ==
1402 slang::syntax::SyntaxKind::StringLiteralExpression) {
1403 exprAttr =
builder.getStringAttr(
1404 spec.value->expr->as<slang::syntax::LiteralExpressionSyntax>()
1405 .literal.rawText());
1407 exprAttr =
builder.getStringAttr(attr->getValue().toString(
1408 slang::SVInt::MAX_BITS));
1412 svAttrs.push_back(sv::SVAttributeAttr::get(
1416 if (!svAttrs.empty())
1422 using slang::ast::ArgumentDirection;
1423 using slang::ast::MultiPortSymbol;
1424 using slang::ast::ParameterSymbol;
1425 using slang::ast::PortSymbol;
1426 using slang::ast::TypeParameterSymbol;
1431 timeScale =
module->getTimeScale().value_or(slang::TimeScale());
1432 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1439 slot = std::make_unique<ModuleLowering>();
1440 auto &lowering = *slot;
1443 OpBuilder::InsertionGuard g(
builder);
1448 auto kind =
module->getDefinition().definitionKind;
1449 if (kind != slang::ast::DefinitionKind::Module &&
1450 kind != slang::ast::DefinitionKind::Program) {
1451 mlir::emitError(loc) <<
"unsupported definition: "
1452 <<
module->getDefinition().getKindString();
1457 auto block = std::make_unique<Block>();
1458 SmallVector<hw::ModulePort> modulePorts;
1461 unsigned int outputIdx = 0, inputIdx = 0;
1462 for (
auto *symbol : module->getPortList()) {
1463 auto handlePort = [&](
const PortSymbol &port) {
1468 auto portName =
builder.getStringAttr(port.name);
1470 std::optional<unsigned> portOutputIdx;
1471 std::optional<unsigned> portInputIdx;
1472 if (port.direction == ArgumentDirection::Out) {
1474 portOutputIdx = outputIdx++;
1478 if (port.direction != ArgumentDirection::In)
1479 type = moore::RefType::get(cast<moore::UnpackedType>(type));
1481 arg = block->addArgument(type, portLoc);
1482 portInputIdx = inputIdx++;
1484 lowering.ports.push_back(
1485 {port, portLoc, arg, portOutputIdx, portInputIdx});
1492 auto handleIfacePort = [&](
const slang::ast::InterfacePortSymbol
1495 auto [connSym, modportSym] = ifacePort.getConnection();
1496 const auto *ifaceInst =
1497 connSym ? connSym->as_if<slang::ast::InstanceSymbol>() :
nullptr;
1498 auto portPrefix = (Twine(ifacePort.name) +
"_").str();
1502 for (
const auto &member : modportSym->members()) {
1503 const auto *mpp = member.as_if<slang::ast::ModportPortSymbol>();
1510 builder.getStringAttr(Twine(portPrefix) + StringRef(mpp->name));
1513 std::optional<unsigned> ifaceOutputIdx;
1514 std::optional<unsigned> ifaceInputIdx;
1515 if (mpp->direction == ArgumentDirection::Out) {
1517 modulePorts.push_back({name, type, dir});
1518 ifaceOutputIdx = outputIdx++;
1521 if (mpp->direction != ArgumentDirection::In)
1522 type = moore::RefType::get(cast<moore::UnpackedType>(type));
1523 modulePorts.push_back({name, type, dir});
1524 arg = block->addArgument(type, portLoc);
1525 ifaceInputIdx = inputIdx++;
1527 lowering.ifacePorts.push_back(
1528 {name, dir, type, portLoc, arg, &ifacePort, mpp->internalSymbol,
1529 ifaceInst, mpp, ifaceOutputIdx, ifaceInputIdx});
1534 const auto *instSym = connSym->as_if<slang::ast::InstanceSymbol>();
1536 mlir::emitError(portLoc)
1537 <<
"unsupported interface port connection for `" << ifacePort.name
1541 for (
const auto &member : instSym->body.members()) {
1542 const slang::ast::Type *slangType =
nullptr;
1543 const slang::ast::Symbol *bodySym =
nullptr;
1544 if (
const auto *var = member.as_if<slang::ast::VariableSymbol>()) {
1545 slangType = &var->getType();
1547 }
else if (
const auto *net = member.as_if<slang::ast::NetSymbol>()) {
1548 slangType = &net->getType();
1556 auto name =
builder.getStringAttr(Twine(portPrefix) +
1557 StringRef(bodySym->name));
1558 auto refType = moore::RefType::get(cast<moore::UnpackedType>(type));
1560 auto arg = block->addArgument(refType, portLoc);
1561 lowering.ifacePorts.push_back(
1563 bodySym, instSym,
nullptr, std::nullopt, inputIdx++});
1569 if (
const auto *port = symbol->as_if<PortSymbol>()) {
1570 if (failed(handlePort(*port)))
1572 }
else if (
const auto *multiPort = symbol->as_if<MultiPortSymbol>()) {
1573 for (
auto *port : multiPort->ports)
1574 if (failed(handlePort(*port)))
1576 }
else if (
const auto *ifacePort =
1577 symbol->as_if<slang::ast::InterfacePortSymbol>()) {
1578 if (failed(handleIfacePort(*ifacePort)))
1582 <<
"unsupported module port `" << symbol->name <<
"` ("
1583 << slang::ast::toString(symbol->kind) <<
")";
1589 lowering.numExplicitOutputs = outputIdx;
1590 lowering.numExplicitInputs = inputIdx;
1593 for (
auto &hierPath :
hierPaths[module]) {
1594 assert(!hierPath.valueSyms.empty() &&
"hierPath must have valueSyms");
1595 auto hierType =
convertType(hierPath.valueSyms.front().first->getType());
1599 if (
auto hierName = hierPath.hierName) {
1601 hierType = moore::RefType::get(cast<moore::UnpackedType>(hierType));
1602 if (hierPath.direction == ArgumentDirection::Out) {
1603 hierPath.idx = outputIdx++;
1606 hierPath.idx = inputIdx++;
1610 block->addArgument(hierType, hierLoc);
1614 auto moduleType = hw::ModuleType::get(
getContext(), modulePorts);
1623 builder.setInsertionPoint(it->second);
1627 moore::SVModuleOp::create(
builder, loc, module->name, moduleType);
1630 moduleOp.getBodyRegion().push_back(block.release());
1631 lowering.op = moduleOp;
1641 for (
const auto &port : lowering.ports)
1642 lowering.portsBySyntaxNode.insert({port.ast.getSyntax(), &port.ast});
1649 auto &lowering = *
modules[module];
1652 llvm::scope_exit currentDefinitionGuard(
1656 OpBuilder::InsertionGuard g(
builder);
1657 builder.setInsertionPointToEnd(lowering.op.getBody());
1666 timeScale =
module->getTimeScale().value_or(slang::TimeScale());
1667 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1672 for (
auto &hierPath :
hierPaths[module])
1673 if (hierPath.direction == slang::ast::ArgumentDirection::In &&
1675 auto arg = lowering.op.getBody()->getArgument(*hierPath.idx);
1676 for (
auto &alias : hierPath.valueSyms)
1684 DenseMap<const slang::ast::InstanceSymbol *, InterfaceLowering *>
1687 auto getIfacePortLowering =
1693 if (
auto it = ifacePortLowerings.find(ifaceInst);
1694 it != ifacePortLowerings.end())
1697 auto lowering = std::make_unique<InterfaceLowering>();
1701 ifacePortLowerings.try_emplace(ifaceInst, ptr);
1705 for (
auto &fp : lowering.ifacePorts) {
1708 auto *valueSym = fp.bodySym->as_if<slang::ast::ValueSymbol>();
1717 portValue = moore::VariableOp::create(
1719 moore::RefType::get(cast<moore::UnpackedType>(fp.type)), fp.name,
1728 if (fp.modportPortSym)
1729 if (
auto *mppSym = fp.modportPortSym->as_if<slang::ast::ValueSymbol>())
1730 if (mppSym != valueSym)
1733 if (!fp.ifaceInstance)
1736 auto *ifaceLowering = getIfacePortLowering(fp.ifaceInstance);
1739 ifaceLowering->expandedMembers[fp.bodySym] = val;
1741 ->expandedMembersByName[
builder.getStringAttr(fp.bodySym->name)] =
1747 llvm::scope_exit predeclaredInstancesGuard(
1757 if (failed(ModulePredeclaration(*this).predeclareScope(*module,
"")))
1761 for (
auto &member : module->members()) {
1763 if (failed(member.visit(ModuleVisitor(*
this, loc))))
1775 SmallVector<Value> outputs(lowering.numExplicitOutputs);
1776 for (
auto &port : lowering.ports) {
1778 if (
auto *expr = port.ast.getInternalExpr()) {
1780 }
else if (port.ast.internalSymbol) {
1781 if (
const auto *sym =
1782 port.ast.internalSymbol->as_if<slang::ast::ValueSymbol>())
1786 return mlir::emitError(port.loc,
"unsupported port: `")
1788 <<
"` does not map to an internal symbol or expression";
1791 if (port.ast.direction == slang::ast::ArgumentDirection::Out) {
1792 if (isa<moore::RefType>(value.getType()))
1793 value = moore::ReadOp::create(
builder, value.getLoc(), value);
1794 outputs[*port.outputIdx] = value;
1800 Value portArg = port.arg;
1801 if (port.ast.direction != slang::ast::ArgumentDirection::In)
1802 portArg = moore::ReadOp::create(
builder, port.loc, port.arg);
1803 moore::ContinuousAssignOp::create(
builder, port.loc, value, portArg);
1808 for (
auto &fp : lowering.ifacePorts) {
1812 fp.bodySym ? fp.bodySym->as_if<slang::ast::ValueSymbol>() :
nullptr;
1818 outputs[*fp.outputIdx] =
1819 moore::ReadOp::create(
builder, fp.loc, ref).getResult();
1824 for (
auto &hierPath :
hierPaths[module]) {
1825 assert(!hierPath.valueSyms.empty() &&
"hierPath must have valueSyms");
1826 if (hierPath.direction != slang::ast::ArgumentDirection::Out)
1830 for (
auto &alias : hierPath.valueSyms)
1836 auto name = hierPath.hierName.getValue();
1837 if (
auto dot = name.find(
"."); dot != llvm::StringRef::npos) {
1838 auto innerName =
builder.getStringAttr(name.drop_front(dot + 1));
1839 for (
auto &member : module->members())
1840 if (
auto *inst = member.as_if<slang::ast::InstanceSymbol>())
1841 if (llvm::StringRef(inst->name.data(), inst->name.size()) ==
1842 name.take_front(dot)) {
1846 }
else if (
auto *sym =
1847 module->find(std::string_view(name.data(), name.size()))) {
1849 if (
auto *valueSym = sym->as_if<slang::ast::ValueSymbol>())
1854 return mlir::emitError(lowering.op.getLoc())
1855 <<
"unable to resolve hierarchical output `"
1856 << hierPath.hierName.getValue() <<
"` in module `" <<
module->name
1858 outputs.push_back(hierValue);
1861 moore::OutputOp::create(
builder, lowering.op.getLoc(), outputs);
1871 timeScale = package.getTimeScale().value_or(slang::TimeScale());
1872 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1876 OpBuilder::InsertionGuard g(
builder);
1879 for (
auto &member : package.members()) {
1881 if (failed(member.visit(PackageVisitor(*
this, loc))))
1892 auto &lowering =
functions[&subroutine];
1894 if (!lowering->op.getOperation())
1896 return lowering.get();
1899 if (!subroutine.thisVar) {
1901 SmallString<64> name;
1903 name += subroutine.name;
1905 SmallVector<Type, 1> noThis = {};
1912 const slang::ast::Type &thisTy = subroutine.thisVar->getType();
1913 moore::ClassDeclOp ownerDecl;
1915 if (
auto *classTy = thisTy.as_if<slang::ast::ClassType>()) {
1916 auto &ownerLowering =
classes[classTy];
1917 ownerDecl = ownerLowering->op;
1919 mlir::emitError(loc) <<
"expected 'this' to be a class type, got "
1920 << thisTy.toString();
1925 SmallString<64> qualName;
1926 qualName += ownerDecl.getSymName();
1928 qualName += subroutine.name;
1931 SmallVector<Type, 1> extraParams;
1933 auto classSym = mlir::FlatSymbolRefAttr::get(ownerDecl.getSymNameAttr());
1934 auto handleTy = moore::ClassHandleType::get(
getContext(), classSym);
1935 extraParams.push_back(handleTy);
1945 Context &
context,
const slang::ast::SubroutineSymbol &subroutine,
1946 ArrayRef<Type> prefixParams, ArrayRef<Type> suffixParams = {}) {
1947 using slang::ast::ArgumentDirection;
1949 SmallVector<Type> inputTypes;
1950 inputTypes.append(prefixParams.begin(), prefixParams.end());
1951 SmallVector<Type, 1> outputTypes;
1953 for (
const auto *arg : subroutine.getArguments()) {
1954 auto type =
context.convertType(arg->getType());
1957 if (arg->direction == ArgumentDirection::In) {
1958 inputTypes.push_back(type);
1960 inputTypes.push_back(
1961 moore::RefType::get(cast<moore::UnpackedType>(type)));
1965 inputTypes.append(suffixParams.begin(), suffixParams.end());
1967 const auto &returnType = subroutine.getReturnType();
1968 if (!returnType.isVoid()) {
1969 auto type =
context.convertType(returnType);
1972 outputTypes.push_back(type);
1975 return FunctionType::get(
context.getContext(), inputTypes, outputTypes);
1978static FailureOr<SmallVector<moore::DPIArgInfo>>
1980 const slang::ast::SubroutineSymbol &subroutine) {
1981 using slang::ast::ArgumentDirection;
1983 SmallVector<moore::DPIArgInfo> args;
1984 args.reserve(subroutine.getArguments().size() +
1985 (!subroutine.getReturnType().isVoid() ? 1 : 0));
1987 for (
const auto *arg : subroutine.getArguments()) {
1988 auto type =
context.convertType(arg->getType());
1991 moore::DPIArgDirection dir;
1992 switch (arg->direction) {
1993 case ArgumentDirection::In:
1994 dir = moore::DPIArgDirection::In;
1996 case ArgumentDirection::Out:
1997 dir = moore::DPIArgDirection::Out;
1999 case ArgumentDirection::InOut:
2000 dir = moore::DPIArgDirection::InOut;
2002 case ArgumentDirection::Ref:
2003 llvm_unreachable(
"'ref' is not legal for DPI functions");
2006 {StringAttr::get(
context.getContext(), arg->name), type, dir});
2009 if (!subroutine.getReturnType().isVoid()) {
2010 auto type =
context.convertType(subroutine.getReturnType());
2013 args.push_back({StringAttr::get(
context.getContext(),
"return"), type,
2014 moore::DPIArgDirection::Return});
2024 mlir::StringRef qualifiedName,
2025 llvm::SmallVectorImpl<Type> &extraParams) {
2029 OpBuilder::InsertionGuard g(
builder);
2035 builder.setInsertionPoint(it->second);
2040 SmallVector<Type> captureTypes;
2043 for (
auto *sym : capturesIt->second) {
2047 captureTypes.push_back(
2048 moore::RefType::get(cast<moore::UnpackedType>(type)));
2057 std::unique_ptr<FunctionLowering> lowering;
2058 Operation *insertedOp =
nullptr;
2063 auto setVisibilityAndExportAttr = [&](Operation *op) {
2066 builder.getStringAttr(dpiExportIt->second));
2067 SymbolTable::setSymbolVisibility(op, SymbolTable::Visibility::Public);
2070 SymbolTable::setSymbolVisibility(op, SymbolTable::Visibility::Private);
2072 if (!subroutine.thisVar &&
2073 subroutine.flags.has(slang::ast::MethodFlags::DPIImport)) {
2079 auto dpiOp = moore::DPIFuncOp::create(
2082 StringAttr::get(
getContext(), subroutine.name));
2083 setVisibilityAndExportAttr(dpiOp);
2084 lowering = std::make_unique<FunctionLowering>(dpiOp);
2086 }
else if (subroutine.subroutineKind == slang::ast::SubroutineKind::Task) {
2088 auto op = moore::CoroutineOp::create(
builder, loc, qualifiedName, funcTy);
2089 setVisibilityAndExportAttr(op);
2090 lowering = std::make_unique<FunctionLowering>(op);
2095 mlir::func::FuncOp::create(
builder, loc, qualifiedName, funcTy);
2096 setVisibilityAndExportAttr(funcOp);
2097 lowering = std::make_unique<FunctionLowering>(funcOp);
2098 insertedOp = funcOp;
2104 lowering->capturedSymbols.assign(capturesIt->second.begin(),
2105 capturesIt->second.end());
2110 functions[&subroutine] = std::move(lowering);
2124 auto *lowering =
functions.at(&subroutine).get();
2129 timeScale = subroutine.getTimeScale().value_or(slang::TimeScale());
2130 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
2135 if (subroutine.flags.has(slang::ast::MethodFlags::DPIImport))
2138 const bool isMethod = (subroutine.thisVar !=
nullptr);
2143 if (
const auto *classTy =
2144 subroutine.thisVar->getType().as_if<slang::ast::ClassType>()) {
2145 for (
auto &member : classTy->members()) {
2146 const auto *prop = member.as_if<slang::ast::ClassPropertySymbol>();
2149 const auto &propCanon = prop->getType().getCanonicalType();
2150 if (
const auto *vi =
2151 propCanon.as_if<slang::ast::VirtualInterfaceType>()) {
2161 SmallVector<moore::VariableOp> argVariables;
2162 auto &block = lowering->op.getFunctionBody().emplaceBlock();
2169 cast<FunctionType>(lowering->op.getFunctionType()).getInput(0);
2170 auto thisArg = block.addArgument(thisType, thisLoc);
2178 auto inputs = cast<FunctionType>(lowering->op.getFunctionType()).getInputs();
2179 auto astArgs = subroutine.getArguments();
2180 unsigned prefixCount = isMethod ? 1 : 0;
2181 auto valInputs = llvm::ArrayRef<Type>(inputs)
2182 .drop_front(prefixCount)
2183 .take_front(astArgs.size());
2185 for (
auto [astArg, type] : llvm::zip(astArgs, valInputs)) {
2187 auto blockArg = block.addArgument(type, loc);
2189 if (isa<moore::RefType>(type)) {
2192 OpBuilder::InsertionGuard g(
builder);
2193 builder.setInsertionPointToEnd(&block);
2195 auto shadowArg = moore::VariableOp::create(
2196 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
2197 StringAttr{}, blockArg);
2199 argVariables.push_back(shadowArg);
2202 const auto &argCanon = astArg->getType().getCanonicalType();
2203 if (
const auto *vi = argCanon.as_if<slang::ast::VirtualInterfaceType>())
2209 OpBuilder::InsertionGuard g(
builder);
2210 builder.setInsertionPointToEnd(&block);
2213 if (subroutine.returnValVar) {
2214 auto type =
convertType(*subroutine.returnValVar->getDeclaredType());
2217 returnVar = moore::VariableOp::create(
2218 builder, lowering->op->getLoc(),
2219 moore::RefType::get(cast<moore::UnpackedType>(type)), StringAttr{},
2221 valueSymbols.insert(subroutine.returnValVar, returnVar);
2229 for (
auto *sym : lowering->capturedSymbols) {
2233 auto refType = moore::RefType::get(cast<moore::UnpackedType>(type));
2235 auto blockArg = block.addArgument(refType, loc);
2241 llvm::scope_exit restoreThis([&] {
currentThisRef = savedThis; });
2245 llvm::scope_exit restoreFunctionLowering(
2254 if (isa<moore::CoroutineOp>(lowering->op.getOperation())) {
2255 moore::ReturnOp::create(
builder, lowering->op->getLoc());
2256 }
else if (returnVar && !subroutine.getReturnType().isVoid()) {
2258 moore::ReadOp::create(
builder, returnVar.getLoc(), returnVar);
2259 mlir::func::ReturnOp::create(
builder, lowering->op->getLoc(), read);
2261 mlir::func::ReturnOp::create(
builder, lowering->op->getLoc(),
2265 if (returnVar && returnVar.use_empty())
2266 returnVar.getDefiningOp()->erase();
2268 for (
auto var : argVariables) {
2269 if (llvm::all_of(var->getUsers(),
2270 [](
auto *user) { return isa<moore::ReadOp>(user); })) {
2271 for (
auto *user : llvm::make_early_inc_range(var->getUsers())) {
2272 user->getResult(0).replaceAllUsesWith(var.getInitial());
2284 const slang::ast::TimingControl *delay,
2287 const slang::ast::Expression *delayExpr;
2288 if (
const auto *delay3 = delay->as_if<slang::ast::Delay3Control>()) {
2289 if (delay3->expr2 || delay3->expr3)
2290 return mlir::emitError(loc) <<
"only primitives that specify a "
2291 "single delay are currently supported.";
2292 delayExpr = &delay3->expr1;
2293 }
else if (
const auto *delayControl =
2294 delay->as_if<slang::ast::DelayControl>()) {
2295 delayExpr = &delayControl->expr;
2297 llvm_unreachable(
"unexpected delay control type in primitive instance");
2300 *delayExpr, moore::TimeType::get(
getContext()));
2303 moore::DelayedContinuousAssignOp::create(
builder, loc, outputVal,
2304 assignment, delayVal);
2306 moore::ContinuousAssignOp::create(
builder, loc, outputVal, assignment);
2314 const slang::ast::PrimitiveInstanceSymbol &prim) {
2315 if (prim.getDriveStrength().first.has_value() ||
2316 prim.getDriveStrength().second.has_value())
2318 <<
"primitive instances with explicit drive strengths are not "
2321 switch (prim.primitiveType.primitiveKind) {
2322 case slang::ast::PrimitiveSymbol::PrimitiveKind::NInput:
2325 case slang::ast::PrimitiveSymbol::PrimitiveKind::NOutput:
2328 case slang::ast::PrimitiveSymbol::PrimitiveKind::Fixed:
2331 case slang::ast::PrimitiveSymbol::PrimitiveKind::UserDefined:
2336 <<
"unsupported instance of primitive `" << prim.primitiveType.name
2342 const slang::ast::PrimitiveInstanceSymbol &prim) {
2344 auto primName = prim.primitiveType.name;
2346 auto portConns = prim.getPortConnections();
2347 assert(portConns.size() >= 2 &&
2348 "n-input primitives should have at least 2 ports");
2352 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2358 SmallVector<Value> inputVals;
2359 inputVals.reserve(portConns.size() - 1);
2360 for (
const auto *inputConn : portConns.subspan(1, portConns.size() - 1)) {
2364 inputVals.push_back(inputVal);
2367 Value nextInput = inputVals.front();
2369 llvm::StringSwitch<std::function<Value()>>(prim.primitiveType.name)
2371 for (Value inputVal : llvm::drop_begin(inputVals))
2373 moore::AndOp::create(
builder, loc, nextInput, inputVal);
2377 for (Value inputVal : llvm::drop_begin(inputVals))
2379 moore::OrOp::create(
builder, loc, nextInput, inputVal);
2383 for (Value inputVal : llvm::drop_begin(inputVals))
2385 moore::XorOp::create(
builder, loc, nextInput, inputVal);
2388 .Case(
"nand", ([&] {
2389 for (Value inputVal : llvm::drop_begin(inputVals))
2391 moore::AndOp::create(
builder, loc, nextInput, inputVal);
2392 return moore::NotOp::create(
builder, loc, nextInput);
2395 for (Value inputVal : llvm::drop_begin(inputVals))
2397 moore::OrOp::create(
builder, loc, nextInput, inputVal);
2398 return moore::NotOp::create(
builder, loc, nextInput);
2400 .Case(
"xnor", ([&] {
2401 for (Value inputVal : llvm::drop_begin(inputVals))
2403 moore::XorOp::create(
builder, loc, nextInput, inputVal);
2404 return moore::NotOp::create(
builder, loc, nextInput);
2407 mlir::emitError(loc)
2408 <<
"unsupported primitive `" << primName <<
"`";
2415 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2424 const slang::ast::PrimitiveInstanceSymbol &prim) {
2426 auto primName = prim.primitiveType.name;
2428 auto portConns = prim.getPortConnections();
2429 assert(portConns.size() >= 2 &&
2430 "n-output primitives should have at least 2 ports");
2433 SmallVector<Value> outputVals;
2434 outputVals.reserve(portConns.size() - 1);
2435 for (
const auto *outputConn : portConns.subspan(0, portConns.size() - 1)) {
2436 auto &output = outputConn->as<slang::ast::AssignmentExpression>().left();
2440 outputVals.push_back(outputVal);
2448 llvm::StringSwitch<std::function<Value()>>(prim.primitiveType.name)
2450 ([&] {
return moore::NotOp::create(
builder, loc, inputVal); }))
2452 return moore::BoolCastOp::create(
builder, loc, inputVal);
2455 mlir::emitError(loc)
2456 <<
"unsupported primitive `" << primName <<
"`";
2463 for (
auto outputVal : outputVals) {
2464 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2477 const slang::ast::PrimitiveInstanceSymbol &prim) {
2478 auto primName = prim.primitiveType.name;
2483 if (primName ==
"pullup" || primName ==
"pulldown")
2486 if (primName ==
"bufif0" || primName ==
"bufif1" || primName ==
"notif0" ||
2487 primName ==
"notif1")
2490 if (primName ==
"nmos" || primName ==
"pmos" || primName ==
"rnmos" ||
2491 primName ==
"rpmos") {
2495 if (primName ==
"cmos" || primName ==
"rcmos")
2499 mlir::emitError(loc) <<
"unsupported primitive `" << primName <<
"`";
2504 const slang::ast::PrimitiveInstanceSymbol &prim) {
2505 assert((prim.primitiveType.name ==
"pullup" ||
2506 prim.primitiveType.name ==
"pulldown") &&
2507 "expected pullup or pulldown primitive");
2509 assert(!prim.getDelay() &&
2510 "SystemVerilog does not allow pull gate primitives with delays");
2512 auto primName = prim.primitiveType.name;
2514 auto portConns = prim.getPortConnections();
2516 assert(portConns.size() == 1 &&
2517 "pullup/pulldown primitives should have exactly one port");
2520 portConns.front()->as<slang::ast::AssignmentExpression>().left());
2522 auto dstType = cast<moore::RefType>(portVal.getType()).getNestedType();
2523 auto dstTypeWidth = dstType.getBitSize();
2526 "expected fixed-width type for pullup/pulldown primitive");
2527 auto constVal = primName ==
"pullup" ? -1 : 0;
2528 auto c = moore::ConstantOp::create(
2530 moore::IntType::getInt(this->
getContext(), dstTypeWidth.value()),
2536 moore::ContinuousAssignOp::create(
builder, loc, portVal, converted);
2547 auto dstIntType = cast<moore::IntType>(dstType);
2549 moore::ConstantOp::create(builder, loc, dstIntType,
FVInt::getAllX(1));
2551 moore::ConstantOp::create(builder, loc, dstIntType,
FVInt::getAllZ(1));
2553 auto isZ = moore::CaseEqOp::create(builder, loc, data, zVal);
2554 auto condOp = moore::ConditionalOp::create(builder, loc, dstType, isZ);
2555 auto &trueBlk = condOp.getTrueRegion().emplaceBlock();
2556 auto &falseBlk = condOp.getFalseRegion().emplaceBlock();
2558 OpBuilder::InsertionGuard g(builder);
2559 builder.setInsertionPointToStart(&trueBlk);
2560 moore::YieldOp::create(builder, loc, xVal);
2561 builder.setInsertionPointToStart(&falseBlk);
2562 moore::YieldOp::create(builder, loc, data);
2564 return condOp.getResult();
2568 const slang::ast::PrimitiveInstanceSymbol &prim) {
2570 auto primName = prim.primitiveType.name;
2572 auto portConns = prim.getPortConnections();
2573 assert(portConns.size() == 3 &&
2574 "Expected exactly 3 ports in three-state gate primitives");
2577 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2584 if (!inVal || !enVal)
2587 auto enType = cast<moore::IntType>(enVal.getType());
2588 [[maybe_unused]]
auto enWidth = enType.getBitSize();
2590 assert(enWidth && *enWidth == 1 &&
2591 "enable signal of a three-state gate primitive must be 1 bit");
2593 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2594 auto dstWidth = dstType.getBitSize();
2595 if (!dstWidth || *dstWidth != 1)
2596 return mlir::emitError(loc)
2597 <<
"output of a three-state gate primitive must be 1 bit";
2599 if (primName ==
"notif0" || primName ==
"notif1")
2600 inVal = moore::NotOp::create(
builder, loc, inVal);
2607 int inactiveLevel = (primName ==
"bufif1" || primName ==
"notif1") ? 0 : 1;
2608 Value inactiveConst =
2609 moore::ConstantOp::create(
builder, loc, enType, inactiveLevel,
false);
2611 auto dstIntType = cast<moore::IntType>(dstType);
2618 moore::CaseEqOp::create(
builder, loc, enVal, inactiveConst);
2620 moore::ConditionalOp::create(
builder, loc, dstType, condInactive);
2621 auto &inactiveTrue = inactiveOp.getTrueRegion().emplaceBlock();
2622 auto &inactiveFalse = inactiveOp.getFalseRegion().emplaceBlock();
2625 OpBuilder::InsertionGuard g(
builder);
2626 builder.setInsertionPointToStart(&inactiveTrue);
2627 moore::YieldOp::create(
builder, loc, zVal);
2628 builder.setInsertionPointToStart(&inactiveFalse);
2629 moore::YieldOp::create(
builder, loc,
2633 Value result = inactiveOp.getResult();
2639 const slang::ast::PrimitiveInstanceSymbol &prim) {
2641 prim.primitiveType.name ==
"nmos" || prim.primitiveType.name ==
"pmos" ||
2642 prim.primitiveType.name ==
"rnmos" || prim.primitiveType.name ==
"rpmos");
2645 auto primName = prim.primitiveType.name;
2647 auto portConns = prim.getPortConnections();
2649 assert(portConns.size() == 3 &&
"mos primitive should have exactly 3 ports");
2652 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2663 assert(cast<moore::IntType>(inputVal.getType()).getBitSize() == 1 &&
2664 "MOS switch input must be 1 bit");
2672 auto controlType = cast<moore::IntType>(control.getType());
2673 assert(controlType.getBitSize() == 1 &&
"MOS switch control must be 1 bit");
2675 int offLevel = (primName ==
"nmos" || primName ==
"rnmos") ? 0 : 1;
2676 auto offValue = moore::ConstantOp::create(
2677 builder, loc, controlType,
FVInt(1,
static_cast<uint64_t
>(offLevel)));
2679 controlIsOff = moore::CaseEqOp::create(
builder, loc, control, offValue);
2680 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2682 auto dstIntType = dyn_cast<moore::IntType>(dstType);
2683 if (!dstIntType || dstIntType.getBitSize() != 1)
2684 return mlir::emitError(loc) <<
"MOS switch output must be 1 bit";
2687 if (!convertedInput)
2694 moore::ConditionalOp::create(
builder, loc, dstType, controlIsOff);
2696 auto &trueBlock = condOp.getTrueRegion().emplaceBlock();
2697 auto &falseBlock = condOp.getFalseRegion().emplaceBlock();
2699 builder.setInsertionPointToStart(&trueBlock);
2700 moore::YieldOp::create(
builder, loc, zVal);
2702 builder.setInsertionPointToStart(&falseBlock);
2703 moore::YieldOp::create(
builder, loc, convertedInput);
2705 builder.setInsertionPointAfter(condOp);
2708 prim.getDelay(), loc);
2712 const slang::ast::PrimitiveInstanceSymbol &prim) {
2713 assert(prim.primitiveType.name ==
"cmos" ||
2714 prim.primitiveType.name ==
"rcmos");
2717 auto portConns = prim.getPortConnections();
2718 assert(portConns.size() == 4 &&
"cmos primitive should have exactly 4 ports");
2721 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2730 assert(cast<moore::IntType>(dataVal.getType()).getBitSize() == 1 &&
2731 "CMOS switch input must be 1 bit");
2736 assert(cast<moore::IntType>(ncontrolVal.getType()).getBitSize() == 1 &&
2737 "CMOS switch ncontrol must be 1 bit");
2742 assert(cast<moore::IntType>(pcontrolVal.getType()).getBitSize() == 1 &&
2743 "CMOS switch pcontrol must be 1 bit");
2745 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2746 auto dstIntType = dyn_cast<moore::IntType>(dstType);
2747 if (!dstIntType || dstIntType.getBitSize() != 1)
2748 return mlir::emitError(loc) <<
"CMOS switch output must be 1 bit";
2754 auto logicType = moore::IntType::getLogic(
getContext(), 1);
2756 auto makeConst = [&](
FVInt val) -> Value {
2757 Value c = moore::ConstantOp::create(
builder, loc, logicType, val);
2765 auto makeLevelConstant = [&](Value value,
int level) -> Value {
2766 auto type = cast<moore::IntType>(value.getType());
2767 return moore::ConstantOp::create(
builder, loc, type,
2768 FVInt(1,
static_cast<uint64_t
>(level)));
2771 auto muxZOrData = [&](Value cond) -> Value {
2772 auto condOp = moore::ConditionalOp::create(
builder, loc, dstType, cond);
2773 auto &trueBlk = condOp.getTrueRegion().emplaceBlock();
2774 auto &falseBlk = condOp.getFalseRegion().emplaceBlock();
2775 builder.setInsertionPointToStart(&trueBlk);
2776 moore::YieldOp::create(
builder, loc, zVal);
2777 builder.setInsertionPointToStart(&falseBlk);
2778 moore::YieldOp::create(
builder, loc, convertedData);
2779 builder.setInsertionPointAfter(condOp);
2780 return condOp.getResult();
2784 auto nOff = makeLevelConstant(ncontrolVal, 0);
2785 auto nIsOff = moore::CaseEqOp::create(
builder, loc, ncontrolVal, nOff);
2786 Value nResult = muxZOrData(nIsOff);
2789 auto pOff = makeLevelConstant(pcontrolVal, 1);
2790 auto pIsOff = moore::CaseEqOp::create(
builder, loc, pcontrolVal, pOff);
2791 Value pResult = muxZOrData(pIsOff);
2793 auto agree = moore::CaseEqOp::create(
builder, loc, nResult, pResult);
2794 auto nIsZ = moore::CaseEqOp::create(
builder, loc, nResult, zVal);
2795 auto pIsZ = moore::CaseEqOp::create(
builder, loc, pResult, zVal);
2797 auto outerCond = moore::ConditionalOp::create(
builder, loc, dstType, agree);
2798 auto &outerTrue = outerCond.getTrueRegion().emplaceBlock();
2799 auto &outerFalse = outerCond.getFalseRegion().emplaceBlock();
2802 OpBuilder::InsertionGuard guard(
builder);
2803 builder.setInsertionPointToStart(&outerTrue);
2804 moore::YieldOp::create(
builder, loc, nResult);
2806 builder.setInsertionPointToStart(&outerFalse);
2807 auto middleCond = moore::ConditionalOp::create(
builder, loc, dstType, nIsZ);
2808 auto &middleTrue = middleCond.getTrueRegion().emplaceBlock();
2809 auto &middleFalse = middleCond.getFalseRegion().emplaceBlock();
2810 moore::YieldOp::create(
builder, loc, middleCond.getResult());
2812 builder.setInsertionPointToStart(&middleTrue);
2813 moore::YieldOp::create(
builder, loc, pResult);
2815 builder.setInsertionPointToStart(&middleFalse);
2816 auto innerCond = moore::ConditionalOp::create(
builder, loc, dstType, pIsZ);
2817 auto &innerTrue = innerCond.getTrueRegion().emplaceBlock();
2818 auto &innerFalse = innerCond.getFalseRegion().emplaceBlock();
2820 builder.setInsertionPointToStart(&innerTrue);
2821 moore::YieldOp::create(
builder, loc, nResult);
2822 builder.setInsertionPointToStart(&innerFalse);
2823 moore::YieldOp::create(
builder, loc, xVal);
2825 builder.setInsertionPointAfter(innerCond);
2826 moore::YieldOp::create(
builder, loc, innerCond.getResult());
2830 prim.getDelay(), loc);
2838enum class UdpLevel {
2849 SmallVector<UdpLevel> inputs;
2860 SmallVector<UdpLevel> inputs;
2867struct SequentialTableInfo {
2869 SmallVector<AsyncRow> asyncRows;
2871 SmallVector<SyncRow> syncRows;
2873 llvm::SmallDenseSet<size_t, 4> asyncPortIndices;
2884struct AsyncConditions {
2901 switch (llvm::toLower(c)) {
2903 return UdpLevel::Zero;
2905 return UdpLevel::One;
2907 return UdpLevel::Unknown;
2912 return UdpLevel::DontCare;
2914 return std::nullopt;
2922 levels.reserve(inputs.size());
2923 for (
char c : inputs) {
2927 levels.push_back(*level);
2935 const slang::ast::PrimitiveSymbol::TableEntry &entry,
2936 ArrayRef<UdpLevel> levels,
size_t numInputs) {
2941 if (entry.output !=
'1' || levels.size() != numInputs ||
2942 entry.isEdgeSensitive)
2944 return llvm::any_of(levels, [](UdpLevel level) {
2946 case UdpLevel::Zero:
2948 case UdpLevel::DontCare:
2950 case UdpLevel::Unknown:
2959 Value val, Value ¬Val) {
2963 case UdpLevel::Zero:
2965 notVal = moore::NotOp::create(builder, loc, val);
2967 case UdpLevel::DontCare:
2969 case UdpLevel::Unknown:
2970 llvm_unreachable(
"unknown level should be filtered before building term");
2977 ArrayRef<UdpLevel> inputs,
2978 ValueRange inputVals,
2979 SmallVectorImpl<Value> ¬Vars) {
2981 for (
size_t i = 0, e = inputVals.size(); i < e; ++i) {
2985 term = term ? moore::AndOp::create(builder, loc, term,
lit) :
lit;
3046 size_t numInputs, Location loc,
3047 SequentialTableInfo &info) {
3048 SmallVector<AsyncRow> rawLevelRows;
3049 std::optional<size_t> edgePortIdx;
3051 for (
const auto &row : primitiveType.table) {
3056 if (row.output ==
'x')
3058 if (row.state ==
'x')
3060 if (llvm::any_of(row.inputs, [](
char c) { return c ==
'x'; }))
3066 if (row.output ==
'-' || row.state == row.output)
3069 assert((row.output ==
'0' || row.output ==
'1') &&
3070 "active UDP transition must specify binary output '0' or '1'");
3073 assert(stateLevel &&
"unexpected sequential UDP state symbol");
3074 if (*stateLevel == UdpLevel::Unknown)
3077 if (!row.isEdgeSensitive) {
3078 SmallVector<UdpLevel> inputs;
3080 llvm_unreachable(
"unexpected token in level-sensitive UDP row");
3081 assert(inputs.size() == numInputs &&
3082 "level-sensitive UDP row input count must match numInputs");
3083 rawLevelRows.push_back(
3084 {std::move(inputs), *stateLevel, row.output ==
'1'});
3088 SmallVector<UdpLevel> inputLevels(numInputs, UdpLevel::DontCare);
3089 std::optional<size_t> edgeIdx;
3090 StringRef inputs = row.inputs;
3091 for (
size_t i = 0; i < numInputs; ++i) {
3092 assert(!inputs.empty() &&
"UDP row token count must match numInputs");
3093 if (inputs.front() ==
'(') {
3096 assert(inputs.size() >= 4 && inputs[3] ==
')' && !edgeIdx.has_value() &&
3097 "expected single well-formed parenthesized edge token");
3099 inputs = inputs.drop_front(4);
3102 char c = inputs.front();
3103 inputs = inputs.drop_front(1);
3105 assert(*level != UdpLevel::Unknown &&
3106 "rows with 'x' inputs should already be skipped");
3107 inputLevels[i] = *level;
3110 assert((c ==
'r' || c ==
'f' || c ==
'p' || c ==
'n' || c ==
'*') &&
3111 "unexpected UDP input symbol");
3112 assert(!edgeIdx.has_value() &&
3113 "at most one edge transition per table row");
3117 assert(inputs.empty() && edgeIdx.has_value() &&
3118 "edge-sensitive row must consume all inputs and have an edge");
3123 if (!edgePortIdx.has_value()) {
3124 edgePortIdx = edgeIdx;
3125 }
else if (*edgePortIdx != *edgeIdx) {
3126 return mlir::emitError(loc)
3127 <<
"unsupported sequential UDP `" << primitiveType.name
3128 <<
"` with multiple distinct edge-sensitive signals";
3131 info.syncRows.push_back({std::move(inputLevels), *stateLevel});
3139 if (edgePortIdx.has_value()) {
3140 size_t clkIdx = *edgePortIdx;
3141 SmallVector<AsyncRow> mergedLevelRows;
3142 for (
auto &asyncRow : rawLevelRows) {
3144 llvm::find_if(mergedLevelRows, [&](
const AsyncRow &existing) {
3145 if (existing.output != asyncRow.output ||
3146 existing.state != asyncRow.state)
3148 return llvm::all_of(
3149 llvm::enumerate(asyncRow.inputs), [&](
const auto &item) {
3150 return item.index() == clkIdx ||
3151 existing.inputs[item.index()] == item.value();
3155 if (matchIt == mergedLevelRows.end()) {
3156 mergedLevelRows.push_back(std::move(asyncRow));
3157 }
else if (matchIt->inputs[clkIdx] != asyncRow.inputs[clkIdx]) {
3158 matchIt->inputs[clkIdx] = UdpLevel::DontCare;
3161 rawLevelRows = std::move(mergedLevelRows);
3164 for (
auto &asyncRow : rawLevelRows) {
3165 if (edgePortIdx.has_value()) {
3176 if (asyncRow.inputs[*edgePortIdx] != UdpLevel::DontCare) {
3177 return mlir::emitError(loc)
3178 <<
"sequential UDP `" << primitiveType.name
3179 <<
"` specifies input `"
3180 << primitiveType.ports[*edgePortIdx + 1]->name
3181 <<
"` with both edge and level sensitivity; mixed "
3182 "latch/flip-flop models are not supported";
3188 if (asyncRow.state != UdpLevel::DontCare) {
3189 return mlir::emitError(loc)
3190 <<
"sequential UDP `" << primitiveType.name
3191 <<
"` specifies asynchronous row depending on internal state; "
3192 "feedback loops in asynchronous control are not supported";
3197 for (
auto [i, level] : llvm::enumerate(asyncRow.inputs)) {
3198 if (i != *edgePortIdx && level != UdpLevel::DontCare)
3199 info.asyncPortIndices.insert(i);
3202 info.asyncRows.push_back(std::move(asyncRow));
3206 if (edgePortIdx.has_value()) {
3212 for (
size_t aIdx : info.asyncPortIndices) {
3213 bool variesInSync =
false;
3214 std::optional<UdpLevel> firstSyncLevel;
3215 for (
const auto &srow : info.syncRows) {
3216 UdpLevel l = srow.inputs[aIdx];
3217 if (l == UdpLevel::Zero || l == UdpLevel::One) {
3218 if (!firstSyncLevel)
3220 else if (*firstSyncLevel != l)
3221 variesInSync =
true;
3225 return mlir::emitError(loc)
3226 <<
"sequential UDP `" << primitiveType.name
3227 <<
"` specifies asynchronous control on data input port; "
3228 "only dedicated clear/preset lines are supported";
3236 for (
const auto &asyncRow : info.asyncRows) {
3237 for (
const auto &srow : info.syncRows) {
3238 bool matchesAny =
false;
3239 bool contradicts =
false;
3240 for (
size_t aIdx : info.asyncPortIndices) {
3241 if (asyncRow.inputs[aIdx] == UdpLevel::DontCare ||
3242 srow.inputs[aIdx] == UdpLevel::DontCare)
3244 if (srow.inputs[aIdx] == asyncRow.inputs[aIdx])
3249 if (matchesAny && !contradicts) {
3250 return mlir::emitError(loc)
3251 <<
"sequential UDP `" << primitiveType.name
3252 <<
"` defines synchronous transitions conditioned on "
3253 "active asynchronous clear/preset";
3273 ArrayRef<AsyncRow> asyncRows,
3274 ArrayRef<Value> inputVals,
3275 Value qVal, moore::IntType i1Ty) {
3276 AsyncConditions result;
3277 SmallVector<Value> notVars(inputVals.size(), Value{});
3279 for (
const auto &asyncRow : asyncRows) {
3282 if (Value stateLit =
3285 term ? moore::AndOp::create(builder, loc, term, stateLit) : stateLit;
3287 term = moore::ConstantOp::create(builder, loc, i1Ty, 1,
false);
3288 if (!asyncRow.output) {
3291 ? moore::OrOp::create(builder, loc, result.clearCond, term)
3296 ? moore::OrOp::create(builder, loc, result.presetCond, term)
3301 if (result.clearCond && result.presetCond) {
3303 moore::OrOp::create(builder, loc, result.clearCond, result.presetCond);
3304 result.asyncVal = result.presetCond;
3305 }
else if (result.clearCond) {
3306 result.asyncCond = result.clearCond;
3307 result.asyncVal = moore::ConstantOp::create(builder, loc, i1Ty, 0,
false);
3308 }
else if (result.presetCond) {
3309 result.asyncCond = result.presetCond;
3310 result.asyncVal = moore::ConstantOp::create(builder, loc, i1Ty, 1,
false);
3318 Location loc, Value asyncCond,
3319 Value asyncVal, Value qVar) {
3320 auto procOp = moore::ProcedureOp::create(builder, loc,
3321 moore::ProcedureKind::AlwaysLatch);
3322 OpBuilder::InsertionGuard guard(builder);
3323 auto &entryBlock = procOp.getBody().emplaceBlock();
3324 builder.setInsertionPointToEnd(&entryBlock);
3326 Value acondI1 =
context.convertToI1(asyncCond);
3327 Block &trueBlock = procOp.getBody().emplaceBlock();
3328 Block &exitBlock = procOp.getBody().emplaceBlock();
3330 mlir::cf::CondBranchOp::create(builder, loc, acondI1, &trueBlock, &exitBlock);
3331 builder.setInsertionPointToEnd(&trueBlock);
3332 moore::BlockingAssignOp::create(builder, loc, qVar, asyncVal);
3333 mlir::cf::BranchOp::create(builder, loc, &exitBlock);
3335 builder.setInsertionPointToEnd(&exitBlock);
3336 moore::ReturnOp::create(builder, loc);
3340 moore::SVModuleOp moduleOp,
const slang::ast::PrimitiveSymbol &primitive) {
3342 auto *block = &moduleOp.getBodyRegion().front();
3343 builder.setInsertionPointToEnd(block);
3345 auto inputArgs = block->getArguments();
3346 size_t numInputs = inputArgs.size();
3350 SequentialTableInfo table;
3354 if (!table.syncRows.empty()) {
3355 return mlir::emitError(loc)
3356 <<
"edge-sensitive sequential user-defined primitives are not "
3361 auto i1Ty = moore::IntType::getInt(
getContext(), 1);
3362 auto i1RefTy = moore::RefType::get(i1Ty);
3364 if (primitive.initVal && primitive.initVal->isInteger()) {
3365 const auto &svInt = primitive.initVal->integer();
3366 if (!svInt.hasUnknown())
3367 initVal = moore::ConstantOp::create(
builder, loc, i1Ty,
3368 svInt == 1 ? 1 : 0,
false);
3370 StringAttr qName =
builder.getStringAttr(primitive.ports[0]->name);
3371 auto qVar = moore::VariableOp::create(
builder, loc, i1RefTy, qName, initVal);
3374 SmallVector<Value> seqInputVals;
3375 seqInputVals.reserve(numInputs);
3376 for (Value arg : inputArgs) {
3380 seqInputVals.push_back(boolVal);
3384 bool usesState = llvm::any_of(table.syncRows,
3385 [](
const SyncRow &r) {
3386 return r.state != UdpLevel::DontCare;
3388 llvm::any_of(table.asyncRows, [](
const AsyncRow &r) {
3389 return r.state != UdpLevel::DontCare;
3393 qVal = moore::ReadOp::create(
builder, loc, qVar);
3397 builder, loc, table.asyncRows, seqInputVals, qVal, i1Ty);
3400 if (asyncConditions.asyncCond) {
3402 asyncConditions.asyncCond,
3403 asyncConditions.asyncVal, qVar);
3404 qOut = moore::ReadOp::create(
builder, loc, qVar);
3406 return mlir::emitError(loc)
3407 <<
"unsupported sequential UDP `" << primitive.name
3408 <<
"` without active transitions";
3411 auto l1Ty = moore::IntType::getLogic(
getContext(), 1);
3416 moore::OutputOp::create(
builder, loc, converted);
3421 const slang::ast::PrimitiveSymbol &primitive) {
3423 if (
auto moduleOp =
symbolTable.lookup<moore::SVModuleOp>(primitive.name))
3429 assert(primitive.ports.size() >= 2 &&
3430 "user-defined primitives must have at least 2 ports");
3434 OpBuilder::InsertionGuard guard(
builder);
3437 auto l1Ty = moore::IntType::getLogic(
getContext(), 1);
3438 SmallVector<hw::ModulePort> modulePorts;
3439 modulePorts.reserve(primitive.ports.size());
3440 modulePorts.push_back({
builder.getStringAttr(primitive.ports[0]->name), l1Ty,
3442 for (
const auto *port : primitive.ports.subspan(1))
3443 modulePorts.push_back(
3452 builder.setInsertionPoint(upperIt->second);
3454 moore::SVModuleOp::create(
builder, loc, primitive.name,
3455 hw::ModuleType::get(
getContext(), modulePorts));
3456 auto *block =
builder.createBlock(&moduleOp.getBodyRegion());
3457 for (
const auto *port : primitive.ports.subspan(1))
3462 if (primitive.isSequential)
3465 auto inputVals = block->getArguments();
3466 size_t numInputs = inputVals.size();
3469 SmallVector<Value> notVars(numInputs, Value{});
3474 SmallVector<UdpLevel> levels;
3475 for (
const auto &entry : primitive.table) {
3482 sum = moore::ConstantOp::create(
builder, loc, l1Ty, 1);
3485 sum = sum ? moore::OrOp::create(
builder, loc, sum, term) : term;
3488 sum = moore::ConstantOp::create(
builder, loc, l1Ty, 0);
3490 moore::OutputOp::create(
builder, loc, sum);
3495 const slang::ast::PrimitiveInstanceSymbol &prim) {
3497 auto portConns = prim.getPortConnections();
3498 assert(portConns.size() >= 2 &&
3499 "user-defined primitives should have at least 2 ports");
3501 size_t numInputs = portConns.size() - 1;
3505 portConns[0]->as<slang::ast::AssignmentExpression>().left();
3511 auto l1Ty = moore::IntType::getLogic(
getContext(), 1);
3512 SmallVector<Value> inputVals;
3513 inputVals.reserve(numInputs);
3514 for (
const auto *inputConn : portConns.subspan(1, numInputs)) {
3521 inputVals.push_back(converted);
3526 FailureOr<moore::SVModuleOp> moduleOpOrFailure =
3528 if (failed(moduleOpOrFailure))
3530 moore::SVModuleOp moduleOp = *moduleOpOrFailure;
3531 hw::ModuleType moduleType = moduleOp.getModuleType();
3532 auto inputNames =
builder.getArrayAttr(moduleType.getInputNames());
3533 auto outputNames =
builder.getArrayAttr(moduleType.getOutputNames());
3534 auto inst = moore::InstanceOp::create(
3535 builder, loc, moduleType.getOutputTypes(),
3536 builder.getStringAttr(prim.name),
3537 FlatSymbolRefAttr::get(moduleOp.getSymNameAttr()), inputVals, inputNames,
3541 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
3554mlir::StringAttr fullyQualifiedClassName(
Context &ctx,
3555 const slang::ast::Type &ty) {
3556 SmallString<64> name;
3557 SmallVector<llvm::StringRef, 8> parts;
3559 const slang::ast::Scope *scope = ty.getParentScope();
3561 const auto &sym = scope->asSymbol();
3563 case slang::ast::SymbolKind::Root:
3566 case slang::ast::SymbolKind::InstanceBody:
3567 case slang::ast::SymbolKind::Instance:
3568 case slang::ast::SymbolKind::Package:
3569 case slang::ast::SymbolKind::ClassType:
3570 if (!sym.name.empty())
3571 parts.push_back(sym.name);
3576 scope = sym.getParentScope();
3579 for (
auto p : llvm::reverse(parts)) {
3584 return mlir::StringAttr::get(ctx.
getContext(), name);
3589std::pair<mlir::SymbolRefAttr, mlir::ArrayAttr>
3591 const slang::ast::ClassType &cls) {
3595 mlir::SymbolRefAttr base;
3596 if (
const auto *b = cls.getBaseClass())
3597 base = mlir::SymbolRefAttr::get(fullyQualifiedClassName(
context, *b));
3600 SmallVector<mlir::Attribute> impls;
3601 if (
auto ifaces = cls.getDeclaredInterfaces(); !ifaces.empty()) {
3602 impls.reserve(ifaces.size());
3603 for (
const auto *iface : ifaces)
3604 impls.push_back(mlir::FlatSymbolRefAttr::get(
3605 fullyQualifiedClassName(
context, *iface)));
3608 mlir::ArrayAttr implArr =
3609 impls.empty() ? mlir::ArrayAttr() : mlir::ArrayAttr::
get(ctx, impls);
3611 return {base, implArr};
3616struct ClassDeclVisitorBase {
3619 ClassLowering &classLowering;
3621 ClassDeclVisitorBase(Context &ctx, ClassLowering &lowering)
3622 :
context(ctx), builder(ctx.builder), classLowering(lowering) {}
3626 return context.convertLocation(sloc);
3632struct ClassPropertyVisitor : ClassDeclVisitorBase {
3633 using ClassDeclVisitorBase::ClassDeclVisitorBase;
3636 LogicalResult
run(
const slang::ast::ClassType &classAST) {
3637 if (!classLowering.
op.getBody().empty())
3640 OpBuilder::InsertionGuard ig(builder);
3642 Block *body = &classLowering.
op.getBody().emplaceBlock();
3643 builder.setInsertionPointToEnd(body);
3646 for (
const auto &mem : classAST.members()) {
3647 if (
const auto *prop = mem.as_if<slang::ast::ClassPropertySymbol>()) {
3648 if (failed(prop->visit(*
this)))
3657 LogicalResult visit(
const slang::ast::ClassPropertySymbol &prop) {
3659 auto ty =
context.convertType(prop.getType());
3663 if (prop.lifetime == slang::ast::VariableLifetime::Automatic) {
3664 moore::ClassPropertyDeclOp::create(builder, loc, prop.name,
3673 if (!
context.globalVariables.lookup(&prop))
3674 return context.convertGlobalVariable(prop);
3679 LogicalResult visit(
const slang::ast::ClassType &cls) {
3680 return context.buildClassProperties(cls);
3684 template <
typename T>
3685 LogicalResult visit(T &&) {
3692struct ClassMethodVisitor : ClassDeclVisitorBase {
3693 using ClassDeclVisitorBase::ClassDeclVisitorBase;
3696 LogicalResult
run(
const slang::ast::ClassType &classAST) {
3700 if (classLowering.
op.getBody().empty())
3703 OpBuilder::InsertionGuard ig(builder);
3704 builder.setInsertionPointToEnd(&classLowering.
op.getBody().front());
3707 for (
const auto &mem : classAST.members()) {
3708 if (failed(mem.visit(*
this)))
3717 LogicalResult visit(
const slang::ast::ClassPropertySymbol &) {
3723 LogicalResult visit(
const slang::ast::ParameterSymbol &) {
return success(); }
3727 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
3733 LogicalResult visit(
const slang::ast::TypeAliasType &) {
return success(); }
3736 LogicalResult visit(
const slang::ast::GenericClassDefSymbol &) {
3741 LogicalResult visit(
const slang::ast::TransparentMemberSymbol &) {
3746 LogicalResult visit(
const slang::ast::EmptyMemberSymbol &) {
3751 LogicalResult visit(
const slang::ast::SubroutineSymbol &fn) {
3752 if (fn.flags & slang::ast::MethodFlags::BuiltIn) {
3753 static bool remarkEmitted =
false;
3757 mlir::emitRemark(classLowering.
op.getLoc())
3758 <<
"Class builtin functions (needed for randomization, constraints, "
3759 "and covergroups) are not yet supported and will be dropped "
3761 remarkEmitted =
true;
3765 const mlir::UnitAttr isVirtual =
3766 (fn.flags & slang::ast::MethodFlags::Virtual)
3767 ? UnitAttr::get(
context.getContext())
3774 if (fn.flags & slang::ast::MethodFlags::Pure) {
3776 SmallVector<Type, 1> extraParams;
3778 mlir::FlatSymbolRefAttr::get(classLowering.
op.getSymNameAttr());
3780 moore::ClassHandleType::get(
context.getContext(), classSym);
3781 extraParams.push_back(handleTy);
3785 mlir::emitError(loc) <<
"Invalid function signature for " << fn.name;
3789 moore::ClassMethodDeclOp::create(builder, loc, fn.name,
3790 {}, funcTy,
nullptr);
3794 auto *lowering =
context.declareFunction(fn);
3803 FunctionType fnTy = cast<FunctionType>(lowering->op.getFunctionType());
3805 moore::ClassMethodDeclOp::create(
3806 builder, loc, fn.name, {}, fnTy,
3807 SymbolRefAttr::get(lowering->op.getNameAttr()));
3824 LogicalResult visit(
const slang::ast::MethodPrototypeSymbol &fn) {
3825 const auto *externImpl = fn.getSubroutine();
3829 <<
"Didn't find an implementation matching the forward declaration "
3834 return visit(*externImpl);
3838 LogicalResult visit(
const slang::ast::ClassType &cls) {
3839 if (failed(
context.buildClassProperties(cls)))
3841 return context.materializeClassMethods(cls);
3845 template <
typename T>
3846 LogicalResult visit(T &&node) {
3847 Location loc = UnknownLoc::get(
context.getContext());
3848 if constexpr (
requires { node.location; })
3850 mlir::emitError(loc) <<
"unsupported construct in ClassType members: "
3851 << slang::ast::toString(node.kind);
3859 auto &lowering =
classes[&cls];
3861 return lowering.get();
3862 lowering = std::make_unique<ClassLowering>();
3867 OpBuilder::InsertionGuard g(
builder);
3873 builder.setInsertionPoint(it->second);
3875 auto symName = fullyQualifiedClassName(*
this, cls);
3877 auto [base, impls] = buildBaseAndImplementsAttrs(*
this, cls);
3878 auto classDeclOp = moore::ClassDeclOp::create(
3879 builder, loc, symName, {}, base, impls);
3881 SymbolTable::setSymbolVisibility(classDeclOp,
3882 SymbolTable::Visibility::Public);
3884 lowering->op = classDeclOp;
3887 return lowering.get();
3894 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
3895 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
3902 if (classdecl.getBaseClass()) {
3903 if (
const auto *baseClassDecl =
3904 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
3915 return ClassPropertyVisitor(*
this, *lowering).run(classdecl);
3922 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
3923 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
3926 auto *lowering =
classes[&classdecl].get();
3933 if (classdecl.getBaseClass()) {
3934 if (
const auto *baseClassDecl =
3935 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
3941 return ClassMethodVisitor(*
this, *lowering).run(classdecl);
3951 OpBuilder::InsertionGuard g(
builder);
3957 builder.setInsertionPoint(it->second);
3961 SmallString<64> symName;
3965 if (
const auto *classVar = var.as_if<slang::ast::ClassPropertySymbol>()) {
3966 if (
const auto *parentScope = classVar->getParentScope()) {
3967 if (
const auto *parentClass =
3968 parentScope->asSymbol().as_if<slang::ast::ClassType>())
3969 symName = fullyQualifiedClassName(*
this, *parentClass);
3971 mlir::emitError(loc)
3972 <<
"Could not access parent class of class property "
3977 mlir::emitError(loc) <<
"Could not get parent scope of class property "
3982 symName += var.name;
3985 symName += var.name;
3994 auto varOp = moore::GlobalVariableOp::create(
builder, loc, symName,
3996 cast<moore::UnpackedType>(type));
4007 if (var.getInitializer())
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Location convertLocation(MLIRContext *context, const slang::SourceManager &sourceManager, slang::SourceLocation loc)
Convert a slang SourceLocation to an MLIR Location.
false return failure()
Parse an optional keyword or string and set instance into 'result'.
static Value collapseZToX(OpBuilder &builder, Location loc, Value data, Type dstType)
Yields data unless it is exactly Z, in which case yields X instead.
static moore::ProcedureKind convertProcedureKind(slang::ast::ProceduralBlockKind kind)
static std::optional< UdpLevel > decodeUdpLevel(char c)
Decode a single UDP level character (0, 1, x, ?, or b, case-insensitive).
static Value buildProductiveTerm(OpBuilder &builder, Location loc, ArrayRef< UdpLevel > inputs, ValueRange inputVals, SmallVectorImpl< Value > ¬Vars)
Build the productive AND-term for this row.
static bool skipUnsupportedCombinationalRow(const slang::ast::PrimitiveSymbol::TableEntry &entry, ArrayRef< UdpLevel > levels, size_t numInputs)
Skip unsupported or non-productive combinational table rows.
static LogicalResult classifySequentialTableRows(const slang::ast::PrimitiveSymbol &primitiveType, size_t numInputs, Location loc, SequentialTableInfo &info)
Classify sequential UDP truth table rows into synchronous (edge-sensitive) transitions and asynchrono...
static Value buildLevelLiteral(OpBuilder &builder, Location loc, UdpLevel level, Value val, Value ¬Val)
Materialize a 2-state literal (val for One, ~val for Zero) or null for DontCare, caching the negation...
static bool parseInputRow(StringRef inputs, SmallVectorImpl< UdpLevel > &levels)
Parse a level-only UDP input row string into UdpLevel entries.
static FailureOr< SmallVector< moore::DPIArgInfo > > getDPISignature(Context &context, const slang::ast::SubroutineSymbol &subroutine)
static void guessNamespacePrefix(const slang::ast::Symbol &symbol, SmallString< 64 > &prefix)
static constexpr StringLiteral dpiExportAttrName
static FunctionType getFunctionSignature(Context &context, const slang::ast::SubroutineSymbol &subroutine, ArrayRef< Type > prefixParams, ArrayRef< Type > suffixParams={})
Helper function to generate the function signature from a SubroutineSymbol and optional extra argumen...
static void recordDPIExportDirectives(Context &context, const slang::ast::Scope &scope, const slang::syntax::SyntaxNode *syntax)
Record export "DPI-C" directives in the given scope so that callable declarations can be tagged with ...
static AsyncConditions buildAsyncConditions(OpBuilder &builder, Location loc, ArrayRef< AsyncRow > asyncRows, ArrayRef< Value > inputVals, Value qVal, moore::IntType i1Ty)
Construct boolean conditions from level-sensitive (AsyncRow) rows by partitioning them into rows driv...
static void emitSequentialLevelSensitiveProcedure(Context &context, OpBuilder &builder, Location loc, Value asyncCond, Value asyncVal, Value qVar)
Emit a level-sensitive moore.procedure always_latch for a latch UDP.
static moore::NetKind convertNetKind(slang::ast::NetType::NetKind kind)
Four-valued arbitrary precision integers.
static FVInt getAllZ(unsigned numBits)
Construct an FVInt with all bits set to Z.
static FVInt getAllX(unsigned numBits)
Construct an FVInt with all bits set to X.
const slang::ast::InstanceBodySymbol * getCanonicalBody(const slang::ast::InstanceSymbol &inst)
Get the slang canonical body for the given instance, if there is one.
CaptureMap analyzeFunctionCaptures(const slang::ast::RootSymbol &root, SmallVectorImpl< AmbiguousHierCapture > &ambiguous)
Analyze the AST rooted at root to determine which variables each function captures: symbols reference...
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
@ TwoValued
Two-valued types such as bit or int.
void setSVAttributes(mlir::Operation *op, mlir::ArrayAttr attrs)
Set the SV attributes of an operation.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
int run(Type[Generator] generator=CppGenerator, List[str] cmdline_args=sys.argv)
circt::moore::ClassDeclOp op
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
FunctionLowering * declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine, mlir::StringRef qualifiedName, llvm::SmallVectorImpl< Type > &extraParams)
Helper function to extract the commonalities in lowering of functions and methods.
ModuleLowering * convertModuleHeader(const slang::ast::InstanceBodySymbol *module)
Convert a module and its ports to an empty module op in the IR.
std::queue< const slang::ast::SubroutineSymbol * > functionWorklist
A list of functions for which the declaration has been created, but the body has not been defined yet...
void populateSampledValueClocks()
Generates a map from sampled value system calls to clocks using Slang's analysis.
Value convertLvalueExpression(const slang::ast::Expression &expr)
LogicalResult registerVirtualInterfaceMembers(const slang::ast::ValueSymbol &base, const slang::ast::VirtualInterfaceType &type, Location loc)
Register the interface members of a virtual interface base symbol for use in later expression convers...
const slang::ast::DefinitionSymbol * currentDefinition
The definition symbol of the module body currently being converted.
LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module)
Convert a module's body to the corresponding IR ops.
FailureOr< moore::SVModuleOp > convertSequentialUserDefinedPrimitiveDef(moore::SVModuleOp moduleOp, const slang::ast::PrimitiveSymbol &primitive)
LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl)
DenseMap< const slang::ast::ValueSymbol *, moore::GlobalVariableOp > globalVariables
A table of defined global variables that may be referred to by name in expressions.
slang::ast::Compilation & compilation
LogicalResult flushPendingMonitors()
Process any pending $monitor calls and generate the monitoring procedures at module level.
LogicalResult convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
LogicalResult assignPrimOutputWithDelay(Value outputVal, Value assignment, const slang::ast::TimingControl *delay, Location loc)
Creates a delayed assignment based on the given TimingControl delay (or without a delay if the Timing...
OpBuilder builder
The builder used to create IR operations.
std::queue< const slang::ast::InstanceBodySymbol * > moduleWorklist
A list of modules for which the header has been created, but the body has not been converted yet.
LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var)
Convert a variable to a moore.global_variable operation.
DenseSet< const slang::ast::InstanceSymbol * > predeclaredInstances
Module instances already emitted by the predeclaration pass.
CaptureMap functionCaptures
Pre-computed capture analysis: maps each function to the set of non-local, non-global variables it ca...
DenseMap< const slang::ast::ClassType *, std::unique_ptr< ClassLowering > > classes
Classes that have already been converted.
LogicalResult convertUserDefinedPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim)
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
DenseMap< const slang::ast::SubroutineSymbol *, std::unique_ptr< FunctionLowering > > functions
Functions that have already been converted.
slang::TimeScale timeScale
The time scale currently in effect.
DenseMap< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr >, Value > hierValueSymbols
Persistent map for hierarchical value lookups.
ClassLowering * declareClass(const slang::ast::ClassType &cls)
VirtualInterfaceMembers::ScopeTy VirtualInterfaceMemberScope
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
LogicalResult convertFixedPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
ValueSymbols valueSymbols
DenseMap< const slang::ast::SubroutineSymbol *, std::string > dpiExportCNames
DPI-C export directives keyed by the SystemVerilog subroutine they expose.
LogicalResult convertCMOSSwitchPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
FailureOr< moore::SVModuleOp > convertUserDefinedPrimitiveDef(const slang::ast::PrimitiveSymbol &primitive)
ValueSymbols::ScopeTy ValueSymbolScope
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
SmallVector< std::unique_ptr< InterfaceLowering > > interfaceInstanceStorage
Owning storage for InterfaceLowering objects because ScopedHashTable stores values by copy.
LogicalResult convertMOSSwitchPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
VirtualInterfaceMembers virtualIfaceMembers
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
const slang::SourceManager & sourceManager
Value materializeConversion(Type type, Value value, bool isSigned, Location loc, bool fallible=false)
Helper function to insert the necessary operations to cast a value from one type to another.
void convertAttributes(const slang::ast::Symbol &symbol, Operation *op)
Convert Slang AST attributes on symbol into sv::SVAttributeAttrs and attach them to op.
void traverseInstanceBody(const slang::ast::InstanceSymbol &symbol)
std::map< LocationKey, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
FunctionLowering * currentFunctionLowering
The function currently being converted, if any.
InterfaceInstances::ScopeTy InterfaceInstanceScope
LogicalResult convertThreeStateGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
LogicalResult convertPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim)
Convert a primitive instance.
mlir::ModuleOp intoModuleOp
SymbolTable symbolTable
A symbol table of the MLIR module we are emitting into.
DenseMap< const slang::ast::InstanceBodySymbol *, SmallVector< HierPathInfo > > hierPaths
Collect all hierarchical names used for the per module/instance.
FunctionLowering * declareFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function and its arguments to a function declaration in the IR.
LogicalResult convertNOutputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
InterfaceInstances interfaceInstances
LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl)
LogicalResult convertPackage(const slang::ast::PackageSymbol &package)
Convert a package and its contents.
LogicalResult convertCompilation()
Convert hierarchy and structure AST nodes to MLIR ops.
MLIRContext * getContext()
Return the MLIR context.
LogicalResult defineFunction(const slang::ast::SubroutineSymbol &subroutine)
Define a function’s body.
LogicalResult convertPullGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
LogicalResult convertStatement(const slang::ast::Statement &stmt)
SmallVector< const slang::ast::ValueSymbol * > globalVariableWorklist
A list of global variables that still need their initializers to be converted.
DenseMap< const slang::ast::InstanceBodySymbol *, std::unique_ptr< ModuleLowering > > modules
How we have lowered modules to MLIR.
Location convertLocation(slang::SourceLocation loc)
Convert a slang SourceLocation into an MLIR Location.
Function lowering information.
Lowering information for an expanded interface instance.
static LocationKey get(const slang::SourceLocation &loc, const slang::SourceManager &mgr)
Module lowering information.