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
19#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
20#include "mlir/Dialect/Func/IR/FuncOps.h"
21#include "slang/ast/ASTVisitor.h"
22#include "llvm/ADT/ScopedHashTable.h"
23#include "llvm/Support/Debug.h"
24#include <map>
25#include <queue>
26
27#define DEBUG_TYPE "import-verilog"
28
29namespace circt {
30namespace ImportVerilog {
31
32using moore::Domain;
33
34/// Port lowering information.
36 const slang::ast::PortSymbol &ast;
37 Location loc;
38 BlockArgument arg;
39};
40
41/// Module lowering information.
43 moore::SVModuleOp op;
44 SmallVector<PortLowering> ports;
45 DenseMap<const slang::syntax::SyntaxNode *, const slang::ast::PortSymbol *>
47};
48
49/// Function lowering information.
51 mlir::func::FuncOp op;
52 llvm::SmallVector<Value, 4> captures;
53 llvm::DenseMap<Value, unsigned> captureIndex;
54 bool capturesFinalized = false;
55 bool isConverting = false;
56};
57
58// Class lowering information.
60 circt::moore::ClassDeclOp op;
61 bool methodsFinalized = false;
62};
63
64/// Information about a loops continuation and exit blocks relevant while
65/// lowering the loop's body statements.
66struct LoopFrame {
67 /// The block to jump to from a `continue` statement.
69 /// The block to jump to from a `break` statement.
70 Block *breakBlock;
71};
72
73/// Hierarchical path information.
74/// The "hierName" means a different hierarchical name at different module
75/// levels.
76/// The "idx" means where the current hierarchical name is on the portlists.
77/// The "direction" means hierarchical names whether downward(In) or
78/// upward(Out).
80 mlir::StringAttr hierName;
81 std::optional<unsigned int> idx;
82 slang::ast::ArgumentDirection direction;
83 const slang::ast::ValueSymbol *valueSym;
84};
85
86/// A helper class to facilitate the conversion from a Slang AST to MLIR
87/// operations. Keeps track of the destination MLIR module, builders, and
88/// various worklists and utilities needed for conversion.
89struct Context {
91 slang::ast::Compilation &compilation, mlir::ModuleOp intoModuleOp,
92 const slang::SourceManager &sourceManager)
95 builder(OpBuilder::atBlockEnd(intoModuleOp.getBody())),
97 Context(const Context &) = delete;
98
99 /// Return the MLIR context.
100 MLIRContext *getContext() { return intoModuleOp.getContext(); }
101
102 /// Convert a slang `SourceLocation` into an MLIR `Location`.
103 Location convertLocation(slang::SourceLocation loc);
104 /// Convert a slang `SourceRange` into an MLIR `Location`.
105 Location convertLocation(slang::SourceRange range);
106
107 /// Convert a slang type into an MLIR type. Returns null on failure. Uses the
108 /// provided location for error reporting, or tries to guess one from the
109 /// given type. Types tend to have unreliable location information, so it's
110 /// generally a good idea to pass in a location.
111 Type convertType(const slang::ast::Type &type, LocationAttr loc = {});
112 Type convertType(const slang::ast::DeclaredType &type);
113
114 /// Convert hierarchy and structure AST nodes to MLIR ops.
115 LogicalResult convertCompilation();
116 ModuleLowering *
117 convertModuleHeader(const slang::ast::InstanceBodySymbol *module);
118 LogicalResult convertModuleBody(const slang::ast::InstanceBodySymbol *module);
119 LogicalResult convertPackage(const slang::ast::PackageSymbol &package);
120 FunctionLowering *
121 declareFunction(const slang::ast::SubroutineSymbol &subroutine);
122 LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine);
123 LogicalResult finalizeFunctionBodyCaptures(FunctionLowering &lowering);
124 ClassLowering *declareClass(const slang::ast::ClassType &cls);
125 LogicalResult buildClassProperties(const slang::ast::ClassType &classdecl);
126 LogicalResult materializeClassMethods(const slang::ast::ClassType &classdecl);
127 LogicalResult convertGlobalVariable(const slang::ast::VariableSymbol &var);
128
129 /// Checks whether one class (actualTy) is derived from another class
130 /// (baseTy). True if it's a subclass, false otherwise.
131 bool isClassDerivedFrom(const moore::ClassHandleType &actualTy,
132 const moore::ClassHandleType &baseTy);
133
134 /// Tries to find the closest base class of actualTy that carries a property
135 /// with name fieldName. The location is used for error reporting.
136 moore::ClassHandleType
137 getAncestorClassWithProperty(const moore::ClassHandleType &actualTy,
138 StringRef fieldName, Location loc);
139
140 Value getImplicitThisRef() const {
141 return currentThisRef; // block arg added in declareFunction
142 }
143 // Convert a statement AST node to MLIR ops.
144 LogicalResult convertStatement(const slang::ast::Statement &stmt);
145
146 // Convert an expression AST node to MLIR ops.
147 Value convertRvalueExpression(const slang::ast::Expression &expr,
148 Type requiredType = {});
149 Value convertLvalueExpression(const slang::ast::Expression &expr);
150
151 // Convert an assertion expression AST node to MLIR ops.
152 Value convertAssertionExpression(const slang::ast::AssertionExpr &expr,
153 Location loc);
154
155 // Convert an assertion expression AST node to MLIR ops.
157 const slang::ast::CallExpression &expr,
158 const slang::ast::CallExpression::SystemCallInfo &info, Location loc);
159
160 // Traverse the whole AST to collect hierarchical names.
161 LogicalResult
162 collectHierarchicalValues(const slang::ast::Expression &expr,
163 const slang::ast::Symbol &outermostModule);
164 LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol);
165
166 // Convert timing controls into a corresponding set of ops that delay
167 // execution of the current block. Produces an error if the implicit event
168 // control `@*` or `@(*)` is used.
169 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl);
170 // Convert timing controls into a corresponding set of ops that delay
171 // execution of the current block. Then converts the given statement, taking
172 // note of the rvalues it reads and adding them to a wait op in case an
173 // implicit event control `@*` or `@(*)` is used.
174 LogicalResult convertTimingControl(const slang::ast::TimingControl &ctrl,
175 const slang::ast::Statement &stmt);
176
177 /// Helper function to convert a value to a MLIR I1 value.
178 Value convertToI1(Value value);
179
180 // Convert a slang timing control for LTL
181 Value convertLTLTimingControl(const slang::ast::TimingControl &ctrl,
182 const Value &seqOrPro);
183
184 /// Helper function to convert a value to its "truthy" boolean value.
185 Value convertToBool(Value value);
186
187 /// Helper function to convert a value to its "truthy" boolean value and
188 /// convert it to the given domain.
189 Value convertToBool(Value value, Domain domain);
190
191 /// Helper function to convert a value to its simple bit vector
192 /// representation, if it has one. Otherwise returns null. Also returns null
193 /// if the given value is null.
194 Value convertToSimpleBitVector(Value value);
195
196 /// Helper function to insert the necessary operations to cast a value from
197 /// one type to another.
198 Value materializeConversion(Type type, Value value, bool isSigned,
199 Location loc);
200
201 /// Helper function to materialize an `SVInt` as an SSA value.
202 Value materializeSVInt(const slang::SVInt &svint,
203 const slang::ast::Type &type, Location loc);
204
205 /// Helper function to materialize a real value as an SSA value.
206 Value materializeSVReal(const slang::ConstantValue &svreal,
207 const slang::ast::Type &type, Location loc);
208
209 /// Helper function to materialize a string as an SSA value.
210 Value materializeString(const slang::ConstantValue &string,
211 const slang::ast::Type &astType, Location loc);
212
213 /// Helper function to materialize an unpacked array of `SVInt`s as an SSA
214 /// value.
216 const slang::ConstantValue &constant,
217 const slang::ast::FixedSizeUnpackedArrayType &astType, Location loc);
218
219 /// Helper function to materialize a `ConstantValue` as an SSA value. Returns
220 /// null if the constant cannot be materialized.
221 Value materializeConstant(const slang::ConstantValue &constant,
222 const slang::ast::Type &type, Location loc);
223
224 /// Convert a list of string literal arguments with formatting specifiers and
225 /// arguments to be interpolated into a `!moore.format_string` value. Returns
226 /// failure if an error occurs. Returns a null value if the formatted string
227 /// is trivially empty. Otherwise returns the formatted string.
228 FailureOr<Value> convertFormatString(
229 std::span<const slang::ast::Expression *const> arguments, Location loc,
230 moore::IntFormat defaultFormat = moore::IntFormat::Decimal,
231 bool appendNewline = false);
232
233 /// Convert system function calls only have arity-0.
234 FailureOr<Value>
235 convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine,
236 Location loc);
237
238 /// Convert system function calls only have arity-1.
239 FailureOr<Value>
240 convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine,
241 Location loc, Value value);
242
243 /// Convert system function calls with arity-2.
244 FailureOr<Value>
245 convertSystemCallArity2(const slang::ast::SystemSubroutine &subroutine,
246 Location loc, Value value1, Value value2);
247
248 /// Convert system function calls within properties and assertion with a
249 /// single argument.
250 FailureOr<Value> convertAssertionSystemCallArity1(
251 const slang::ast::SystemSubroutine &subroutine, Location loc, Value value,
252 Type originalType);
253
254 /// Evaluate the constant value of an expression.
255 slang::ConstantValue evaluateConstant(const slang::ast::Expression &expr);
256
258 slang::ast::Compilation &compilation;
259 mlir::ModuleOp intoModuleOp;
260 const slang::SourceManager &sourceManager;
261
262 /// The builder used to create IR operations.
263 OpBuilder builder;
264 /// A symbol table of the MLIR module we are emitting into.
265 SymbolTable symbolTable;
266
267 /// The top-level operations ordered by their Slang source location. This is
268 /// used to produce IR that follows the source file order.
269 std::map<slang::SourceLocation, Operation *> orderedRootOps;
270
271 /// How we have lowered modules to MLIR.
272 DenseMap<const slang::ast::InstanceBodySymbol *,
273 std::unique_ptr<ModuleLowering>>
275 /// A list of modules for which the header has been created, but the body has
276 /// not been converted yet.
277 std::queue<const slang::ast::InstanceBodySymbol *> moduleWorklist;
278
279 /// Functions that have already been converted.
280 DenseMap<const slang::ast::SubroutineSymbol *,
281 std::unique_ptr<FunctionLowering>>
283
284 /// Classes that have already been converted.
285 DenseMap<const slang::ast::ClassType *, std::unique_ptr<ClassLowering>>
287
288 /// A table of defined values, such as variables, that may be referred to by
289 /// name in expressions. The expressions use this table to lookup the MLIR
290 /// value that was created for a given declaration in the Slang AST node.
292 llvm::ScopedHashTable<const slang::ast::ValueSymbol *, Value>;
293 using ValueSymbolScope = ValueSymbols::ScopeTy;
295
296 /// A table of defined global variables that may be referred to by name in
297 /// expressions.
298 DenseMap<const slang::ast::ValueSymbol *, moore::GlobalVariableOp>
300 /// A list of global variables that still need their initializers to be
301 /// converted.
302 SmallVector<const slang::ast::ValueSymbol *> globalVariableWorklist;
303
304 /// Collect all hierarchical names used for the per module/instance.
305 DenseMap<const slang::ast::InstanceBodySymbol *, SmallVector<HierPathInfo>>
307
308 /// It's used to collect the repeat hierarchical names on the same path.
309 /// Such as `Top.sub.a` and `sub.a`, they are equivalent. The variable "a"
310 /// will be added to the port list. But we only record once. If we don't do
311 /// that. We will view the strange IR, such as `module @Sub(out y, out y)`;
312 DenseSet<StringAttr> sameHierPaths;
313
314 /// A stack of assignment left-hand side values. Each assignment will push its
315 /// lowered left-hand side onto this stack before lowering its right-hand
316 /// side. This allows expressions to resolve the opaque
317 /// `LValueReferenceExpression`s in the AST.
318 SmallVector<Value> lvalueStack;
319
320 /// A stack of loop continuation and exit blocks. Each loop will push the
321 /// relevant info onto this stack, lower its loop body statements, and pop the
322 /// info off the stack again. Continue and break statements encountered as
323 /// part of the loop body statements will use this information to branch to
324 /// the correct block.
325 SmallVector<LoopFrame> loopStack;
326
327 /// A listener called for every variable or net being read. This can be used
328 /// to collect all variables read as part of an expression or statement, for
329 /// example to populate the list of observed signals in an implicit event
330 /// control `@*`.
331 std::function<void(moore::ReadOp)> rvalueReadCallback;
332 /// A listener called for every variable or net being assigned. This can be
333 /// used to collect all variables assigned in a task scope.
334 std::function<void(mlir::Operation *)> variableAssignCallback;
335
336 /// The time scale currently in effect.
337 slang::TimeScale timeScale;
338
339 /// Variable to track the value of the current function's implicit `this`
340 /// reference
341 Value currentThisRef = {};
342
343private:
344 /// Helper function to extract the commonalities in lowering of functions and
345 /// methods
347 declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine,
348 mlir::StringRef qualifiedName,
349 llvm::SmallVectorImpl<Type> &extraParams);
350};
351
352} // namespace ImportVerilog
353} // namespace circt
354#endif // CONVERSION_IMPORTVERILOG_IMPORTVERILOGINTERNALS_H
Domain
The number of values each bit of a type can assume.
Definition MooreTypes.h:49
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Options that control how Verilog input files are parsed and processed.
A helper class to facilitate the conversion from a Slang AST to MLIR operations.
LogicalResult convertFunction(const slang::ast::SubroutineSymbol &subroutine)
Convert a function.
Value convertToI1(Value value)
Helper function to convert a value to a MLIR I1 value.
Value materializeConversion(Type type, Value value, bool isSigned, Location loc)
Helper function to insert the necessary operations to cast a value from one type to another.
FunctionLowering * declareCallableImpl(const slang::ast::SubroutineSymbol &subroutine, mlir::StringRef qualifiedName, llvm::SmallVectorImpl< Type > &extraParams)
Helper function to extract the commonalities in lowering of functions and methods.
ModuleLowering * convertModuleHeader(const slang::ast::InstanceBodySymbol *module)
Convert a module and its ports to an empty module op in the IR.
Value convertLvalueExpression(const slang::ast::Expression &expr)
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.
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)
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)
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
std::map< slang::SourceLocation, Operation * > orderedRootOps
The top-level operations ordered by their Slang source location.
Type convertType(const slang::ast::Type &type, LocationAttr loc={})
Convert a slang type into an MLIR type.
Definition Types.cpp:206
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.
LogicalResult finalizeFunctionBodyCaptures(FunctionLowering &lowering)
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)
Value convertToBool(Value value)
Helper function to convert a value to its "truthy" boolean value.
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.
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={})
FailureOr< Value > convertSystemCallArity0(const slang::ast::SystemSubroutine &subroutine, Location loc)
Convert system function calls only have arity-0.
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.
LogicalResult traverseInstanceBody(const slang::ast::Symbol &symbol)
Value materializeString(const slang::ConstantValue &string, const slang::ast::Type &astType, Location loc)
Helper function to materialize a string as an SSA value.
Value currentThisRef
Variable to track the value of the current function's implicit this reference.
FailureOr< Value > convertSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value)
Convert system function calls only have arity-1.
const slang::SourceManager & sourceManager
DenseSet< StringAttr > sameHierPaths
It's used to collect the repeat hierarchical names on the same path.
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 collectHierarchicalValues(const slang::ast::Expression &expr, const slang::ast::Symbol &outermostModule)
Value convertAssertionExpression(const slang::ast::AssertionExpr &expr, Location loc)
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.
FailureOr< Value > convertAssertionSystemCallArity1(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value, Type originalType)
Convert system function calls within properties and assertion with a single argument.
LogicalResult convertStatement(const slang::ast::Statement &stmt)
FailureOr< Value > convertSystemCallArity2(const slang::ast::SystemSubroutine &subroutine, Location loc, Value value1, Value value2)
Convert system function calls with arity-2.
SmallVector< const slang::ast::ValueSymbol * > globalVariableWorklist
A list of global variables that still need their initializers to be converted.
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.
llvm::DenseMap< Value, unsigned > captureIndex
Hierarchical path information.
slang::ast::ArgumentDirection direction
const slang::ast::ValueSymbol * valueSym
std::optional< unsigned int > idx
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
const slang::ast::PortSymbol & ast