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