CIRCT 24.0.0git
Loading...
Searching...
No Matches
Structure.cpp
Go to the documentation of this file.
1//===- Structure.cpp - Slang hierarchy conversion -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "circt/Support/FVInt.h"
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"
20
21using namespace circt;
22using namespace ImportVerilog;
23
24static constexpr StringLiteral dpiExportAttrName = "circt.dpi.export";
25
26//===----------------------------------------------------------------------===//
27// Utilities
28//===----------------------------------------------------------------------===//
29
30/// Record `export "DPI-C"` directives in the given scope so that callable
31/// declarations can be tagged with the exported C name. Slang resolves the
32/// directives during elaboration but does not expose them on the subroutine
33/// symbols themselves, so walk the scope's syntax to recover them.
35 const slang::ast::Scope &scope,
36 const slang::syntax::SyntaxNode *syntax) {
37 if (!syntax)
38 return;
39
40 auto visitor = slang::syntax::makeSyntaxVisitor(
41 [&](auto &visitor, const slang::syntax::DPIExportSyntax &exportSyntax) {
42 auto svName = exportSyntax.name.valueText();
43 if (svName.empty())
44 return;
45
46 const auto *symbol = scope.find(svName);
47 const auto *subroutine =
48 symbol ? symbol->as_if<slang::ast::SubroutineSymbol>() : nullptr;
49 if (!subroutine)
50 return;
51
52 auto cName = exportSyntax.c_identifier.valueText();
53 if (cName.empty())
54 cName = svName;
55 context.dpiExportCNames[subroutine] = std::string(cName);
56 },
57 [](auto &visitor, const slang::syntax::SyntaxNode &node) {
58 visitor.visitDefault(node);
59 });
60 syntax->visit(visitor);
61}
62
63static void guessNamespacePrefix(const slang::ast::Symbol &symbol,
64 SmallString<64> &prefix) {
65 if (symbol.kind != slang::ast::SymbolKind::Package)
66 return;
67 guessNamespacePrefix(symbol.getParentScope()->asSymbol(), prefix);
68 if (!symbol.name.empty()) {
69 prefix += symbol.name;
70 prefix += "::";
71 }
72}
73
74//===----------------------------------------------------------------------===//
75// Base Visitor
76//===----------------------------------------------------------------------===//
77
78namespace {
79/// Base visitor which ignores AST nodes that are handled by Slang's name
80/// resolution and type checking.
81struct BaseVisitor {
82 Context &context;
83 Location loc;
84 OpBuilder &builder;
85
86 BaseVisitor(Context &context, Location loc)
87 : context(context), loc(loc), builder(context.builder) {}
88
89 // Skip semicolons.
90 LogicalResult visit(const slang::ast::EmptyMemberSymbol &) {
91 return success();
92 }
93
94 // Skip members that are implicitly imported from some other scope for the
95 // sake of name resolution, such as enum variant names.
96 LogicalResult visit(const slang::ast::TransparentMemberSymbol &) {
97 return success();
98 }
99
100 // Handle classes without parameters or specialized generic classes
101 LogicalResult visit(const slang::ast::ClassType &classdecl) {
102 if (failed(context.buildClassProperties(classdecl)))
103 return failure();
104 return context.materializeClassMethods(classdecl);
105 }
106
107 // GenericClassDefSymbol represents parameterized (template) classes, which
108 // per IEEE 1800-2023 §8.25 are abstract and not instantiable. Slang models
109 // concrete specializations as ClassType, so we skip GenericClassDefSymbol
110 // entirely.
111 LogicalResult visit(const slang::ast::GenericClassDefSymbol &) {
112 return success();
113 }
114
115 // Skip typedefs.
116 LogicalResult visit(const slang::ast::TypeAliasType &) { return success(); }
117 LogicalResult visit(const slang::ast::ForwardingTypedefSymbol &) {
118 return success();
119 }
120
121 // Skip imports. The AST already has its names resolved.
122 LogicalResult visit(const slang::ast::ExplicitImportSymbol &) {
123 return success();
124 }
125 LogicalResult visit(const slang::ast::WildcardImportSymbol &) {
126 return success();
127 }
128
129 // Skip type parameters. The Slang AST is already monomorphized.
130 LogicalResult visit(const slang::ast::TypeParameterSymbol &) {
131 return success();
132 }
133
134 // Skip elaboration system tasks. These are reported directly by Slang.
135 LogicalResult visit(const slang::ast::ElabSystemTaskSymbol &) {
136 return success();
137 }
138
139 // Handle UDP declarations.
140 LogicalResult visit(const slang::ast::PrimitiveSymbol &primitive) {
141 return context.convertUserDefinedPrimitiveDef(primitive);
142 }
143
144 // Handle parameters.
145 LogicalResult visit(const slang::ast::ParameterSymbol &param) {
146 visitParameter(param);
147 return success();
148 }
149
150 LogicalResult visit(const slang::ast::SpecparamSymbol &param) {
151 visitParameter(param);
152 return success();
153 }
154
155 template <class Node>
156 void visitParameter(const Node &param) {
157 // If debug info is enabled, try to materialize the parameter's constant
158 // value on a best-effort basis and create a `dbg.variable` to track the
159 // value.
160 if (!context.options.debugInfo)
161 return;
162 auto value =
163 context.materializeConstant(param.getValue(), param.getType(), loc);
164 if (!value)
165 return;
166 if (builder.getInsertionBlock()->getParentOp() == context.intoModuleOp) {
167 auto key = LocationKey::get(param.location, context.sourceManager);
168 context.orderedRootOps.insert({key, value.getDefiningOp()});
169 }
170
171 // Prefix the parameter name with the surrounding namespace to create
172 // somewhat sane names in the IR.
173 SmallString<64> paramName;
174 guessNamespacePrefix(param.getParentScope()->asSymbol(), paramName);
175 paramName += param.name;
176
177 debug::VariableOp::create(builder, loc, builder.getStringAttr(paramName),
178 value, Value{});
179 }
180};
181} // namespace
182
183//===----------------------------------------------------------------------===//
184// Top-Level Item Conversion
185//===----------------------------------------------------------------------===//
186
187namespace {
188struct RootVisitor : public BaseVisitor {
189 using BaseVisitor::BaseVisitor;
190 using BaseVisitor::visit;
191
192 // Handle packages.
193 LogicalResult visit(const slang::ast::PackageSymbol &package) {
194 return context.convertPackage(package);
195 }
196
197 // Handle functions and tasks.
198 LogicalResult visit(const slang::ast::SubroutineSymbol &subroutine) {
199 if (!context.declareFunction(subroutine))
200 return failure();
201 return success();
202 }
203
204 // Handle global variables.
205 LogicalResult visit(const slang::ast::VariableSymbol &var) {
206 return context.convertGlobalVariable(var);
207 }
208
209 // Emit an error for all other members.
210 template <typename T>
211 LogicalResult visit(T &&node) {
212 mlir::emitError(loc, "unsupported construct: ")
213 << slang::ast::toString(node.kind);
214 return failure();
215 }
216};
217} // namespace
218
219//===----------------------------------------------------------------------===//
220// Package Conversion
221//===----------------------------------------------------------------------===//
222
223namespace {
224struct PackageVisitor : public BaseVisitor {
225 using BaseVisitor::BaseVisitor;
226 using BaseVisitor::visit;
227
228 // Handle functions and tasks.
229 LogicalResult visit(const slang::ast::SubroutineSymbol &subroutine) {
230 if (!context.declareFunction(subroutine))
231 return failure();
232 return success();
233 }
234
235 // Handle global variables.
236 LogicalResult visit(const slang::ast::VariableSymbol &var) {
237 return context.convertGlobalVariable(var);
238 }
239
240 /// Emit an error for all other members.
241 template <typename T>
242 LogicalResult visit(T &&node) {
243 mlir::emitError(loc, "unsupported package member: ")
244 << slang::ast::toString(node.kind);
245 return failure();
246 }
247};
248} // namespace
249
250//===----------------------------------------------------------------------===//
251// Module Conversion
252//===----------------------------------------------------------------------===//
253
254static moore::ProcedureKind
255convertProcedureKind(slang::ast::ProceduralBlockKind kind) {
256 switch (kind) {
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;
269 }
270 llvm_unreachable("all procedure kinds handled");
271}
272
273static moore::NetKind convertNetKind(slang::ast::NetType::NetKind kind) {
274 switch (kind) {
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;
305 }
306 llvm_unreachable("all net kinds handled");
307}
308
309namespace {
310struct ModuleVisitor : public BaseVisitor {
311 using BaseVisitor::visit;
312
313 // A prefix of block names such as `foo.bar.` to put in front of variable and
314 // instance names.
315 StringRef blockNamePrefix;
316
317 ModuleVisitor(Context &context, Location loc, StringRef blockNamePrefix = "")
318 : BaseVisitor(context, loc), blockNamePrefix(blockNamePrefix) {}
319
320 // Skip ports which are already handled by the module itself.
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 &) {
324 return success();
325 }
326
327 // Skip genvars.
328 LogicalResult visit(const slang::ast::GenvarSymbol &genvarNode) {
329 return success();
330 }
331
332 // Skip defparams which have been handled by slang.
333 LogicalResult visit(const slang::ast::DefParamSymbol &) { return success(); }
334
335 // Ignore type parameters. These have already been handled by Slang's type
336 // checking.
337 LogicalResult visit(const slang::ast::TypeParameterSymbol &) {
338 return success();
339 }
340
341 // Expand an interface instance into individual variable/net ops
342 // in the enclosing module. Each signal declared in the interface body becomes
343 // a separate op, named with the instance name as a prefix.
344 LogicalResult
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);
349
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);
357 };
358
359 for (const auto &member : instNode.body.members()) {
360 // Error on nested interface instances.
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 << "`";
367 }
368 // Expand variables.
369 if (const auto *var = member.as_if<slang::ast::VariableSymbol>()) {
370 auto loweredType = context.convertType(*var->getDeclaredType());
371 if (!loweredType)
372 return failure();
373 auto varOp = moore::VariableOp::create(
374 builder, loc,
375 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
376 builder.getStringAttr(Twine(prefix) + StringRef(var->name)),
377 Value());
378 recordMember(*var, varOp);
379 continue;
380 }
381 // Expand nets
382 if (const auto *net = member.as_if<slang::ast::NetSymbol>()) {
383 auto loweredType = context.convertType(*net->getDeclaredType());
384 if (!loweredType)
385 return failure();
386 auto netKind = convertNetKind(net->netType.netKind);
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(
393 builder, loc,
394 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
395 builder.getStringAttr(Twine(prefix) + StringRef(net->name)),
396 netKind, Value());
397 recordMember(*net, netOp);
398 continue;
399 }
400 // Silently skip other members (modports, parameters , etc.)
401 }
402
403 // Record interface ports by mapping them to their connected expressions.
404 // This is required for virtual interface usage (e.g. `vif.clk`) and for
405 // modports that reference interface ports.
406 for (const auto *con : instNode.getPortConnections()) {
407 const auto *expr = con->getExpression();
408 const auto *port = con->port.as_if<slang::ast::PortSymbol>();
409 if (!port)
410 continue;
411 if (!expr) {
412 // Leave unconnected interface ports unresolved for now.
413 continue;
414 }
415
416 Value lvalue = context.convertLvalueExpression(*expr);
417 if (!lvalue)
418 return failure();
419
420 recordMember(*port, lvalue);
421 if (port->internalSymbol) {
422 recordMember(*port->internalSymbol, lvalue);
423 }
424 }
425
426 // Lower executable interface body members now that all interface signals
427 // and port bindings are available in the scoped `valueSymbols` table.
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:
433 break;
434 default:
435 continue;
436 }
437 auto memberLoc = context.convertLocation(member.location);
438 if (failed(member.visit(ModuleVisitor(context, memberLoc, prefix))))
439 return failure();
440 if (failed(context.flushPendingMonitors()))
441 return failure();
442 }
443
444 context.interfaceInstanceStorage.push_back(std::move(lowering));
445 context.interfaceInstances.insert(
446 &instNode, context.interfaceInstanceStorage.back().get());
447 return success();
448 }
449
450 // Handle instances.
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;
456
457 if (context.predeclaredInstances.contains(&instNode))
458 return success();
459
460 // Always operate on the canonical instance body if there is one.
461 // This means any symbols we record will be the symbols from the
462 // canonical body, which will match up with the symbols encountered
463 // by analyses which visit the canonical bodies.
464 const slang::ast::InstanceBodySymbol *body = getCanonicalBody(instNode);
465
466 // Interface instances are expanded inline into individual variable/net ops
467 // rather than creating a moore.instance op.
468 auto defKind = body->getDefinition().definitionKind;
469 if (defKind == slang::ast::DefinitionKind::Interface) {
470 if (context.interfaceInstances.lookup(&instNode))
471 return success();
472 return expandInterfaceInstance(instNode);
473 }
474
475 auto *moduleLowering = context.convertModuleHeader(body);
476 if (!moduleLowering)
477 return failure();
478 auto module = moduleLowering->op;
479 auto moduleType = module.getModuleType();
480
481 // Set visibility attribute for instantiated module.
482 SymbolTable::setSymbolVisibility(module, SymbolTable::Visibility::Private);
483
484 // Prepare the values that are involved in port connections. This creates
485 // rvalues for input ports and appropriate lvalues for output, inout, and
486 // ref ports. We also separate multi-ports into the individual underlying
487 // ports with their corresponding connection.
488 SmallDenseMap<const PortSymbol *, Value> portValues;
489 portValues.reserve(moduleType.getNumPorts());
490
491 // Map each InterfacePortSymbol to the connected interface instance.
492 SmallDenseMap<const slang::ast::InterfacePortSymbol *,
493 const slang::ast::InstanceSymbol *>
494 ifaceConnMap;
495
496 for (const auto *con : instNode.getPortConnections()) {
497 const auto *expr = con->getExpression();
498
499 // Handle unconnected behavior. The expression is null if it have no
500 // connection for the port.
501 if (!expr) {
502 auto *port = con->port.as_if<PortSymbol>();
503 if (auto *existingPort =
504 moduleLowering->portsBySyntaxNode.lookup(port->getSyntax()))
505 port = existingPort;
506
507 switch (port->direction) {
508 case ArgumentDirection::In: {
509 auto refType = moore::RefType::get(
510 cast<moore::UnpackedType>(context.convertType(port->getType())));
511
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),
517 convertNetKind(net->netType.netKind), nullptr);
518 auto readOp = moore::ReadOp::create(builder, loc, netOp);
519 portValues.insert({port, readOp});
520 } else if (const auto *var =
521 port->internalSymbol
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});
528 } else {
529 return mlir::emitError(loc)
530 << "unsupported internal symbol for unconnected port `"
531 << port->name << "`";
532 }
533 continue;
534 }
535
536 // No need to express unconnected behavior for output port, skip to the
537 // next iteration of the loop.
538 case ArgumentDirection::Out:
539 continue;
540
541 case ArgumentDirection::InOut:
542 case ArgumentDirection::Ref: {
543 auto refType = moore::RefType::get(
544 cast<moore::UnpackedType>(context.convertType(port->getType())));
545
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),
551 convertNetKind(net->netType.netKind), nullptr);
552 portValues.insert({port, netOp});
553 } else if (const auto *var =
554 port->internalSymbol
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});
560 } else {
561 return mlir::emitError(loc)
562 << "unsupported internal symbol for unconnected port `"
563 << port->name << "`";
564 }
565 continue;
566 }
567 }
568 }
569
570 // Unpack the `<expr> = EmptyArgument` pattern emitted by Slang for
571 // output and inout ports.
572 if (const auto *assign = expr->as_if<AssignmentExpression>())
573 expr = &assign->left();
574
575 // Regular ports lower the connected expression to an lvalue or rvalue and
576 // either attach it to the instance as an operand (for input, inout, and
577 // ref ports), or assign an instance output to it (for output ports).
578 if (auto *port = con->port.as_if<PortSymbol>()) {
579 // Convert as rvalue for inputs, lvalue for all others.
580 auto value = (port->direction == ArgumentDirection::In)
581 ? context.convertRvalueExpression(*expr)
582 : context.convertLvalueExpression(*expr);
583 if (!value)
584 return failure();
585 if (auto *existingPort =
586 moduleLowering->portsBySyntaxNode.lookup(con->port.getSyntax()))
587 port = existingPort;
588
589 // IEEE 1800-2017 §23.3.3 requires `inout` port connections to be direct
590 // connections, which does not allow for type conversion.
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();
598 }
599
600 portValues.insert({port, value});
601 continue;
602 }
603
604 // Multi-ports lower the connected expression to an lvalue and then slice
605 // it up into multiple sub-values, one for each of the ports in the
606 // multi-port.
607 if (const auto *multiPort = con->port.as_if<MultiPortSymbol>()) {
608 // Convert as lvalue.
609 auto value = context.convertLvalueExpression(*expr);
610 if (!value)
611 return failure();
612 unsigned offset = 0;
613 for (const auto *port : llvm::reverse(multiPort->ports)) {
614 if (auto *existingPort = moduleLowering->portsBySyntaxNode.lookup(
615 con->port.getSyntax()))
616 port = existingPort;
617 unsigned width = port->getType().getBitWidth();
618 auto sliceType = context.convertType(port->getType());
619 if (!sliceType)
620 return failure();
621 Value slice = moore::ExtractRefOp::create(
622 builder, loc,
623 moore::RefType::get(cast<moore::UnpackedType>(sliceType)), value,
624 offset);
625 // Create the "ReadOp" for input ports.
626 if (port->direction == ArgumentDirection::In)
627 slice = moore::ReadOp::create(builder, loc, slice);
628 portValues.insert({port, slice});
629 offset += width;
630 }
631 continue;
632 }
633
634 // Interface ports: record the connected interface instance for later
635 // resolution via InterfaceLowering.
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>();
641 if (connInst)
642 ifaceConnMap[ifacePort] = connInst;
643 continue;
644 }
645
646 mlir::emitError(loc) << "unsupported instance port `" << con->port.name
647 << "` (" << slang::ast::toString(con->port.kind)
648 << ")";
649 return failure();
650 }
651
652 // Match the module's ports up with the port values determined above.
653 // Values are placed by slot index so regular and expanded
654 // interface-modport ports interleave in declaration order.
655 SmallVector<Value> inputValues(moduleLowering->numExplicitInputs);
656 SmallVector<Value> outputValues(moduleLowering->numExplicitOutputs);
657
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;
662 else
663 inputValues[*port.inputIdx] = value;
664 }
665
666 // Resolve flattened interface port values. For each flattened port,
667 // look up the connected interface instance's InterfaceLowering and
668 // find the body member's expanded SSA value.
669 for (auto &fp : moduleLowering->ifacePorts) {
670 if (!fp.bodySym || !fp.origin)
671 continue;
672 // Find which interface instance is connected to this port.
673 auto it = ifaceConnMap.find(fp.origin);
674 if (it == ifaceConnMap.end()) {
675 mlir::emitError(loc)
676 << "no interface connection for port `" << fp.name << "`";
677 return failure();
678 }
679 const auto *connInst = it->second;
680 // Look up the InterfaceLowering for that instance.
681 auto *ifaceLowering = context.interfaceInstances.lookup(connInst);
682 if (!ifaceLowering) {
683 mlir::emitError(loc)
684 << "interface instance `" << connInst->name << "` was not expanded";
685 return failure();
686 }
687 // Find the expanded SSA value for this body member.
688 auto valIt = ifaceLowering->expandedMembers.find(fp.bodySym);
689 if (valIt == ifaceLowering->expandedMembers.end()) {
690 mlir::emitError(loc)
691 << "unresolved interface port signal `" << fp.name << "`";
692 return failure();
693 }
694 Value val = valIt->second;
695 if (fp.direction == hw::ModulePort::Output) {
696 outputValues[*fp.outputIdx] = val;
697 } else {
698 // For input ports, if the value is a ref (from VariableOp/NetOp),
699 // read it to get the rvalue, unless the port itself expects a ref.
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;
703 }
704 }
705
706 // Insert conversions for input ports. Unfilled slots (e.g. unresolved
707 // interface-modport ports) are reported by the null-check loop below.
708 for (auto [value, type] :
709 llvm::zip(inputValues, moduleType.getInputTypes())) {
710 if (!value)
711 continue;
712 // TODO: This should honor signedness in the conversion.
713 value = context.materializeConversion(type, value, false, value.getLoc());
714 if (!value)
715 return mlir::emitError(loc) << "unsupported port";
716 }
717
718 // Here we use the hierarchical value recorded in `Context::valueSymbols`.
719 // Then we pass it as the input port with the ref<T> type of the instance.
720 // Note that `body` is always the canonical instance body here and in the
721 // `hierPaths` keys.
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)
725 continue;
726 // Which alias is bound in scope depends on which subtree the reference
727 // was observed in, so try them all; a null value is caught below.
728 Value hierValue;
729 for (auto &alias : hierPath.valueSyms)
730 if ((hierValue = context.valueSymbols.lookup(alias.first)))
731 break;
732 inputValues.push_back(hierValue);
733 }
734
735 // Check that all input values are non-null before creating the instance.
736 for (auto value : inputValues)
737 if (!value)
738 return mlir::emitError(loc) << "unsupported port";
739
740 // Determine the name of the instance. Slang clears the name of instance
741 // array elements during elaboration; only the outermost array symbol
742 // retains the name written in the source. Reconstruct per-element names by
743 // appending the source index of each array dimension to the array name,
744 // such that `foo u [2:0][1:0]` produces `u_0_0`, `u_0_1`, `u_1_0`, etc.
745 // This mirrors the naming scheme used for for-generate blocks.
746 SmallString<64> instName(blockNamePrefix);
747 if (instNode.arrayPath.empty()) {
748 instName += instNode.name;
749 } else {
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)) {
754 instName += '_';
755 Twine(dim.lower() + int32_t(index)).toVector(instName);
756 }
757 }
758
759 // Create the instance op itself.
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);
768
769 // An alias belongs to this instance if the body containing its symbol is
770 // nested anywhere under the instance in the elaborated tree.
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)
776 return true;
777 return false;
778 };
779
780 // Record instance's results generated by hierarchical names.
781 // Store in both valueSymbols (for same-scope lookups) and the persistent
782 // hierValueSymbols map (for cross-scope lookups from other modules).
783 // The hierValueSymbols key is {&instNode, hierName} to ensure
784 // instance-specific resolution (e.g., p1 vs p2 get separate entries).
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;
792 }
793
794 // Assign output values from the instance to the connected expression.
795 for (auto [lvalue, output] : llvm::zip(outputValues, inst.getOutputs())) {
796 if (!lvalue)
797 continue;
798 Value rvalue = output;
799 auto dstType = cast<moore::RefType>(lvalue.getType()).getNestedType();
800 // TODO: This should honor signedness in the conversion.
801 rvalue = context.materializeConversion(dstType, rvalue, false, loc);
802 if (!rvalue)
803 return failure();
804 moore::ContinuousAssignOp::create(builder, loc, lvalue, rvalue);
805 }
806
807 return success();
808 }
809
810 // Handle variables.
811 LogicalResult visit(const slang::ast::VariableSymbol &varNode) {
812 auto ref = context.valueSymbols.lookup(&varNode);
813 if (!ref)
814 return mlir::emitError(loc)
815 << "internal error: missing predeclared variable `" << varNode.name
816 << "`";
817
818 auto varOp = ref.getDefiningOp<moore::VariableOp>();
819 if (!varOp)
820 return mlir::emitError(loc)
821 << "internal error: predeclared variable `" << varNode.name
822 << "` is not a moore.variable";
823
824 if (const auto *init = varNode.getInitializer()) {
825 auto loweredType = cast<moore::RefType>(ref.getType()).getNestedType();
826 auto initial = context.convertRvalueExpression(*init, loweredType);
827 if (!initial)
828 return failure();
829 varOp.getInitialMutable().assign(initial);
830 }
831
832 return success();
833 }
834
835 // Handle nets.
836 LogicalResult visit(const slang::ast::NetSymbol &netNode) {
837 auto ref = context.valueSymbols.lookup(&netNode);
838 if (!ref)
839 return mlir::emitError(loc) << "internal error: missing predeclared net `"
840 << netNode.name << "`";
841
842 auto netOp = ref.getDefiningOp<moore::NetOp>();
843 if (!netOp)
844 return mlir::emitError(loc) << "internal error: predeclared net `"
845 << netNode.name << "` is not a moore.net";
846
847 if (const auto *init = netNode.getInitializer()) {
848 auto loweredType = cast<moore::RefType>(ref.getType()).getNestedType();
849 auto assignment = context.convertRvalueExpression(*init, loweredType);
850 if (!assignment)
851 return failure();
852 netOp.getAssignmentMutable().assign(assignment);
853 }
854 return success();
855 }
856
857 // Handle continuous assignments.
858 LogicalResult visit(const slang::ast::ContinuousAssignSymbol &assignNode) {
859 const auto &expr =
860 assignNode.getAssignment().as<slang::ast::AssignmentExpression>();
861 auto lhs = context.convertLvalueExpression(expr.left());
862 if (!lhs)
863 return failure();
864
865 auto rhs = context.convertRvalueExpression(
866 expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
867 if (!rhs)
868 return failure();
869
870 // Handle delayed assignments.
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()));
875 if (!delay)
876 return failure();
877 moore::DelayedContinuousAssignOp::create(builder, loc, lhs, rhs, delay);
878 return success();
879 }
880 mlir::emitError(loc) << "unsupported delay with rise/fall/turn-off";
881 return failure();
882 }
883
884 // Otherwise this is a regular assignment.
885 moore::ContinuousAssignOp::create(builder, loc, lhs, rhs);
886 return success();
887 }
888
889 // Handle procedures.
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(
899 context.virtualIfaceMembers);
900 if (failed(context.convertStatement(body)))
901 return failure();
902 if (builder.getBlock())
903 moore::ReturnOp::create(builder, loc);
904 return success();
905 }
906
907 LogicalResult visit(const slang::ast::ProceduralBlockSymbol &procNode) {
908 // Slang wraps module-level concurrent assertions in a synthetic `always`
909 // procedure. The assertion is self-clocked, so it needs no process.
910 if (auto *syntax = procNode.getSyntax();
911 syntax &&
912 syntax->kind == slang::syntax::SyntaxKind::ConcurrentAssertionMember)
913 return context.convertStatement(procNode.getBody());
914
915 // Detect `always @(*) <stmt>` and convert to `always_comb <stmt>` if
916 // requested by the user.
917 if (context.options.lowerAlwaysAtStarAsComb) {
918 auto *stmt = procNode.getBody().as_if<slang::ast::TimedStatement>();
919 if (procNode.procedureKind == slang::ast::ProceduralBlockKind::Always &&
920 stmt &&
921 stmt->timing.kind == slang::ast::TimingControlKind::ImplicitEvent)
922 return convertProcedure(moore::ProcedureKind::AlwaysComb, stmt->stmt);
923 }
924
925 return convertProcedure(convertProcedureKind(procNode.procedureKind),
926 procNode.getBody());
927 }
928
929 // Handle generate block.
930 LogicalResult visit(const slang::ast::GenerateBlockSymbol &genNode) {
931 // Ignore uninstantiated blocks.
932 if (genNode.isUninstantiated)
933 return success();
934
935 // If the block has a name, add it to the list of block name prefices.
936 SmallString<64> prefix = blockNamePrefix;
937 if (!genNode.name.empty() ||
938 genNode.getParentScope()->asSymbol().kind !=
939 slang::ast::SymbolKind::GenerateBlockArray) {
940 prefix += genNode.getExternalName();
941 prefix += '.';
942 }
943
944 // Visit each member of the generate block.
945 for (auto &member : genNode.members())
946 if (failed(member.visit(ModuleVisitor(context, loc, prefix))))
947 return failure();
948 return success();
949 }
950
951 // Handle generate block array.
952 LogicalResult visit(const slang::ast::GenerateBlockArraySymbol &genArrNode) {
953 // If the block has a name, add it to the list of block name prefices and
954 // prepare to append the array index and a `.` in each iteration.
955 SmallString<64> prefix = blockNamePrefix;
956 prefix += genArrNode.getExternalName();
957 prefix += '_';
958 auto prefixBaseLen = prefix.size();
959
960 // Visit each iteration entry of the generate block.
961 for (const auto *entry : genArrNode.entries) {
962 // Append the index to the prefix.
963 prefix.resize(prefixBaseLen);
964 if (entry->arrayIndex)
965 prefix += entry->arrayIndex->toString();
966 else
967 Twine(entry->constructIndex).toVector(prefix);
968 prefix += '.';
969
970 // Visit this iteration entry.
971 if (failed(entry->asSymbol().visit(ModuleVisitor(context, loc, prefix))))
972 return failure();
973 }
974 return success();
975 }
976
977 // Ignore statement block symbols. These get generated by Slang for blocks
978 // with variables and other declarations. For example, having an initial
979 // procedure with a variable declaration, such as `initial begin int x;
980 // end`, will create the procedure with a block and variable declaration as
981 // expected, but will also create a `StatementBlockSymbol` with just the
982 // variable layout _next to_ the initial procedure.
983 LogicalResult visit(const slang::ast::StatementBlockSymbol &) {
984 return success();
985 }
986
987 // Ignore sequence declarations. The declarations are already evaluated by
988 // Slang and are part of an AssertionInstance.
989 LogicalResult visit(const slang::ast::SequenceSymbol &seqNode) {
990 return success();
991 }
992
993 // Ignore property declarations. The declarations are already evaluated by
994 // Slang and are part of an AssertionInstance.
995 LogicalResult visit(const slang::ast::PropertySymbol &propNode) {
996 return success();
997 }
998
999 // Ignore clocking blocks. The clocking is already inferred by slang at
1000 // each use.
1001 LogicalResult visit(const slang::ast::ClockingBlockSymbol &) {
1002 return success();
1003 }
1004
1005 // Ignore let declarations. Slang expands uses into AssertionInstance
1006 // expressions, which are lowered when the use site is imported.
1007 LogicalResult visit(const slang::ast::LetDeclSymbol &) { return success(); }
1008
1009 // Handle functions and tasks.
1010 LogicalResult visit(const slang::ast::SubroutineSymbol &subroutine) {
1011 if (!context.declareFunction(subroutine))
1012 return failure();
1013 return success();
1014 }
1015
1016 // Handle primitive instances.
1017 LogicalResult visit(const slang::ast::PrimitiveInstanceSymbol &prim) {
1018 return context.convertPrimitiveInstance(prim);
1019 }
1020
1021 // Handle instance arrays.
1022 LogicalResult visit(const slang::ast::InstanceArraySymbol &arrNode) {
1023 // Slang already nicely unrolls these into distinct instances for us.
1024 for (const auto *element : arrNode.elements)
1025 if (failed(element->visit(*this)))
1026 return failure();
1027 return success();
1028 }
1029
1030 /// Emit an error for all other members.
1031 template <typename T>
1032 LogicalResult visit(T &&node) {
1033 mlir::emitError(loc, "unsupported module member: ")
1034 << slang::ast::toString(node.kind);
1035 return failure();
1036 }
1037};
1038
1039struct ModulePredeclaration {
1040 Context &context;
1041 OpBuilder &builder;
1042
1043 ModulePredeclaration(Context &context)
1044 : context(context), builder(context.builder) {}
1045
1046 LogicalResult declareVariable(const slang::ast::VariableSymbol &varNode,
1047 Location loc, StringRef blockNamePrefix) {
1048 auto loweredType = context.convertType(*varNode.getDeclaredType());
1049 if (!loweredType)
1050 return failure();
1051
1052 auto varOp = moore::VariableOp::create(
1053 builder, loc,
1054 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
1055 builder.getStringAttr(Twine(blockNamePrefix) + varNode.name), Value{});
1056 context.valueSymbols.insert(&varNode, varOp);
1057
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)))
1061 return failure();
1062
1063 return success();
1064 }
1065
1066 LogicalResult declareNet(const slang::ast::NetSymbol &netNode, Location loc,
1067 StringRef blockNamePrefix) {
1068 auto loweredType = context.convertType(*netNode.getDeclaredType());
1069 if (!loweredType)
1070 return failure();
1071
1072 auto netkind = convertNetKind(netNode.netType.netKind);
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 << "`";
1078
1079 auto netOp = moore::NetOp::create(
1080 builder, loc,
1081 moore::RefType::get(cast<moore::UnpackedType>(loweredType)),
1082 builder.getStringAttr(Twine(blockNamePrefix) + netNode.name), netkind,
1083 Value{});
1084 context.valueSymbols.insert(&netNode, netOp);
1085 return success();
1086 }
1087
1088 SmallString<64>
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();
1096 prefix += '.';
1097 }
1098 return prefix;
1099 }
1100
1101 LogicalResult
1102 predeclareStorageGenerateBlock(const slang::ast::GenerateBlockSymbol &genNode,
1103 StringRef blockNamePrefix) {
1104 if (genNode.isUninstantiated)
1105 return success();
1106 return predeclareStorageScope(
1107 genNode, getGenerateBlockPrefix(genNode, blockNamePrefix));
1108 }
1109
1110 LogicalResult predeclareInterfaceGenerateBlock(
1111 const slang::ast::GenerateBlockSymbol &genNode,
1112 StringRef blockNamePrefix) {
1113 if (genNode.isUninstantiated)
1114 return success();
1115 return predeclareInterfaceScope(
1116 genNode, getGenerateBlockPrefix(genNode, blockNamePrefix));
1117 }
1118
1119 LogicalResult predeclareModuleInstanceGenerateBlock(
1120 const slang::ast::GenerateBlockSymbol &genNode,
1121 StringRef blockNamePrefix) {
1122 if (genNode.isUninstantiated)
1123 return success();
1124 return predeclareModuleInstanceScope(
1125 genNode, getGenerateBlockPrefix(genNode, blockNamePrefix));
1126 }
1127
1128 LogicalResult predeclareGenerateBlockArray(
1129 const slang::ast::GenerateBlockArraySymbol &genArrNode,
1130 StringRef blockNamePrefix,
1131 llvm::function_ref<LogicalResult(const slang::ast::GenerateBlockSymbol &,
1132 StringRef)>
1133 predeclareBlock) {
1134 SmallString<64> prefix = blockNamePrefix;
1135 prefix += genArrNode.getExternalName();
1136 prefix += '_';
1137 auto prefixBaseLen = prefix.size();
1138
1139 for (const auto *entry : genArrNode.entries) {
1140 prefix.resize(prefixBaseLen);
1141 if (entry->arrayIndex)
1142 prefix += entry->arrayIndex->toString();
1143 else
1144 Twine(entry->constructIndex).toVector(prefix);
1145 prefix += '.';
1146
1147 if (failed(predeclareBlock(*entry, prefix)))
1148 return failure();
1149 }
1150 return success();
1151 }
1152
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);
1158
1159 if (const auto *netNode = member.as_if<slang::ast::NetSymbol>())
1160 return declareNet(*netNode, loc, blockNamePrefix);
1161
1162 if (const auto *genNode = member.as_if<slang::ast::GenerateBlockSymbol>())
1163 return predeclareStorageGenerateBlock(*genNode, blockNamePrefix);
1164
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);
1171 });
1172
1173 return success();
1174 }
1175
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);
1184 return success();
1185 }
1186
1187 if (const auto *genNode = member.as_if<slang::ast::GenerateBlockSymbol>())
1188 return predeclareInterfaceGenerateBlock(*genNode, blockNamePrefix);
1189
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);
1196 });
1197
1198 return success();
1199 }
1200
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) {
1207 if (failed(
1208 ModuleVisitor(context, loc, blockNamePrefix).visit(*instNode)))
1209 return failure();
1210 context.predeclaredInstances.insert(instNode);
1211 }
1212 return success();
1213 }
1214
1215 if (const auto *arrNode = member.as_if<slang::ast::InstanceArraySymbol>()) {
1216 for (const auto *element : arrNode->elements)
1217 if (failed(predeclareModuleInstanceMember(*element, blockNamePrefix)))
1218 return failure();
1219 return success();
1220 }
1221
1222 if (const auto *genNode = member.as_if<slang::ast::GenerateBlockSymbol>())
1223 return predeclareModuleInstanceGenerateBlock(*genNode, blockNamePrefix);
1224
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);
1231 });
1232
1233 return success();
1234 }
1235
1236 LogicalResult predeclareStorageScope(const slang::ast::Scope &scope,
1237 StringRef blockNamePrefix) {
1238 for (auto &member : scope.members())
1239 if (failed(predeclareStorageMember(member, blockNamePrefix)))
1240 return failure();
1241 return success();
1242 }
1243
1244 LogicalResult predeclareInterfaceScope(const slang::ast::Scope &scope,
1245 StringRef blockNamePrefix) {
1246 for (auto &member : scope.members())
1247 if (failed(predeclareInterfaceMember(member, blockNamePrefix)))
1248 return failure();
1249 return success();
1250 }
1251
1252 LogicalResult predeclareModuleInstanceScope(const slang::ast::Scope &scope,
1253 StringRef blockNamePrefix) {
1254 for (auto &member : scope.members())
1255 if (failed(predeclareModuleInstanceMember(member, blockNamePrefix)))
1256 return failure();
1257 return success();
1258 }
1259
1260 LogicalResult predeclareScope(const slang::ast::Scope &scope,
1261 StringRef blockNamePrefix) {
1262 // First create variables and nets for the whole generated scope tree so
1263 // later phases can bind port connections or hierarchical references to
1264 // declarations that appear later in source.
1265 if (failed(predeclareStorageScope(scope, blockNamePrefix)))
1266 return failure();
1267
1268 // Then expand interface instances. Interface expansion may lower
1269 // continuous assignments or procedures from the interface body, so all
1270 // storage symbols must already be available.
1271 if (failed(predeclareInterfaceScope(scope, blockNamePrefix)))
1272 return failure();
1273
1274 // Finally instantiate modules. This makes later hierarchical references
1275 // to instance internals available before earlier procedural blocks lower.
1276 return predeclareModuleInstanceScope(scope, blockNamePrefix);
1277 }
1278};
1279} // namespace
1280
1281//===----------------------------------------------------------------------===//
1282// Structure and Hierarchy Conversion
1283//===----------------------------------------------------------------------===//
1284
1285/// Convert an entire Slang compilation to MLIR ops. This is the main entry
1286/// point for the conversion.
1288 const auto &root = compilation.getRoot();
1289
1290 // Keep track of the local time scale. `getTimeScale` automatically looks
1291 // through parent scopes to find the time scale effective locally.
1292 auto prevTimeScale = timeScale;
1293 timeScale = root.getTimeScale().value_or(slang::TimeScale());
1294 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
1295
1296 // Analyze function captures upfront so that function declarations can be
1297 // created with the correct signature including capture parameters.
1298 SmallVector<AmbiguousHierCapture> ambiguousHierCaptures;
1299 functionCaptures = analyzeFunctionCaptures(root, 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";
1305 d.attachNote(convertLocation(ambiguous.symbol->location))
1306 << "symbol declared here";
1307 }
1308 if (!ambiguousHierCaptures.empty())
1309 return failure();
1310
1311 // Visit the whole AST to collect the hierarchical names without any operation
1312 // creating.
1313 for (auto *inst : root.topInstances)
1314 traverseInstanceBody(*inst);
1315
1316 // Analyze the compilation to infer clocks for assertion system calls
1317 // using Slang's LRM clock inference.
1319
1320 // Visit all top-level declarations in all compilation units. This does not
1321 // include instantiable constructs like modules, interfaces, and programs,
1322 // which are listed separately as top instances.
1323 for (auto *unit : root.compilationUnits) {
1324 recordDPIExportDirectives(*this, *unit, unit->getSyntax());
1325 for (const auto &member : unit->members()) {
1326 auto loc = convertLocation(member.location);
1327 if (failed(member.visit(RootVisitor(*this, loc))))
1328 return failure();
1329 }
1330 }
1331
1332 // Prime the root definition worklist by adding all the top-level modules.
1333 // Interfaces are not lowered as modules; they are expanded inline at each
1334 // use site, so skip them here.
1335 SmallVector<const slang::ast::InstanceSymbol *> topInstances;
1336 for (auto *inst : root.topInstances) {
1337 const slang::ast::InstanceBodySymbol *body = getCanonicalBody(*inst);
1338 if (body->getDefinition().definitionKind !=
1339 slang::ast::DefinitionKind::Interface)
1340 if (!convertModuleHeader(body))
1341 return failure();
1342 }
1343
1344 // Convert all the root module definitions.
1345 while (!moduleWorklist.empty()) {
1346 auto *module = moduleWorklist.front();
1347 moduleWorklist.pop();
1348 if (failed(convertModuleBody(module)))
1349 return failure();
1350 }
1351
1352 // It's possible that after converting modules, we haven't converted all
1353 // methods yet, especially if they are unused. Do that in this pass.
1354 SmallVector<const slang::ast::ClassType *, 16> classMethodWorklist;
1355 classMethodWorklist.reserve(classes.size());
1356 for (auto &kv : classes)
1357 classMethodWorklist.push_back(kv.first);
1358
1359 for (auto *inst : classMethodWorklist) {
1360 if (failed(materializeClassMethods(*inst)))
1361 return failure();
1362 }
1363
1364 // Define all function bodies. Functions are declared (and pushed onto the
1365 // worklist) during module body conversion and class method materialization.
1366 // Defining a function body may discover additional functions through call
1367 // expressions, which are declared and added to the worklist on the fly.
1368 while (!functionWorklist.empty()) {
1369 auto *fn = functionWorklist.front();
1370 functionWorklist.pop();
1371 if (failed(defineFunction(*fn)))
1372 return failure();
1373 }
1374
1375 // Convert the initializers of global variables.
1376 for (auto *var : globalVariableWorklist) {
1377 auto varOp = globalVariables.at(var);
1378 auto &block = varOp.getInitRegion().emplaceBlock();
1379 OpBuilder::InsertionGuard guard(builder);
1380 builder.setInsertionPointToEnd(&block);
1381 auto value =
1382 convertRvalueExpression(*var->getInitializer(), varOp.getType());
1383 if (!value)
1384 return failure();
1385 moore::YieldOp::create(builder, varOp.getLoc(), value);
1386 }
1387 globalVariableWorklist.clear();
1388
1389 return success();
1390}
1391
1392void Context::convertAttributes(const slang::ast::Symbol &symbol,
1393 Operation *op) {
1394 SmallVector<sv::SVAttributeAttr> svAttrs;
1395 for (const slang::ast::AttributeSymbol *attr :
1396 compilation.getAttributes(symbol)) {
1397 StringAttr exprAttr;
1398 if (const slang::syntax::SyntaxNode *syntax = attr->getSyntax()) {
1399 const auto &spec = syntax->as<slang::syntax::AttributeSpecSyntax>();
1400 if (spec.value) {
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());
1406 } else {
1407 exprAttr = builder.getStringAttr(attr->getValue().toString(
1408 /*abbreviateThresholdBits=*/slang::SVInt::MAX_BITS));
1409 }
1410 }
1411 }
1412 svAttrs.push_back(sv::SVAttributeAttr::get(
1413 getContext(), builder.getStringAttr(attr->name), exprAttr,
1414 /*emitAsComment=*/false));
1415 }
1416 if (!svAttrs.empty())
1417 sv::setSVAttributes(op, svAttrs);
1418}
1419
1421Context::convertModuleHeader(const slang::ast::InstanceBodySymbol *module) {
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;
1427
1428 // Keep track of the local time scale. `getTimeScale` automatically looks
1429 // through parent scopes to find the time scale effective locally.
1430 auto prevTimeScale = timeScale;
1431 timeScale = module->getTimeScale().value_or(slang::TimeScale());
1432 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
1433
1434 // `module` is the canonical module body if it exists (i.e. deduplicated by
1435 // slang).
1436 auto &slot = modules[module];
1437 if (slot)
1438 return slot.get();
1439 slot = std::make_unique<ModuleLowering>();
1440 auto &lowering = *slot;
1441
1442 auto loc = convertLocation(module->location);
1443 OpBuilder::InsertionGuard g(builder);
1444
1445 // We only support modules and programs here. Interfaces are handled
1446 // separately by expanding them inline at each use site (see
1447 // expandInterfaceInstance in ModuleVisitor)
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();
1453 return {};
1454 }
1455
1456 // Handle the port list.
1457 auto block = std::make_unique<Block>();
1458 SmallVector<hw::ModulePort> modulePorts;
1459
1460 // It's used to tag where a hierarchical name is on the port list.
1461 unsigned int outputIdx = 0, inputIdx = 0;
1462 for (auto *symbol : module->getPortList()) {
1463 auto handlePort = [&](const PortSymbol &port) {
1464 auto portLoc = convertLocation(port.location);
1465 auto type = convertType(port.getType());
1466 if (!type)
1467 return failure();
1468 auto portName = builder.getStringAttr(port.name);
1469 BlockArgument arg;
1470 std::optional<unsigned> portOutputIdx;
1471 std::optional<unsigned> portInputIdx;
1472 if (port.direction == ArgumentDirection::Out) {
1473 modulePorts.push_back({portName, type, hw::ModulePort::Output});
1474 portOutputIdx = outputIdx++;
1475 } else {
1476 // Only the ref type wrapper exists for the time being, the net type
1477 // wrapper for inout may be introduced later if necessary.
1478 if (port.direction != ArgumentDirection::In)
1479 type = moore::RefType::get(cast<moore::UnpackedType>(type));
1480 modulePorts.push_back({portName, type, hw::ModulePort::Input});
1481 arg = block->addArgument(type, portLoc);
1482 portInputIdx = inputIdx++;
1483 }
1484 lowering.ports.push_back(
1485 {port, portLoc, arg, portOutputIdx, portInputIdx});
1486 return success();
1487 };
1488
1489 // Lambda to handle interface ports by flattening them into individual
1490 // signal ports. Uses modport directions if a modport is specified,
1491 // otherwise treats all signals as inout (ref type)
1492 auto handleIfacePort = [&](const slang::ast::InterfacePortSymbol
1493 &ifacePort) {
1494 auto portLoc = convertLocation(ifacePort.location);
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();
1499
1500 if (modportSym) {
1501 // Modport specified: iterate modport members for signal directions.
1502 for (const auto &member : modportSym->members()) {
1503 const auto *mpp = member.as_if<slang::ast::ModportPortSymbol>();
1504 if (!mpp)
1505 continue;
1506 auto type = convertType(mpp->getType());
1507 if (!type)
1508 return failure();
1509 auto name =
1510 builder.getStringAttr(Twine(portPrefix) + StringRef(mpp->name));
1511 BlockArgument arg;
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++;
1519 } else {
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++;
1526 }
1527 lowering.ifacePorts.push_back(
1528 {name, dir, type, portLoc, arg, &ifacePort, mpp->internalSymbol,
1529 ifaceInst, mpp, ifaceOutputIdx, ifaceInputIdx});
1530 }
1531 } else {
1532 // No modport: iterate interface body for all variables and nets.
1533 // Treat them all as inout (input with ref type).
1534 const auto *instSym = connSym->as_if<slang::ast::InstanceSymbol>();
1535 if (!instSym) {
1536 mlir::emitError(portLoc)
1537 << "unsupported interface port connection for `" << ifacePort.name
1538 << "`";
1539 return failure();
1540 }
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();
1546 bodySym = var;
1547 } else if (const auto *net = member.as_if<slang::ast::NetSymbol>()) {
1548 slangType = &net->getType();
1549 bodySym = net;
1550 } else {
1551 continue;
1552 }
1553 auto type = convertType(*slangType);
1554 if (!type)
1555 return failure();
1556 auto name = builder.getStringAttr(Twine(portPrefix) +
1557 StringRef(bodySym->name));
1558 auto refType = moore::RefType::get(cast<moore::UnpackedType>(type));
1559 modulePorts.push_back({name, refType, hw::ModulePort::Input});
1560 auto arg = block->addArgument(refType, portLoc);
1561 lowering.ifacePorts.push_back(
1562 {name, hw::ModulePort::Input, refType, portLoc, arg, &ifacePort,
1563 bodySym, instSym, nullptr, std::nullopt, inputIdx++});
1564 }
1565 }
1566 return success();
1567 };
1568
1569 if (const auto *port = symbol->as_if<PortSymbol>()) {
1570 if (failed(handlePort(*port)))
1571 return {};
1572 } else if (const auto *multiPort = symbol->as_if<MultiPortSymbol>()) {
1573 for (auto *port : multiPort->ports)
1574 if (failed(handlePort(*port)))
1575 return {};
1576 } else if (const auto *ifacePort =
1577 symbol->as_if<slang::ast::InterfacePortSymbol>()) {
1578 if (failed(handleIfacePort(*ifacePort)))
1579 return {};
1580 } else {
1581 mlir::emitError(convertLocation(symbol->location))
1582 << "unsupported module port `" << symbol->name << "` ("
1583 << slang::ast::toString(symbol->kind) << ")";
1584 return {};
1585 }
1586 }
1587
1588 // Record explicit-port counts before hierarchical-name ports are appended.
1589 lowering.numExplicitOutputs = outputIdx;
1590 lowering.numExplicitInputs = inputIdx;
1591
1592 // Mapping hierarchical names into the module's ports.
1593 for (auto &hierPath : hierPaths[module]) {
1594 assert(!hierPath.valueSyms.empty() && "hierPath must have valueSyms");
1595 auto hierType = convertType(hierPath.valueSyms.front().first->getType());
1596 if (!hierType)
1597 return {};
1598
1599 if (auto hierName = hierPath.hierName) {
1600 // The type of all hierarchical names are marked as the "RefType".
1601 hierType = moore::RefType::get(cast<moore::UnpackedType>(hierType));
1602 if (hierPath.direction == ArgumentDirection::Out) {
1603 hierPath.idx = outputIdx++;
1604 modulePorts.push_back({hierName, hierType, hw::ModulePort::Output});
1605 } else {
1606 hierPath.idx = inputIdx++;
1607 modulePorts.push_back({hierName, hierType, hw::ModulePort::Input});
1608 auto hierLoc =
1609 convertLocation(hierPath.valueSyms.front().first->location);
1610 block->addArgument(hierType, hierLoc);
1611 }
1612 }
1613 }
1614 auto moduleType = hw::ModuleType::get(getContext(), modulePorts);
1615
1616 // Pick an insertion point for this module according to the source file
1617 // location.
1618 auto key = LocationKey::get(module->location, sourceManager);
1619 auto it = orderedRootOps.upper_bound(key);
1620 if (it == orderedRootOps.end())
1621 builder.setInsertionPointToEnd(intoModuleOp.getBody());
1622 else
1623 builder.setInsertionPoint(it->second);
1624
1625 // Create an empty module that corresponds to this module.
1626 auto moduleOp =
1627 moore::SVModuleOp::create(builder, loc, module->name, moduleType);
1628 convertAttributes(module->getDefinition(), moduleOp);
1629 orderedRootOps.insert(it, {key, moduleOp});
1630 moduleOp.getBodyRegion().push_back(block.release());
1631 lowering.op = moduleOp;
1632
1633 // Add the module to the symbol table of the MLIR module, which uniquifies its
1634 // name as we'd expect.
1635 symbolTable.insert(moduleOp);
1636
1637 // Schedule the body to be lowered.
1638 moduleWorklist.push(module);
1639
1640 // Map duplicate port by Syntax
1641 for (const auto &port : lowering.ports)
1642 lowering.portsBySyntaxNode.insert({port.ast.getSyntax(), &port.ast});
1643
1644 return &lowering;
1645}
1646
1647LogicalResult
1648Context::convertModuleBody(const slang::ast::InstanceBodySymbol *module) {
1649 auto &lowering = *modules[module];
1650 const auto *prevDefinition = currentDefinition;
1651 currentDefinition = &module->getDefinition();
1652 llvm::scope_exit currentDefinitionGuard(
1653 [&] { currentDefinition = prevDefinition; });
1654 recordDPIExportDirectives(*this, *module, module->getSyntax());
1655
1656 OpBuilder::InsertionGuard g(builder);
1657 builder.setInsertionPointToEnd(lowering.op.getBody());
1658
1662
1663 // Keep track of the local time scale. `getTimeScale` automatically looks
1664 // through parent scopes to find the time scale effective locally.
1665 auto prevTimeScale = timeScale;
1666 timeScale = module->getTimeScale().value_or(slang::TimeScale());
1667 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
1668
1669 // Collect downward hierarchical names. Such as,
1670 // module SubA; int x = Top.y; endmodule. The "Top" module is the parent of
1671 // the "SubA", so "Top.y" is the downward hierarchical name.
1672 for (auto &hierPath : hierPaths[module])
1673 if (hierPath.direction == slang::ast::ArgumentDirection::In &&
1674 hierPath.idx) {
1675 auto arg = lowering.op.getBody()->getArgument(*hierPath.idx);
1676 for (auto &alias : hierPath.valueSyms)
1677 valueSymbols.insert(alias.first, arg);
1678 }
1679
1680 // Register flattened interface port members before lowering the module body
1681 // so expressions can refer to them. Also build per-port interface instance
1682 // lowerings, which enables materializing virtual interface values from
1683 // interface ports.
1684 DenseMap<const slang::ast::InstanceSymbol *, InterfaceLowering *>
1685 ifacePortLowerings;
1686
1687 auto getIfacePortLowering =
1688 [&](const slang::ast::InstanceSymbol *ifaceInst) -> InterfaceLowering * {
1689 if (!ifaceInst)
1690 return nullptr;
1691 if (auto *existing = interfaceInstances.lookup(ifaceInst))
1692 return existing;
1693 if (auto it = ifacePortLowerings.find(ifaceInst);
1694 it != ifacePortLowerings.end())
1695 return it->second;
1696
1697 auto lowering = std::make_unique<InterfaceLowering>();
1698 InterfaceLowering *ptr = lowering.get();
1699 interfaceInstanceStorage.push_back(std::move(lowering));
1700 interfaceInstances.insert(ifaceInst, ptr);
1701 ifacePortLowerings.try_emplace(ifaceInst, ptr);
1702 return ptr;
1703 };
1704
1705 for (auto &fp : lowering.ifacePorts) {
1706 if (!fp.bodySym)
1707 continue;
1708 auto *valueSym = fp.bodySym->as_if<slang::ast::ValueSymbol>();
1709 if (!valueSym)
1710 continue;
1711
1712 Value portValue;
1713 if (fp.direction == hw::ModulePort::Output) {
1714 // Output interface ports are not referenceable within the module body.
1715 // Create internal variables for them and return their value through the
1716 // module terminator.
1717 portValue = moore::VariableOp::create(
1718 builder, fp.loc,
1719 moore::RefType::get(cast<moore::UnpackedType>(fp.type)), fp.name,
1720 Value());
1721 } else {
1722 portValue = fp.arg;
1723 }
1724 valueSymbols.insert(valueSym, portValue);
1725 // Slang resolves in-body accesses (e.g. `bus.r`) through the
1726 // ModportPortSymbol rather than the interface body's variable. Register
1727 // both so the body-level expression lookup finds this port.
1728 if (fp.modportPortSym)
1729 if (auto *mppSym = fp.modportPortSym->as_if<slang::ast::ValueSymbol>())
1730 if (mppSym != valueSym)
1731 valueSymbols.insert(mppSym, portValue);
1732
1733 if (!fp.ifaceInstance)
1734 continue;
1735 if (Value val = valueSymbols.lookup(valueSym)) {
1736 auto *ifaceLowering = getIfacePortLowering(fp.ifaceInstance);
1737 if (!ifaceLowering)
1738 continue;
1739 ifaceLowering->expandedMembers[fp.bodySym] = val;
1740 ifaceLowering
1741 ->expandedMembersByName[builder.getStringAttr(fp.bodySym->name)] =
1742 val;
1743 }
1744 }
1745
1746 predeclaredInstances.clear();
1747 llvm::scope_exit predeclaredInstancesGuard(
1748 [&] { predeclaredInstances.clear(); });
1749
1750 // Always create module-scope storage, expanded interface members, and
1751 // instance shells before the source-order body walk. Slang rejects
1752 // use-before-declare before ImportVerilog runs unless the option is enabled,
1753 // but once the AST is valid this predeclaration supports both source-order
1754 // and forward references. Declaration initializers are still lowered when the
1755 // body visitor reaches the declaration, so they see the same local context as
1756 // other source-ordered expressions.
1757 if (failed(ModulePredeclaration(*this).predeclareScope(*module, "")))
1758 return failure();
1759
1760 // Convert the body of the module.
1761 for (auto &member : module->members()) {
1762 auto loc = convertLocation(member.location);
1763 if (failed(member.visit(ModuleVisitor(*this, loc))))
1764 return failure();
1765 // Flush any pending monitors after each member. This places the monitor
1766 // procedures immediately after the code that sets them up.
1767 if (failed(flushPendingMonitors()))
1768 return failure();
1769 }
1770
1771 // Create additional ops to drive input port values onto the corresponding
1772 // internal variables and nets, and to collect output port values for the
1773 // terminator. Outputs are placed by slot index so regular and
1774 // interface-modport outputs interleave in declaration order.
1775 SmallVector<Value> outputs(lowering.numExplicitOutputs);
1776 for (auto &port : lowering.ports) {
1777 Value value;
1778 if (auto *expr = port.ast.getInternalExpr()) {
1779 value = convertLvalueExpression(*expr);
1780 } else if (port.ast.internalSymbol) {
1781 if (const auto *sym =
1782 port.ast.internalSymbol->as_if<slang::ast::ValueSymbol>())
1783 value = valueSymbols.lookup(sym);
1784 }
1785 if (!value)
1786 return mlir::emitError(port.loc, "unsupported port: `")
1787 << port.ast.name
1788 << "` does not map to an internal symbol or expression";
1789
1790 // Collect output port values to be returned in the terminator.
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;
1795 continue;
1796 }
1797
1798 // Assign the value coming in through the port to the internal net or symbol
1799 // of that port.
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);
1804 }
1805
1806 // Collect output values for flattened interface ports. The internal
1807 // references are set up before lowering the module body.
1808 for (auto &fp : lowering.ifacePorts) {
1809 if (fp.direction != hw::ModulePort::Output)
1810 continue;
1811 auto *valueSym =
1812 fp.bodySym ? fp.bodySym->as_if<slang::ast::ValueSymbol>() : nullptr;
1813 if (!valueSym)
1814 continue;
1815 Value ref = valueSymbols.lookup(valueSym);
1816 if (!ref)
1817 continue;
1818 outputs[*fp.outputIdx] =
1819 moore::ReadOp::create(builder, fp.loc, ref).getResult();
1820 }
1821
1822 // Ensure the number of operands of this module's terminator and the number of
1823 // its(the current module) output ports remain consistent.
1824 for (auto &hierPath : hierPaths[module]) {
1825 assert(!hierPath.valueSyms.empty() && "hierPath must have valueSyms");
1826 if (hierPath.direction != slang::ast::ArgumentDirection::Out)
1827 continue;
1828 // A Symbol lowered in this module body resolves through the scoped table.
1829 Value hierValue;
1830 for (auto &alias : hierPath.valueSyms)
1831 if ((hierValue = valueSymbols.lookup(alias.first)))
1832 break;
1833 // Otherwise the value comes from an inner instance's hierarchical port:
1834 // strip the leading instance name and use the instance-keyed map.
1835 if (!hierValue) {
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)) {
1843 hierValue = hierValueSymbols.lookup({inst, innerName});
1844 break;
1845 }
1846 } else if (auto *sym =
1847 module->find(std::string_view(name.data(), name.size()))) {
1848 // A dot-free path names a symbol declared directly in this module.
1849 if (auto *valueSym = sym->as_if<slang::ast::ValueSymbol>())
1850 hierValue = valueSymbols.lookup(valueSym);
1851 }
1852 }
1853 if (!hierValue)
1854 return mlir::emitError(lowering.op.getLoc())
1855 << "unable to resolve hierarchical output `"
1856 << hierPath.hierName.getValue() << "` in module `" << module->name
1857 << "`";
1858 outputs.push_back(hierValue);
1859 }
1860
1861 moore::OutputOp::create(builder, lowering.op.getLoc(), outputs);
1862 return success();
1863}
1864
1865/// Convert a package and its contents.
1866LogicalResult
1867Context::convertPackage(const slang::ast::PackageSymbol &package) {
1868 // Keep track of the local time scale. `getTimeScale` automatically looks
1869 // through parent scopes to find the time scale effective locally.
1870 auto prevTimeScale = timeScale;
1871 timeScale = package.getTimeScale().value_or(slang::TimeScale());
1872 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
1873
1874 recordDPIExportDirectives(*this, package, package.getSyntax());
1875
1876 OpBuilder::InsertionGuard g(builder);
1877 builder.setInsertionPointToEnd(intoModuleOp.getBody());
1879 for (auto &member : package.members()) {
1880 auto loc = convertLocation(member.location);
1881 if (failed(member.visit(PackageVisitor(*this, loc))))
1882 return failure();
1883 }
1884 return success();
1885}
1886
1887/// Convert a function and its arguments to a function declaration in the IR.
1888/// This does not convert the function body.
1890Context::declareFunction(const slang::ast::SubroutineSymbol &subroutine) {
1891 // Check if there already is a declaration for this function.
1892 auto &lowering = functions[&subroutine];
1893 if (lowering) {
1894 if (!lowering->op.getOperation())
1895 return {};
1896 return lowering.get();
1897 }
1898
1899 if (!subroutine.thisVar) {
1900
1901 SmallString<64> name;
1902 guessNamespacePrefix(subroutine.getParentScope()->asSymbol(), name);
1903 name += subroutine.name;
1904
1905 SmallVector<Type, 1> noThis = {};
1906 return declareCallableImpl(subroutine, name, noThis);
1907 }
1908
1909 auto loc = convertLocation(subroutine.location);
1910
1911 // Extract 'this' type and ensure it's a class.
1912 const slang::ast::Type &thisTy = subroutine.thisVar->getType();
1913 moore::ClassDeclOp ownerDecl;
1914
1915 if (auto *classTy = thisTy.as_if<slang::ast::ClassType>()) {
1916 auto &ownerLowering = classes[classTy];
1917 ownerDecl = ownerLowering->op;
1918 } else {
1919 mlir::emitError(loc) << "expected 'this' to be a class type, got "
1920 << thisTy.toString();
1921 return {};
1922 }
1923
1924 // Build qualified name: @"Pkg::Class"::subroutine
1925 SmallString<64> qualName;
1926 qualName += ownerDecl.getSymName(); // already qualified
1927 qualName += "::";
1928 qualName += subroutine.name;
1929
1930 // %this : class<@C>
1931 SmallVector<Type, 1> extraParams;
1932 {
1933 auto classSym = mlir::FlatSymbolRefAttr::get(ownerDecl.getSymNameAttr());
1934 auto handleTy = moore::ClassHandleType::get(getContext(), classSym);
1935 extraParams.push_back(handleTy);
1936 }
1937
1938 auto *fLowering = declareCallableImpl(subroutine, qualName, extraParams);
1939 return fLowering;
1940}
1941
1942/// Helper function to generate the function signature from a SubroutineSymbol
1943/// and optional extra arguments (used for %this argument)
1944static FunctionType getFunctionSignature(
1945 Context &context, const slang::ast::SubroutineSymbol &subroutine,
1946 ArrayRef<Type> prefixParams, ArrayRef<Type> suffixParams = {}) {
1947 using slang::ast::ArgumentDirection;
1948
1949 SmallVector<Type> inputTypes;
1950 inputTypes.append(prefixParams.begin(), prefixParams.end());
1951 SmallVector<Type, 1> outputTypes;
1952
1953 for (const auto *arg : subroutine.getArguments()) {
1954 auto type = context.convertType(arg->getType());
1955 if (!type)
1956 return {};
1957 if (arg->direction == ArgumentDirection::In) {
1958 inputTypes.push_back(type);
1959 } else {
1960 inputTypes.push_back(
1961 moore::RefType::get(cast<moore::UnpackedType>(type)));
1962 }
1963 }
1964
1965 inputTypes.append(suffixParams.begin(), suffixParams.end());
1966
1967 const auto &returnType = subroutine.getReturnType();
1968 if (!returnType.isVoid()) {
1969 auto type = context.convertType(returnType);
1970 if (!type)
1971 return {};
1972 outputTypes.push_back(type);
1973 }
1974
1975 return FunctionType::get(context.getContext(), inputTypes, outputTypes);
1976}
1977
1978static FailureOr<SmallVector<moore::DPIArgInfo>>
1980 const slang::ast::SubroutineSymbol &subroutine) {
1981 using slang::ast::ArgumentDirection;
1982
1983 SmallVector<moore::DPIArgInfo> args;
1984 args.reserve(subroutine.getArguments().size() +
1985 (!subroutine.getReturnType().isVoid() ? 1 : 0));
1986
1987 for (const auto *arg : subroutine.getArguments()) {
1988 auto type = context.convertType(arg->getType());
1989 if (!type)
1990 return failure();
1991 moore::DPIArgDirection dir;
1992 switch (arg->direction) {
1993 case ArgumentDirection::In:
1994 dir = moore::DPIArgDirection::In;
1995 break;
1996 case ArgumentDirection::Out:
1997 dir = moore::DPIArgDirection::Out;
1998 break;
1999 case ArgumentDirection::InOut:
2000 dir = moore::DPIArgDirection::InOut;
2001 break;
2002 case ArgumentDirection::Ref:
2003 llvm_unreachable("'ref' is not legal for DPI functions");
2004 }
2005 args.push_back(
2006 {StringAttr::get(context.getContext(), arg->name), type, dir});
2007 }
2008
2009 if (!subroutine.getReturnType().isVoid()) {
2010 auto type = context.convertType(subroutine.getReturnType());
2011 if (!type)
2012 return failure();
2013 args.push_back({StringAttr::get(context.getContext(), "return"), type,
2014 moore::DPIArgDirection::Return});
2015 }
2016
2017 return args;
2018}
2019
2020/// Convert a function and its arguments to a function declaration in the IR.
2021/// This does not convert the function body.
2023Context::declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
2024 mlir::StringRef qualifiedName,
2025 llvm::SmallVectorImpl<Type> &extraParams) {
2026 auto loc = convertLocation(subroutine.location);
2027 // Pick an insertion point for this function according to the source file
2028 // location.
2029 OpBuilder::InsertionGuard g(builder);
2030 auto locationKey = LocationKey::get(subroutine.location, sourceManager);
2031 auto it = orderedRootOps.upper_bound(locationKey);
2032 if (it == orderedRootOps.end())
2033 builder.setInsertionPointToEnd(intoModuleOp.getBody());
2034 else
2035 builder.setInsertionPoint(it->second);
2036
2037 // Build the capture parameter types. These are appended after the user-
2038 // defined arguments, not in the extraParams prefix, so the function type has
2039 // the layout [this?] [user args] [captures].
2040 SmallVector<Type> captureTypes;
2041 auto capturesIt = functionCaptures.find(&subroutine);
2042 if (capturesIt != functionCaptures.end()) {
2043 for (auto *sym : capturesIt->second) {
2044 auto type = convertType(sym->getType());
2045 if (!type)
2046 return nullptr;
2047 captureTypes.push_back(
2048 moore::RefType::get(cast<moore::UnpackedType>(type)));
2049 }
2050 }
2051
2052 auto funcTy =
2053 getFunctionSignature(*this, subroutine, extraParams, captureTypes);
2054 if (!funcTy)
2055 return nullptr;
2056
2057 std::unique_ptr<FunctionLowering> lowering;
2058 Operation *insertedOp = nullptr;
2059 auto dpiExportIt = dpiExportCNames.find(&subroutine);
2060 bool isDPIExport = dpiExportIt != dpiExportCNames.end();
2061 // DPI-exported subroutines must keep a public symbol tagged with the
2062 // exported C name so later pipeline stages can materialize the export.
2063 auto setVisibilityAndExportAttr = [&](Operation *op) {
2064 if (isDPIExport) {
2065 op->setAttr(dpiExportAttrName,
2066 builder.getStringAttr(dpiExportIt->second));
2067 SymbolTable::setSymbolVisibility(op, SymbolTable::Visibility::Public);
2068 return;
2069 }
2070 SymbolTable::setSymbolVisibility(op, SymbolTable::Visibility::Private);
2071 };
2072 if (!subroutine.thisVar &&
2073 subroutine.flags.has(slang::ast::MethodFlags::DPIImport)) {
2074 // DPI-imported function: create a moore.func.dpi declaration.
2075 auto dpiSig = getDPISignature(*this, subroutine);
2076 if (failed(dpiSig))
2077 return nullptr;
2078
2079 auto dpiOp = moore::DPIFuncOp::create(
2080 builder, loc, StringAttr::get(getContext(), qualifiedName), *dpiSig,
2081 /*argumentLocs=*/ArrayAttr(),
2082 StringAttr::get(getContext(), subroutine.name));
2083 setVisibilityAndExportAttr(dpiOp);
2084 lowering = std::make_unique<FunctionLowering>(dpiOp);
2085 insertedOp = dpiOp;
2086 } else if (subroutine.subroutineKind == slang::ast::SubroutineKind::Task) {
2087 // Create a coroutine for tasks (which can suspend).
2088 auto op = moore::CoroutineOp::create(builder, loc, qualifiedName, funcTy);
2089 setVisibilityAndExportAttr(op);
2090 lowering = std::make_unique<FunctionLowering>(op);
2091 insertedOp = op;
2092 } else {
2093 // Create a function for regular functions (which cannot suspend).
2094 auto funcOp =
2095 mlir::func::FuncOp::create(builder, loc, qualifiedName, funcTy);
2096 setVisibilityAndExportAttr(funcOp);
2097 lowering = std::make_unique<FunctionLowering>(funcOp);
2098 insertedOp = funcOp;
2099 }
2100 orderedRootOps.insert(it, {locationKey, insertedOp});
2101
2102 // Store the captured symbols so call sites can look them up.
2103 if (capturesIt != functionCaptures.end())
2104 lowering->capturedSymbols.assign(capturesIt->second.begin(),
2105 capturesIt->second.end());
2106
2107 // Add the op to the symbol table of the MLIR module, which uniquifies
2108 // its name.
2109 symbolTable.insert(insertedOp);
2110 functions[&subroutine] = std::move(lowering);
2111
2112 // Schedule the body to be defined later.
2113 functionWorklist.push(&subroutine);
2114
2115 return functions[&subroutine].get();
2116}
2117
2118/// Define a function’s body. The function must already have been declared via
2119/// `declareFunction`. This is called from the function worklist after all
2120/// declarations have been created, ensuring that all function prototypes are
2121/// available for calls within the body.
2122LogicalResult
2123Context::defineFunction(const slang::ast::SubroutineSymbol &subroutine) {
2124 auto *lowering = functions.at(&subroutine).get();
2125
2126 // Keep track of the local time scale. `getTimeScale` automatically looks
2127 // through parent scopes to find the time scale effective locally.
2128 auto prevTimeScale = timeScale;
2129 timeScale = subroutine.getTimeScale().value_or(slang::TimeScale());
2130 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
2131
2132 // DPI-C imported functions are extern declarations with no Verilog body.
2133 // Leave the func.func without a body region so it survives as an external
2134 // symbol and calls to it are not eliminated.
2135 if (subroutine.flags.has(slang::ast::MethodFlags::DPIImport))
2136 return success();
2137
2138 const bool isMethod = (subroutine.thisVar != nullptr);
2139
2142 if (isMethod) {
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>();
2147 if (!prop)
2148 continue;
2149 const auto &propCanon = prop->getType().getCanonicalType();
2150 if (const auto *vi =
2151 propCanon.as_if<slang::ast::VirtualInterfaceType>()) {
2152 auto propLoc = convertLocation(prop->location);
2153 if (failed(registerVirtualInterfaceMembers(*prop, *vi, propLoc)))
2154 return failure();
2155 }
2156 }
2157 }
2158 }
2159
2160 // Create a function body block and populate it with block arguments.
2161 SmallVector<moore::VariableOp> argVariables;
2162 auto &block = lowering->op.getFunctionBody().emplaceBlock();
2163
2164 // If this is a class method, the first input is %this :
2165 // !moore.class<@C>
2166 if (isMethod) {
2167 auto thisLoc = convertLocation(subroutine.location);
2168 auto thisType =
2169 cast<FunctionType>(lowering->op.getFunctionType()).getInput(0);
2170 auto thisArg = block.addArgument(thisType, thisLoc);
2171
2172 // Bind `this` so NamedValue/MemberAccess can find it.
2173 valueSymbols.insert(subroutine.thisVar, thisArg);
2174 }
2175
2176 // Add user-defined block arguments. The function type has the shape
2177 // [this?] [user args] [capture args], so we skip the prefix and suffix.
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());
2184
2185 for (auto [astArg, type] : llvm::zip(astArgs, valInputs)) {
2186 auto loc = convertLocation(astArg->location);
2187 auto blockArg = block.addArgument(type, loc);
2188
2189 if (isa<moore::RefType>(type)) {
2190 valueSymbols.insert(astArg, blockArg);
2191 } else {
2192 OpBuilder::InsertionGuard g(builder);
2193 builder.setInsertionPointToEnd(&block);
2194
2195 auto shadowArg = moore::VariableOp::create(
2196 builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
2197 StringAttr{}, blockArg);
2198 valueSymbols.insert(astArg, shadowArg);
2199 argVariables.push_back(shadowArg);
2200 }
2201
2202 const auto &argCanon = astArg->getType().getCanonicalType();
2203 if (const auto *vi = argCanon.as_if<slang::ast::VirtualInterfaceType>())
2204 if (failed(registerVirtualInterfaceMembers(*astArg, *vi, loc)))
2205 return failure();
2206 }
2207
2208 // Convert the body of the function.
2209 OpBuilder::InsertionGuard g(builder);
2210 builder.setInsertionPointToEnd(&block);
2211
2212 Value returnVar;
2213 if (subroutine.returnValVar) {
2214 auto type = convertType(*subroutine.returnValVar->getDeclaredType());
2215 if (!type)
2216 return failure();
2217 returnVar = moore::VariableOp::create(
2218 builder, lowering->op->getLoc(),
2219 moore::RefType::get(cast<moore::UnpackedType>(type)), StringAttr{},
2220 Value{});
2221 valueSymbols.insert(subroutine.returnValVar, returnVar);
2222 }
2223
2224 // Add block arguments for captured variables and bind them in the symbol
2225 // table. The captures were already added to the function type during
2226 // declaration; here we create the corresponding block arguments and map each
2227 // captured AST symbol to its block argument so that references in the body
2228 // resolve to the capture parameter instead of the enclosing scope’s value.
2229 for (auto *sym : lowering->capturedSymbols) {
2230 auto type = convertType(sym->getType());
2231 if (!type)
2232 return failure();
2233 auto refType = moore::RefType::get(cast<moore::UnpackedType>(type));
2234 auto loc = convertLocation(sym->location);
2235 auto blockArg = block.addArgument(refType, loc);
2236 valueSymbols.insert(sym, blockArg);
2237 }
2238
2239 auto savedThis = currentThisRef;
2240 currentThisRef = valueSymbols.lookup(subroutine.thisVar);
2241 llvm::scope_exit restoreThis([&] { currentThisRef = savedThis; });
2242
2243 auto *savedFunctionLowering = currentFunctionLowering;
2244 currentFunctionLowering = lowering;
2245 llvm::scope_exit restoreFunctionLowering(
2246 [&] { currentFunctionLowering = savedFunctionLowering; });
2247
2248 if (failed(convertStatement(subroutine.getBody())))
2249 return failure();
2250
2251 // If there was no explicit return statement provided by the user, insert a
2252 // default one.
2253 if (builder.getBlock()) {
2254 if (isa<moore::CoroutineOp>(lowering->op.getOperation())) {
2255 moore::ReturnOp::create(builder, lowering->op->getLoc());
2256 } else if (returnVar && !subroutine.getReturnType().isVoid()) {
2257 Value read =
2258 moore::ReadOp::create(builder, returnVar.getLoc(), returnVar);
2259 mlir::func::ReturnOp::create(builder, lowering->op->getLoc(), read);
2260 } else {
2261 mlir::func::ReturnOp::create(builder, lowering->op->getLoc(),
2262 ValueRange{});
2263 }
2264 }
2265 if (returnVar && returnVar.use_empty())
2266 returnVar.getDefiningOp()->erase();
2267
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());
2273 user->erase();
2274 }
2275 var->erase();
2276 }
2277 }
2278
2279 return success();
2280}
2281
2282LogicalResult
2283Context::assignPrimOutputWithDelay(Value outputVal, Value assignment,
2284 const slang::ast::TimingControl *delay,
2285 Location loc) {
2286 if (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;
2296 } else {
2297 llvm_unreachable("unexpected delay control type in primitive instance");
2298 }
2299 auto delayVal = this->convertRvalueExpression(
2300 *delayExpr, moore::TimeType::get(getContext()));
2301 if (!delayVal)
2302 return failure();
2303 moore::DelayedContinuousAssignOp::create(builder, loc, outputVal,
2304 assignment, delayVal);
2305 } else {
2306 moore::ContinuousAssignOp::create(builder, loc, outputVal, assignment);
2307 }
2308
2309 return success();
2310}
2311
2312/// Convert a primitive instance.
2314 const slang::ast::PrimitiveInstanceSymbol &prim) {
2315 if (prim.getDriveStrength().first.has_value() ||
2316 prim.getDriveStrength().second.has_value())
2317 return mlir::emitError(convertLocation(prim.location))
2318 << "primitive instances with explicit drive strengths are not "
2319 "supported.";
2320
2321 switch (prim.primitiveType.primitiveKind) {
2322 case slang::ast::PrimitiveSymbol::PrimitiveKind::NInput:
2323 return this->convertNInputPrimitive(prim);
2324 break;
2325 case slang::ast::PrimitiveSymbol::PrimitiveKind::NOutput:
2326 return this->convertNOutputPrimitive(prim);
2327 break;
2328 case slang::ast::PrimitiveSymbol::PrimitiveKind::Fixed:
2329 return this->convertFixedPrimitive(prim);
2330 break;
2331 case slang::ast::PrimitiveSymbol::PrimitiveKind::UserDefined:
2332 return this->convertUserDefinedPrimitiveInstance(prim);
2333 break;
2334 default:
2335 return mlir::emitError(convertLocation(prim.location))
2336 << "unsupported instance of primitive `" << prim.primitiveType.name
2337 << "`";
2338 }
2339}
2340
2342 const slang::ast::PrimitiveInstanceSymbol &prim) {
2343 auto loc = convertLocation(prim.location);
2344 auto primName = prim.primitiveType.name;
2345
2346 auto portConns = prim.getPortConnections();
2347 assert(portConns.size() >= 2 &&
2348 "n-input primitives should have at least 2 ports");
2349
2350 // Get SSA values corresponding to operands (and unwrap where necessary)
2351 auto &outputConn =
2352 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2353
2354 auto outputVal = this->convertLvalueExpression(outputConn);
2355 if (!outputVal)
2356 return failure();
2357
2358 SmallVector<Value> inputVals;
2359 inputVals.reserve(portConns.size() - 1);
2360 for (const auto *inputConn : portConns.subspan(1, portConns.size() - 1)) {
2361 auto inputVal = convertRvalueExpression(*inputConn);
2362 if (!inputVal)
2363 return failure();
2364 inputVals.push_back(inputVal);
2365 }
2366
2367 Value nextInput = inputVals.front();
2368 auto result =
2369 llvm::StringSwitch<std::function<Value()>>(prim.primitiveType.name)
2370 .Case("and", ([&] {
2371 for (Value inputVal : llvm::drop_begin(inputVals))
2372 nextInput =
2373 moore::AndOp::create(builder, loc, nextInput, inputVal);
2374 return nextInput;
2375 }))
2376 .Case("or", ([&] {
2377 for (Value inputVal : llvm::drop_begin(inputVals))
2378 nextInput =
2379 moore::OrOp::create(builder, loc, nextInput, inputVal);
2380 return nextInput;
2381 }))
2382 .Case("xor", ([&] {
2383 for (Value inputVal : llvm::drop_begin(inputVals))
2384 nextInput =
2385 moore::XorOp::create(builder, loc, nextInput, inputVal);
2386 return nextInput;
2387 }))
2388 .Case("nand", ([&] {
2389 for (Value inputVal : llvm::drop_begin(inputVals))
2390 nextInput =
2391 moore::AndOp::create(builder, loc, nextInput, inputVal);
2392 return moore::NotOp::create(builder, loc, nextInput);
2393 }))
2394 .Case("nor", ([&] {
2395 for (Value inputVal : llvm::drop_begin(inputVals))
2396 nextInput =
2397 moore::OrOp::create(builder, loc, nextInput, inputVal);
2398 return moore::NotOp::create(builder, loc, nextInput);
2399 }))
2400 .Case("xnor", ([&] {
2401 for (Value inputVal : llvm::drop_begin(inputVals))
2402 nextInput =
2403 moore::XorOp::create(builder, loc, nextInput, inputVal);
2404 return moore::NotOp::create(builder, loc, nextInput);
2405 }))
2406 .Default([&] {
2407 mlir::emitError(loc)
2408 << "unsupported primitive `" << primName << "`";
2409 return Value();
2410 })();
2411
2412 if (!result)
2413 return failure();
2414
2415 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2416 result = materializeConversion(dstType, result, false, loc);
2417 if (!result)
2418 return failure();
2419
2420 return assignPrimOutputWithDelay(outputVal, result, prim.getDelay(), loc);
2421}
2422
2424 const slang::ast::PrimitiveInstanceSymbol &prim) {
2425 auto loc = convertLocation(prim.location);
2426 auto primName = prim.primitiveType.name;
2427
2428 auto portConns = prim.getPortConnections();
2429 assert(portConns.size() >= 2 &&
2430 "n-output primitives should have at least 2 ports");
2431
2432 // Get SSA values corresponding to operands (and unwrap where necessary)
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();
2437 auto outputVal = this->convertLvalueExpression(output);
2438 if (!outputVal)
2439 return failure();
2440 outputVals.push_back(outputVal);
2441 }
2442
2443 auto inputVal = this->convertRvalueExpression(*portConns.back());
2444 if (!inputVal)
2445 return failure();
2446
2447 auto result =
2448 llvm::StringSwitch<std::function<Value()>>(prim.primitiveType.name)
2449 .Case("not",
2450 ([&] { return moore::NotOp::create(builder, loc, inputVal); }))
2451 .Case("buf", ([&] {
2452 return moore::BoolCastOp::create(builder, loc, inputVal);
2453 }))
2454 .Default([&] {
2455 mlir::emitError(loc)
2456 << "unsupported primitive `" << primName << "`";
2457 return Value();
2458 })();
2459
2460 if (!result)
2461 return failure();
2462
2463 for (auto outputVal : outputVals) {
2464 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2465 Value converted = materializeConversion(dstType, result, false, loc);
2466 if (!converted)
2467 return failure();
2468 if (failed(assignPrimOutputWithDelay(outputVal, converted, prim.getDelay(),
2469 loc)))
2470 return failure();
2471 }
2472
2473 return success();
2474}
2475
2477 const slang::ast::PrimitiveInstanceSymbol &prim) {
2478 auto primName = prim.primitiveType.name;
2479 auto loc = convertLocation(prim.location);
2480
2481 // Fixed primitives cover a few different cases, so dispatch those separately
2482
2483 if (primName == "pullup" || primName == "pulldown")
2484 return convertPullGatePrimitive(prim);
2485
2486 if (primName == "bufif0" || primName == "bufif1" || primName == "notif0" ||
2487 primName == "notif1")
2488 return convertThreeStateGatePrimitive(prim);
2489
2490 if (primName == "nmos" || primName == "pmos" || primName == "rnmos" ||
2491 primName == "rpmos") {
2492 return convertMOSSwitchPrimitive(prim);
2493 }
2494
2495 if (primName == "cmos" || primName == "rcmos")
2496 return convertCMOSSwitchPrimitive(prim);
2497
2498 // Remaining fixed primitives still need handling
2499 mlir::emitError(loc) << "unsupported primitive `" << primName << "`";
2500 return failure();
2501}
2502
2504 const slang::ast::PrimitiveInstanceSymbol &prim) {
2505 assert((prim.primitiveType.name == "pullup" ||
2506 prim.primitiveType.name == "pulldown") &&
2507 "expected pullup or pulldown primitive");
2508 // Slang should catch this
2509 assert(!prim.getDelay() &&
2510 "SystemVerilog does not allow pull gate primitives with delays");
2511 auto loc = convertLocation(prim.location);
2512 auto primName = prim.primitiveType.name;
2513
2514 auto portConns = prim.getPortConnections();
2515 // Slang should ensure this for us
2516 assert(portConns.size() == 1 &&
2517 "pullup/pulldown primitives should have exactly one port");
2518
2519 Value portVal = this->convertLvalueExpression(
2520 portConns.front()->as<slang::ast::AssignmentExpression>().left());
2521
2522 auto dstType = cast<moore::RefType>(portVal.getType()).getNestedType();
2523 auto dstTypeWidth = dstType.getBitSize();
2524 // This should be caught elsewhere
2525 assert(dstTypeWidth &&
2526 "expected fixed-width type for pullup/pulldown primitive");
2527 auto constVal = primName == "pullup" ? -1 : 0;
2528 auto c = moore::ConstantOp::create(
2529 builder, loc,
2530 moore::IntType::getInt(this->getContext(), dstTypeWidth.value()),
2531 constVal);
2532
2533 Value converted = materializeConversion(dstType, c, false, loc);
2534 if (!converted)
2535 return failure();
2536 moore::ContinuousAssignOp::create(builder, loc, portVal, converted);
2537 return success();
2538}
2539
2540/// Yields `data` unless it is exactly Z, in which case yields X instead.
2541/// Per IEEE 1800-2023 Section 28.6's table 28-5 for three-state gates, a Z
2542/// data input yields X on either the actively-driven or ambiguous-enable path.
2543/// Known 0/1 data values pass through unchanged. For three-state gates this
2544/// depends on the assumption that we collapse L to 0 and H to 1.
2545static Value collapseZToX(OpBuilder &builder, Location loc, Value data,
2546 Type dstType) {
2547 auto dstIntType = cast<moore::IntType>(dstType);
2548 Value xVal =
2549 moore::ConstantOp::create(builder, loc, dstIntType, FVInt::getAllX(1));
2550 Value zVal =
2551 moore::ConstantOp::create(builder, loc, dstIntType, FVInt::getAllZ(1));
2552
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();
2557 {
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);
2563 }
2564 return condOp.getResult();
2565}
2566
2568 const slang::ast::PrimitiveInstanceSymbol &prim) {
2569 auto loc = convertLocation(prim.location);
2570 auto primName = prim.primitiveType.name;
2571
2572 auto portConns = prim.getPortConnections();
2573 assert(portConns.size() == 3 &&
2574 "Expected exactly 3 ports in three-state gate primitives");
2575
2576 auto &outputConn =
2577 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2578 auto outputVal = convertLvalueExpression(outputConn);
2579 if (!outputVal)
2580 return failure();
2581
2582 auto inVal = convertRvalueExpression(*portConns[1]);
2583 auto enVal = convertRvalueExpression(*portConns[2]);
2584 if (!inVal || !enVal)
2585 return failure();
2586
2587 auto enType = cast<moore::IntType>(enVal.getType());
2588 [[maybe_unused]] auto enWidth = enType.getBitSize();
2589 // Slang automatically casts enable signals (or errors if it can't be cast)
2590 assert(enWidth && *enWidth == 1 &&
2591 "enable signal of a three-state gate primitive must be 1 bit");
2592
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";
2598
2599 if (primName == "notif0" || primName == "notif1")
2600 inVal = moore::NotOp::create(builder, loc, inVal);
2601
2602 inVal = materializeConversion(dstType, inVal, false, loc);
2603 if (!inVal)
2604 return failure();
2605
2606 // Value of enable to be considered active or inactive
2607 int inactiveLevel = (primName == "bufif1" || primName == "notif1") ? 0 : 1;
2608 Value inactiveConst =
2609 moore::ConstantOp::create(builder, loc, enType, inactiveLevel, false);
2610
2611 auto dstIntType = cast<moore::IntType>(dstType);
2612 Value zVal =
2613 moore::ConstantOp::create(builder, loc, dstIntType, FVInt::getAllZ(1));
2614
2615 // Compare enable to what we consider inactive (0 or 1 depending on type of
2616 // buffer)
2617 auto condInactive =
2618 moore::CaseEqOp::create(builder, loc, enVal, inactiveConst);
2619 auto inactiveOp =
2620 moore::ConditionalOp::create(builder, loc, dstType, condInactive);
2621 auto &inactiveTrue = inactiveOp.getTrueRegion().emplaceBlock();
2622 auto &inactiveFalse = inactiveOp.getFalseRegion().emplaceBlock();
2623
2624 {
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,
2630 collapseZToX(builder, loc, inVal, dstType));
2631 }
2632
2633 Value result = inactiveOp.getResult();
2634
2635 return assignPrimOutputWithDelay(outputVal, result, prim.getDelay(), loc);
2636}
2637
2639 const slang::ast::PrimitiveInstanceSymbol &prim) {
2640 assert(
2641 prim.primitiveType.name == "nmos" || prim.primitiveType.name == "pmos" ||
2642 prim.primitiveType.name == "rnmos" || prim.primitiveType.name == "rpmos");
2643
2644 auto loc = convertLocation(prim.location);
2645 auto primName = prim.primitiveType.name;
2646
2647 auto portConns = prim.getPortConnections();
2648
2649 assert(portConns.size() == 3 && "mos primitive should have exactly 3 ports");
2650
2651 auto &outputConn =
2652 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2653
2654 auto outputVal = convertLvalueExpression(outputConn);
2655 if (!outputVal)
2656 return failure();
2657
2658 auto inputVal = convertRvalueExpression(*portConns[1]);
2659 if (!inputVal)
2660 return failure();
2661
2662 // Slang automatically casts MOS switch inputs to 1-bit logic.
2663 assert(cast<moore::IntType>(inputVal.getType()).getBitSize() == 1 &&
2664 "MOS switch input must be 1 bit");
2665
2666 Value controlIsOff;
2667
2668 auto control = convertRvalueExpression(*portConns[2]);
2669 if (!control)
2670 return failure();
2671
2672 auto controlType = cast<moore::IntType>(control.getType());
2673 assert(controlType.getBitSize() == 1 && "MOS switch control must be 1 bit");
2674
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)));
2678
2679 controlIsOff = moore::CaseEqOp::create(builder, loc, control, offValue);
2680 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
2681
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";
2685
2686 auto convertedInput = materializeConversion(dstType, inputVal, false, loc);
2687 if (!convertedInput)
2688 return failure();
2689
2690 Value zVal =
2691 moore::ConstantOp::create(builder, loc, dstIntType, FVInt::getAllZ(1));
2692
2693 auto condOp =
2694 moore::ConditionalOp::create(builder, loc, dstType, controlIsOff);
2695
2696 auto &trueBlock = condOp.getTrueRegion().emplaceBlock();
2697 auto &falseBlock = condOp.getFalseRegion().emplaceBlock();
2698
2699 builder.setInsertionPointToStart(&trueBlock);
2700 moore::YieldOp::create(builder, loc, zVal);
2701
2702 builder.setInsertionPointToStart(&falseBlock);
2703 moore::YieldOp::create(builder, loc, convertedInput);
2704
2705 builder.setInsertionPointAfter(condOp);
2706
2707 return assignPrimOutputWithDelay(outputVal, condOp.getResult(),
2708 prim.getDelay(), loc);
2709}
2710
2712 const slang::ast::PrimitiveInstanceSymbol &prim) {
2713 assert(prim.primitiveType.name == "cmos" ||
2714 prim.primitiveType.name == "rcmos");
2715
2716 auto loc = convertLocation(prim.location);
2717 auto portConns = prim.getPortConnections();
2718 assert(portConns.size() == 4 && "cmos primitive should have exactly 4 ports");
2719
2720 auto &outputConn =
2721 portConns[0]->as<slang::ast::AssignmentExpression>().left();
2722 auto outputVal = convertLvalueExpression(outputConn);
2723 if (!outputVal)
2724 return failure();
2725
2726 auto dataVal = convertRvalueExpression(*portConns[1]);
2727 if (!dataVal)
2728 return failure();
2729 // Slang automatically casts CMOS switch inputs to 1-bit logic.
2730 assert(cast<moore::IntType>(dataVal.getType()).getBitSize() == 1 &&
2731 "CMOS switch input must be 1 bit");
2732
2733 auto ncontrolVal = convertRvalueExpression(*portConns[2]);
2734 if (!ncontrolVal)
2735 return failure();
2736 assert(cast<moore::IntType>(ncontrolVal.getType()).getBitSize() == 1 &&
2737 "CMOS switch ncontrol must be 1 bit");
2738
2739 auto pcontrolVal = convertRvalueExpression(*portConns[3]);
2740 if (!pcontrolVal)
2741 return failure();
2742 assert(cast<moore::IntType>(pcontrolVal.getType()).getBitSize() == 1 &&
2743 "CMOS switch pcontrol must be 1 bit");
2744
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";
2749
2750 auto convertedData = materializeConversion(dstType, dataVal, false, loc);
2751 if (!convertedData)
2752 return failure();
2753
2754 auto logicType = moore::IntType::getLogic(getContext(), 1);
2755
2756 auto makeConst = [&](FVInt val) -> Value {
2757 Value c = moore::ConstantOp::create(builder, loc, logicType, val);
2758 return materializeConversion(dstType, c, false, loc);
2759 };
2760 Value zVal = makeConst(FVInt::getAllZ(1));
2761 Value xVal = makeConst(FVInt::getAllX(1));
2762 if (!zVal || !xVal)
2763 return failure();
2764
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)));
2769 };
2770
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();
2781 };
2782
2783 // N side: behaves like NMOS -- off (Z) when ncontrol === 0.
2784 auto nOff = makeLevelConstant(ncontrolVal, 0);
2785 auto nIsOff = moore::CaseEqOp::create(builder, loc, ncontrolVal, nOff);
2786 Value nResult = muxZOrData(nIsOff);
2787
2788 // P side: behaves like PMOS -- off (Z) when pcontrol === 1.
2789 auto pOff = makeLevelConstant(pcontrolVal, 1);
2790 auto pIsOff = moore::CaseEqOp::create(builder, loc, pcontrolVal, pOff);
2791 Value pResult = muxZOrData(pIsOff);
2792
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);
2796
2797 auto outerCond = moore::ConditionalOp::create(builder, loc, dstType, agree);
2798 auto &outerTrue = outerCond.getTrueRegion().emplaceBlock();
2799 auto &outerFalse = outerCond.getFalseRegion().emplaceBlock();
2800
2801 {
2802 OpBuilder::InsertionGuard guard(builder);
2803 builder.setInsertionPointToStart(&outerTrue);
2804 moore::YieldOp::create(builder, loc, nResult);
2805
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());
2811
2812 builder.setInsertionPointToStart(&middleTrue);
2813 moore::YieldOp::create(builder, loc, pResult);
2814
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();
2819
2820 builder.setInsertionPointToStart(&innerTrue);
2821 moore::YieldOp::create(builder, loc, nResult);
2822 builder.setInsertionPointToStart(&innerFalse);
2823 moore::YieldOp::create(builder, loc, xVal);
2824
2825 builder.setInsertionPointAfter(innerCond);
2826 moore::YieldOp::create(builder, loc, innerCond.getResult());
2827 }
2828
2829 return assignPrimOutputWithDelay(outputVal, outerCond.getResult(),
2830 prim.getDelay(), loc);
2831}
2832
2833// Auxiliary functions for UDP truth-table lowering.
2834
2835namespace {
2836
2837/// Logic level for an input or current-state entry in a UDP truth table.
2838enum class UdpLevel {
2839 Zero,
2840 One,
2841 Unknown,
2842 DontCare,
2843};
2844
2845/// A level-sensitive truth table row (a latch transition, or an asynchronous
2846/// clear/preset override in an edge-triggered UDP).
2847struct AsyncRow {
2848 /// Required logic levels (`Zero`, `One`, or `DontCare`) for each input port.
2849 SmallVector<UdpLevel> inputs;
2850 /// Required current state `q` (`Zero`, `One`, or `DontCare`).
2851 UdpLevel state;
2852 /// Forced output value: false for '0' (clear), true for '1' (preset).
2853 bool output;
2854};
2855
2856/// An edge-sensitive truth table row.
2857struct SyncRow {
2858 /// Required logic levels (`Zero`, `One`, or `DontCare`, with `DontCare` at
2859 /// the edge-triggered port) for each input port.
2860 SmallVector<UdpLevel> inputs;
2861 /// Required current state `q` (`Zero`, `One`, or `DontCare`).
2862 UdpLevel state;
2863};
2864
2865/// Classified truth table entries and structural information for a sequential
2866/// UDP.
2867struct SequentialTableInfo {
2868 /// Active asynchronous (level-sensitive) transition rows.
2869 SmallVector<AsyncRow> asyncRows;
2870 /// Active synchronous (edge-sensitive) transition rows.
2871 SmallVector<SyncRow> syncRows;
2872 /// Indices of input ports that act as asynchronous controls.
2873 llvm::SmallDenseSet<size_t, 4> asyncPortIndices;
2874};
2875
2876/// Synthesized boolean conditions for level-sensitive (`AsyncRow`) transitions.
2877///
2878/// Because a sequential UDP output is 1-bit, every active level-sensitive row
2879/// either drives `'0'` (`clearCond`) or `'1'` (`presetCond`). For a
2880/// level-sensitive latch, `asyncCond` is the combined enable condition and
2881/// `asyncVal` is the assigned value; for an edge-triggered flip-flop,
2882/// `clearCond` and `presetCond` also provide the individual asynchronous
2883/// clear/preset override conditions.
2884struct AsyncConditions {
2885 /// Sum-of-products condition of all level-sensitive rows driving `'0'`.
2886 Value clearCond;
2887 /// Sum-of-products condition of all level-sensitive rows driving `'1'`.
2888 Value presetCond;
2889 /// Combined level-sensitive enable condition (`clearCond | presetCond`).
2890 Value asyncCond;
2891 /// Value assigned to state `q` when `asyncCond` is active.
2892 Value asyncVal;
2893};
2894
2895} // namespace
2896
2897/// Decode a single UDP level character (`0`, `1`, `x`, `?`, or `b`,
2898/// case-insensitive). Returns `std::nullopt` for non-level characters such as
2899/// edge specifiers (`r`, `f`, `p`, `n`, `*`, `(`, `)`).
2900static std::optional<UdpLevel> decodeUdpLevel(char c) {
2901 switch (llvm::toLower(c)) {
2902 case '0':
2903 return UdpLevel::Zero;
2904 case '1':
2905 return UdpLevel::One;
2906 case 'x':
2907 return UdpLevel::Unknown;
2908 case '?':
2909 case 'b':
2910 // In 2-state UDP lowering, 'b' (0 or 1) and '?' (0, 1, or x) are both
2911 // wildcards over {0, 1}; canonicalize both to `DontCare`.
2912 return UdpLevel::DontCare;
2913 default:
2914 return std::nullopt;
2915 }
2916}
2917
2918/// Parse a level-only UDP input row string into `UdpLevel` entries.
2919/// Returns false if any character is not a recognized UDP level symbol.
2920static bool parseInputRow(StringRef inputs, SmallVectorImpl<UdpLevel> &levels) {
2921 levels.clear();
2922 levels.reserve(inputs.size());
2923 for (char c : inputs) {
2924 auto level = decodeUdpLevel(c);
2925 if (!level)
2926 return false;
2927 levels.push_back(*level);
2928 }
2929 return true;
2930}
2931
2932/// Skip unsupported or non-productive combinational table rows. Currently,
2933/// only combinational UDPs with 0/1/?/b inputs are supported.
2935 const slang::ast::PrimitiveSymbol::TableEntry &entry,
2936 ArrayRef<UdpLevel> levels, size_t numInputs) {
2937 // In the sum-of-products (SOP) representation below, only rows producing '1'
2938 // generate product terms in the disjunction; other outputs (e.g., '0' or 'x')
2939 // do not contribute. Also skip edge-sensitive entries and rows with
2940 // mismatched input counts.
2941 if (entry.output != '1' || levels.size() != numInputs ||
2942 entry.isEdgeSensitive)
2943 return true;
2944 return llvm::any_of(levels, [](UdpLevel level) {
2945 switch (level) {
2946 case UdpLevel::Zero:
2947 case UdpLevel::One:
2948 case UdpLevel::DontCare:
2949 return false;
2950 case UdpLevel::Unknown:
2951 return true;
2952 }
2953 });
2954}
2955
2956/// Materialize a 2-state literal (`val` for `One`, `~val` for `Zero`) or null
2957/// for `DontCare`, caching the negation in `notVal`.
2958static Value buildLevelLiteral(OpBuilder &builder, Location loc, UdpLevel level,
2959 Value val, Value &notVal) {
2960 switch (level) {
2961 case UdpLevel::One:
2962 return val;
2963 case UdpLevel::Zero:
2964 if (!notVal)
2965 notVal = moore::NotOp::create(builder, loc, val);
2966 return notVal;
2967 case UdpLevel::DontCare:
2968 return {};
2969 case UdpLevel::Unknown:
2970 llvm_unreachable("unknown level should be filtered before building term");
2971 }
2972}
2973
2974/// Build the productive AND-term for this row. Returns nullptr if the row is
2975/// unproductive (all don't cares).
2976static Value buildProductiveTerm(OpBuilder &builder, Location loc,
2977 ArrayRef<UdpLevel> inputs,
2978 ValueRange inputVals,
2979 SmallVectorImpl<Value> &notVars) {
2980 Value term;
2981 for (size_t i = 0, e = inputVals.size(); i < e; ++i) {
2982 Value lit =
2983 buildLevelLiteral(builder, loc, inputs[i], inputVals[i], notVars[i]);
2984 if (lit)
2985 term = term ? moore::AndOp::create(builder, loc, term, lit) : lit;
2986 }
2987 return term;
2988}
2989
2990/// Classify sequential UDP truth table rows into synchronous (edge-sensitive)
2991/// transitions and asynchronous (level-sensitive) transitions.
2992///
2993/// Sequential UDPs in hardware are modeled either as edge-triggered flip-flops
2994/// (where edge-sensitive rows `syncRows` describe clocked transitions on the
2995/// edge-sensitive port and level-sensitive rows `asyncRows` describe
2996/// asynchronous clear/preset overrides on asynchronous control ports) or as
2997/// level-sensitive latches (where only `asyncRows` are present).
2998///
2999/// Safe Filtering and Benign Hold Rules:
3000/// Truth tables may include entries that do not produce active 2-state
3001/// transitions and are skipped before lowering:
3002/// - Unknown ('x') rows: Like combinational UDP lowering
3003/// (`skipUnsupportedCombinationalRow`), sequential UDP lowering models
3004/// transitions in 2-state `i1` logic (matching `MooreToCore`'s 2-state
3005/// lowering rather than 4-state `X` propagation). In IEEE 1800-2017 Table
3006/// 29-1, `'x'` in inputs or state only matches literal unknown `x` (unlike
3007/// `'?'`, which matches `0`, `1`, or `x`) so it cannot trigger in 2-state
3008/// logic, and `'x'` next-state outputs have no 2-state value, so rows
3009/// containing `'x'` are skipped.
3010/// - Explicit hold rows: Rows specifying '-' as next-state explicitly indicate
3011/// retaining the current state (e.g. on inactive clock edges `(10) : -`).
3012/// Because the lowered `moore.procedure` only assigns to the state variable
3013/// when an active transition condition holds, the state variable naturally
3014/// retains its value when no active transition matches.
3015/// - Idempotent hold rows: Rows where next-state matches current state
3016/// (`state == output`, e.g. steady-state hold rows `0 : 0 : 0` or
3017/// `1 : 1 : 1`) preserve state and do not create active transitions.
3018///
3019/// Structural Lowering Requirements:
3020/// Pure level-sensitive UDPs (latches) have no structural restrictions beyond
3021/// Slang's table validation. For edge-triggered UDPs, while IEEE 1800-2017
3022/// Section 29.6 syntactically permits arbitrary combinations of level-sensitive
3023/// and edge-sensitive rows, lowering to a structured flip-flop procedure (with
3024/// outer asynchronous clear/preset priority branches and an inner clocked data
3025/// branch) requires surviving active transitions to satisfy:
3026/// 1. Well-formed edge transitions (guaranteed by Slang and asserted here):
3027/// a. At most one edge transition per table row.
3028/// b. Supported transition specifiers: each edge transition must specify a
3029/// recognized 2-state edge token.
3030/// 2. Single edge-sensitive port: all active edge transitions must share the
3031/// same edge-sensitive input port.
3032/// 3. No mixed sensitivity on edge-sensitive port: an input cannot have both
3033/// edge and level sensitivity (in an edge-triggered model, all active level
3034/// rows must specify '?' on the edge-sensitive port).
3035/// 4. Pure asynchronous control: in an edge-triggered UDP, level-sensitive
3036/// (asynchronous clear/preset) rows must not depend on the current state q
3037/// (all active level rows must specify '?' on state).
3038/// 5. Separation of asynchronous control and synchronous data:
3039/// a. Asynchronous control ports (input ports with a '0' or '1' level in
3040/// `asyncRows`) cannot also act as varying synchronous data inputs across
3041/// `syncRows`.
3042/// b. Synchronous transitions (`syncRows`) cannot be conditioned on active
3043/// asynchronous control levels.
3044static LogicalResult
3045classifySequentialTableRows(const slang::ast::PrimitiveSymbol &primitiveType,
3046 size_t numInputs, Location loc,
3047 SequentialTableInfo &info) {
3048 SmallVector<AsyncRow> rawLevelRows;
3049 std::optional<size_t> edgePortIdx;
3050
3051 for (const auto &row : primitiveType.table) {
3052 // Skip rows containing 'x': UDP lowering here models transitions in 2-state
3053 // (`i1`) logic rather than 4-state `X` propagation (matching
3054 // `skipUnsupportedCombinationalRow`), so literal-'x' matchers cannot
3055 // trigger and 'x' outputs cannot be represented.
3056 if (row.output == 'x')
3057 continue;
3058 if (row.state == 'x')
3059 continue;
3060 if (llvm::any_of(row.inputs, [](char c) { return c == 'x'; }))
3061 continue;
3062
3063 // Benign Hold Rule: skip explicit hold ('-') and idempotent hold
3064 // (state == output) rows, since the state variable is only assigned when
3065 // an active transition condition holds.
3066 if (row.output == '-' || row.state == row.output)
3067 continue;
3068
3069 assert((row.output == '0' || row.output == '1') &&
3070 "active UDP transition must specify binary output '0' or '1'");
3071
3072 auto stateLevel = decodeUdpLevel(row.state);
3073 assert(stateLevel && "unexpected sequential UDP state symbol");
3074 if (*stateLevel == UdpLevel::Unknown)
3075 continue;
3076
3077 if (!row.isEdgeSensitive) {
3078 SmallVector<UdpLevel> inputs;
3079 if (!parseInputRow(row.inputs, 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'});
3085 continue;
3086 }
3087
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() == '(') {
3094 // Requirement 1a/1b: Slang guarantees well-formed 2-state '(ab)' edges
3095 // (rows containing 'x' were filtered above) and at most one per row.
3096 assert(inputs.size() >= 4 && inputs[3] == ')' && !edgeIdx.has_value() &&
3097 "expected single well-formed parenthesized edge token");
3098 edgeIdx = i;
3099 inputs = inputs.drop_front(4);
3100 continue;
3101 }
3102 char c = inputs.front();
3103 inputs = inputs.drop_front(1);
3104 if (auto level = decodeUdpLevel(c)) {
3105 assert(*level != UdpLevel::Unknown &&
3106 "rows with 'x' inputs should already be skipped");
3107 inputLevels[i] = *level;
3108 } else {
3109 // Edge shorthand ('r', 'f', 'p', 'n', '*'), guaranteed by Slang.
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");
3114 edgeIdx = i;
3115 }
3116 }
3117 assert(inputs.empty() && edgeIdx.has_value() &&
3118 "edge-sensitive row must consume all inputs and have an edge");
3119
3120 // Requirement 2 (Single edge-sensitive port):
3121 // After benign hold filtering, all surviving active edge transitions must
3122 // share the same edge-sensitive input port.
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";
3129 }
3130
3131 info.syncRows.push_back({std::move(inputLevels), *stateLevel});
3132 }
3133
3134 // Merge level rows that differ only on the edge-sensitive column
3135 // (cell-library idiom where an asynchronous clear or preset is enumerated for
3136 // both clock levels: e.g. '0 0 ? ? : ? : 0' and '1 0 ? ? : ? : 0'). In
3137 // 2-state logic, matching '0' and '1' clock levels combine into a single
3138 // unconditional `DontCare` level row.
3139 if (edgePortIdx.has_value()) {
3140 size_t clkIdx = *edgePortIdx;
3141 SmallVector<AsyncRow> mergedLevelRows;
3142 for (auto &asyncRow : rawLevelRows) {
3143 auto *matchIt =
3144 llvm::find_if(mergedLevelRows, [&](const AsyncRow &existing) {
3145 if (existing.output != asyncRow.output ||
3146 existing.state != asyncRow.state)
3147 return false;
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();
3152 });
3153 });
3154
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;
3159 }
3160 }
3161 rawLevelRows = std::move(mergedLevelRows);
3162 }
3163
3164 for (auto &asyncRow : rawLevelRows) {
3165 if (edgePortIdx.has_value()) {
3166 // Requirement 3 (No mixed sensitivity on edge-sensitive port):
3167 // An input cannot have both edge and level sensitivity. In an
3168 // edge-triggered primitive, active level-sensitive rows must specify
3169 // `DontCare` ('?') on the edge-sensitive port or enumerate both '0' and
3170 // '1' clock levels (merged above). Any surviving row specifying a fixed
3171 // level on this port means the input has both edge and level
3172 // sensitivity (e.g. transparent latch behavior or level override while
3173 // the edge signal is stationary), which cannot be lowered to an
3174 // `always_ff`-style clocked/async-reset procedure for register
3175 // extraction (`llhd-deseq`) and simulation in `arcilator`.
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";
3183 }
3184
3185 // Requirement 4 (Pure asynchronous control without state feedback):
3186 // Asynchronous clear/preset rows must not depend on the current state q;
3187 // feedback loops in asynchronous control 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";
3193 }
3194
3195 // Record which input ports act as asynchronous controls (i.e. specify a
3196 // `Zero` or `One` level in an asynchronous row).
3197 for (auto [i, level] : llvm::enumerate(asyncRow.inputs)) {
3198 if (i != *edgePortIdx && level != UdpLevel::DontCare)
3199 info.asyncPortIndices.insert(i);
3200 }
3201 }
3202 info.asyncRows.push_back(std::move(asyncRow));
3203 }
3204
3205 // Requirement 5 (Separation of asynchronous control and synchronous data):
3206 if (edgePortIdx.has_value()) {
3207 // Requirement 5a: In `syncRows`, an asynchronous control port may only
3208 // be `DontCare` or held at its single inactive level (e.g. `rst = 0`
3209 // across all clocked rows). If it is specified as `Zero` in one `syncRow`
3210 // and `One` in another (`variesInSync`), it is also acting as a synchronous
3211 // data input, which is not supported.
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)
3219 firstSyncLevel = l;
3220 else if (*firstSyncLevel != l)
3221 variesInSync = true;
3222 }
3223 }
3224 if (variesInSync) {
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";
3229 }
3230 }
3231
3232 // Requirement 5b: Verify that synchronous transitions are not conditioned
3233 // on an active asynchronous clear/preset row (i.e. a `syncRow` cannot
3234 // match an `asyncRow` on its specified control port levels without
3235 // contradicting it on another control port).
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)
3243 continue;
3244 if (srow.inputs[aIdx] == asyncRow.inputs[aIdx])
3245 matchesAny = true;
3246 else
3247 contradicts = true;
3248 }
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";
3254 }
3255 }
3256 }
3257 }
3258
3259 return success();
3260}
3261
3262/// Construct boolean conditions from level-sensitive (`AsyncRow`) rows by
3263/// partitioning them into rows driving `'0'` (`clearCond`) and rows driving
3264/// `'1'` (`presetCond`).
3265///
3266/// Because Slang's table conflict check (`BitTrie`) guarantees that
3267/// `'0'`-output and `'1'`-output rows are mutually exclusive for any 2-state
3268/// input/state combination, when both `'0'` and `'1'` rows exist (e.g. D or SR
3269/// latches), they combine into a single enable condition (`asyncCond =
3270/// clearCond | presetCond`) with dynamic value (`asyncVal = presetCond`). When
3271/// only `'0'` or only `'1'` rows exist, `asyncVal` is a constant 0 or 1.
3272static AsyncConditions buildAsyncConditions(OpBuilder &builder, Location loc,
3273 ArrayRef<AsyncRow> asyncRows,
3274 ArrayRef<Value> inputVals,
3275 Value qVal, moore::IntType i1Ty) {
3276 AsyncConditions result;
3277 SmallVector<Value> notVars(inputVals.size(), Value{});
3278 Value notQ;
3279 for (const auto &asyncRow : asyncRows) {
3280 Value term =
3281 buildProductiveTerm(builder, loc, asyncRow.inputs, inputVals, notVars);
3282 if (Value stateLit =
3283 buildLevelLiteral(builder, loc, asyncRow.state, qVal, notQ))
3284 term =
3285 term ? moore::AndOp::create(builder, loc, term, stateLit) : stateLit;
3286 if (!term)
3287 term = moore::ConstantOp::create(builder, loc, i1Ty, 1, false);
3288 if (!asyncRow.output) {
3289 result.clearCond =
3290 result.clearCond
3291 ? moore::OrOp::create(builder, loc, result.clearCond, term)
3292 : term;
3293 } else {
3294 result.presetCond =
3295 result.presetCond
3296 ? moore::OrOp::create(builder, loc, result.presetCond, term)
3297 : term;
3298 }
3299 }
3300
3301 if (result.clearCond && result.presetCond) {
3302 result.asyncCond =
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);
3311 }
3312 return result;
3313}
3314
3315/// Emit a level-sensitive `moore.procedure always_latch` for a latch UDP.
3317 OpBuilder &builder,
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);
3325
3326 Value acondI1 = context.convertToI1(asyncCond);
3327 Block &trueBlock = procOp.getBody().emplaceBlock();
3328 Block &exitBlock = procOp.getBody().emplaceBlock();
3329
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);
3334
3335 builder.setInsertionPointToEnd(&exitBlock);
3336 moore::ReturnOp::create(builder, loc);
3337}
3338
3340 moore::SVModuleOp moduleOp, const slang::ast::PrimitiveSymbol &primitive) {
3341 auto loc = convertLocation(primitive.location);
3342 auto *block = &moduleOp.getBodyRegion().front();
3343 builder.setInsertionPointToEnd(block);
3344
3345 auto inputArgs = block->getArguments();
3346 size_t numInputs = inputArgs.size();
3347
3348 // Classify the truth table rows into edge-sensitive (sync) and
3349 // level-sensitive (async), and record asynchronous control ports.
3350 SequentialTableInfo table;
3351 if (failed(classifySequentialTableRows(primitive, numInputs, loc, table)))
3352 return failure();
3353
3354 if (!table.syncRows.empty()) {
3355 return mlir::emitError(loc)
3356 << "edge-sensitive sequential user-defined primitives are not "
3357 "supported yet";
3358 }
3359
3360 // Instantiate the state variable.
3361 auto i1Ty = moore::IntType::getInt(getContext(), 1);
3362 auto i1RefTy = moore::RefType::get(i1Ty);
3363 Value initVal;
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);
3369 }
3370 StringAttr qName = builder.getStringAttr(primitive.ports[0]->name);
3371 auto qVar = moore::VariableOp::create(builder, loc, i1RefTy, qName, initVal);
3372
3373 // Convert all input arguments to 2-state boolean values.
3374 SmallVector<Value> seqInputVals;
3375 seqInputVals.reserve(numInputs);
3376 for (Value arg : inputArgs) {
3377 auto boolVal = convertToBool(arg, Domain::TwoValued);
3378 if (!boolVal)
3379 return failure();
3380 seqInputVals.push_back(boolVal);
3381 }
3382
3383 // Read internal state q only if any active row depends on it.
3384 bool usesState = llvm::any_of(table.syncRows,
3385 [](const SyncRow &r) {
3386 return r.state != UdpLevel::DontCare;
3387 }) ||
3388 llvm::any_of(table.asyncRows, [](const AsyncRow &r) {
3389 return r.state != UdpLevel::DontCare;
3390 });
3391 Value qVal;
3392 if (usesState)
3393 qVal = moore::ReadOp::create(builder, loc, qVar);
3394
3395 // Build level-sensitive clear/preset conditions from table.asyncRows.
3396 AsyncConditions asyncConditions = buildAsyncConditions(
3397 builder, loc, table.asyncRows, seqInputVals, qVal, i1Ty);
3398
3399 Value qOut;
3400 if (asyncConditions.asyncCond) {
3402 asyncConditions.asyncCond,
3403 asyncConditions.asyncVal, qVar);
3404 qOut = moore::ReadOp::create(builder, loc, qVar);
3405 } else {
3406 return mlir::emitError(loc)
3407 << "unsupported sequential UDP `" << primitive.name
3408 << "` without active transitions";
3409 }
3410
3411 auto l1Ty = moore::IntType::getLogic(getContext(), 1);
3412 Value converted = materializeConversion(l1Ty, qOut, false, loc);
3413 if (!converted)
3414 return failure();
3415
3416 moore::OutputOp::create(builder, loc, converted);
3417 return moduleOp;
3418}
3419
3420FailureOr<moore::SVModuleOp> Context::convertUserDefinedPrimitiveDef(
3421 const slang::ast::PrimitiveSymbol &primitive) {
3422 // Return the existing module if this UDP was already converted.
3423 if (auto moduleOp = symbolTable.lookup<moore::SVModuleOp>(primitive.name))
3424 return moduleOp;
3425
3426 // The first port of UDP is the output, the remaining ports should have at
3427 // least one input.
3428 auto loc = convertLocation(primitive.location);
3429 assert(primitive.ports.size() >= 2 &&
3430 "user-defined primitives must have at least 2 ports");
3431
3432 // Protect the caller's insertion point while creating the UDP module and its
3433 // body.
3434 OpBuilder::InsertionGuard guard(builder);
3435
3436 // UDP ports: the first port is output, the remaining ports are inputs.
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(
3444 {builder.getStringAttr(port->name), l1Ty, hw::ModulePort::Input});
3445
3446 // Pick an insertion point according to the source file location.
3447 auto key = LocationKey::get(primitive.location, sourceManager);
3448 auto upperIt = orderedRootOps.upper_bound(key);
3449 if (upperIt == orderedRootOps.end())
3450 builder.setInsertionPointToEnd(intoModuleOp.getBody());
3451 else
3452 builder.setInsertionPoint(upperIt->second);
3453 auto moduleOp =
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))
3458 block->addArgument(l1Ty, convertLocation(port->location));
3459 orderedRootOps.insert(upperIt, {key, moduleOp});
3460 symbolTable.insert(moduleOp);
3461
3462 if (primitive.isSequential)
3463 return convertSequentialUserDefinedPrimitiveDef(moduleOp, primitive);
3464
3465 auto inputVals = block->getArguments();
3466 size_t numInputs = inputVals.size();
3467
3468 // Memoization cache for cross-row moore.not deduplication.
3469 SmallVector<Value> notVars(numInputs, Value{});
3470
3471 // Construct Disjunctive Normal Form (sum-of-products) boolean logic from
3472 // the UDP truth table.
3473 Value sum;
3474 SmallVector<UdpLevel> levels;
3475 for (const auto &entry : primitive.table) {
3476 if (!parseInputRow(entry.inputs, levels) ||
3477 skipUnsupportedCombinationalRow(entry, levels, numInputs))
3478 continue;
3479 Value term = buildProductiveTerm(builder, loc, levels, inputVals, notVars);
3480 if (!term) {
3481 // All inputs were don't cares ('?'): row unconditionally evaluates to 1.
3482 sum = moore::ConstantOp::create(builder, loc, l1Ty, 1);
3483 break;
3484 }
3485 sum = sum ? moore::OrOp::create(builder, loc, sum, term) : term;
3486 }
3487 if (!sum)
3488 sum = moore::ConstantOp::create(builder, loc, l1Ty, 0);
3489
3490 moore::OutputOp::create(builder, loc, sum);
3491 return moduleOp;
3492}
3493
3495 const slang::ast::PrimitiveInstanceSymbol &prim) {
3496 auto loc = convertLocation(prim.location);
3497 auto portConns = prim.getPortConnections();
3498 assert(portConns.size() >= 2 &&
3499 "user-defined primitives should have at least 2 ports");
3500
3501 size_t numInputs = portConns.size() - 1;
3502
3503 // Output port is the first connection.
3504 auto &outputConn =
3505 portConns[0]->as<slang::ast::AssignmentExpression>().left();
3506 auto outputVal = this->convertLvalueExpression(outputConn);
3507 if (!outputVal)
3508 return failure();
3509
3510 // UDP allows multiple 1-bit inputs.
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)) {
3515 auto rawVal = convertRvalueExpression(*inputConn);
3516 if (!rawVal)
3517 return failure();
3518 auto converted = materializeConversion(l1Ty, rawVal, false, loc);
3519 if (!converted)
3520 return failure();
3521 inputVals.push_back(converted);
3522 }
3523
3524 // Look up or convert the UDP definition into a moore.module and instantiate
3525 // it.
3526 FailureOr<moore::SVModuleOp> moduleOpOrFailure =
3527 convertUserDefinedPrimitiveDef(prim.primitiveType);
3528 if (failed(moduleOpOrFailure))
3529 return failure();
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,
3538 outputNames);
3539
3540 // Connect output port and emit moore.assign or moore.delayed_assign.
3541 auto dstType = cast<moore::RefType>(outputVal.getType()).getNestedType();
3542 Value converted =
3543 materializeConversion(dstType, inst.getResult(0), false, loc);
3544 if (!converted)
3545 return failure();
3546
3547 return assignPrimOutputWithDelay(outputVal, converted, prim.getDelay(), loc);
3548}
3549
3550namespace {
3551
3552/// Construct a fully qualified class name containing the instance hierarchy
3553/// and the class name formatted as H1::H2::@C
3554mlir::StringAttr fullyQualifiedClassName(Context &ctx,
3555 const slang::ast::Type &ty) {
3556 SmallString<64> name;
3557 SmallVector<llvm::StringRef, 8> parts;
3558
3559 const slang::ast::Scope *scope = ty.getParentScope();
3560 while (scope) {
3561 const auto &sym = scope->asSymbol();
3562 switch (sym.kind) {
3563 case slang::ast::SymbolKind::Root:
3564 scope = nullptr; // stop at $root
3565 continue;
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); // keep packages + outer classes
3572 break;
3573 default:
3574 break;
3575 }
3576 scope = sym.getParentScope();
3577 }
3578
3579 for (auto p : llvm::reverse(parts)) {
3580 name += p;
3581 name += "::";
3582 }
3583 name += ty.name; // class’s own name
3584 return mlir::StringAttr::get(ctx.getContext(), name);
3585}
3586
3587/// Helper function to construct the classes fully qualified base class name
3588/// and the name of all implemented interface classes
3589std::pair<mlir::SymbolRefAttr, mlir::ArrayAttr>
3590buildBaseAndImplementsAttrs(Context &context,
3591 const slang::ast::ClassType &cls) {
3592 mlir::MLIRContext *ctx = context.getContext();
3593
3594 // Base class (if any)
3595 mlir::SymbolRefAttr base;
3596 if (const auto *b = cls.getBaseClass())
3597 base = mlir::SymbolRefAttr::get(fullyQualifiedClassName(context, *b));
3598
3599 // Implemented interfaces (if any)
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)));
3606 }
3607
3608 mlir::ArrayAttr implArr =
3609 impls.empty() ? mlir::ArrayAttr() : mlir::ArrayAttr::get(ctx, impls);
3610
3611 return {base, implArr};
3612}
3613
3614/// Base class for visiting slang::ast::ClassType members.
3615/// Contains common state and utility methods.
3616struct ClassDeclVisitorBase {
3617 Context &context;
3618 OpBuilder &builder;
3619 ClassLowering &classLowering;
3620
3621 ClassDeclVisitorBase(Context &ctx, ClassLowering &lowering)
3622 : context(ctx), builder(ctx.builder), classLowering(lowering) {}
3623
3624protected:
3625 Location convertLocation(const slang::SourceLocation &sloc) {
3626 return context.convertLocation(sloc);
3627 }
3628};
3629
3630/// Visitor for class property declarations.
3631/// Populates the ClassDeclOp body with PropertyDeclOps.
3632struct ClassPropertyVisitor : ClassDeclVisitorBase {
3633 using ClassDeclVisitorBase::ClassDeclVisitorBase;
3634
3635 /// Build the ClassDeclOp body and populate it with property declarations.
3636 LogicalResult run(const slang::ast::ClassType &classAST) {
3637 if (!classLowering.op.getBody().empty())
3638 return success();
3639
3640 OpBuilder::InsertionGuard ig(builder);
3641
3642 Block *body = &classLowering.op.getBody().emplaceBlock();
3643 builder.setInsertionPointToEnd(body);
3644
3645 // Visit only ClassPropertySymbols
3646 for (const auto &mem : classAST.members()) {
3647 if (const auto *prop = mem.as_if<slang::ast::ClassPropertySymbol>()) {
3648 if (failed(prop->visit(*this)))
3649 return failure();
3650 }
3651 }
3652
3653 return success();
3654 }
3655
3656 // Properties: ClassPropertySymbol
3657 LogicalResult visit(const slang::ast::ClassPropertySymbol &prop) {
3658 auto loc = convertLocation(prop.location);
3659 auto ty = context.convertType(prop.getType());
3660 if (!ty)
3661 return failure();
3662
3663 if (prop.lifetime == slang::ast::VariableLifetime::Automatic) {
3664 moore::ClassPropertyDeclOp::create(builder, loc, prop.name,
3665 /*sym_visibility=*/{}, ty);
3666 return success();
3667 }
3668
3669 // Static variables should be accessed like globals, and not emit any
3670 // property declaration. Static variables might get hoisted elsewhere
3671 // so check first whether they have been declared already.
3672
3673 if (!context.globalVariables.lookup(&prop))
3674 return context.convertGlobalVariable(prop);
3675 return success();
3676 }
3677
3678 // Nested class definition, convert
3679 LogicalResult visit(const slang::ast::ClassType &cls) {
3680 return context.buildClassProperties(cls);
3681 }
3682
3683 // Catch-all: ignore everything else during property pass
3684 template <typename T>
3685 LogicalResult visit(T &&) {
3686 return success();
3687 }
3688};
3689
3690/// Visitor for class method declarations.
3691/// Materializes methods and nested class definitions.
3692struct ClassMethodVisitor : ClassDeclVisitorBase {
3693 using ClassDeclVisitorBase::ClassDeclVisitorBase;
3694
3695 /// Materialize class methods. The body must already exist from property pass.
3696 LogicalResult run(const slang::ast::ClassType &classAST) {
3697 if (classLowering.methodsFinalized)
3698 return success();
3699
3700 if (classLowering.op.getBody().empty())
3701 return failure();
3702
3703 OpBuilder::InsertionGuard ig(builder);
3704 builder.setInsertionPointToEnd(&classLowering.op.getBody().front());
3705
3706 // Visit everything except ClassPropertySymbols
3707 for (const auto &mem : classAST.members()) {
3708 if (failed(mem.visit(*this)))
3709 return failure();
3710 }
3711
3712 classLowering.methodsFinalized = true;
3713 return success();
3714 }
3715
3716 // Skip properties during method pass
3717 LogicalResult visit(const slang::ast::ClassPropertySymbol &) {
3718 return success();
3719 }
3720
3721 // Parameters in specialized classes hold no further information; slang
3722 // already elaborates them in all relevant places.
3723 LogicalResult visit(const slang::ast::ParameterSymbol &) { return success(); }
3724
3725 // Parameters in specialized classes hold no further information; slang
3726 // already elaborates them in all relevant places.
3727 LogicalResult visit(const slang::ast::TypeParameterSymbol &) {
3728 return success();
3729 }
3730
3731 // Type aliases in specialized classes hold no further information; slang
3732 // already elaborates them in all relevant places.
3733 LogicalResult visit(const slang::ast::TypeAliasType &) { return success(); }
3734
3735 // Nested class definition, skip
3736 LogicalResult visit(const slang::ast::GenericClassDefSymbol &) {
3737 return success();
3738 }
3739
3740 // Transparent members: ignore (inherited names pulled in by slang)
3741 LogicalResult visit(const slang::ast::TransparentMemberSymbol &) {
3742 return success();
3743 }
3744
3745 // Empty members: ignore
3746 LogicalResult visit(const slang::ast::EmptyMemberSymbol &) {
3747 return success();
3748 }
3749
3750 // Fully-fledged functions - SubroutineSymbol
3751 LogicalResult visit(const slang::ast::SubroutineSymbol &fn) {
3752 if (fn.flags & slang::ast::MethodFlags::BuiltIn) {
3753 static bool remarkEmitted = false;
3754 if (remarkEmitted)
3755 return success();
3756
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 "
3760 "during lowering.";
3761 remarkEmitted = true;
3762 return success();
3763 }
3764
3765 const mlir::UnitAttr isVirtual =
3766 (fn.flags & slang::ast::MethodFlags::Virtual)
3767 ? UnitAttr::get(context.getContext())
3768 : nullptr;
3769
3770 auto loc = convertLocation(fn.location);
3771 // Pure virtual functions regulate inheritance rules during parsing.
3772 // They don't emit any code, so we don't need to convert them, we only need
3773 // to register them for the purpose of stable VTable construction.
3774 if (fn.flags & slang::ast::MethodFlags::Pure) {
3775 // Add an extra %this argument.
3776 SmallVector<Type, 1> extraParams;
3777 auto classSym =
3778 mlir::FlatSymbolRefAttr::get(classLowering.op.getSymNameAttr());
3779 auto handleTy =
3780 moore::ClassHandleType::get(context.getContext(), classSym);
3781 extraParams.push_back(handleTy);
3782
3783 auto funcTy = getFunctionSignature(context, fn, extraParams);
3784 if (!funcTy) {
3785 mlir::emitError(loc) << "Invalid function signature for " << fn.name;
3786 return failure();
3787 }
3788
3789 moore::ClassMethodDeclOp::create(builder, loc, fn.name,
3790 /*sym_visibility=*/{}, funcTy, nullptr);
3791 return success();
3792 }
3793
3794 auto *lowering = context.declareFunction(fn);
3795 if (!lowering)
3796 return failure();
3797
3798 // We only emit methoddecls for virtual methods.
3799 if (!isVirtual)
3800 return success();
3801
3802 // Grab the function type from the declaration.
3803 FunctionType fnTy = cast<FunctionType>(lowering->op.getFunctionType());
3804 // Emit the method decl into the class body, preserving source order.
3805 moore::ClassMethodDeclOp::create(
3806 builder, loc, fn.name, /*sym_visibility=*/{}, fnTy,
3807 SymbolRefAttr::get(lowering->op.getNameAttr()));
3808
3809 return success();
3810 }
3811
3812 // A method prototype corresponds to the forward declaration of a concrete
3813 // method, the forward declaration of a virtual method, or the defintion of an
3814 // interface method meant to be implemented by classes implementing the
3815 // interface class.
3816 // In the first two cases, the best thing to do is to look up the actual
3817 // implementation and translate it when reading the method prototype, so we
3818 // can insert the MethodDeclOp in the correct order in the ClassDeclOp.
3819 // The latter case requires support for virtual interface methods, which is
3820 // currently not implemented. Since forward declarations of non-interface
3821 // methods must be followed by an implementation within the same compilation
3822 // unit, we can simply return a failure if we can't find a unique
3823 // implementation until we implement support for interface methods.
3824 LogicalResult visit(const slang::ast::MethodPrototypeSymbol &fn) {
3825 const auto *externImpl = fn.getSubroutine();
3826 // We needn't convert a forward declaration without a unique implementation.
3827 if (!externImpl) {
3828 mlir::emitError(convertLocation(fn.location))
3829 << "Didn't find an implementation matching the forward declaration "
3830 "of "
3831 << fn.name;
3832 return failure();
3833 }
3834 return visit(*externImpl);
3835 }
3836
3837 // Nested class definition, convert
3838 LogicalResult visit(const slang::ast::ClassType &cls) {
3839 if (failed(context.buildClassProperties(cls)))
3840 return failure();
3841 return context.materializeClassMethods(cls);
3842 }
3843
3844 // Emit an error for all other members.
3845 template <typename T>
3846 LogicalResult visit(T &&node) {
3847 Location loc = UnknownLoc::get(context.getContext());
3848 if constexpr (requires { node.location; })
3849 loc = convertLocation(node.location);
3850 mlir::emitError(loc) << "unsupported construct in ClassType members: "
3851 << slang::ast::toString(node.kind);
3852 return failure();
3853 }
3854};
3855} // namespace
3856
3857ClassLowering *Context::declareClass(const slang::ast::ClassType &cls) {
3858 // Check if there already is a declaration for this class.
3859 auto &lowering = classes[&cls];
3860 if (lowering)
3861 return lowering.get();
3862 lowering = std::make_unique<ClassLowering>();
3863 auto loc = convertLocation(cls.location);
3864
3865 // Pick an insertion point for this function according to the source file
3866 // location.
3867 OpBuilder::InsertionGuard g(builder);
3868 auto locationKey = LocationKey::get(cls.location, sourceManager);
3869 auto it = orderedRootOps.upper_bound(locationKey);
3870 if (it == orderedRootOps.end())
3871 builder.setInsertionPointToEnd(intoModuleOp.getBody());
3872 else
3873 builder.setInsertionPoint(it->second);
3874
3875 auto symName = fullyQualifiedClassName(*this, cls);
3876
3877 auto [base, impls] = buildBaseAndImplementsAttrs(*this, cls);
3878 auto classDeclOp = moore::ClassDeclOp::create(
3879 builder, loc, symName, /*sym_visibility=*/{}, base, impls);
3880
3881 SymbolTable::setSymbolVisibility(classDeclOp,
3882 SymbolTable::Visibility::Public);
3883 orderedRootOps.insert(it, {locationKey, classDeclOp});
3884 lowering->op = classDeclOp;
3885
3886 symbolTable.insert(classDeclOp);
3887 return lowering.get();
3888}
3889
3890LogicalResult
3891Context::buildClassProperties(const slang::ast::ClassType &classdecl) {
3892 // Keep track of local time scale.
3893 auto prevTimeScale = timeScale;
3894 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
3895 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
3896
3897 // Skip if classdecl is already built
3898 if (classes[&classdecl])
3899 return success();
3900
3901 // Build base class properties first.
3902 if (classdecl.getBaseClass()) {
3903 if (const auto *baseClassDecl =
3904 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
3905 if (failed(buildClassProperties(*baseClassDecl)))
3906 return failure();
3907 }
3908 }
3909
3910 // Declare the class and build the ClassDeclOp with property declarations.
3911 auto *lowering = declareClass(classdecl);
3912 if (!lowering)
3913 return failure();
3914
3915 return ClassPropertyVisitor(*this, *lowering).run(classdecl);
3916}
3917
3918LogicalResult
3919Context::materializeClassMethods(const slang::ast::ClassType &classdecl) {
3920 // Keep track of local time scale.
3921 auto prevTimeScale = timeScale;
3922 timeScale = classdecl.getTimeScale().value_or(slang::TimeScale());
3923 llvm::scope_exit timeScaleGuard([&] { timeScale = prevTimeScale; });
3924
3925 // The class must have been declared already via buildClassProperties.
3926 auto *lowering = classes[&classdecl].get();
3927 if (!lowering)
3928 return failure();
3929
3930 // Materialize base class methods first. This may insert new entries into the
3931 // `classes` map (e.g. for nested classes), so we must not hold an iterator
3932 // or reference into the map across this call.
3933 if (classdecl.getBaseClass()) {
3934 if (const auto *baseClassDecl =
3935 classdecl.getBaseClass()->as_if<slang::ast::ClassType>()) {
3936 if (failed(materializeClassMethods(*baseClassDecl)))
3937 return failure();
3938 }
3939 }
3940
3941 return ClassMethodVisitor(*this, *lowering).run(classdecl);
3942}
3943
3944/// Convert a variable to a `moore.global_variable` operation.
3945LogicalResult
3946Context::convertGlobalVariable(const slang::ast::VariableSymbol &var) {
3947 auto loc = convertLocation(var.location);
3948
3949 // Pick an insertion point for this variable according to the source file
3950 // location.
3951 OpBuilder::InsertionGuard g(builder);
3952 auto locationKey = LocationKey::get(var.location, sourceManager);
3953 auto it = orderedRootOps.upper_bound(locationKey);
3954 if (it == orderedRootOps.end())
3955 builder.setInsertionPointToEnd(intoModuleOp.getBody());
3956 else
3957 builder.setInsertionPoint(it->second);
3958
3959 // Prefix the variable name with the surrounding namespace to create somewhat
3960 // sane names in the IR.
3961 SmallString<64> symName;
3962
3963 // If the variable is a class property, the symbol name needs to be fully
3964 // qualified with the hierarchical class name
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);
3970 else {
3971 mlir::emitError(loc)
3972 << "Could not access parent class of class property "
3973 << classVar->name;
3974 return failure();
3975 }
3976 } else {
3977 mlir::emitError(loc) << "Could not get parent scope of class property "
3978 << classVar->name;
3979 return failure();
3980 }
3981 symName += "::";
3982 symName += var.name;
3983 } else {
3984 guessNamespacePrefix(var.getParentScope()->asSymbol(), symName);
3985 symName += var.name;
3986 }
3987
3988 // Determine the type of the variable.
3989 auto type = convertType(var.getType());
3990 if (!type)
3991 return failure();
3992
3993 // Create the variable op itself.
3994 auto varOp = moore::GlobalVariableOp::create(builder, loc, symName,
3995 /*sym_visibility=*/{},
3996 cast<moore::UnpackedType>(type));
3997 orderedRootOps.insert({locationKey, varOp});
3998 globalVariables.insert({&var, varOp});
3999
4000 // Add the variable to the symbol table of the MLIR module, which uniquifies
4001 // its name.
4002 symbolTable.insert(varOp);
4003
4004 // If the variable has an initializer expression, remember it for later such
4005 // that we can convert the initializers once we have seen all global
4006 // variables.
4007 if (var.getInitializer())
4008 globalVariableWorklist.push_back(&var);
4009
4010 return success();
4011}
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'.
return success()
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 > &notVars)
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 &notVal)
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)
Definition Structure.cpp:63
static constexpr StringLiteral dpiExportAttrName
Definition Structure.cpp:24
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 ...
Definition Structure.cpp:34
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.
Definition FVInt.h:37
static FVInt getAllZ(unsigned numBits)
Construct an FVInt with all bits set to Z.
Definition FVInt.h:80
static FVInt getAllX(unsigned numBits)
Construct an FVInt with all bits set to X.
Definition FVInt.h:75
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.
Definition CalyxOps.cpp:56
@ TwoValued
Two-valued types such as bit or int.
Definition MooreTypes.h:53
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)
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...
Definition Types.cpp:474
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.
Definition Types.cpp:224
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)
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)
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.
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)
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.
Lowering information for an expanded interface instance.
static LocationKey get(const slang::SourceLocation &loc, const slang::SourceManager &mgr)