diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index a7e271a6439..27d6ebb280d 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -160,6 +160,9 @@ pub(crate) struct LoweredSvModule { level_lists_lowered: Vec, /// The write streams one flip-flop evaluation may write twice. repeated_ff_writes: Vec, + /// The `inout` ports whose net has its driver in this module or below it, + /// filled in by [`resolve_inout_drivers`]. + inout_driven_inside: HashSet, } #[derive(Clone)] @@ -570,6 +573,49 @@ fn analyze_sources_with_requests( Ok((modules, root_names)) } +/// Record the `inout` ports whose net has its driver in their module or +/// below it. Both sides of an inout port connection form one net (IEEE +/// 1800-2023 23.3.3), so the connection carries the value away from the side +/// that drives it. A net driven on both sides is then reported by +/// [`validate_specialized_instance_net_drivers`]. +fn resolve_inout_drivers( + module_ids: &HashMap, + modules: &mut HashMap, +) { + loop { + let mut driven = Vec::new(); + for (&module_id, module) in modules.iter() { + for port in module.source.ports() { + if port.direction() != sv::ir::PortDirection::Inout + || module.inout_driven_inside.contains(port.name()) + { + continue; + } + if !local_driver_ranges( + &module.source, + port.name(), + &module.constants, + &module.parameter_types, + ) + .is_empty() + || !child_output_driver_ranges(module, port.name(), module_ids, modules) + .is_empty() + { + driven.push((module_id, port.name().to_string())); + } + } + } + if driven.is_empty() { + return; + } + for (module_id, port) in driven { + if let Some(module) = modules.get_mut(&module_id) { + module.inout_driven_inside.insert(port); + } + } + } +} + fn validate_specialized_instance_net_drivers( module_ids: &HashMap, modules: &HashMap, @@ -769,10 +815,13 @@ fn child_output_driver_ranges( for connection in connections { if !child.source.ports().iter().any(|port| { port.name() == connection.formal - && matches!( - port.direction(), - sv::ir::PortDirection::Output | sv::ir::PortDirection::Inout - ) + && match port.direction() { + sv::ir::PortDirection::Output => true, + sv::ir::PortDirection::Inout => { + child.inout_driven_inside.contains(port.name()) + } + _ => false, + } }) { continue; } @@ -1998,6 +2047,7 @@ fn prepare_external_hierarchy_collecting( event_assignments: Vec::new(), level_lists_lowered: Vec::new(), repeated_ff_writes: Vec::new(), + inout_driven_inside: HashSet::default(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -2167,7 +2217,7 @@ fn prepare_external_hierarchy_collecting( } } - let lowered_modules = module_ids + let mut lowered_modules = module_ids .iter() .map(|(key, &module_id)| { if let Some(module) = foreign_specializations.get(key) { @@ -2193,6 +2243,7 @@ fn prepare_external_hierarchy_collecting( )) }) .collect::, FrontendError>>()?; + resolve_inout_drivers(&module_ids, &mut lowered_modules); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let mut modules = HashMap::default(); for (key, &module_id) in &module_ids { @@ -2776,10 +2827,11 @@ fn schedule_sources_collecting( }, )?) }; - let lowered_modules = module_ids + let mut lowered_modules = module_ids .iter() .map(|(key, &module_id)| Ok((module_id, specialize(key, module_id)?))) .collect::, FrontendError>>()?; + resolve_inout_drivers(&module_ids, &mut lowered_modules); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let root = &lowered_modules[&root_id]; if let Some(port) = root @@ -3801,6 +3853,7 @@ fn lower_module_with_overrides( event_assignments, level_lists_lowered, repeated_ff_writes, + inout_driven_inside: HashSet::default(), }) } @@ -5482,9 +5535,6 @@ fn ensure_parent_output_signals( ) -> Result<(), ParserError> { for child_port_id in &child.port_order { let child_var = &child.variables[child_port_id]; - if child_var.kind != VariableKind::Output { - continue; - } let formal = child_var.path.join("."); let Some(connection) = connections .iter() @@ -5492,6 +5542,20 @@ fn ensure_parent_output_signals( else { continue; }; + if child_var.kind == VariableKind::Inout { + check_inout_port_actual( + connection, + parent_variables, + parent_signal_names, + implicit_output_signals, + parent_source, + parent_constants, + parent_parameter_types, + )?; + } + if child_port_direction(child, child_var) != Some(VariableKind::Output) { + continue; + } let Some(actual) = connection .actual_expr .as_ref() @@ -5569,6 +5633,68 @@ fn ensure_parent_output_signals( Ok(()) } +/// Rejects a variable or an expression connected to an `inout` port: only +/// nets may be on either side of one (IEEE 1800-2023 23.3.3.2). An +/// undeclared identifier is an implicit net. +fn check_inout_port_actual( + connection: &LoweredSvPortConnection, + parent_variables: &HashMap, + parent_signal_names: &HashMap, + implicit_nets: &HashSet, + parent_source: &sv::ir::Module, + parent_constants: &HashMap, + parent_parameter_types: &HashMap, +) -> Result<(), ParserError> { + let Some(actual) = connection.actual_expr.as_ref() else { + return Ok(()); + }; + let is_net = |name: &str| { + implicit_nets.contains(name) + || parent_source + .signals() + .iter() + .any(|signal| signal.name() == name && signal.is_net()) + || parent_source + .ports() + .iter() + .any(|port| port.name() == name && port.is_net()) + }; + let error = |detail: String| { + Err(ParserError::illegal_context( + "systemverilog inout port connection", + detail, + None, + )) + }; + let Some(accesses) = output_lvalue_accesses( + actual, + parent_variables, + parent_signal_names, + parent_constants, + parent_parameter_types, + ) else { + if simple_output_lvalue_ident(actual) + .is_some_and(|name| !parent_signal_names.contains_key(name)) + { + return Ok(()); + } + return error(format!( + "inout port `{}` must connect to a net, not `{}`", + connection.formal, connection.actual + )); + }; + for OutputLvalueAccess { signal, .. } in accesses { + let name = parent_variables[&signal].path.join("."); + if !is_net(&name) { + return error(format!( + "inout port `{}` must connect to a net, not variable `{name}`", + connection.formal + )); + } + } + Ok(()) +} + type SvGlue = ( Vec<(Vec, LogicPath)>, Vec<(Vec, LogicPath)>, @@ -5670,7 +5796,10 @@ fn build_instance_glue( .iter() .find(|connection| connection.formal == formal); let width = child_var.width; - match child_var.kind { + let Some(direction) = child_port_direction(child, child_var) else { + return Err(unsupported_sv_inout(formal)); + }; + match direction { VariableKind::Input => { let collapse_unknown_literal = !four_state && connection @@ -5967,9 +6096,6 @@ fn build_instance_glue( )); } } - VariableKind::Inout => { - return Err(unsupported_sv_inout(child_var.path.join("."))); - } _ => {} } } @@ -5977,6 +6103,29 @@ fn build_instance_glue( Ok((input_ports, output_ports, arena)) } +/// The direction in which the connection of `port` carries its value. An +/// `inout` port carries the value of its net out of the child when the child +/// drives the net, and into it otherwise. `None` is an inout port that the +/// child's frontend does not describe. +fn child_port_direction(child: &LoweredSvModule, port: &SvVariable) -> Option { + if port.kind != VariableKind::Inout { + return Some(port.kind); + } + let name = port.path.join("."); + child + .source + .ports() + .iter() + .any(|source| source.name() == name && source.direction() == sv::ir::PortDirection::Inout) + .then(|| { + if child.inout_driven_inside.contains(&name) { + VariableKind::Output + } else { + VariableKind::Input + } + }) +} + fn simple_output_lvalue_ident(expr: &sv::ir::Expr) -> Option<&str> { match expr { sv::ir::Expr::Ident(name) => Some(name), diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 25b0a4d8715..1dc7a3c7ed2 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1561,3 +1561,126 @@ (top Top) (run_to_finish) (expect_output "59 593\n")) + +(case inout_tristate_driver_in_child_reaches_parent + (four_state) + (source "inout_child_driver.sv" #" + module Pad(input logic [7:0] oe, dr, inout wire [7:0] pad, + output wire [7:0] ext); + for (genvar i = 0; i < 8; i++) begin : g + assign ext[i] = pad[i]; + assign pad[i] = oe[i] ? dr[i] : 1'bz; + end + endmodule + module Block(input logic [7:0] oe, dr, inout wire [7:0] pad, + output wire [7:0] ext); + Pad pad_cell(.oe(oe), .dr(dr), .pad(pad), .ext(ext)); + endmodule + module Top(input logic [7:0] oe, dr, output wire [7:0] ext, seen, + output logic floating); + wire [7:0] pad; + Block block(.oe(oe), .dr(dr), .pad(pad), .ext(ext)); + assign seen = pad; + assign floating = (pad[7] === 1'bz); + endmodule + "#) + (top Top) + (modify (set oe 0xff) (set dr 0xa5)) + (assert_eq ext 0xa5) + (assert_eq seen 0xa5) + (assert_eq floating 0) + (modify (set oe 0x0f)) + (assert_eq ext (fourstate 0x05 0xf0)) + (assert_eq seen (fourstate 0x05 0xf0)) + (assert_eq floating 1) + (modify (set oe 0)) + (assert_eq ext (fourstate 0 0xff)) + (assert_eq seen (fourstate 0 0xff))) + +(case inout_tristate_nets_read_zero_in_two_state + (source "inout_two_state.sv" #" + module Pad(input logic [7:0] oe, dr, inout wire [7:0] pad, + output wire [7:0] ext); + for (genvar i = 0; i < 8; i++) begin : g + assign ext[i] = pad[i]; + assign pad[i] = oe[i] ? dr[i] : 1'bz; + end + endmodule + module Reader(inout wire [7:0] io, output wire [7:0] y); + assign y = io; + endmodule + module Top(input logic [7:0] oe, dr, input logic en, input logic [7:0] a, + output bit [7:0] ext, seen, read); + wire [7:0] pad, w; + Pad pad_cell(.oe(oe), .dr(dr), .pad(pad), .ext(ext)); + assign seen = pad; + assign w = en ? a : 8'bz; + Reader reader(.io(w), .y(read)); + endmodule + "#) + (top Top) + (modify (set oe 0xff) (set dr 0x5a) (set en 1) (set a 0xc3)) + (assert_eq ext 0x5a) + (assert_eq seen 0x5a) + (assert_eq read 0xc3) + (modify (set oe 0xf0) (set en 0)) + (assert_eq ext 0x50) + (assert_eq seen 0x50) + (assert_eq read 0) + (modify (set oe 0)) + (assert_eq ext 0) + (assert_eq seen 0)) + +(case inout_tristate_driver_in_parent_reaches_child + (four_state) + (source "inout_parent_driver.sv" #" + module Reader(inout wire [3:0] io, output wire [3:0] y); + assign y = io; + endmodule + module Pass(inout wire [3:0] io, output wire [3:0] y); + Reader reader(.io(io), .y(y)); + endmodule + module Top(input logic en, input logic [3:0] a, + output wire [3:0] direct, nested, open); + wire [3:0] w; + assign w = en ? a : 4'bz; + Reader reader(.io(w), .y(direct)); + Pass pass(.io(w), .y(nested)); + Reader unconnected(.y(open)); + endmodule + "#) + (top Top) + (modify (set en 1) (set a 0x9)) + (assert_eq direct 0x9) + (assert_eq nested 0x9) + (assert_eq open (fourstate 0 0xf)) + (modify (set en 0)) + (assert_eq direct (fourstate 0 0xf)) + (assert_eq nested (fourstate 0 0xf))) + +(case inout_tristate_drivers_reach_implicit_nets + (four_state) + (source "inout_implicit_net.sv" #" + module Pad(input logic oe, d, inout wire io); + assign io = oe ? d : 1'bz; + endmodule + module Source(input logic d, output wire y); + assign y = d; + endmodule + module Reader(inout wire io, output wire y); + assign y = io; + endmodule + module Top(input logic oe, d, output wire from_pad, from_source); + Pad pad(.oe(oe), .d(d), .io(pad_net)); + Reader pad_reader(.io(pad_net), .y(from_pad)); + Source source(.d(d), .y(source_net)); + Reader source_reader(.io(source_net), .y(from_source)); + endmodule + "#) + (top Top) + (modify (set oe 1) (set d 1)) + (assert_eq from_pad 1) + (assert_eq from_source 1) + (modify (set oe 0) (set d 0)) + (assert_eq from_pad (fourstate 0 1)) + (assert_eq from_source 0)) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index f50db145ec4..617a4470cd9 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -709,6 +709,18 @@ sv_backends! { fn child_ports_keep_the_bit_ranges_of_selected_connections(sim) { @case "hierarchy::child_ports_keep_the_bit_ranges_of_selected_connections"; } + fn inout_tristate_driver_in_child_reaches_parent(sim) { + @case "hierarchy::inout_tristate_driver_in_child_reaches_parent"; + } + fn inout_tristate_nets_read_zero_in_two_state(sim) { + @case "hierarchy::inout_tristate_nets_read_zero_in_two_state"; + } + fn inout_tristate_driver_in_parent_reaches_child(sim) { + @case "hierarchy::inout_tristate_driver_in_parent_reaches_child"; + } + fn inout_tristate_drivers_reach_implicit_nets(sim) { + @case "hierarchy::inout_tristate_drivers_reach_implicit_nets"; + } } #[test] diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 3b4348a8717..578c6c460fa 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -4841,6 +4841,103 @@ fn expands_function_calls_in_child_input_connections() { assert_eq!(sim.get(y), 1u8.into()); } +#[test] +fn rejects_inout_nets_with_several_drivers() { + // Both sides of an inout connection are one net (IEEE 1800-2023 23.3.3); + // resolving several drivers of it is not supported yet. + let pad = r#" + module Pad(input logic oe, inout wire io); assign io = oe ? 1'b1 : 1'bz; endmodule + module Pass(input logic oe, inout wire io); Pad pad(.oe(oe), .io(io)); endmodule + "#; + for top in [ + // Two children drive the net. + r#"module Top(input logic a, b, output wire y); + wire w; + Pad left(.oe(a), .io(w)); + Pad right(.oe(b), .io(w)); + assign y = w; + endmodule"#, + // The parent and a child below a pass-through module drive the net. + r#"module Top(input logic a, b, output wire y); + wire w; + assign w = a ? 1'b0 : 1'bz; + Pass pass(.oe(b), .io(w)); + assign y = w; + endmodule"#, + // A child output and a child inout drive the net. + r#"module Source(output logic y); assign y = 1'b0; endmodule + module Top(input logic a, output wire y); + wire w; + Source source(.y(w)); + Pad pad(.oe(a), .io(w)); + assign y = w; + endmodule"#, + ] { + let error = cranelift_build_error(&format!("{pad}{top}")); + assert!(error.contains("multiple net drivers for `w`"), "{error}"); + } + // A driver of the net inside the child and one on the parent's side of + // an inout port of the child. + let error = cranelift_build_error( + r#" + module Pad(input logic oe, inout wire io); assign io = oe ? 1'b1 : 1'bz; endmodule + module Block(input logic a, b, inout wire io); + assign io = a ? 1'b0 : 1'bz; + Pad pad(.oe(b), .io(io)); + endmodule + module Top(input logic a, b, output wire y); + wire w; + Block block(.a(a), .b(b), .io(w)); + assign y = w; + endmodule + "#, + ); + assert!(error.contains("multiple net drivers for `io`"), "{error}"); +} + +#[test] +fn rejects_variables_and_expressions_on_inout_ports() { + // Only nets may be on either side of an inout port (IEEE 1800-2023 + // 23.3.3.2). + let reader = r#" + module Reader(inout wire [3:0] io, output wire [3:0] y); assign y = io; endmodule + module Pad(input logic oe, inout wire [3:0] io); assign io = oe ? 4'h1 : 4'hz; endmodule + "#; + for (top, variable) in [ + ( + r#"module Top(input logic [3:0] a, output wire [3:0] y); + logic [3:0] v; + assign v = a; + Reader reader(.io(v), .y(y)); + endmodule"#, + Some("variable `v`"), + ), + ( + r#"module Top(input logic oe, output logic [3:0] v); + Pad pad(.oe(oe), .io(v)); + endmodule"#, + Some("variable `v`"), + ), + ( + r#"module Top(input logic [3:0] a, output wire [3:0] y); + wire [3:0] w; + Reader reader(.io(w[3:0] ^ a), .y(y)); + endmodule"#, + None, + ), + ] { + let error = cranelift_build_error(&format!("{reader}{top}")); + assert!( + error.contains("inout port `io` must connect to a net"), + "{error}" + ); + assert!( + variable.is_none_or(|variable| error.contains(variable)), + "{error}" + ); + } +} + #[test] fn rejects_local_drivers_of_implicit_child_output_nets() { let source = r#" diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 779e2e7260e..9115fbed642 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -16,7 +16,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Modules | ANSI ports, non-ANSI ports (a header of port names and body `input` / `output` / `inout` declarations, optionally completed by a net or variable declaration of the same name), `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | +| Modules | ANSI ports, non-ANSI ports (a header of port names and body `input` / `output` / `inout` declarations, optionally completed by a net or variable declaration of the same name), `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them), `inout` ports below the top module whose net has one continuous driver on either side, such as a tristate `assign io = oe ? d : 'z;` (both sides read the driven value, or `z`) | | Programs | `program` declarations with ports and parameters, instantiated from modules like a module; their `initial` procedures run in the reactive region set (see [Programs](#programs)) | | Generate | `for` (with `genvar`), `if`, `case`; constant expressions including `**` | | Hierarchical references | reads of nets and variables of other instances, and procedural writes of their variables, including selects of unpacked array elements (`u.mem[i][7:0] = v`), through names that start at an instance of the module (also of a generate block or an instance array element), at the module's own name, at an enclosing module's name (upward) or at `$root`; see [Hierarchical references](#hierarchical-references) | @@ -221,7 +221,8 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: function, a call with the wrong number of arguments, an omitted argument without a declared default, and a task used as a value are errors. - DPI-C beyond the subset described in [DPI-C imports](#dpi-c-imports), DPI - exports, tri-state buses and multiple drivers. + exports, nets with several drivers (including tri-state buses) and `inout` + ports of the top module. ### Interface restrictions {#interface-restrictions} diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index efe68525764..b2ec786604f 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -15,7 +15,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| モジュール | ANSI ポート、non-ANSI ポート(ヘッダのポート名と本体の `input` / `output` / `inout` 宣言。同名のネットまたは変数の宣言で型を補える)、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割) | +| モジュール | ANSI ポート、non-ANSI ポート(ヘッダのポート名と本体の `input` / `output` / `inout` 宣言。同名のネットまたは変数の宣言で型を補える)、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割)、トップ以外のモジュールの `inout` ポートで、どちらか一方の側に連続代入のドライバが1つだけあるネット(`assign io = oe ? d : 'z;` のようなトライステートを含む。両側から駆動値または `z` が読める) | | プログラム | ポートとパラメータを持つ `program` 宣言。モジュールと同じくモジュールからインスタンス化し、その `initial` 手続きはリアクティブ領域セットで実行します(下記の「プログラム」を参照) | | generate | `for`(`genvar`)、`if`、`case`。`**` を含む定数式 | | package | 型、パラメータ、enum、関数。`import p::*;`、`import p::x;`、`p::x` で参照 | @@ -192,7 +192,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 使われていないパラメータや関数本体の中を含め、書かれた 場所にかかわらず名前を示して報告します。システムタスクでもシステム関数でもない `$` 名、 引数の数が誤っている呼び出し、既定値のない引数の省略、値として使ったタスクはエラーです。 -- [DPI-C の対応範囲](#dpi-c-imports)を超える機能と DPI export、トライステートバスと複数ドライバ、階層参照。 +- [DPI-C の対応範囲](#dpi-c-imports)を超える機能と DPI export、複数のドライバを持つネット(トライステートバスを含む)、トップモジュールの `inout` ポート、階層参照。 ## 実行時の挙動 {#semantics-worth-knowing}