10#include "slang/ast/Compilation.h"
11#include "slang/ast/symbols/ClassSymbols.h"
12#include "llvm/ADT/ScopeExit.h"
15using namespace ImportVerilog;
22 SmallString<64> &prefix) {
23 if (symbol.kind != slang::ast::SymbolKind::Package)
26 if (!symbol.name.empty()) {
27 prefix += symbol.name;
44 BaseVisitor(
Context &context, Location loc)
45 : context(context), loc(loc), builder(context.builder) {}
48 LogicalResult visit(
const slang::ast::EmptyMemberSymbol &) {
54 LogicalResult visit(
const slang::ast::TransparentMemberSymbol &) {
59 LogicalResult visit(
const slang::ast::ClassType &classdecl) {
69 LogicalResult visit(
const slang::ast::GenericClassDefSymbol &) {
74 LogicalResult visit(
const slang::ast::TypeAliasType &) {
return success(); }
75 LogicalResult visit(
const slang::ast::ForwardingTypedefSymbol &) {
80 LogicalResult visit(
const slang::ast::ExplicitImportSymbol &) {
83 LogicalResult visit(
const slang::ast::WildcardImportSymbol &) {
88 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
93 LogicalResult visit(
const slang::ast::ElabSystemTaskSymbol &) {
98 LogicalResult visit(
const slang::ast::ParameterSymbol ¶m) {
99 visitParameter(param);
103 LogicalResult visit(
const slang::ast::SpecparamSymbol ¶m) {
104 visitParameter(param);
108 template <
class Node>
109 void visitParameter(
const Node ¶m) {
119 if (builder.getInsertionBlock()->getParentOp() == context.
intoModuleOp)
120 context.
orderedRootOps.insert({param.location, value.getDefiningOp()});
124 SmallString<64> paramName;
126 paramName += param.name;
128 debug::VariableOp::create(builder, loc, builder.getStringAttr(paramName),
139struct RootVisitor :
public BaseVisitor {
140 using BaseVisitor::BaseVisitor;
141 using BaseVisitor::visit;
144 LogicalResult visit(
const slang::ast::PackageSymbol &package) {
145 return context.convertPackage(package);
149 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
150 return context.convertFunction(subroutine);
154 LogicalResult visit(
const slang::ast::VariableSymbol &var) {
155 return context.convertGlobalVariable(var);
159 template <
typename T>
160 LogicalResult visit(T &&node) {
161 mlir::emitError(loc,
"unsupported construct: ")
162 << slang::ast::toString(node.kind);
173struct PackageVisitor :
public BaseVisitor {
174 using BaseVisitor::BaseVisitor;
175 using BaseVisitor::visit;
178 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
179 return context.convertFunction(subroutine);
183 LogicalResult visit(
const slang::ast::VariableSymbol &var) {
184 return context.convertGlobalVariable(var);
188 template <
typename T>
189 LogicalResult visit(T &&node) {
190 mlir::emitError(loc,
"unsupported package member: ")
191 << slang::ast::toString(node.kind);
201static moore::ProcedureKind
204 case slang::ast::ProceduralBlockKind::Always:
205 return moore::ProcedureKind::Always;
206 case slang::ast::ProceduralBlockKind::AlwaysComb:
207 return moore::ProcedureKind::AlwaysComb;
208 case slang::ast::ProceduralBlockKind::AlwaysLatch:
209 return moore::ProcedureKind::AlwaysLatch;
210 case slang::ast::ProceduralBlockKind::AlwaysFF:
211 return moore::ProcedureKind::AlwaysFF;
212 case slang::ast::ProceduralBlockKind::Initial:
213 return moore::ProcedureKind::Initial;
214 case slang::ast::ProceduralBlockKind::Final:
215 return moore::ProcedureKind::Final;
217 llvm_unreachable(
"all procedure kinds handled");
222 case slang::ast::NetType::Supply0:
223 return moore::NetKind::Supply0;
224 case slang::ast::NetType::Supply1:
225 return moore::NetKind::Supply1;
226 case slang::ast::NetType::Tri:
227 return moore::NetKind::Tri;
228 case slang::ast::NetType::TriAnd:
229 return moore::NetKind::TriAnd;
230 case slang::ast::NetType::TriOr:
231 return moore::NetKind::TriOr;
232 case slang::ast::NetType::TriReg:
233 return moore::NetKind::TriReg;
234 case slang::ast::NetType::Tri0:
235 return moore::NetKind::Tri0;
236 case slang::ast::NetType::Tri1:
237 return moore::NetKind::Tri1;
238 case slang::ast::NetType::UWire:
239 return moore::NetKind::UWire;
240 case slang::ast::NetType::Wire:
241 return moore::NetKind::Wire;
242 case slang::ast::NetType::WAnd:
243 return moore::NetKind::WAnd;
244 case slang::ast::NetType::WOr:
245 return moore::NetKind::WOr;
246 case slang::ast::NetType::Interconnect:
247 return moore::NetKind::Interconnect;
248 case slang::ast::NetType::UserDefined:
249 return moore::NetKind::UserDefined;
250 case slang::ast::NetType::Unknown:
251 return moore::NetKind::Unknown;
253 llvm_unreachable(
"all net kinds handled");
257struct ModuleVisitor :
public BaseVisitor {
258 using BaseVisitor::visit;
262 StringRef blockNamePrefix;
264 ModuleVisitor(
Context &
context, Location loc, StringRef blockNamePrefix =
"")
265 : BaseVisitor(
context, loc), blockNamePrefix(blockNamePrefix) {}
268 LogicalResult visit(
const slang::ast::PortSymbol &) {
return success(); }
269 LogicalResult visit(
const slang::ast::MultiPortSymbol &) {
return success(); }
272 LogicalResult visit(
const slang::ast::GenvarSymbol &genvarNode) {
277 LogicalResult visit(
const slang::ast::DefParamSymbol &) {
return success(); }
281 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
286 LogicalResult visit(
const slang::ast::InstanceSymbol &instNode) {
287 using slang::ast::ArgumentDirection;
288 using slang::ast::AssignmentExpression;
289 using slang::ast::MultiPortSymbol;
290 using slang::ast::PortSymbol;
292 auto *moduleLowering =
context.convertModuleHeader(&instNode.body);
295 auto module = moduleLowering->op;
296 auto moduleType =
module.getModuleType();
299 SymbolTable::setSymbolVisibility(module, SymbolTable::Visibility::Private);
306 portValues.reserve(moduleType.getNumPorts());
308 for (
const auto *con : instNode.getPortConnections()) {
309 const auto *expr = con->getExpression();
314 auto *port = con->port.as_if<PortSymbol>();
315 if (
auto *existingPort =
316 moduleLowering->portsBySyntaxNode.lookup(port->getSyntax()))
319 switch (port->direction) {
320 case ArgumentDirection::In: {
321 auto refType = moore::RefType::get(
322 cast<moore::UnpackedType>(
context.convertType(port->getType())));
324 if (
const auto *net =
325 port->internalSymbol->as_if<slang::ast::NetSymbol>()) {
326 auto netOp = moore::NetOp::create(
327 builder, loc, refType,
328 StringAttr::get(builder.getContext(), net->name),
330 auto readOp = moore::ReadOp::create(builder, loc, netOp);
331 portValues.insert({port, readOp});
332 }
else if (
const auto *var =
334 ->as_if<slang::ast::VariableSymbol>()) {
335 auto varOp = moore::VariableOp::create(
336 builder, loc, refType,
337 StringAttr::get(builder.getContext(), var->name),
nullptr);
338 auto readOp = moore::ReadOp::create(builder, loc, varOp);
339 portValues.insert({port, readOp});
341 return mlir::emitError(loc)
342 <<
"unsupported internal symbol for unconnected port `"
343 << port->name <<
"`";
350 case ArgumentDirection::Out:
355 return mlir::emitError(loc)
356 <<
"unsupported port `" << port->name <<
"` ("
357 << slang::ast::toString(port->kind) <<
")";
363 if (
const auto *assign = expr->as_if<AssignmentExpression>())
364 expr = &assign->left();
369 if (
auto *port = con->port.as_if<PortSymbol>()) {
371 auto value = (port->direction == ArgumentDirection::In)
372 ?
context.convertRvalueExpression(*expr)
373 :
context.convertLvalueExpression(*expr);
376 if (
auto *existingPort =
377 moduleLowering->portsBySyntaxNode.lookup(con->port.getSyntax()))
379 portValues.insert({port, value});
386 if (
const auto *multiPort = con->port.as_if<MultiPortSymbol>()) {
388 auto value =
context.convertLvalueExpression(*expr);
392 for (
const auto *port :
llvm::reverse(multiPort->ports)) {
393 if (
auto *existingPort = moduleLowering->portsBySyntaxNode.lookup(
394 con->port.getSyntax()))
396 unsigned width = port->getType().getBitWidth();
397 auto sliceType =
context.convertType(port->getType());
400 Value slice = moore::ExtractRefOp::create(
402 moore::RefType::get(cast<moore::UnpackedType>(sliceType)), value,
405 if (port->direction == ArgumentDirection::In)
406 slice = moore::ReadOp::create(builder, loc, slice);
407 portValues.insert({port, slice});
413 mlir::emitError(loc) <<
"unsupported instance port `" << con->port.name
414 <<
"` (" << slang::ast::toString(con->port.kind)
420 SmallVector<Value> inputValues;
421 SmallVector<Value> outputValues;
422 inputValues.reserve(moduleType.getNumInputs());
423 outputValues.reserve(moduleType.getNumOutputs());
425 for (
auto &port : moduleLowering->ports) {
426 auto value = portValues.lookup(&port.ast);
427 if (port.ast.direction == ArgumentDirection::Out)
428 outputValues.push_back(value);
430 inputValues.push_back(value);
434 for (
auto [value, type] :
435 llvm::zip(inputValues, moduleType.getInputTypes()))
437 value =
context.materializeConversion(type, value, false, value.
getLoc());
441 for (
const auto &hierPath :
context.hierPaths[&instNode.body])
442 if (auto hierValue =
context.valueSymbols.lookup(hierPath.valueSym);
443 hierPath.hierName && hierPath.direction == ArgumentDirection::In)
444 inputValues.push_back(hierValue);
447 auto inputNames = builder.getArrayAttr(moduleType.getInputNames());
448 auto outputNames = builder.getArrayAttr(moduleType.getOutputNames());
449 auto inst = moore::InstanceOp::create(
450 builder, loc, moduleType.getOutputTypes(),
451 builder.getStringAttr(Twine(blockNamePrefix) + instNode.name),
452 FlatSymbolRefAttr::get(module.getSymNameAttr()), inputValues,
453 inputNames, outputNames);
456 for (
const auto &hierPath :
context.hierPaths[&instNode.body])
457 if (hierPath.idx && hierPath.direction == ArgumentDirection::
Out)
458 context.valueSymbols.insert(hierPath.valueSym,
459 inst->getResult(*hierPath.idx));
462 for (
auto [lvalue, output] :
llvm::zip(outputValues, inst.getOutputs())) {
465 Value rvalue = output;
466 auto dstType = cast<moore::RefType>(lvalue.getType()).getNestedType();
468 rvalue =
context.materializeConversion(dstType, rvalue,
false, loc);
469 moore::ContinuousAssignOp::create(builder, loc, lvalue, rvalue);
476 LogicalResult visit(
const slang::ast::VariableSymbol &varNode) {
477 auto loweredType =
context.convertType(*varNode.getDeclaredType());
482 if (
const auto *init = varNode.getInitializer()) {
483 initial =
context.convertRvalueExpression(*init, loweredType);
488 auto varOp = moore::VariableOp::create(
490 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
491 builder.getStringAttr(Twine(blockNamePrefix) + varNode.name), initial);
492 context.valueSymbols.insert(&varNode, varOp);
497 LogicalResult visit(
const slang::ast::NetSymbol &netNode) {
498 auto loweredType =
context.convertType(*netNode.getDeclaredType());
503 if (
const auto *init = netNode.getInitializer()) {
504 assignment =
context.convertRvalueExpression(*init, loweredType);
510 if (netkind == moore::NetKind::Interconnect ||
511 netkind == moore::NetKind::UserDefined ||
512 netkind == moore::NetKind::Unknown)
513 return mlir::emitError(loc,
"unsupported net kind `")
514 << netNode.netType.name <<
"`";
516 auto netOp = moore::NetOp::create(
518 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
519 builder.getStringAttr(Twine(blockNamePrefix) + netNode.name), netkind,
521 context.valueSymbols.insert(&netNode, netOp);
526 LogicalResult visit(
const slang::ast::ContinuousAssignSymbol &assignNode) {
528 assignNode.getAssignment().as<slang::ast::AssignmentExpression>();
529 auto lhs =
context.convertLvalueExpression(expr.left());
533 auto rhs =
context.convertRvalueExpression(
534 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
539 if (
auto *timingCtrl = assignNode.getDelay()) {
540 auto *ctrl = timingCtrl->as_if<slang::ast::DelayControl>();
541 assert(ctrl &&
"slang guarantees this to be a simple delay");
542 auto delay =
context.convertRvalueExpression(
543 ctrl->expr, moore::TimeType::get(builder.getContext()));
546 moore::DelayedContinuousAssignOp::create(builder, loc, lhs, rhs, delay);
551 moore::ContinuousAssignOp::create(builder, loc, lhs, rhs);
556 LogicalResult convertProcedure(moore::ProcedureKind kind,
557 const slang::ast::Statement &body) {
558 if (body.as_if<slang::ast::ConcurrentAssertionStatement>())
559 return context.convertStatement(body);
560 auto procOp = moore::ProcedureOp::create(builder, loc, kind);
561 OpBuilder::InsertionGuard guard(builder);
562 builder.setInsertionPointToEnd(&procOp.getBody().emplaceBlock());
563 Context::ValueSymbolScope scope(
context.valueSymbols);
564 if (failed(
context.convertStatement(body)))
566 if (builder.getBlock())
567 moore::ReturnOp::create(builder, loc);
571 LogicalResult visit(
const slang::ast::ProceduralBlockSymbol &procNode) {
574 if (
context.options.lowerAlwaysAtStarAsComb) {
575 auto *stmt = procNode.getBody().as_if<slang::ast::TimedStatement>();
576 if (procNode.procedureKind == slang::ast::ProceduralBlockKind::Always &&
578 stmt->timing.kind == slang::ast::TimingControlKind::ImplicitEvent)
579 return convertProcedure(moore::ProcedureKind::AlwaysComb, stmt->stmt);
587 LogicalResult visit(
const slang::ast::GenerateBlockSymbol &genNode) {
589 if (genNode.isUninstantiated)
593 SmallString<64> prefix = blockNamePrefix;
594 if (!genNode.name.empty() ||
595 genNode.getParentScope()->asSymbol().kind !=
596 slang::ast::SymbolKind::GenerateBlockArray) {
597 prefix += genNode.getExternalName();
602 for (
auto &member : genNode.members())
603 if (failed(member.visit(ModuleVisitor(
context, loc, prefix))))
609 LogicalResult visit(
const slang::ast::GenerateBlockArraySymbol &genArrNode) {
612 SmallString<64> prefix = blockNamePrefix;
613 prefix += genArrNode.getExternalName();
615 auto prefixBaseLen = prefix.size();
618 for (
const auto *entry : genArrNode.entries) {
620 prefix.resize(prefixBaseLen);
621 if (entry->arrayIndex)
622 prefix += entry->arrayIndex->toString();
624 Twine(entry->constructIndex).toVector(prefix);
628 if (failed(entry->asSymbol().visit(ModuleVisitor(
context, loc, prefix))))
640 LogicalResult visit(
const slang::ast::StatementBlockSymbol &) {
646 LogicalResult visit(
const slang::ast::SequenceSymbol &seqNode) {
652 LogicalResult visit(
const slang::ast::PropertySymbol &propNode) {
657 LogicalResult visit(
const slang::ast::SubroutineSymbol &subroutine) {
658 return context.convertFunction(subroutine);
662 template <
typename T>
663 LogicalResult visit(T &&node) {
664 mlir::emitError(loc,
"unsupported module member: ")
665 << slang::ast::toString(node.kind);
677LogicalResult Context::convertCompilation() {
683 timeScale = root.getTimeScale().value_or(slang::TimeScale());
684 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
688 for (
auto *inst : root.topInstances)
695 for (
auto *unit : root.compilationUnits) {
696 for (
const auto &member : unit->members()) {
698 if (failed(member.visit(RootVisitor(*
this, loc))))
704 SmallVector<const slang::ast::InstanceSymbol *> topInstances;
705 for (
auto *inst : root.topInstances)
711 auto *
module = moduleWorklist.front();
719 SmallVector<const slang::ast::ClassType *, 16> classMethodWorklist;
720 classMethodWorklist.reserve(
classes.size());
722 classMethodWorklist.push_back(kv.first);
724 for (
auto *inst : classMethodWorklist) {
732 auto &block = varOp.getInitRegion().emplaceBlock();
733 OpBuilder::InsertionGuard guard(
builder);
734 builder.setInsertionPointToEnd(&block);
739 moore::YieldOp::create(
builder, varOp.getLoc(), value);
752 using slang::ast::ArgumentDirection;
753 using slang::ast::MultiPortSymbol;
754 using slang::ast::ParameterSymbol;
755 using slang::ast::PortSymbol;
756 using slang::ast::TypeParameterSymbol;
761 timeScale =
module->getTimeScale().value_or(slang::TimeScale());
762 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
764 auto parameters =
module->getParameters();
765 bool hasModuleSame =
false;
769 for (
auto const &existingModule :
modules) {
770 if (module->getDeclaringDefinition() ==
771 existingModule.getFirst()->getDeclaringDefinition()) {
772 auto moduleParameters = existingModule.getFirst()->getParameters();
773 hasModuleSame =
true;
774 for (
auto it1 = parameters.begin(), it2 = moduleParameters.begin();
775 it1 != parameters.end() && it2 != moduleParameters.end();
778 if (it1 == parameters.end() || it2 == moduleParameters.end()) {
779 hasModuleSame =
false;
782 const auto *para1 = (*it1)->symbol.as_if<ParameterSymbol>();
783 const auto *para2 = (*it2)->symbol.as_if<ParameterSymbol>();
785 if ((para1 ==
nullptr) ^ (para2 ==
nullptr)) {
786 hasModuleSame =
false;
790 if (para1 !=
nullptr) {
791 hasModuleSame = para1->getValue() == para2->getValue();
794 if (para1 ==
nullptr) {
796 (*it1)->symbol.as<TypeParameterSymbol>().getTypeAlias());
798 (*it2)->symbol.as<TypeParameterSymbol>().getTypeAlias());
799 hasModuleSame = para1Type == para2Type;
805 module = existingModule.first;
814 slot = std::make_unique<ModuleLowering>();
815 auto &lowering = *slot;
818 OpBuilder::InsertionGuard g(
builder);
823 auto kind =
module->getDefinition().definitionKind;
824 if (kind != slang::ast::DefinitionKind::Module &&
825 kind != slang::ast::DefinitionKind::Program) {
826 mlir::emitError(loc) <<
"unsupported definition: "
827 <<
module->getDefinition().getKindString();
832 auto block = std::make_unique<Block>();
833 SmallVector<hw::ModulePort> modulePorts;
836 unsigned int outputIdx = 0, inputIdx = 0;
837 for (
auto *symbol :
module->getPortList()) {
838 auto handlePort = [&](const PortSymbol &port) {
839 auto portLoc = convertLocation(port.location);
843 auto portName =
builder.getStringAttr(port.name);
845 if (port.direction == ArgumentDirection::Out) {
851 if (port.direction != ArgumentDirection::In)
852 type = moore::RefType::get(cast<moore::UnpackedType>(type));
854 arg = block->addArgument(type, portLoc);
857 lowering.ports.push_back({port, portLoc, arg});
861 if (
const auto *port = symbol->as_if<PortSymbol>()) {
862 if (failed(handlePort(*port)))
864 }
else if (
const auto *multiPort = symbol->as_if<MultiPortSymbol>()) {
865 for (
auto *port : multiPort->ports)
866 if (failed(handlePort(*port)))
870 <<
"unsupported module port `" << symbol->name <<
"` ("
871 << slang::ast::toString(symbol->kind) <<
")";
877 for (
auto &hierPath : hierPaths[module]) {
878 auto hierType =
convertType(hierPath.valueSym->getType());
882 if (
auto hierName = hierPath.hierName) {
884 hierType = moore::RefType::get(cast<moore::UnpackedType>(hierType));
885 if (hierPath.direction == ArgumentDirection::Out) {
886 hierPath.idx = outputIdx++;
889 hierPath.idx = inputIdx++;
892 block->addArgument(hierType, hierLoc);
896 auto moduleType = hw::ModuleType::get(getContext(), modulePorts);
900 auto it = orderedRootOps.upper_bound(module->location);
901 if (it == orderedRootOps.end())
902 builder.setInsertionPointToEnd(intoModuleOp.getBody());
904 builder.setInsertionPoint(it->second);
908 moore::SVModuleOp::create(builder, loc, module->name, moduleType);
909 orderedRootOps.insert(it, {
module->location, moduleOp});
910 moduleOp.getBodyRegion().push_back(block.release());
911 lowering.op = moduleOp;
915 symbolTable.insert(moduleOp);
918 moduleWorklist.push(module);
921 for (
const auto &port : lowering.ports)
922 lowering.portsBySyntaxNode.insert({port.ast.getSyntax(), &port.ast});
931 auto &lowering = *
modules[module];
932 OpBuilder::InsertionGuard g(
builder);
933 builder.setInsertionPointToEnd(lowering.op.getBody());
940 timeScale =
module->getTimeScale().value_or(slang::TimeScale());
941 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
947 if (hierPath.direction == slang::ast::ArgumentDirection::In && hierPath.idx)
949 lowering.op.getBody()->getArgument(*hierPath.idx));
952 for (
auto &member :
module->members()) {
953 auto loc = convertLocation(member.location);
954 if (failed(member.visit(ModuleVisitor(*
this, loc))))
961 SmallVector<Value> outputs;
962 for (
auto &port : lowering.ports) {
964 if (
auto *expr = port.ast.getInternalExpr()) {
965 value = convertLvalueExpression(*expr);
966 }
else if (port.ast.internalSymbol) {
967 if (
const auto *sym =
968 port.ast.internalSymbol->as_if<slang::ast::ValueSymbol>())
969 value = valueSymbols.lookup(sym);
972 return mlir::emitError(port.loc,
"unsupported port: `")
974 <<
"` does not map to an internal symbol or expression";
977 if (port.ast.direction == slang::ast::ArgumentDirection::Out) {
978 if (isa<moore::RefType>(value.getType()))
979 value = moore::ReadOp::create(builder, value.getLoc(), value);
980 outputs.push_back(value);
986 Value portArg = port.arg;
987 if (port.ast.direction != slang::ast::ArgumentDirection::In)
988 portArg = moore::ReadOp::create(builder, port.loc, port.arg);
989 moore::ContinuousAssignOp::create(builder, port.loc, value, portArg);
994 for (
auto &hierPath : hierPaths[module])
995 if (auto hierValue = valueSymbols.lookup(hierPath.valueSym))
996 if (hierPath.direction == slang::ast::ArgumentDirection::
Out)
997 outputs.push_back(hierValue);
999 moore::OutputOp::create(builder, lowering.op.getLoc(), outputs);
1009 timeScale = package.getTimeScale().value_or(slang::TimeScale());
1010 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1012 OpBuilder::InsertionGuard g(
builder);
1015 for (
auto &member : package.members()) {
1017 if (failed(member.visit(PackageVisitor(*
this, loc))))
1028 auto &lowering =
functions[&subroutine];
1032 return lowering.get();
1035 if (!subroutine.thisVar) {
1037 SmallString<64> name;
1039 name += subroutine.name;
1041 SmallVector<Type, 1> noThis = {};
1048 const slang::ast::Type &thisTy = subroutine.thisVar->getType();
1049 moore::ClassDeclOp ownerDecl;
1051 if (
auto *classTy = thisTy.as_if<slang::ast::ClassType>()) {
1052 auto &ownerLowering =
classes[classTy];
1053 ownerDecl = ownerLowering->op;
1055 mlir::emitError(loc) <<
"expected 'this' to be a class type, got "
1056 << thisTy.toString();
1061 SmallString<64> qualName;
1062 qualName += ownerDecl.getSymName();
1064 qualName += subroutine.name;
1067 SmallVector<Type, 1> extraParams;
1069 auto classSym = mlir::FlatSymbolRefAttr::get(ownerDecl.getSymNameAttr());
1070 auto handleTy = moore::ClassHandleType::get(
getContext(), classSym);
1071 extraParams.push_back(handleTy);
1082 const slang::ast::SubroutineSymbol &subroutine,
1083 llvm::SmallVectorImpl<Type> &extraParams) {
1084 using slang::ast::ArgumentDirection;
1086 SmallVector<Type> inputTypes;
1087 inputTypes.append(extraParams.begin(), extraParams.end());
1088 SmallVector<Type, 1> outputTypes;
1090 for (
const auto *arg : subroutine.getArguments()) {
1091 auto type =
context.convertType(arg->getType());
1094 if (arg->direction == ArgumentDirection::In) {
1095 inputTypes.push_back(type);
1097 inputTypes.push_back(
1098 moore::RefType::get(cast<moore::UnpackedType>(type)));
1102 const auto &returnType = subroutine.getReturnType();
1103 if (!returnType.isVoid()) {
1104 auto type =
context.convertType(returnType);
1107 outputTypes.push_back(type);
1111 FunctionType::get(
context.getContext(), inputTypes, outputTypes);
1121 mlir::StringRef qualifiedName,
1122 llvm::SmallVectorImpl<Type> &extraParams) {
1124 std::unique_ptr<FunctionLowering> lowering =
1125 std::make_unique<FunctionLowering>();
1129 OpBuilder::InsertionGuard g(
builder);
1134 builder.setInsertionPoint(it->second);
1139 auto funcOp = mlir::func::FuncOp::create(
builder, loc, qualifiedName, funcTy);
1141 SymbolTable::setSymbolVisibility(funcOp, SymbolTable::Visibility::Private);
1143 lowering->op = funcOp;
1148 functions[&subroutine] = std::move(lowering);
1157 ArrayRef<Value> captures) {
1158 if (captures.empty())
1161 mlir::ModuleOp
module = callee->getParentOfType<mlir::ModuleOp>();
1163 return callee.emitError(
"expected callee to be nested under ModuleOp");
1165 auto usesOpt = mlir::SymbolTable::getSymbolUses(callee, module);
1167 return callee.emitError(
"failed to compute symbol uses");
1170 SmallVector<mlir::func::CallOp, 8> callSites;
1171 callSites.reserve(std::distance(usesOpt->begin(), usesOpt->end()));
1172 for (
const mlir::SymbolTable::SymbolUse &use : *usesOpt) {
1173 if (
auto call = llvm::dyn_cast<mlir::func::CallOp>(use.getUser()))
1174 callSites.push_back(call);
1176 if (callSites.empty())
1179 Block &entry = callee.getBody().front();
1180 const unsigned numCaps = captures.size();
1181 const unsigned numEntryArgs = entry.getNumArguments();
1182 if (numEntryArgs < numCaps)
1183 return callee.emitError(
"entry block has fewer args than captures");
1184 const unsigned capArgStart = numEntryArgs - numCaps;
1187 auto fTy = callee.getFunctionType();
1189 for (
auto call : callSites) {
1190 SmallVector<Value> newOperands(call.getArgOperands().begin(),
1191 call.getArgOperands().end());
1193 const bool inSameFunc = callee->isProperAncestor(call);
1196 for (
unsigned i = 0; i < numCaps; ++i)
1197 newOperands.push_back(entry.getArgument(capArgStart + i));
1200 newOperands.append(captures.begin(), captures.end());
1204 auto flatRef = mlir::FlatSymbolRefAttr::get(callee);
1205 auto newCall = mlir::func::CallOp::create(
1206 b, call.getLoc(), fTy.getResults(), flatRef, newOperands);
1207 call->replaceAllUsesWith(newCall.getOperation());
1220 timeScale = subroutine.getTimeScale().value_or(slang::TimeScale());
1221 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1230 if (lowering->capturesFinalized || lowering->isConverting)
1233 const bool isMethod = (subroutine.thisVar !=
nullptr);
1238 SmallVector<moore::VariableOp> argVariables;
1239 auto &block = lowering->op.getBody().emplaceBlock();
1245 auto thisType = lowering->op.getFunctionType().getInput(0);
1246 auto thisArg = block.addArgument(thisType, thisLoc);
1253 auto inputs = lowering->op.getFunctionType().getInputs();
1254 auto astArgs = subroutine.getArguments();
1255 auto valInputs = llvm::ArrayRef<Type>(inputs).drop_front(isMethod ? 1 : 0);
1257 for (
auto [astArg, type] : llvm::zip(astArgs, valInputs)) {
1259 auto blockArg = block.addArgument(type, loc);
1261 if (isa<moore::RefType>(type)) {
1264 OpBuilder::InsertionGuard g(
builder);
1265 builder.setInsertionPointToEnd(&block);
1267 auto shadowArg = moore::VariableOp::create(
1268 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
1269 StringAttr{}, blockArg);
1271 argVariables.push_back(shadowArg);
1276 OpBuilder::InsertionGuard g(
builder);
1277 builder.setInsertionPointToEnd(&block);
1280 if (subroutine.returnValVar) {
1281 auto type =
convertType(*subroutine.returnValVar->getDeclaredType());
1284 returnVar = moore::VariableOp::create(
1285 builder, lowering->op.getLoc(),
1286 moore::RefType::get(cast<moore::UnpackedType>(type)), StringAttr{},
1288 valueSymbols.insert(subroutine.returnValVar, returnVar);
1294 llvm::scope_exit prevRCbGuard([&] {
1301 mlir::Value ref = rop.getInput();
1304 mlir::Type ty = ref.getType();
1305 if (!ty || !(isa<moore::RefType>(ty)))
1309 mlir::Region *defReg = ref.getParentRegion();
1310 if (defReg && lowering->op.getBody().isAncestor(defReg))
1314 if (lowering->captureIndex.count(ref))
1318 auto [it, inserted] =
1319 lowering->captureIndex.try_emplace(ref, lowering->captures.size());
1321 lowering->captures.push_back(ref);
1329 mlir::Value dstRef =
1330 llvm::TypeSwitch<mlir::Operation *, mlir::Value>(op)
1331 .Case<moore::BlockingAssignOp, moore::NonBlockingAssignOp,
1332 moore::DelayedNonBlockingAssignOp>(
1333 [](
auto op) {
return op.getDst(); })
1334 .Default([](
auto) -> mlir::Value {
return {}; });
1337 mlir::Type ty = dstRef.getType();
1338 if (!ty || !(isa<moore::RefType>(ty)))
1342 mlir::Region *defReg = dstRef.getParentRegion();
1343 if (defReg && lowering->op.getBody().isAncestor(defReg))
1347 if (lowering->captureIndex.count(dstRef))
1351 auto [it, inserted] =
1352 lowering->captureIndex.try_emplace(dstRef, lowering->captures.size());
1354 lowering->captures.push_back(dstRef);
1363 llvm::scope_exit restoreThis([&] {
currentThisRef = savedThis; });
1365 lowering->isConverting =
true;
1366 llvm::scope_exit convertingGuard([&] { lowering->isConverting =
false; });
1383 if (returnVar && !subroutine.getReturnType().isVoid()) {
1385 moore::ReadOp::create(
builder, returnVar.getLoc(), returnVar);
1386 mlir::func::ReturnOp::create(
builder, lowering->op.getLoc(), read);
1388 mlir::func::ReturnOp::create(
builder, lowering->op.getLoc(),
1392 if (returnVar && returnVar.use_empty())
1393 returnVar.getDefiningOp()->erase();
1395 for (
auto var : argVariables) {
1396 if (llvm::all_of(var->getUsers(),
1397 [](
auto *user) { return isa<moore::ReadOp>(user); })) {
1398 for (
auto *user : llvm::make_early_inc_range(var->getUsers())) {
1399 user->getResult(0).replaceAllUsesWith(var.getInitial());
1406 lowering->capturesFinalized =
true;
1418 SmallVector<Type> newInputs(lowering.
op.getFunctionType().getInputs().begin(),
1419 lowering.
op.getFunctionType().getInputs().end());
1421 for (Value cap : lowering.
captures) {
1423 Type capTy = cap.getType();
1424 if (!isa<moore::RefType>(capTy)) {
1425 return lowering.
op.emitError(
1426 "expected captured value to be a ref-like type");
1428 newInputs.push_back(capTy);
1432 auto newFuncTy = FunctionType::get(
1433 ctx, newInputs, lowering.
op.getFunctionType().getResults());
1434 lowering.
op.setFunctionType(newFuncTy);
1437 Block &entry = lowering.
op.getBody().front();
1438 SmallVector<Value> capArgs;
1439 capArgs.reserve(lowering.
captures.size());
1441 llvm::ArrayRef<Type>(newInputs).take_back(lowering.
captures.size())) {
1442 capArgs.push_back(entry.addArgument(t, lowering.
op.getLoc()));
1448 Value arg = capArgs[idx];
1449 cap.replaceUsesWithIf(arg, [&](OpOperand &use) {
1450 return lowering.
op->isProperAncestor(use.getOwner());
1461mlir::StringAttr fullyQualifiedClassName(
Context &ctx,
1462 const slang::ast::Type &ty) {
1463 SmallString<64> name;
1464 SmallVector<llvm::StringRef, 8> parts;
1466 const slang::ast::Scope *scope = ty.getParentScope();
1468 const auto &sym = scope->asSymbol();
1470 case slang::ast::SymbolKind::Root:
1473 case slang::ast::SymbolKind::InstanceBody:
1474 case slang::ast::SymbolKind::Instance:
1475 case slang::ast::SymbolKind::Package:
1476 case slang::ast::SymbolKind::ClassType:
1477 if (!sym.name.empty())
1478 parts.push_back(sym.name);
1483 scope = sym.getParentScope();
1486 for (
auto p :
llvm::reverse(parts)) {
1491 return mlir::StringAttr::get(ctx.
getContext(), name);
1496std::pair<mlir::SymbolRefAttr, mlir::ArrayAttr>
1498 const slang::ast::ClassType &cls) {
1502 mlir::SymbolRefAttr base;
1503 if (
const auto *b = cls.getBaseClass())
1504 base = mlir::SymbolRefAttr::get(fullyQualifiedClassName(
context, *b));
1507 SmallVector<mlir::Attribute> impls;
1508 if (
auto ifaces = cls.getDeclaredInterfaces(); !ifaces.empty()) {
1509 impls.reserve(ifaces.size());
1510 for (
const auto *iface : ifaces)
1511 impls.push_back(
mlir::FlatSymbolRefAttr::
get(
1512 fullyQualifiedClassName(
context, *iface)));
1515 mlir::ArrayAttr implArr =
1516 impls.empty() ? mlir::ArrayAttr() :
mlir::ArrayAttr::
get(ctx, impls);
1518 return {base, implArr};
1523struct ClassDeclVisitorBase {
1529 :
context(ctx), builder(ctx.builder), classLowering(lowering) {}
1533 return context.convertLocation(sloc);
1539struct ClassPropertyVisitor : ClassDeclVisitorBase {
1540 using ClassDeclVisitorBase::ClassDeclVisitorBase;
1543 LogicalResult
run(
const slang::ast::ClassType &classAST) {
1544 if (!classLowering.
op.getBody().empty())
1547 OpBuilder::InsertionGuard ig(builder);
1549 Block *body = &classLowering.
op.getBody().emplaceBlock();
1550 builder.setInsertionPointToEnd(body);
1553 for (
const auto &mem : classAST.members()) {
1554 if (
const auto *prop = mem.as_if<slang::ast::ClassPropertySymbol>()) {
1555 if (failed(prop->visit(*
this)))
1564 LogicalResult visit(
const slang::ast::ClassPropertySymbol &prop) {
1566 auto ty =
context.convertType(prop.getType());
1570 if (prop.lifetime == slang::ast::VariableLifetime::Automatic) {
1571 moore::ClassPropertyDeclOp::create(builder, loc, prop.name, ty);
1579 if (!
context.globalVariables.lookup(&prop))
1580 return context.convertGlobalVariable(prop);
1585 LogicalResult visit(
const slang::ast::ClassType &cls) {
1586 return context.buildClassProperties(cls);
1590 template <
typename T>
1591 LogicalResult visit(T &&) {
1598struct ClassMethodVisitor : ClassDeclVisitorBase {
1599 using ClassDeclVisitorBase::ClassDeclVisitorBase;
1602 LogicalResult
run(
const slang::ast::ClassType &classAST) {
1606 if (classLowering.
op.getBody().empty())
1609 OpBuilder::InsertionGuard ig(builder);
1610 builder.setInsertionPointToEnd(&classLowering.
op.getBody().front());
1613 for (
const auto &mem : classAST.members()) {
1614 if (failed(mem.visit(*
this)))
1623 LogicalResult visit(
const slang::ast::ClassPropertySymbol &) {
1629 LogicalResult visit(
const slang::ast::ParameterSymbol &) {
return success(); }
1633 LogicalResult visit(
const slang::ast::TypeParameterSymbol &) {
1639 LogicalResult visit(
const slang::ast::TypeAliasType &) {
return success(); }
1642 LogicalResult visit(
const slang::ast::GenericClassDefSymbol &) {
1647 LogicalResult visit(
const slang::ast::TransparentMemberSymbol &) {
1652 LogicalResult visit(
const slang::ast::EmptyMemberSymbol &) {
1657 LogicalResult visit(
const slang::ast::SubroutineSymbol &fn) {
1658 if (fn.flags & slang::ast::MethodFlags::BuiltIn) {
1659 static bool remarkEmitted =
false;
1663 mlir::emitRemark(classLowering.
op.getLoc())
1664 <<
"Class builtin functions (needed for randomization, constraints, "
1665 "and covergroups) are not yet supported and will be dropped "
1667 remarkEmitted =
true;
1671 const mlir::UnitAttr isVirtual =
1672 (fn.flags & slang::ast::MethodFlags::Virtual)
1673 ? UnitAttr::get(
context.getContext())
1680 if (fn.flags & slang::ast::MethodFlags::Pure) {
1682 SmallVector<Type, 1> extraParams;
1684 mlir::FlatSymbolRefAttr::get(classLowering.
op.getSymNameAttr());
1686 moore::ClassHandleType::get(
context.getContext(), classSym);
1687 extraParams.push_back(handleTy);
1691 mlir::emitError(loc) <<
"Invalid function signature for " << fn.name;
1695 moore::ClassMethodDeclOp::create(builder, loc, fn.name, funcTy,
nullptr);
1699 auto *lowering =
context.declareFunction(fn);
1703 if (failed(
context.convertFunction(fn)))
1706 if (!lowering->capturesFinalized)
1714 FunctionType fnTy = lowering->op.getFunctionType();
1716 moore::ClassMethodDeclOp::create(builder, loc, fn.name, fnTy,
1717 SymbolRefAttr::get(lowering->op));
1734 LogicalResult visit(
const slang::ast::MethodPrototypeSymbol &fn) {
1735 const auto *externImpl = fn.getSubroutine();
1739 <<
"Didn't find an implementation matching the forward declaration "
1744 return visit(*externImpl);
1748 LogicalResult visit(
const slang::ast::ClassType &cls) {
1749 if (failed(
context.buildClassProperties(cls)))
1751 return context.materializeClassMethods(cls);
1755 template <
typename T>
1756 LogicalResult visit(T &&node) {
1757 Location loc = UnknownLoc::get(
context.getContext());
1758 if constexpr (
requires { node.location; })
1760 mlir::emitError(loc) <<
"unsupported construct in ClassType members: "
1761 << slang::ast::toString(node.kind);
1769 auto &lowering =
classes[&cls];
1771 return lowering.get();
1772 lowering = std::make_unique<ClassLowering>();
1777 OpBuilder::InsertionGuard g(
builder);
1782 builder.setInsertionPoint(it->second);
1784 auto symName = fullyQualifiedClassName(*
this, cls);
1786 auto [base, impls] = buildBaseAndImplementsAttrs(*
this, cls);
1788 moore::ClassDeclOp::create(
builder, loc, symName, base, impls);
1790 SymbolTable::setSymbolVisibility(classDeclOp,
1791 SymbolTable::Visibility::Public);
1793 lowering->op = classDeclOp;
1796 return lowering.get();
1803 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
1804 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1811 if (classdecl.getBaseClass()) {
1812 if (
const auto *baseClassDecl =
1813 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
1824 return ClassPropertyVisitor(*
this, *lowering).run(classdecl);
1831 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
1832 llvm::scope_exit timeScaleGuard([&] {
timeScale = prevTimeScale; });
1835 auto it =
classes.find(&classdecl);
1836 if (it ==
classes.end() || !it->second)
1840 if (classdecl.getBaseClass()) {
1841 if (
const auto *baseClassDecl =
1842 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
1848 return ClassMethodVisitor(*
this, *it->second).run(classdecl);
1858 OpBuilder::InsertionGuard g(
builder);
1863 builder.setInsertionPoint(it->second);
1867 SmallString<64> symName;
1871 if (
const auto *classVar = var.as_if<slang::ast::ClassPropertySymbol>()) {
1872 if (
const auto *parentScope = classVar->getParentScope()) {
1873 if (
const auto *parentClass =
1874 parentScope->asSymbol().as_if<slang::ast::ClassType>())
1875 symName = fullyQualifiedClassName(*
this, *parentClass);
1877 mlir::emitError(loc)
1878 <<
"Could not access parent class of class property "
1883 mlir::emitError(loc) <<
"Could not get parent scope of class property "
1888 symName += var.name;
1891 symName += var.name;
1900 auto varOp = moore::GlobalVariableOp::create(
builder, loc, symName,
1901 cast<moore::UnpackedType>(type));
1908 if (var.getInitializer())
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static FIRRTLBaseType convertType(FIRRTLBaseType type)
Returns null type if no conversion is needed.
static Location convertLocation(MLIRContext *context, const slang::SourceManager &sourceManager, slang::SourceLocation loc)
Convert a slang SourceLocation to an MLIR Location.
static Location getLoc(DefSlot slot)
static moore::ProcedureKind convertProcedureKind(slang::ast::ProceduralBlockKind kind)
static FunctionType getFunctionSignature(Context &context, const slang::ast::SubroutineSymbol &subroutine, llvm::SmallVectorImpl< Type > &extraParams)
Helper function to generate the function signature from a SubroutineSymbol and optional extra argumen...
static void guessNamespacePrefix(const slang::ast::Symbol &symbol, SmallString< 64 > &prefix)
static LogicalResult rewriteCallSitesToPassCaptures(mlir::func::FuncOp callee, ArrayRef< Value > captures)
Special case handling for recursive functions with captures; this function fixes the in-body call of ...
static moore::NetKind convertNetKind(slang::ast::NetType::NetKind kind)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
int run(Type[Generator] generator=CppGenerator, cmdline_args=sys.argv)
bool debugInfo
Generate debug information in the form of debug dialect ops in the IR.
circt::moore::ClassDeclOp op
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function.
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.
Value materializeConstant(const slang::ConstantValue &constant, const slang::ast::Type &type, Location loc)
Helper function to materialize a ConstantValue as an SSA value.
LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module)
Convert a module's body to the corresponding IR ops.
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
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.
DenseMap< const slang::ast::ClassType *, std::unique_ptr< ClassLowering > > classes
Classes that have already been converted.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
std::map< slang::SourceLocation, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
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.
LogicalResult finalizeFunctionBodyCaptures(FunctionLowering &lowering)
ClassLowering * declareClass(const slang::ast::ClassType &cls)
ValueSymbols valueSymbols
std::function< void(mlir::Operation *)> variableAssignCallback
A listener called for every variable or net being assigned.
ValueSymbols::ScopeTy ValueSymbolScope
const ImportVerilogOptions & options
Value convertRvalueExpression(const slang::ast::Expression &expr, Type requiredType={})
LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol)
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
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 buildClassProperties(const slang::ast::ClassType &classdecl)
LogicalResult convertPackage(const slang::ast::PackageSymbol &package)
Convert a package and its contents.
MLIRContext * getContext()
Return the MLIR context.
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.
llvm::DenseMap< Value, unsigned > captureIndex
llvm::SmallVector< Value, 4 > captures
Module lowering information.