CIRCT 23.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/text/SourceManager.h"
24#include "llvm/ADT/ScopedHashTable.h"
25#include "llvm/Support/Debug.h"
26#include <map>
27#include <queue>
28
29#define DEBUG_TYPE "import-verilog"
30
31namespace circt {
32namespace ImportVerilog {
33
34using moore::Domain;
35
36/// Get the slang canonical body for the given `instance`, if there is one.
37/// If there isn't one, fall back to the normal body.
38inline const slang::ast::InstanceBodySymbol *
39getCanonicalBody(const slang::ast::InstanceSymbol &inst) {
40 const slang::ast::InstanceBodySymbol *body = inst.getCanonicalBody();
41 return body == nullptr ? &inst.body : body;
42}
43
44/// Port lowering information.
46 const slang::ast::PortSymbol &ast;
47 Location loc;
48 BlockArgument arg;
49};
50
51/// Lowering information for a single signal flattened from an interface port.
53 StringAttr name;
55 mlir::Type type;
56 Location loc;
57 BlockArgument arg;
58 /// the origin interface port symbol this was flattened from.
59 const slang::ast::InterfacePortSymbol *origin;
60 /// the interface body member (VariableSymbol , NetSymbol)
61 const slang::ast::Symbol *bodySym;
62 /// The connected interface instance backing this port (if any). This enables
63 /// materializing virtual interface handles from interface ports.
64 const slang::ast::InstanceSymbol *ifaceInstance = nullptr;
65 /// For modport-typed iface ports, the ModportPortSymbol this was flattened
66 /// from. Slang resolves in-body accesses like `bus.member` to a
67 /// `HierarchicalValueExpression` whose symbol is the `ModportPortSymbol`,
68 /// not the underlying interface body variable, so we register both keys in
69 /// `valueSymbols` to make the lookup find this port's `BlockArgument`.
70 const slang::ast::Symbol *modportPortSym = nullptr;
71};
72
73/// Lowering information for an expanded interface instance. Maps each interface
74/// body member to its expanded SSA value (moore.variable or moore.net).
76 DenseMap<const slang::ast::Symbol *, Value> expandedMembers;
77 DenseMap<StringAttr, Value> expandedMembersByName;
78};
79
80/// Cached lowering information for representing SystemVerilog `virtual
81/// interface` handles as Moore types (a struct of references to interface
82/// members).
84 moore::UnpackedStructType type;
85 SmallVector<StringAttr, 8> fieldNames;
86};
87
88/// A mapping entry for resolving Slang virtual interface member accesses.
89///
90/// Slang may resolve `vif.member` expressions (where `vif` has a
91/// `VirtualInterfaceType`) directly to a `NamedValueExpression` for `member`.
92/// This table records which virtual interface base symbol that member access is
93/// rooted in, so ImportVerilog can materialize the appropriate Moore IR.
95 const slang::ast::ValueSymbol *base = nullptr;
96 /// The name of the field in the lowered virtual interface handle struct that
97 /// should be accessed for this member.
98 StringAttr fieldName;
99};
100
101/// Module lowering information.
103 moore::SVModuleOp op;
104 SmallVector<PortLowering> ports;
105 SmallVector<FlattenedIfacePort> ifacePorts;
106 DenseMap<const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol *>
108};
109
110/// Function lowering information. The `op` field holds either a `func::FuncOp`
111/// (for SystemVerilog functions), a `moore::CoroutineOp` (for tasks), or a
112/// `moore::DPIFuncOp` (for DPI-imported functions), all accessed through the
113/// `FunctionOpInterface`.
115 mlir::FunctionOpInterface op;
116
117 /// The AST symbols captured by this function, determined by the capture
118 /// analysis pre-pass. These are added as extra parameters to the function
119 /// during declaration.
120 SmallVector<const slang::ast::ValueSymbol *, 4> capturedSymbols;
121
122 explicit FunctionLowering(mlir::FunctionOpInterface op) : op(op) {}
123};
124
125// Class lowering information.
127 circt::moore::ClassDeclOp op;
128 bool methodsFinalized = false;
129};
130
131/// Information about a loops continuation and exit blocks relevant while
132/// lowering the loop's body statements.
133struct LoopFrame {
134 /// The block to jump to from a `continue` statement.
136 /// The block to jump to from a `break` statement.
138};
139
140/// Hierarchical path information.
141/// The "hierName" means a different hierarchical name at different module
142/// levels.
143/// The "idx" means where the current hierarchical name is on the portlists.
144/// The "direction" means hierarchical names whether downward(In) or
145/// upward(Out).
147 mlir::StringAttr hierName;
148 std::optional<unsigned int> idx;
149 slang::ast::ArgumentDirection direction;
150
151 /// The value symbols associated with this hierarchical path. Multiple
152 /// symbols may be present when different instances resolve the same
153 /// logical variable to different elaborated symbol objects (e.g., due to
154 /// Slang's per-instance elaboration of shared module bodies).
155 llvm::SmallVector<const slang::ast::ValueSymbol *, 2> valueSyms;
156};
157
158/// ImportVerilog Elaboration Phases for Hierarchical Names
159///
160/// Hierarchical name resolution is performed in four distinct phases:
161///
162/// 1. Collection: The `traverseInstanceBody` pass walks the Slang AST to
163/// identify all hierarchical references (e.g., `Top.sub.var`). It records
164/// these in `hierPaths` mapped by module body.
165///
166/// 2. Port Generation: In `convertModuleHeader`, we inspect `hierPaths` for
167/// the module and add corresponding input/output ports to the generated
168/// `moore.module` to allow cross-module communication.
169///
170/// 3. Wiring: In `Structure.cpp` during instance creation, we look up the
171/// canonical module body's `hierPaths` to determine which hierarchical
172/// values need to be passed as inputs or captured as outputs from the
173/// instance.
174///
175/// 4. Resolution: In `Expressions.cpp`, visitors for rvalues and lvalues
176/// resolve hierarchical names by first checking the instance-aware
177/// `hierValueSymbols` map (for cross-instance references) and falling back
178/// to standard scoped lookups.
179
180// A slang::SourceLocation for deterministic comparisons. Comparisons use the
181// buffer's sortKey rather than bufferId.
183 uint64_t sortKey;
184 size_t offset;
185
186 static LocationKey get(const slang::SourceLocation &loc,
187 const slang::SourceManager &mgr) {
188 return {
189 mgr.getSortKey(loc.buffer()),
190 loc.offset(),
191 };
192 }
193
194 std::strong_ordering operator<=>(const LocationKey &) const = default;
195 bool operator==(const LocationKey &) const = default;
196};
197
198/// A helper class to facilitate the conversion from a Slang AST to MLIR
199/// operations. Keeps track of the destination MLIR module, builders, and
200/// various worklists and utilities needed for conversion.
201struct Context {
203 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
204 const slang::SourceManager &sourceManager)
207 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
209 Context(const Context &) = delete;
210
211 /// Return the MLIR context.
212 MLIRContext *getContext() { return intoModuleOp.getContext(); }
213
214 /// Convert a slang `SourceLocation` into an MLIR `Location`.
215 Location convertLocation(slang::SourceLocation loc);
216 /// Convert a slang `SourceRange` into an MLIR `Location`.
217 Location convertLocation(slang::SourceRange range);
218
219 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
220 /// provided location for error reporting, or tries to guess one from the
221 /// given type. Types tend to have unreliable location information, so it's
222 /// generally a good idea to pass in a location.
223 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
224 Type convertType(const slang::ast::DeclaredType &type);
225
226 /// Convert hierarchy and structure AST nodes to MLIR ops.
227 LogicalResult convertCompilation();
228 /// Convert a module and its ports to an empty module op in the IR. Also adds
229 /// the op to the worklist of module bodies to be lowered. This acts like a
230 /// module "declaration", allowing instances to already refer to a module even
231 /// before its body has been lowered.
232 /// `module` must be the canonical module body if there is one.
233 ModuleLowering *
234 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
235 /// Convert a module's body to the corresponding IR ops. The module op must
236 /// have already been created earlier through a `convertModuleHeader` call.
237 /// `module` must be the canonical module body if there is one.
238 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
239 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
240 FunctionLowering *
241 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
242 LogicalResult defineFunction(const slang::ast::SubroutineSymbol &subroutine);
243 LogicalResult
244 convertPrimitiveInstance(const slang::ast::PrimitiveInstanceSymbol &prim);
245 ClassLowering *declareClass(const slang::ast::ClassType &cls);
246 LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl);
247 LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl);
248 LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var);
249
250 /// Convert a Slang virtual interface type into the Moore type used to
251 /// represent virtual interface handles. Populates internal caches so that
252 /// interface instance references can be materialized consistently.
253 FailureOr<moore::UnpackedStructType>
254 convertVirtualInterfaceType(const slang::ast::VirtualInterfaceType &type,
255 Location loc);
256
257 /// Materialize a Moore value representing a concrete interface instance as a
258 /// virtual interface handle. This only succeeds for the Slang
259 /// `VirtualInterfaceType` wrappers that refer to a real interface instance
260 /// (`isRealIface`).
261 FailureOr<Value>
262 materializeVirtualInterfaceValue(const slang::ast::VirtualInterfaceType &type,
263 Location loc);
264
265 /// Register the interface members of a virtual interface base symbol for use
266 /// in later expression conversion.
267 LogicalResult
268 registerVirtualInterfaceMembers(const slang::ast::ValueSymbol &base,
269 const slang::ast::VirtualInterfaceType &type,
270 Location loc);
271
272 /// Checks whether one class (actualTy) is derived from another class
273 /// (baseTy). True if it's a subclass, false otherwise.
274 bool isClassDerivedFrom(const moore::ClassHandleType &actualTy,
275 const moore::ClassHandleType &baseTy);
276
277 /// Tries to find the closest base class of actualTy that carries a property
278 /// with name fieldName. The location is used for error reporting.
279 moore::ClassHandleType
280 getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
281 StringRef fieldName, Location loc);
282
283 Value getImplicitThisRef() const {
284 return currentThisRef; // block arg added in declareFunction
285 }
286
287 /// Maps assertion system calls to their corresponding clocks
288 DenseMap<const slang::ast::CallExpression *,
289 const slang::ast::TimingControl *>
291
292 /// Generates a map from assertions to clocks using Slang's analysis
294
295 Value getIndexedQueue() const { return currentQueue; }
296
297 // Convert a statement AST node to MLIR ops.
298 LogicalResult convertStatement(const slang::ast::Statement &stmt);
299
300 // Convert an expression AST node to MLIR ops.
301 Value convertRvalueExpression(const slang::ast::Expression &expr,
302 Type requiredType = {});
303 Value convertLvalueExpression(const slang::ast::Expression &expr);
304
305 // Convert an assertion expression AST node to MLIR ops.
306 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
307 Location loc);
308
309 // Convert an assertion expression AST node to MLIR ops.
311 const slang::ast::CallExpression &expr,
312 const slang::ast::CallExpression::SystemCallInfo &info, Location loc);
313
314 // Traverse the whole AST to collect hierarchical names.
315 void traverseInstanceBody(const slang::ast::InstanceSymbol &symbol);
316
317 /// Build a composite key for hierValueSymbols from a hierarchical value
318 /// expression. Returns {firstInstanceSymbol, dottedHierName} or std::nullopt
319 /// if the expression has no instance path.
320 std::optional<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>>
321 buildHierValueKey(const slang::ast::HierarchicalValueExpression &expr);
322
323 // Convert timing controls into a corresponding set of ops that delay
324 // execution of the current block. Produces an error if the implicit event
325 // control `@*` or `@(*)` is used.
326 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl);
327 // Convert timing controls into a corresponding set of ops that delay
328 // execution of the current block. Then converts the given statement, taking
329 // note of the rvalues it reads and adding them to a wait op in case an
330 // implicit event control `@*` or `@(*)` is used.
331 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
332 const slang::ast::Statement &stmt);
333
334 /// Helper function to convert a value to a MLIR I1 value.
335 Value convertToI1(Value value);
336
337 // Convert a slang timing control for LTL
338 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
339 const Value &seqOrPro);
340
341 LogicalResult
342 convertNInputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
343
344 LogicalResult
345 convertNOutputPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
346
347 LogicalResult
348 convertFixedPrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
349
350 LogicalResult
351 convertPullGatePrimitive(const slang::ast::PrimitiveInstanceSymbol &prim);
352
353 /// Helper function to convert a value to its "truthy" boolean value.
354 Value convertToBool(Value value);
355
356 /// Helper function to convert a value to its "truthy" boolean value and
357 /// convert it to the given domain.
358 Value convertToBool(Value value, Domain domain);
359
360 /// Helper function to convert a value to its simple bit vector
361 /// representation, if it has one. Otherwise returns null. Also returns null
362 /// if the given value is null.
363 Value convertToSimpleBitVector(Value value);
364
365 /// Helper function to insert the necessary operations to cast a value from
366 /// one type to another. If `fallible` is true, conversion failures are
367 /// reported by returning a null value without emitting diagnostics.
368 Value materializeConversion(Type type, Value value, bool isSigned,
369 Location loc, bool fallible = false);
370
371 /// Helper function to materialize an `SVInt` as an SSA value.
372 Value materializeSVInt(const slang::SVInt &svint,
373 const slang::ast::Type &type, Location loc);
374
375 /// Helper function to materialize a real value as an SSA value.
376 Value materializeSVReal(const slang::ConstantValue &svreal,
377 const slang::ast::Type &type, Location loc);
378
379 /// Helper function to materialize a string as an SSA value.
380 Value materializeString(const slang::ConstantValue &string,
381 const slang::ast::Type &astType, Location loc);
382
383 /// Helper function to materialize an unpacked array of `SVInt`s as an SSA
384 /// value.
386 const slang::ConstantValue &constant,
387 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc);
388
389 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
390 /// null if the constant cannot be materialized.
391 Value materializeConstant(const slang::ConstantValue &constant,
392 const slang::ast::Type &type, Location loc);
393
394 /// Convert a list of string literal arguments with formatting specifiers and
395 /// arguments to be interpolated into a `!moore.format_string` value. Returns
396 /// failure if an error occurs. Returns a null value if the formatted string
397 /// is trivially empty. Otherwise returns the formatted string.
398 FailureOr<Value> convertFormatString(
399 std::span<const slang::ast::Expression *const> arguments, Location loc,
400 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
401 bool appendNewline = false);
402
403 /// Convert system function calls. Returns a null `Value` on failure after
404 /// emitting an error.
405 Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine,
406 Location loc,
407 std::span<const slang::ast::Expression *const> args);
408
409 /// Convert system function calls within properties and assertion with a
410 /// single argument.
411 FailureOr<Value> convertAssertionSystemCallArity1(
412 const slang::ast::SystemSubroutine &subroutine, Location loc, Value value,
413 Type originalType, Value clockVal);
414
415 /// Evaluate the constant value of an expression.
416 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
417
418 /// Convert the inside/set-membership expression.
419 Value convertInsideCheck(Value insideLhs, Location loc,
420 const slang::ast::Expression &expr);
421
423 slang::ast::Compilation &compilation;
424 mlir::ModuleOp intoModuleOp;
425 const slang::SourceManager &sourceManager;
426
427 /// The builder used to create IR operations.
428 OpBuilder builder;
429 /// A symbol table of the MLIR module we are emitting into.
430 SymbolTable symbolTable;
431
432 /// The top-level operations ordered by their Slang source location. This is
433 /// used to produce IR that follows the source file order.
434 std::map<LocationKey, Operation *> orderedRootOps;
435
436 /// How we have lowered modules to MLIR.
437 /// The keys must be the slang canonical module bodies where they exist.
438 DenseMap<const slang::ast::InstanceBodySymbol *,
439 std::unique_ptr<ModuleLowering>>
441
442 /// Expanded interface instances, keyed by the InstanceSymbol pointer.
443 /// Each entry maps body members to their expanded SSA values. Scoped
444 /// per-module so entries are cleaned up when a module's conversion ends.
446 llvm::ScopedHashTable<const slang::ast::InstanceSymbol *,
448 using InterfaceInstanceScope = InterfaceInstances::ScopeTy;
450 /// Owning storage for InterfaceLowering objects
451 /// because ScopedHashTable stores values by copy.
452 SmallVector<std::unique_ptr<InterfaceLowering>> interfaceInstanceStorage;
453
454 /// Cached virtual interface layouts (type + field order).
455 DenseMap<const slang::ast::InstanceBodySymbol *, VirtualInterfaceLowering>
457 DenseMap<const slang::ast::ModportSymbol *, VirtualInterfaceLowering>
459 /// A list of modules for which the header has been created, but the body has
460 /// not been converted yet.
461 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
462
463 /// A list of functions for which the declaration has been created, but the
464 /// body has not been defined yet.
465 std::queue<const slang::ast::SubroutineSymbol *> functionWorklist;
466
467 /// Functions that have already been converted.
468 DenseMap<const slang::ast::SubroutineSymbol *,
469 std::unique_ptr<FunctionLowering>>
471
472 /// Classes that have already been converted.
473 DenseMap<const slang::ast::ClassType *, std::unique_ptr<ClassLowering>>
475
476 /// A table of defined values, such as variables, that may be referred to by
477 /// name in expressions. The expressions use this table to lookup the MLIR
478 /// value that was created for a given declaration in the Slang AST node.
480 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
481 using ValueSymbolScope = ValueSymbols::ScopeTy;
483
484 /// A table mapping symbols for interface members accessed through a virtual
485 /// interface to the virtual interface base value symbol.
487 llvm::ScopedHashTable<const slang::ast::ValueSymbol *,
489 using VirtualInterfaceMemberScope = VirtualInterfaceMembers::ScopeTy;
491
492 /// A table of defined global variables that may be referred to by name in
493 /// expressions.
494 DenseMap<const slang::ast::ValueSymbol *, moore::GlobalVariableOp>
496 /// A list of global variables that still need their initializers to be
497 /// converted.
498 SmallVector<const slang::ast::ValueSymbol *> globalVariableWorklist;
499
500 /// Pre-computed capture analysis: maps each function to the set of non-local,
501 /// non-global variables it captures (directly or transitively).
503
504 /// Collect all hierarchical names used for the per module/instance.
505 /// The keys are the slang canonical instance bodies (or the real instance
506 /// if slang's getCanonicalBody() returned null).
507 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
509
510 /// Persistent map for hierarchical value lookups. Keyed by a composite
511 /// of the instance symbol (the specific instance being wired, e.g., p1 or
512 /// p2) and the hierarchical path name (e.g., "child.child_val"). This
513 /// ensures instance-specific resolution even when Slang shares or doesn't
514 /// share instance bodies across multiple instances of the same module.
515 DenseMap<std::pair<const slang::ast::InstanceSymbol *, mlir::StringAttr>,
516 Value>
518
519 /// A stack of assignment left-hand side values. Each assignment will push its
520 /// lowered left-hand side onto this stack before lowering its right-hand
521 /// side. This allows expressions to resolve the opaque
522 /// `LValueReferenceExpression`s in the AST.
523 SmallVector<Value> lvalueStack;
524
525 /// A stack of loop continuation and exit blocks. Each loop will push the
526 /// relevant info onto this stack, lower its loop body statements, and pop the
527 /// info off the stack again. Continue and break statements encountered as
528 /// part of the loop body statements will use this information to branch to
529 /// the correct block.
530 SmallVector<LoopFrame> loopStack;
531
532 /// A listener called for every variable or net being read. This can be used
533 /// to collect all variables read as part of an expression or statement, for
534 /// example to populate the list of observed signals in an implicit event
535 /// control `@*`.
536 std::function<void(moore::ReadOp)> rvalueReadCallback;
537 /// A listener called for every variable or net being assigned. This can be
538 /// used to collect all variables assigned in a task scope.
539 std::function<void(mlir::Operation *)> variableAssignCallback;
540
541 /// Whether we are currently converting expressions inside a timing control,
542 /// such as `@(posedge clk)`. This is used by the implicit event control
543 /// callback to avoid adding reads from explicit event controls to the
544 /// implicit sensitivity list.
546
547 /// The time scale currently in effect.
548 slang::TimeScale timeScale;
549
550 /// Variable to track the value of the current function's implicit `this`
551 /// reference
552 Value currentThisRef = {};
553
554 /// Variable that tracks the queue which we are currently converting the index
555 /// expression for. This is necessary to implement the `$` operator, which
556 /// returns the index of the last element of the queue.
557 Value currentQueue = {};
558
559 /// Ensure that the global variables for `$monitor` state exist. This creates
560 /// the `__monitor_active_id` and `__monitor_enabled` globals on first call.
562
563 /// Process any pending `$monitor` calls and generate the monitoring
564 /// procedures at module level.
565 LogicalResult flushPendingMonitors();
566
567 /// Global variable ops for `$monitor` state management. These are created on
568 /// demand by `ensureMonitorGlobals()`.
569 moore::GlobalVariableOp monitorActiveIdGlobal = nullptr;
570 moore::GlobalVariableOp monitorEnabledGlobal = nullptr;
571
572 /// The next monitor ID to allocate. ID 0 is reserved for "no monitor active".
573 unsigned nextMonitorId = 1;
574
575 /// Information about a pending `$monitor` call that needs to be converted
576 /// after the current module's body has been processed.
578 unsigned id;
579 Location loc;
580 const slang::ast::CallExpression *call;
581 };
582
583 /// Pending `$monitor` calls that need to be converted at module level.
584 SmallVector<PendingMonitor> pendingMonitors;
585
586private:
587 /// Helper function to extract the commonalities in lowering of functions and
588 /// methods
590 declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
591 mlir::StringRef qualifiedName,
592 llvm::SmallVectorImpl<Type> &extraParams);
593};
594
595} // namespace ImportVerilog
596} // namespace circt
597#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
const slang::ast::InstanceBodySymbol * getCanonicalBody(const slang::ast::InstanceSymbol &inst)
Get the slang canonical body for the given instance, if there is one.
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 ...
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.
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...
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.
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...
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 convertAssertionCallExpression(const slang::ast::CallExpression &expr, const slang::ast::CallExpression::SystemCallInfo &info, Location loc)
FailureOr< Value > convertAssertionSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value, Type originalType, Value clockVal)
Convert system function calls within properties and assertion with a single argument.
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
Value convertSystemCall(const slang::ast::SystemSubroutine &subroutine, Location loc, std::span< const slang::ast::Expression *const > args)
Convert system function calls.
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.
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.
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 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.
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.
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)
void populateAssertionClocks()
Generates a map from assertions to clocks using Slang's analysis.
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.
DenseMap< const slang::ast::CallExpression *, const slang::ast::TimingControl * > assertionCallClocks
Maps assertion system calls to their corresponding clocks.
InterfaceInstances::ScopeTy InterfaceInstanceScope
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< 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)
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< const slang::ast::ValueSymbol *, 2 > valueSyms
The value symbols associated with this hierarchical path.
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
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...