CIRCT 24.0.0git
Loading...
Searching...
No Matches
ImportVerilogInternals.h
Go to the documentation of this file.
1//===- ImportVerilogInternals.h - Internal implementation details ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// NOLINTNEXTLINE(llvm-header-guard)
10#ifndef CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
11#define CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
12
13#include "CaptureAnalysis.h"
20#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
21#include "mlir/Dialect/Func/IR/FuncOps.h"
22#include "slang/ast/ASTVisitor.h"
23#include "slang/ast/TimingControl.h"
24#include "slang/text/SourceManager.h"
25#include "llvm/ADT/ScopedHashTable.h"
26#include "llvm/Support/Debug.h"
27#include <map>
28#include <queue>
29
30#define DEBUG_TYPE "import-verilog"
31
32namespace circt {
33namespace ImportVerilog {
34
35using moore::Domain;
36
37/// Get the slang canonical body for the given `instance`, if there is one.
38/// If there isn't one, fall back to the normal body.
39inline const slang::ast::InstanceBodySymbol *
40getCanonicalBody(const slang::ast::InstanceSymbol &inst) {
41 const slang::ast::InstanceBodySymbol *body = inst.getCanonicalBody();
42 return body == nullptr ? &inst.body : body;
43}
44
45/// Port lowering information.
47 const slang::ast::PortSymbol &ast;
48 Location loc;
49 BlockArgument arg;
50 /// Slot index in the module signature. `outputIdx` is set for outputs;
51 /// `inputIdx` is set for inputs and inouts. Regular and expanded
52 /// interface-modport ports share one numbering per direction.
53 std::optional<unsigned> outputIdx;
54 std::optional<unsigned> inputIdx;
55};
56
57/// Lowering information for a single signal flattened from an interface port.
59 StringAttr name;
61 mlir::Type type;
62 Location loc;
63 BlockArgument arg;
64 /// the origin interface port symbol this was flattened from.
65 const slang::ast::InterfacePortSymbol *origin;
66 /// the interface body member (VariableSymbol , NetSymbol)
67 const slang::ast::Symbol *bodySym;
68 /// The connected interface instance backing this port (if any). This enables
69 /// materializing virtual interface handles from interface ports.
70 const slang::ast::InstanceSymbol *ifaceInstance = nullptr;
71 /// For modport-typed iface ports, the ModportPortSymbol this was flattened
72 /// from. Slang resolves in-body accesses like `bus.member` to a
73 /// `HierarchicalValueExpression` whose symbol is the `ModportPortSymbol`,
74 /// not the underlying interface body variable, so we register both keys in
75 /// `valueSymbols` to make the lookup find this port's `BlockArgument`.
76 const slang::ast::Symbol *modportPortSym = nullptr;
77 /// Slot index in the module signature; see `PortLowering::outputIdx`.
78 std::optional<unsigned> outputIdx;
79 std::optional<unsigned> inputIdx;
80};
81
82/// Lowering information for an expanded interface instance. Maps each interface
83/// body member to its expanded SSA value (moore.variable or moore.net).
85 DenseMap<const slang::ast::Symbol *, Value> expandedMembers;
86 DenseMap<StringAttr, Value> expandedMembersByName;
87};
88
89/// Cached lowering information for representing SystemVerilog `virtual
90/// interface` handles as Moore types (a struct of references to interface
91/// members).
93 moore::UnpackedStructType type;
94 SmallVector<StringAttr, 8> fieldNames;
95};
96
97/// A mapping entry for resolving Slang virtual interface member accesses.
98///
99/// Slang may resolve `vif.member` expressions (where `vif` has a
100/// `VirtualInterfaceType`) directly to a `NamedValueExpression` for `member`.
101/// This table records which virtual interface base symbol that member access is
102/// rooted in, so ImportVerilog can materialize the appropriate Moore IR.
104 const slang::ast::ValueSymbol *base = nullptr;
105 /// The name of the field in the lowered virtual interface handle struct that
106 /// should be accessed for this member.
107 StringAttr fieldName;
108};
109
110/// Module lowering information.
112 moore::SVModuleOp op;
113 SmallVector<PortLowering> ports;
114 SmallVector<FlattenedIfacePort> ifacePorts;
115 DenseMap<const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol *>
117 /// Number of explicit-port slots per direction. Hierarchical-name ports
118 /// are appended after these in the module signature.
119 unsigned numExplicitOutputs = 0;
120 unsigned numExplicitInputs = 0;
121};
122
123/// Function lowering information. The `op` field holds either a `func::FuncOp`
124/// (for SystemVerilog functions), a `moore::CoroutineOp` (for tasks), or a
125/// `moore::DPIFuncOp` (for DPI-imported functions), all accessed through the
126/// `FunctionOpInterface`.
128 mlir::FunctionOpInterface op;
129
130 /// The AST symbols captured by this function, determined by the capture
131 /// analysis pre-pass. These are added as extra parameters to the function
132 /// during declaration.
133 SmallVector<const slang::ast::ValueSymbol *, 4> capturedSymbols;
134
135 explicit FunctionLowering(mlir::FunctionOpInterface op) : op(op) {}
136};
137
138// Class lowering information.
140 circt::moore::ClassDeclOp op;
141 bool methodsFinalized = false;
142};
143
144/// Information about a loops continuation and exit blocks relevant while
145/// lowering the loop's body statements.
146struct LoopFrame {
147 /// The block to jump to from a `continue` statement.
149 /// The block to jump to from a `break` statement.
151};
152
153/// Hierarchical path information.
154/// The "hierName" means a different hierarchical name at different module
155/// levels.
156/// The "idx" means where the current hierarchical name is on the portlists.
157/// The "direction" means hierarchical names whether downward(In) or
158/// upward(Out).
160 mlir::StringAttr hierName;
161 std::optional<unsigned int> idx;
162 slang::ast::ArgumentDirection direction;
163
164 /// The symbols this path resolves to, each paired with the elaborated
165 /// instance body it was observed in. Sibling instances elaborate the same
166 /// logical variable to distinct symbol objects. The pairing lets instance
167 /// wiring bind each one to the right instance.
168 llvm::SmallVector<std::pair<const slang::ast::ValueSymbol *,
169 const slang::ast::InstanceBodySymbol *>,
170 2>
172};
173
174/// ImportVerilog Elaboration Phases for Hierarchical Names
175///
176/// Hierarchical name resolution is performed in four distinct phases:
177///
178/// 1. Collection: The `traverseInstanceBody` pass walks the Slang AST to
179/// identify all hierarchical references (e.g., `Top.sub.var`). It records
180/// these in `hierPaths` mapped by module body.
181///
182/// 2. Port Generation: In `convertModuleHeader`, we inspect `hierPaths` for
183/// the module and add corresponding input/output ports to the generated
184/// `moore.module` to allow cross-module communication.
185///
186/// 3. Wiring: In `Structure.cpp` during instance creation, we look up the
187/// canonical module body's `hierPaths` to determine which hierarchical
188/// values need to be passed as inputs or captured as outputs from the
189/// instance.
190///
191/// 4. Resolution: In `Expressions.cpp`, visitors for rvalues and lvalues
192/// resolve hierarchical names by first checking function captures (inside
193/// a function body the capture argument must be used to respect region
194/// isolation), then the instance-aware `hierValueSymbols` map, and finally
195/// standard scoped lookups.
196
197// A slang::SourceLocation for deterministic comparisons. Comparisons use the
198// buffer's sortKey rather than bufferId.
200 uint64_t sortKey;
201 size_t offset;
202
203 static LocationKey get(const slang::SourceLocation &loc,
204 const slang::SourceManager &mgr) {
205 return {
206 mgr.getSortKey(loc.buffer()),
207 loc.offset(),
208 };
209 }
210
211 std::strong_ordering operator<=>(const LocationKey &) const = default;
212 bool operator==(const LocationKey &) const = default;
213};
214
215/// A helper class to facilitate the conversion from a Slang AST to MLIR
216/// operations. Keeps track of the destination MLIR module, builders, and
217/// various worklists and utilities needed for conversion.
218struct Context {
220 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
221 const slang::SourceManager &sourceManager)
224 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
226 Context(const Context &) = delete;
227
228 /// Return the MLIR context.
229 MLIRContext *getContext() { return intoModuleOp.getContext(); }
230
231 /// Convert a slang `SourceLocation` into an MLIR `Location`.
232 Location convertLocation(slang::SourceLocation loc);
233 /// Convert a slang `SourceRange` into an MLIR `Location`.
234 Location convertLocation(slang::SourceRange range);
235
236 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
237 /// provided location for error reporting, or tries to guess one from the
238 /// given type. Types tend to have unreliable location information, so it's
239 /// generally a good idea to pass in a location.
240 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
241 Type convertType(const slang::ast::DeclaredType &type);
242
243 /// Convert hierarchy and structure AST nodes to MLIR ops.
244 LogicalResult convertCompilation();
245 /// Convert a module and its ports to an empty module op in the IR. Also adds
246 /// the op to the worklist of module bodies to be lowered. This acts like a
247 /// module "declaration", allowing instances to already refer to a module even
248 /// before its body has been lowered.
249 /// `module` must be the canonical module body if there is one.
250 ModuleLowering *
251 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
252 /// Convert a module's body to the corresponding IR ops. The module op must
253 /// have already been created earlier through a `convertModuleHeader` call.
254 /// `module` must be the canonical module body if there is one.
255 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
256 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
257 FunctionLowering *
258 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
259 LogicalResult defineFunction(const slang::ast::SubroutineSymbol &subroutine);
260 LogicalResult
261 convertPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim);
262 ClassLowering *declareClass(const slang::ast::ClassType &cls);
263 LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl);
264 LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl);
265 LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var);
266
267 /// Get the helper function implementing one of the `name`, `next`, and `prev`
268 /// built-in methods for the given enum type, creating it on first use.
269 /// Returns null and emits an error if the helper cannot be created.
270 mlir::func::FuncOp
271 getOrCreateEnumHelper(const slang::ast::Type &type,
272 slang::parsing::KnownSystemName method, Location loc);
273
274 /// Convert a Slang virtual interface type into the Moore type used to
275 /// represent virtual interface handles. Populates internal caches so that
276 /// interface instance references can be materialized consistently.
277 FailureOr<moore::UnpackedStructType>
278 convertVirtualInterfaceType(const slang::ast::VirtualInterfaceType &type,
279 Location loc);
280
281 /// Materialize a Moore value representing a concrete interface instance as a
282 /// virtual interface handle. This only succeeds for the Slang
283 /// `VirtualInterfaceType` wrappers that refer to a real interface instance
284 /// (`isRealIface`).
285 FailureOr<Value>
286 materializeVirtualInterfaceValue(const slang::ast::VirtualInterfaceType &type,
287 Location loc);
288
289 /// Register the interface members of a virtual interface base symbol for use
290 /// in later expression conversion.
291 LogicalResult
292 registerVirtualInterfaceMembers(const slang::ast::ValueSymbol &base,
293 const slang::ast::VirtualInterfaceType &type,
294 Location loc);
295
296 /// Checks whether one class (actualTy) is derived from another class
297 /// (baseTy). True if it's a subclass, false otherwise.
298 bool isClassDerivedFrom(const moore::ClassHandleType &actualTy,
299 const moore::ClassHandleType &baseTy);
300
301 /// Tries to find the closest base class of actualTy that carries a property
302 /// with name fieldName. The location is used for error reporting.
303 moore::ClassHandleType
304 getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
305 StringRef fieldName, Location loc);
306
307 Value getImplicitThisRef() const {
308 return currentThisRef; // block arg added in declareFunction
309 }
310
311 /// Maps sampled value system calls to their corresponding clocks
312 DenseMap<const slang::ast::CallExpression *,
313 const slang::ast::TimingControl *>
315
316 /// Generates a map from sampled value system calls to clocks using Slang's
317 /// analysis
319
320 Value getIndexedQueue() const { return currentQueue; }
321
322 // Convert a statement AST node to MLIR ops.
323 LogicalResult convertStatement(const slang::ast::Statement &stmt);
324
325 // Convert an expression AST node to MLIR ops.
326 Value convertRvalueExpression(const slang::ast::Expression &expr,
327 Type requiredType = {});
328 Value convertLvalueExpression(const slang::ast::Expression &expr);
329
330 // Convert an assertion expression AST node to MLIR ops.
331 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
332 Location loc);
333
334 // Convert a sampled value system call expression AST node to MLIR ops.
336 const slang::ast::CallExpression &expr,
337 const slang::ast::CallExpression::SystemCallInfo &info, Location loc);
338
339 // Traverse the whole AST to collect hierarchical names.
340 void traverseInstanceBody(const slang::ast::InstanceSymbol &symbol);
341
342 /// Build a composite key for hierValueSymbols from a hierarchical value
343 /// expression. Returns {firstInstanceSymbol, dottedHierName} or std::nullopt
344 /// if the expression has no instance path.
345 std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
346 buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr);
347
348 /// If `sym` is captured by the function currently being converted, return the
349 /// value it is bound to (the capture block argument); otherwise return null.
350 Value resolveCapturedValue(const slang::ast::ValueSymbol &sym);
351
352 // Convert timing controls into a corresponding set of ops that delay
353 // execution of the current block. Produces an error if the implicit event
354 // control `@*` or `@(*)` is used.
355 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl);
356 // Convert timing controls into a corresponding set of ops that delay
357 // execution of the current block. Then converts the given statement, taking
358 // note of the rvalues it reads and adding them to a wait op in case an
359 // implicit event control `@*` or `@(*)` is used.
360 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
361 const slang::ast::Statement &stmt);
362
363 /// Helper function to convert a value to a MLIR I1 value.
364 Value convertToI1(Value value);
365
366 // Convert a slang timing control for LTL
367 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
368 const Value &seqOrPro);
369
370 /// Creates a delayed assignment based on the given TimingControl delay (or
371 /// without a delay if the TimingControl is null)
372 LogicalResult
373 assignPrimOutputWithDelay(Value outputVal, Value assignment,
374 const slang::ast::TimingControl *delay,
375 Location loc);
376
377 LogicalResult
378 convertMOSSwitchPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
379
380 LogicalResult
381 convertCMOSSwitchPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
382
383 LogicalResult
384 convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
385
386 LogicalResult
387 convertNOutputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
388
389 LogicalResult
390 convertFixedPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
391
392 LogicalResult
393 convertPullGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
394
395 LogicalResult convertThreeStateGatePrimitive(
396 const slang::ast::PrimitiveInstanceSymbol &prim);
397
398 /// Helper function to convert a value to its "truthy" boolean value.
399 Value convertToBool(Value value);
400
401 /// Helper function to convert a value to its "truthy" boolean value and
402 /// convert it to the given domain.
403 Value convertToBool(Value value, Domain domain);
404
405 /// Helper function to convert a value to its simple bit vector
406 /// representation, if it has one. Otherwise returns null. Also returns null
407 /// if the given value is null.
408 Value convertToSimpleBitVector(Value value);
409
410 /// Helper function to convert a `PackedType` value to its simple bit
411 /// vector representation, with special handling for time values which
412 /// require scaling by the local timescale. If `fallible` is true,
413 /// conversion failures are reported by returning a null value without
414 /// emitting diagnostics.
415 Value materializePackedToSBVConversion(Value value, Location loc,
416 bool fallible);
417
418 /// Helper function to insert the necessary operations to cast a value from
419 /// one type to another. If `fallible` is true, conversion failures are
420 /// reported by returning a null value without emitting diagnostics.
421 Value materializeConversion(Type type, Value value, bool isSigned,
422 Location loc, bool fallible = false);
423
424 /// Helper function to materialize an `SVInt` as an SSA value.
425 Value materializeSVInt(const slang::SVInt &svint,
426 const slang::ast::Type &type, Location loc);
427
428 /// Helper function to materialize a real value as an SSA value.
429 Value materializeSVReal(const slang::ConstantValue &svreal,
430 const slang::ast::Type &type, Location loc);
431
432 /// Helper function to materialize a string as an SSA value.
433 Value materializeString(const slang::ConstantValue &string,
434 const slang::ast::Type &astType, Location loc);
435
436 /// Helper function to materialize an unpacked array of `SVInt`s as an SSA
437 /// value.
439 const slang::ConstantValue &constant,
440 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc);
441
442 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
443 /// null if the constant cannot be materialized.
444 Value materializeConstant(const slang::ConstantValue &constant,
445 const slang::ast::Type &type, Location loc);
446
447 /// Convert a list of string literal arguments with formatting specifiers and
448 /// arguments to be interpolated into a `!moore.format_string` value. Returns
449 /// failure if an error occurs. Returns a null value if the formatted string
450 /// is trivially empty. Otherwise returns the formatted string.
451 FailureOr<Value> convertFormatString(
452 std::span<const slang::ast::Expression *const> arguments, Location loc,
453 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
454 bool appendNewline = false);
455
456 /// Result of converting a scan format string. The final cursor of the
457 /// consuming chain and the list of (destination expression, scanned value,
458 /// matched flag) tuples to assign
461 SmallVector<std::tuple<const slang::ast::Expression *, Value, Value>>
463 };
464
465 /// Convert a scan format string into a consuming chain of `moore.scan.*`
466 /// operations starting from `initialCursor`. Each non-suppressed specifier
467 /// produces an entry in `assignments`; the caller is responsible for emitting
468 /// the corresponding `moore.blocking_assign` ops. Returns failur if an erro
469 /// occurs.
470 FailureOr<ScanStringResult>
471 convertScanString(StringRef formatStr, Value initialCursor,
472 std::span<const slang::ast::Expression *const> destinations,
473 Location loc);
474
475 /// Convert system function calls. Returns a null `Value` on failure after
476 /// emitting an error.
477 Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine,
478 Location loc,
479 std::span<const slang::ast::Expression *const> args);
480
481 /// Convert sampled value system function calls with a single argument.
482 FailureOr<Value>
483 convertSampledValueCallArity1(const slang::ast::SystemSubroutine &subroutine,
484 Location loc, Value value, Type originalType,
485 Value clockVal);
486
487 /// Evaluate the constant value of an expression.
488 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
489
490 /// Convert the inside/set-membership expression.
491 Value convertInsideCheck(Value insideLhs, Location loc,
492 const slang::ast::Expression &expr);
493
495 slang::ast::Compilation &compilation;
496 mlir::ModuleOp intoModuleOp;
497 const slang::SourceManager &sourceManager;
498
499 /// The builder used to create IR operations.
500 OpBuilder builder;
501 /// A symbol table of the MLIR module we are emitting into.
502 SymbolTable symbolTable;
503
504 /// The top-level operations ordered by their Slang source location. This is
505 /// used to produce IR that follows the source file order.
506 std::map<LocationKey, Operation *> orderedRootOps;
507
508 /// How we have lowered modules to MLIR.
509 /// The keys must be the slang canonical module bodies where they exist.
510 DenseMap<const slang::ast::InstanceBodySymbol *,
511 std::unique_ptr<ModuleLowering>>
513
514 /// Expanded interface instances, keyed by the InstanceSymbol pointer.
515 /// Each entry maps body members to their expanded SSA values. Scoped
516 /// per-module so entries are cleaned up when a module's conversion ends.
518 llvm::ScopedHashTable<const slang::ast::InstanceSymbol *,
520 using InterfaceInstanceScope = InterfaceInstances::ScopeTy;
522 /// Owning storage for InterfaceLowering objects
523 /// because ScopedHashTable stores values by copy.
524 SmallVector<std::unique_ptr<InterfaceLowering>> interfaceInstanceStorage;
525
526 /// Module instances already emitted by the predeclaration pass. These are
527 /// skipped during the later source-order module-body walk to avoid emitting
528 /// duplicate instances.
529 DenseSet<const slang::ast::InstanceSymbol *> predeclaredInstances;
530
531 /// Cached virtual interface layouts (type + field order).
532 DenseMap<const slang::ast::InstanceBodySymbol *, VirtualInterfaceLowering>
534 DenseMap<const slang::ast::ModportSymbol *, VirtualInterfaceLowering>
536 /// A list of modules for which the header has been created, but the body has
537 /// not been converted yet.
538 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
539
540 /// A list of functions for which the declaration has been created, but the
541 /// body has not been defined yet.
542 std::queue<const slang::ast::SubroutineSymbol *> functionWorklist;
543
544 /// Functions that have already been converted.
545 DenseMap<const slang::ast::SubroutineSymbol *,
546 std::unique_ptr<FunctionLowering>>
548
549 /// DPI-C export directives keyed by the SystemVerilog subroutine they expose.
550 DenseMap<const slang::ast::SubroutineSymbol *, std::string> dpiExportCNames;
551
552 /// Helper functions generated for the enum built-in methods, keyed by the
553 /// canonical enum type and the method they implement.
554 DenseMap<
555 std::pair<const slang::ast::EnumType *, slang::parsing::KnownSystemName>,
556 mlir::func::FuncOp>
558
559 /// Classes that have already been converted.
560 DenseMap<const slang::ast::ClassType *, std::unique_ptr<ClassLowering>>
562
563 /// A table of defined values, such as variables, that may be referred to by
564 /// name in expressions. The expressions use this table to lookup the MLIR
565 /// value that was created for a given declaration in the Slang AST node.
567 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
568 using ValueSymbolScope = ValueSymbols::ScopeTy;
570
571 /// A table mapping symbols for interface members accessed through a virtual
572 /// interface to the virtual interface base value symbol.
574 llvm::ScopedHashTable<const slang::ast::ValueSymbol *,
576 using VirtualInterfaceMemberScope = VirtualInterfaceMembers::ScopeTy;
578
579 /// A table of defined global variables that may be referred to by name in
580 /// expressions.
581 DenseMap<const slang::ast::ValueSymbol *, moore::GlobalVariableOp>
583 /// A list of global variables that still need their initializers to be
584 /// converted.
585 SmallVector<const slang::ast::ValueSymbol *> globalVariableWorklist;
586
587 /// Pre-computed capture analysis: maps each function to the set of non-local,
588 /// non-global variables it captures (directly or transitively).
590
591 /// Collect all hierarchical names used for the per module/instance.
592 /// The keys are the slang canonical instance bodies (or the real instance
593 /// if slang's getCanonicalBody() returned null).
594 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
596
597 /// Persistent map for hierarchical value lookups. Keyed by a composite
598 /// of the instance symbol (the specific instance being wired, e.g., p1 or
599 /// p2) and the hierarchical path name (e.g., "child.child_val"). This
600 /// ensures instance-specific resolution even when Slang shares or doesn't
601 /// share instance bodies across multiple instances of the same module.
602 DenseMap<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>,
603 Value>
605
606 /// A stack of assignment left-hand side values. Each assignment will push its
607 /// lowered left-hand side onto this stack before lowering its right-hand
608 /// side. This allows expressions to resolve the opaque
609 /// `LValueReferenceExpression`s in the AST.
610 SmallVector<Value> lvalueStack;
611
612 /// A stack of loop continuation and exit blocks. Each loop will push the
613 /// relevant info onto this stack, lower its loop body statements, and pop the
614 /// info off the stack again. Continue and break statements encountered as
615 /// part of the loop body statements will use this information to branch to
616 /// the correct block.
617 SmallVector<LoopFrame> loopStack;
618
619 /// A listener called for every variable or net being read. This can be used
620 /// to collect all variables read as part of an expression or statement, for
621 /// example to populate the list of observed signals in an implicit event
622 /// control `@*`.
623 std::function<void(moore::ReadOp)> rvalueReadCallback;
624 /// A listener called for every variable or net being assigned. This can be
625 /// used to collect all variables assigned in a task scope.
626 std::function<void(mlir::Operation *)> variableAssignCallback;
627
628 /// Whether we are currently converting expressions inside a timing control,
629 /// such as `@(posedge clk)`. This is used by the implicit event control
630 /// callback to avoid adding reads from explicit event controls to the
631 /// implicit sensitivity list.
633
634 /// The time scale currently in effect.
635 slang::TimeScale timeScale;
636
637 /// Variable to track the value of the current function's implicit `this`
638 /// reference
639 Value currentThisRef = {};
640
641 /// The function currently being converted, if any. Used to give captured
642 /// symbols priority over module-level hierarchical values inside function
643 /// bodies.
645
646 /// Variable that tracks the queue which we are currently converting the index
647 /// expression for. This is necessary to implement the `$` operator, which
648 /// returns the index of the last element of the queue.
649 Value currentQueue = {};
650
651 /// The definition symbol of the module body currently being converted.
652 /// Used to resolve the `%l`/`%L` library binding format specifier.
653 const slang::ast::DefinitionSymbol *currentDefinition = nullptr;
654
655 /// Ensure that the global variables for `$monitor` state exist. This creates
656 /// the `__monitor_active_id` and `__monitor_enabled` globals on first call.
658
659 /// Ensure that the global variable for `$timeformat` state exists.
660 /// This creates the `__timeformat_state` global on first call.
662
663 /// Process any pending `$monitor` calls and generate the monitoring
664 /// procedures at module level.
665 LogicalResult flushPendingMonitors();
666
667 /// Global variable ops for `$monitor` state management. These are created on
668 /// demand by `ensureMonitorGlobals()`.
669 moore::GlobalVariableOp monitorActiveIdGlobal = nullptr;
670 moore::GlobalVariableOp monitorEnabledGlobal = nullptr;
671
672 /// Global variable ops for `$timeformat` state management. These are created
673 /// on demand by `ensureTimeFormatGlobal()`.
674 moore::GlobalVariableOp timeFormatGlobal = nullptr;
675
676 /// The next monitor ID to allocate. ID 0 is reserved for "no monitor active".
677 unsigned nextMonitorId = 1;
678
679 /// Information about a pending `$monitor` call that needs to be converted
680 /// after the current module's body has been processed.
682 unsigned id;
683 Location loc;
684 const slang::ast::CallExpression *call;
685 };
686
687 /// Pending `$monitor` calls that need to be converted at module level.
688 SmallVector<PendingMonitor> pendingMonitors;
689
690private:
691 /// Helper function to extract the commonalities in lowering of functions and
692 /// methods
694 declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
695 mlir::StringRef qualifiedName,
696 llvm::SmallVectorImpl<Type> &extraParams);
697};
698
699/// Map an index into an array, with bounds `range`, to a bit offset of the
700/// underlying bit storage. This is a dynamic version of
701/// `slang::ConstantRange::translateIndex`.
702Value getSelectIndex(Context &context, Location loc, Value index,
703 const slang::ConstantRange &range);
704
705} // namespace ImportVerilog
706} // namespace circt
707#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
static std::unique_ptr< Context > context
const slang::ast::InstanceBodySymbol * getCanonicalBody(const slang::ast::InstanceSymbol &inst)
Get the slang canonical body for the given instance, if there is one.
Value getSelectIndex(Context &context, Location loc, Value index, const slang::ConstantRange &range)
Map an index into an array, with bounds range, to a bit offset of the underlying bit storage.
DenseMap< const slang::ast::SubroutineSymbol *, SmallSetVector< const slang::ast::ValueSymbol *, 4 > > CaptureMap
The result of capture analysis: for each function, the set of non-local, non-global variable symbols ...
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:50
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Options that control how Verilog input files are parsed and processed.
Information about a pending $monitor call that needs to be converted after the current module's body ...
Result of converting a scan format string.
SmallVector< std::tuple< const slang::ast::Expression *, Value, Value > > assignments
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
Value convertToI1(Value value)
Helper function to convert a value to a MLIR I1 value.
llvm::ScopedHashTable< const slang::ast::InstanceSymbol *, InterfaceLowering * > InterfaceInstances
Expanded interface instances, keyed by the InstanceSymbol pointer.
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.
FailureOr< ScanStringResult > convertScanString(StringRef formatStr, Value initialCursor, std::span< const slang::ast::Expression *const > destinations, Location loc)
Convert a scan format string into a consuming chain of moore.scan.
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
Value materializeConstant(const slang::ConstantValue &constant, const slang::ast::Type &type, Location loc)
Helper function to materialize a ConstantValue as an SSA value.
SmallVector< LoopFrame > loopStack
A stack of loop continuation and exit blocks.
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.
slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr)
Evaluate the constant value of an expression.
SmallVector< PendingMonitor > pendingMonitors
Pending $monitor calls that need to be converted at module level.
Value convertInsideCheck(Value insideLhs, Location loc, const slang::ast::Expression &expr)
Convert the inside/set-membership expression.
Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl, const Value &seqOrPro)
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 convertTimingControl(const slang::ast::TimingControl &ctrl)
DenseMap< const slang::ast::InstanceBodySymbol *, VirtualInterfaceLowering > virtualIfaceLowerings
Cached virtual interface layouts (type + field order).
LogicalResult flushPendingMonitors()
Process any pending $monitor calls and generate the monitoring procedures at module level.
LogicalResult convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
llvm::ScopedHashTable< const slang::ast::ValueSymbol *, VirtualInterfaceMemberAccess > VirtualInterfaceMembers
A table mapping symbols for interface members accessed through a virtual interface to the virtual int...
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...
Context(const ImportVerilogOptions &options, slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp, const slang::SourceManager &sourceManager)
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.
Value materializeFixedSizeUnpackedArrayType(const slang::ConstantValue &constant, const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc)
Helper function to materialize an unpacked array of SVInts as an SSA value.
Value convertSampledValueCallExpression(const slang::ast::CallExpression &expr, const slang::ast::CallExpression::SystemCallInfo &info, Location loc)
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.
std::function< void(moore::ReadOp)> rvalueReadCallback
A listener called for every variable or net being read.
bool isClassDerivedFrom(const moore::ClassHandleType &actualTy, const moore::ClassHandleType &baseTy)
Checks whether one class (actualTy) is derived from another class (baseTy).
Context(const Context &)=delete
void ensureTimeFormatGlobal()
Ensure that the global variable for $timeformat state exists.
Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine, Location loc, std::span< const slang::ast::Expression *const > args)
Convert system function calls.
DenseMap< std::pair< const slang::ast::EnumType *, slang::parsing::KnownSystemName >, mlir::func::FuncOp > enumHelpers
Helper functions generated for the enum built-in methods, keyed by the canonical enum type and the me...
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.
Value materializeSVInt(const slang::SVInt &svint, const slang::ast::Type &type, Location loc)
Helper function to materialize an SVInt as an SSA value.
slang::TimeScale timeScale
The time scale currently in effect.
Value resolveCapturedValue(const slang::ast::ValueSymbol &sym)
If sym is captured by the function currently being converted, return the value it is bound to (the ca...
DenseMap< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr >, Value > hierValueSymbols
Persistent map for hierarchical value lookups.
Value materializeSVReal(const slang::ConstantValue &svreal, const slang::ast::Type &type, Location loc)
Helper function to materialize a real value as an SSA value.
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)
std::function< void(mlir::Operation *)> variableAssignCallback
A listener called for every variable or net being assigned.
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)
mlir::func::FuncOp getOrCreateEnumHelper(const slang::ast::Type &type, slang::parsing::KnownSystemName method, Location loc)
Get the helper function implementing one of the name, next, and prev built-in methods for the given e...
moore::ClassHandleType getAncestorClassWithProperty(const moore::ClassHandleType &actualTy, StringRef fieldName, Location loc)
Tries to find the closest base class of actualTy that carries a property with name fieldName.
void ensureMonitorGlobals()
Ensure that the global variables for $monitor state exist.
FailureOr< Value > convertFormatString(std::span< const slang::ast::Expression *const > arguments, Location loc, moore::IntFormat defaultFormat=moore::IntFormat::Decimal, bool appendNewline=false)
Convert a list of string literal arguments with formatting specifiers and arguments to be interpolate...
const ImportVerilogOptions & options
Value materializePackedToSBVConversion(Value value, Location loc, bool fallible)
Helper function to convert a PackedType value to its simple bit vector representation,...
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.
llvm::ScopedHashTable< const slang::ast::ValueSymbol *, Value > ValueSymbols
A table of defined values, such as variables, that may be referred to by name in expressions.
Value convertToSimpleBitVector(Value value)
Helper function to convert a value to its simple bit vector representation, if it has one.
moore::GlobalVariableOp monitorActiveIdGlobal
Global variable ops for $monitor state management.
LogicalResult convertMOSSwitchPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
VirtualInterfaceMembers virtualIfaceMembers
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
DenseMap< const slang::ast::CallExpression *, const slang::ast::TimingControl * > sampledValueCallClocks
Maps sampled value system calls to their corresponding clocks.
moore::GlobalVariableOp monitorEnabledGlobal
DenseMap< const slang::ast::ModportSymbol *, VirtualInterfaceLowering > virtualIfaceModportLowerings
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 traverseInstanceBody(const slang::ast::InstanceSymbol &symbol)
Value currentQueue
Variable that tracks the queue which we are currently converting the index expression for.
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
moore::GlobalVariableOp timeFormatGlobal
Global variable ops for $timeformat state management.
LogicalResult convertThreeStateGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim)
FailureOr< Value > materializeVirtualInterfaceValue(const slang::ast::VirtualInterfaceType &type, Location loc)
Materialize a Moore value representing a concrete interface instance as a virtual interface handle.
Definition Types.cpp:357
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.
bool isInsideTimingControl
Whether we are currently converting expressions inside a timing control, such as @(posedge clk).
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)
Value convertAssertionExpression(const slang::ast::AssertionExpr &expr, Location loc)
LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl)
std::optional< std::pair< const slang::ast::InstanceSymbol *, mlir::StringAttr > > buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr)
Build a composite key for hierValueSymbols from a hierarchical value expression.
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.
unsigned nextMonitorId
The next monitor ID to allocate. ID 0 is reserved for "no monitor active".
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.
FailureOr< Value > convertSampledValueCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value, Type originalType, Value clockVal)
Convert sampled value system function calls with a single argument.
FailureOr< moore::UnpackedStructType > convertVirtualInterfaceType(const slang::ast::VirtualInterfaceType &type, Location loc)
Convert a Slang virtual interface type into the Moore type used to represent virtual interface handle...
Definition Types.cpp:238
SmallVector< Value > lvalueStack
A stack of assignment left-hand side values.
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 a single signal flattened from an interface port.
const slang::ast::InterfacePortSymbol * origin
the origin interface port symbol this was flattened from.
const slang::ast::Symbol * modportPortSym
For modport-typed iface ports, the ModportPortSymbol this was flattened from.
const slang::ast::Symbol * bodySym
the interface body member (VariableSymbol , NetSymbol)
std::optional< unsigned > outputIdx
Slot index in the module signature; see PortLowering::outputIdx.
const slang::ast::InstanceSymbol * ifaceInstance
The connected interface instance backing this port (if any).
SmallVector< const slang::ast::ValueSymbol *, 4 > capturedSymbols
The AST symbols captured by this function, determined by the capture analysis pre-pass.
FunctionLowering(mlir::FunctionOpInterface op)
slang::ast::ArgumentDirection direction
llvm::SmallVector< std::pair< const slang::ast::ValueSymbol *, const slang::ast::InstanceBodySymbol * >, 2 > valueSyms
The symbols this path resolves to, each paired with the elaborated instance body it was observed in.
Lowering information for an expanded interface instance.
DenseMap< const slang::ast::Symbol *, Value > expandedMembers
DenseMap< StringAttr, Value > expandedMembersByName
ImportVerilog Elaboration Phases for Hierarchical Names.
bool operator==(const LocationKey &) const =default
static LocationKey get(const slang::SourceLocation &loc, const slang::SourceManager &mgr)
std::strong_ordering operator<=>(const LocationKey &) const =default
Information about a loops continuation and exit blocks relevant while lowering the loop's body statem...
Block * breakBlock
The block to jump to from a break statement.
Block * continueBlock
The block to jump to from a continue statement.
DenseMap< const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol * > portsBySyntaxNode
SmallVector< FlattenedIfacePort > ifacePorts
unsigned numExplicitOutputs
Number of explicit-port slots per direction.
std::optional< unsigned > outputIdx
Slot index in the module signature.
const slang::ast::PortSymbol & ast
Cached lowering information for representing SystemVerilog virtual interface handles as Moore types (...
A mapping entry for resolving Slang virtual interface member accesses.
StringAttr fieldName
The name of the field in the lowered virtual interface handle struct that should be accessed for this...