Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2263,6 +2263,25 @@ impl<'p, 'a> Ff<'p, 'a> {
Ok(Expr::Ident(ret_name))
}

/// The value of `expr` now, in a temporary of its type.
fn keep_argument(&mut self, expr: &sv::ir::Expr) -> Result<sv::ir::Expr, sv::AnalyzerError> {
let signed = self.expr_signed(expr);
let float = floating::precision(expr, self.m.variables, self.m.name_to_id);
let handle = reads_string_variable(expr, self.m.variables, self.m.name_to_id);
let value = self.eval(expr, None)?;
let register = self.b.register(&value).clone();
let width = register.width();
let four_state = matches!(register, celox_sir::RegisterType::Logic { .. });
let (temp, name) = self.m.temp("task_argument", width, signed, four_state);
let variable = self.m.variables.get_mut(&temp).unwrap();
variable.float = float;
if handle {
variable.value_kind = celox_design::ValueKind::StrRef;
}
self.store(temp, SIROffset::Static(0), width, value);
Ok(sv::ir::Expr::Ident(name))
}

fn plusargs(
&mut self,
function: sv::ir::SystemFunction,
Expand Down Expand Up @@ -3216,6 +3235,32 @@ impl<'p, 'a> Ff<'p, 'a> {
};
let (template, mut values) = system_task_template(self.m, &kind, args);
prepare_time_operands(self.m, template.as_deref(), &mut values)?;
// Arguments are evaluated left to right. A later argument's call can
// change what an earlier one reads, or suspend the process (a host
// request) so that a value read before it would not survive the
// resume. So every argument before the last one with a call is
// evaluated whole into a temporary at its place; that one only has
// its calls run before its own reads, as any expression does.
let last_call = values.iter().rposition(
|value| matches!(value, sv::ir::SystemTaskArg::Expr(expr) if self.m.calls(expr)),
);
if let Some(last_call) = last_call {
for (index, value) in values[..=last_call].iter_mut().enumerate() {
let sv::ir::SystemTaskArg::Expr(expr) = value else {
continue;
};
let hoisted = if self.m.calls(expr) {
self.hoist(expr)?
} else {
expr.clone()
};
*expr = if index == last_call || matches!(hoisted, sv::ir::Expr::Literal(_)) {
hoisted
} else {
self.keep_argument(&hoisted)?
};
}
}
let mut regs = Vec::with_capacity(values.len());
let mut arg_widths = Vec::with_capacity(values.len());
let mut arg_signed = Vec::with_capacity(values.len());
Expand All @@ -3225,11 +3270,7 @@ impl<'p, 'a> Ff<'p, 'a> {
for value in &values {
match value {
sv::ir::SystemTaskArg::Expr(expr) => {
let expr = if self.m.calls(expr) {
self.hoist(expr)?
} else {
expr.clone()
};
let expr = expr.clone();
let signed = self.expr_signed(&expr);
arg_is_handle.push(reads_string_variable(
&expr,
Expand Down
31 changes: 24 additions & 7 deletions crates/celox-sv-analyzer/src/ast/interface_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,13 @@ pub(super) fn analyze_module(
return Ok(None);
}
let array_scope = if interface_ports.iter().any(|port| port.array_rank != 0) {
let (header_ports, header_tree) =
binding_declaration_view(&view_ports, &instantiations, tree, &imported)?;
let (header_ports, header_tree) = binding_declaration_view(
&view_ports,
&instantiations,
interface_ports,
tree,
&imported,
)?;
let mut header_imports = imported.clone();
header_imports.declarations_only = true;
Some(Module::from_selected_scope(
Expand Down Expand Up @@ -257,8 +262,13 @@ pub(super) fn analyze_module(
}
}
// Resolve the caller's declarations before evaluating instance overrides.
let (header_ports, header_tree) =
binding_declaration_view(&view_ports, &instantiations, tree, &imported)?;
let (header_ports, header_tree) = binding_declaration_view(
&view_ports,
&instantiations,
interface_ports,
tree,
&imported,
)?;
let mut header_imports = imported.clone();
header_imports.declarations_only = true;
let caller = Module::from_selected_scope(
Expand Down Expand Up @@ -324,8 +334,13 @@ pub(super) fn analyze_module(
if generated_item.is_none() {
// Newly bound instances may unlock declarations used by the next
// instance's overrides. Keep only still-unbound dependencies out.
let (header_ports, header_tree) =
binding_declaration_view(&view_ports, &instantiations, tree, &imported)?;
let (header_ports, header_tree) = binding_declaration_view(
&view_ports,
&instantiations,
interface_ports,
tree,
&imported,
)?;
let mut header_imports = imported.clone();
header_imports.declarations_only = true;
let caller = Module::from_selected_scope(
Expand Down Expand Up @@ -817,11 +832,12 @@ fn native_body_items(tree: &SyntaxTree) -> Converted<Vec<celox_sv_syntax::BodyIt
Ok(items)
}

/// Delay declarations that reference local interface instances (and declarations
/// Delay declarations that reference unbound interface instances or ports (and declarations
/// depending on those names) until the instances have populated semantic scopes.
fn binding_declaration_view<'a>(
selected: &port_owners::Selection<'a>,
instances: &[celox_sv_syntax::BodyItemId],
ports: &[interfaces::NativePortPlan],
tree: &AnalysisContext<'_>,
imported: &scope::ScopeSymbols,
) -> Converted<(port_owners::Selection<'a>, SyntaxTree)> {
Expand All @@ -831,6 +847,7 @@ fn binding_declaration_view<'a>(
.filter_map(|id| instances::declaration_from_item(*id, tree).ok())
.flat_map(|instance| instance.instances.iter())
.map(|instance| instances::normalize_identifier(&instance.name.spelling))
.chain(ports.iter().map(|port| port.name.clone()))
.filter(|name| {
!imported.interface_types.contains_key(name)
&& !imported.interface_arrays.contains_key(name)
Expand Down
36 changes: 36 additions & 0 deletions crates/celox-test-suite/src/sv/cases/interfaces.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -946,3 +946,39 @@
(<< (trunc 8 (+ value 4)) 8) (trunc 8 (+ value 5))))
(assert_eq first (| (<< (trunc 8 (+ value 1)) 8) (trunc 8 (+ value 2))))
(assert_eq second (| (<< (trunc 8 (+ value 3)) 8) (trunc 8 (+ value 4))))))

(case defers_interface_dependent_declarations_before_binding_array_ports
(source "interface_array_declarations.sv" #"
interface Bus #(parameter int W = 8);
logic [W-1:0] data;
modport sink(input data);
endinterface
module Reader #(parameter int LEFT = 3, RIGHT = 2)(
Bus.sink a[LEFT:RIGHT], Bus.sink b,
input logic [b.W-1:0] delta, output wire [31:0] y);
localparam SCALAR_W = b.W;
localparam ARRAY_W = a[LEFT].W;
localparam TOTAL_W = SCALAR_W + ARRAY_W;
typedef logic [TOTAL_W-1:0] sum_t;
sum_t sum;
assign sum = b.data + a[LEFT].data + a[RIGHT].data + delta;
assign y = sum + TOTAL_W;
endmodule
module Top(input logic [7:0] value,
output wire [31:0] descending, ascending);
Bus #(.W(8)) scalar();
Bus #(.W(12)) down[3:2](), up[5:6]();
assign scalar.data = value;
assign down[3].data = 12'h100;
assign down[2].data = 12'h200;
assign up[5].data = 12'h400;
assign up[6].data = 12'h800;
Reader d(down, scalar, value, descending);
Reader #(.LEFT(5), .RIGHT(6)) u(up, scalar, value, ascending);
endmodule
"#)
(top Top)
(for value (list 0 1 0x7f 0xff)
(modify (set value value))
(assert_eq descending (+ (* value 2) 0x300 20))
(assert_eq ascending (+ (* value 2) 0xc00 20))))
3 changes: 3 additions & 0 deletions crates/celox/tests/frontends/systemverilog/interfaces.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use super::*;

sv_backends! {
fn defers_interface_dependent_declarations_before_binding_array_ports(sim) {
@case "interfaces::defers_interface_dependent_declarations_before_binding_array_ports";
}
fn connects_interface_array_slices_in_declaration_order(sim) {
@case "interfaces::connects_interface_array_slices_in_declaration_order";
}
Expand Down
76 changes: 76 additions & 0 deletions crates/celox/tests/sv_plusargs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,79 @@ packed_string_literals_backend!(packed_string_literals_cranelift, build);
#[cfg(target_arch = "x86_64")]
packed_string_literals_backend!(packed_string_literals_native, build_native);
packed_string_literals_backend!(packed_string_literals_wasm, build_wasm);

/// A plusargs query among the arguments of a `$display` suspends the process
/// for the host; the arguments read before and after it keep their values.
const DISPLAYED: &str = r#"
module Top;
int i;
logic [7:0] v;
initial begin
i = 3;
v = 0;
$display("%0d %0d %0d %0d", i, $test$plusargs("verbose"), $value$plusargs("v=%d", v), v);
end
endmodule
"#;

/// Arguments are evaluated left to right: a later argument's call does not
/// change what an earlier argument read (Icarus prints `3 1 5 7`).
const ORDERED: &str = r#"
module Top;
int i;
function automatic int f();
return 0;
endfunction
function automatic int g();
i = 7;
return 5;
endfunction
initial begin
i = 3;
$display("%0d %0d %0d %0d", i + f(), $test$plusargs("verbose"), g(), i);
end
endmodule
"#;

macro_rules! display_plusargs {
($name:ident, $backend:ident) => {
display_plusargs!($name, $backend, DISPLAYED, "3 1 1 7");
};
($name:ident, $backend:ident, $source:expr, $expected:literal) => {
#[test]
fn $name() {
let mut sim = celox::Simulation::from_sv_sources(
vec![($source, Path::new("displayed.sv"))],
"Top",
)
.plusargs(["+verbose", "+v=7"])
.$backend()
.unwrap();
sim.run_until(0).unwrap();
let lines: Vec<String> = sim
.drain_runtime_events()
.into_iter()
.filter_map(|event| match event {
celox::RuntimeEvent::Display { message } => {
Some(String::from_utf8_lossy(&message).into_owned())
}
_ => None,
})
.collect();
assert_eq!(lines, [$expected]);
}
};
}
display_plusargs!(display_of_plusargs_interpreter, build_interpreter);
display_plusargs!(display_of_plusargs_compiled, build);
#[cfg(target_arch = "x86_64")]
display_plusargs!(display_of_plusargs_native, build_native);
display_plusargs!(
ordered_arguments_interpreter,
build_interpreter,
ORDERED,
"3 1 5 7"
);
display_plusargs!(ordered_arguments_compiled, build, ORDERED, "3 1 5 7");
#[cfg(target_arch = "x86_64")]
display_plusargs!(ordered_arguments_native, build_native, ORDERED, "3 1 5 7");
Loading