rtl: fix single-step execution and validate simulation inputs

This commit is contained in:
dsh committed 2026-11-28 11:05:34 +08:00
1 parent a6c5d4039a
commit aa00ec5fb2
7 files changed
+393 -327

No files matched your search

+41 -36
View File
@@ -1,46 +1,51 @@
#!/bin/sh
# tests/rtl_probe.sh -- 不依赖 R8Forge 的两条探针。
#
# ./tests/rtl_probe.sh in-ready
# 只跑 in_ready 的定向测试(自带纸带,不需要镜像)
#
# ./tests/rtl_probe.sh states <image.hex> <LEN> [input.txt] [eprom]
# 跑一张镜像,打印步数/拍数/扫描占比/最大栈深
#
# 镜像来源(R8Forge,8 位 / 64 格的构建):
# r8forge examples/calc.r8asm > calc.rot8
# r8forge_tape_pack calc.rot8 -o calc.r8t --hex calc.hex --verify
# r8forge_tape_pack calc.rot8 -o calc_e.r8t --eprom --hex calc_e.hex # 一字节一指令
#
# 注意:Icarus 把 plusarg 原样传给 $readmemh,路径里有非 ASCII 字符时内存会**静默留空**
# (见 rtl/README.md 的坑 1)——所以这里一律先 cd 到镜像目录再用相对路径。
# Run the input handshake regression or measure cycles for an existing ROM image.
set -e
usage() {
printf '%s\n' "Usage: $0 in-ready | step | states <image.hex> <instruction count> [input.txt] [eprom]" >&2
exit 2
}
# Resolve image and input paths from the repository root, as in the examples.
cd "$(dirname "$0")/.."
mode=${1:-in-ready}
build=$(mktemp -d)
trap 'rm -rf "$build"' EXIT
case "$mode" in
in-ready)
iverilog -g2012 -o "$build/tb.vvp" rtl/rot8.v tests/tb_in_ready.v
exec vvp "$build/tb.vvp"
testbench=tests/tb_in_ready.v
set --
;;
step)
testbench=tests/tb_step.v
set --
;;
states)
hex=$2; len=$3; infile=$4; eprom=$5
[ -n "$hex" ] && [ -n "$len" ] || { echo "usage: $0 states <image.hex> <LEN> [input.txt] [eprom]"; exit 2; }
dir=$(cd "$(dirname "$hex")" && pwd); base=$(basename "$hex")
extra=""
[ -n "$infile" ] && extra="+INFILE=$(cd "$(dirname "$infile")" && pwd)/$(basename "$infile")"
if [ "$eprom" = "eprom" ]; then
iverilog -g2012 -DEPROM_MODE -o "$build/tb.vvp" rtl/rot8.v tests/tb_state_mix.v
else
iverilog -g2012 -o "$build/tb.vvp" rtl/rot8.v tests/tb_state_mix.v
fi
cd "$dir"
exec vvp "$build/tb.vvp" "+HEX=$base" "+LEN=$len" $extra
;;
*)
echo "usage: $0 in-ready | states <image.hex> <LEN> [input.txt] [eprom]"; exit 2
[ "$#" -ge 3 ] && [ "$#" -le 5 ] || usage
image=$2
length=$3
input=${4:-}
testbench=tests/tb_state_mix.v
case "${5:-}" in
'') set -- ;;
eprom) set -- -DEPROM_MODE ;;
*) usage ;;
esac
;;
*) usage ;;
esac
build_dir=$(mktemp -d)
trap 'rm -r -- "$build_dir"' 0
iverilog -g2012 "$@" -o "$build_dir/tb.vvp" rtl/rot8.v "$testbench"
if [ "$mode" = states ]; then
# Use short ASCII file names for Icarus plusargs on Windows.
cp -- "$image" "$build_dir/program.hex"
set -- "+HEX=program.hex" "+LEN=$length"
if [ -n "$input" ]; then
cp -- "$input" "$build_dir/input.txt"
set -- "$@" "+INFILE=input.txt"
fi
fi
cd "$build_dir"
vvp tb.vvp "$@"
+25 -38
View File
@@ -1,22 +1,6 @@
# Compare the RTL against the R8Forge interpreter, on a real tape.
#
# The one standard this machine answers to: same OUT stream, same step count as
# `r8forge_tape_run --loop-stack --retest` (the bracket discipline the board
# implements: jump back *onto* the [, so ] pops the loop stack on the jump).
#
# cmake -DRTL=rtl
# -DPACK=<R8Forge>/build/Release/r8forge_tape_pack
# -DRUN=<R8Forge>/build/Release/r8forge_tape_run
# -DR8FORGE=<R8Forge>/build/Release/r8forge
# -DSOURCE=../R8Forge/examples/hello.r8asm
# -DWORK=build [-DINPUT="12 34 + ."] [-DTAPE_ARGS=""]
# -P tests/rtl_sim.cmake
#
# It assembles SOURCE, packs it, runs the interpreter, compiles rtl/rot8.v with
# iverilog, runs the testbench, and compares both the OUT stream and the step
# count. The RTL is the 8 bit / 64 cell machine, so SOURCE has to be a tape that
# fits in 64 cells (all the shipped examples do; the flagship peaks at 155 and
# therefore wraps, which still matches the interpreter but is not a good test).
# Compare OUT bytes and instruction counts against the R8Forge interpreter.
# See rtl/README.md for the toolchain setup and an invocation example.
foreach(var RTL PACK RUN R8FORGE SOURCE WORK)
if(NOT DEFINED ${var})
message(FATAL_ERROR "rtl_sim.cmake needs -D${var}=...")
@@ -28,6 +12,7 @@ endif()
get_filename_component(rtl_dir "${RTL}" ABSOLUTE)
get_filename_component(work_dir "${WORK}" ABSOLUTE)
get_filename_component(SOURCE "${SOURCE}" ABSOLUTE)
get_filename_component(source_dir "${SOURCE}" DIRECTORY)
file(MAKE_DIRECTORY "${work_dir}")
@@ -37,15 +22,14 @@ if(NOT IVERILOG OR NOT VVP)
message(FATAL_ERROR "rtl_sim needs iverilog and vvp on PATH")
endif()
# The assembler resolves `%include "lib/..."` against the *working directory*, not
# against the source file, so it has to run from the R8Forge root (the parent of
# examples/). -DASSEMBLE_DIR overrides that when the source lives elsewhere.
# The assembler resolves includes from its working directory. Use the parent
# of examples/ or asm/ by default.
if(NOT DEFINED ASSEMBLE_DIR)
get_filename_component(ASSEMBLE_DIR "${source_dir}/.." ABSOLUTE)
endif()
execute_process(COMMAND ${R8FORGE} ${SOURCE} OUTPUT_VARIABLE text RESULT_VARIABLE rc
WORKING_DIRECTORY ${ASSEMBLE_DIR})
if(NOT rc EQUAL 0)
if(NOT rc STREQUAL "0")
message(FATAL_ERROR "assembling ${SOURCE} in ${ASSEMBLE_DIR} failed: ${rc}")
endif()
string(LENGTH "${text}" length)
@@ -53,7 +37,7 @@ file(WRITE ${work_dir}/rtl_sim.rot8 "${text}")
execute_process(COMMAND ${PACK} ${work_dir}/rtl_sim.rot8 -o ${work_dir}/rtl_sim.r8t
--hex ${work_dir}/rtl_sim.hex
OUTPUT_VARIABLE packed RESULT_VARIABLE rc)
if(NOT rc EQUAL 0)
if(NOT rc STREQUAL "0")
message(FATAL_ERROR "packing failed: ${rc} ${packed}")
endif()
message(STATUS "${packed}")
@@ -67,7 +51,7 @@ else()
-i "${INPUT}"
OUTPUT_VARIABLE sw RESULT_VARIABLE rc)
endif()
if(NOT rc EQUAL 0)
if(NOT rc STREQUAL "0")
message(FATAL_ERROR "software run failed: ${rc} ${sw}")
endif()
@@ -75,29 +59,32 @@ execute_process(COMMAND ${IVERILOG} -g2012 -o rot8_tb.vvp
${rtl_dir}/rot8.v ${rtl_dir}/tb_rot8.v
WORKING_DIRECTORY ${work_dir}
OUTPUT_VARIABLE build_log RESULT_VARIABLE rc)
if(NOT rc EQUAL 0)
message(FATAL_ERROR "iverilog failed: ${build_log}")
if(NOT rc STREQUAL "0")
message(FATAL_ERROR "iverilog failed (${rc}): ${build_log}")
endif()
# Run vvp *from the work directory* with relative file names. Icarus passes
# plusargs through as raw bytes, so an absolute path containing non-ASCII (this
# checkout lives under a Chinese directory name) arrives at $readmemh mangled and
# the memory silently stays empty -- the machine then runs a tape of opcode 0.
# Relative ASCII plusargs avoid path encoding issues in Icarus on Windows.
execute_process(COMMAND ${VVP} rot8_tb.vvp +HEX=rtl_sim.hex
+LEN=${length} +INFILE=rtl_sim_in.txt
WORKING_DIRECTORY ${work_dir}
OUTPUT_VARIABLE rtl RESULT_VARIABLE rc)
if(NOT rc EQUAL 0)
if(NOT rc STREQUAL "0")
message(FATAL_ERROR "vvp failed: ${rc} ${rtl}")
endif()
string(REGEX MATCH "out[^\n]*" rtl_out "${rtl}")
string(REGEX MATCH "^out([^()]*) *\\(([0-9]+) steps" _ "${sw}")
set(out_pattern "out([^()\r\n]*) *\\(([0-9]+) steps")
string(REGEX MATCH "^${out_pattern}" sw_summary "${sw}")
if(sw_summary STREQUAL "")
message(FATAL_ERROR "Interpreter did not report an OUT stream and step count:\n${sw}")
endif()
set(sw_values "${CMAKE_MATCH_1}")
set(sw_steps "${CMAKE_MATCH_2}")
string(REGEX MATCH "^out([^()]*) *\\(([0-9]+) steps" _ "${rtl_out}")
set(rtl_values "${CMAKE_MATCH_1}")
set(rtl_steps "${CMAKE_MATCH_2}")
string(REGEX MATCH "(^|\n)${out_pattern}" rtl_summary "${rtl}")
if(rtl_summary STREQUAL "")
message(FATAL_ERROR "RTL did not report an OUT stream and step count:\n${rtl}")
endif()
set(rtl_values "${CMAKE_MATCH_2}")
set(rtl_steps "${CMAKE_MATCH_3}")
if(NOT sw_values STREQUAL rtl_values)
message(FATAL_ERROR "OUT streams differ\n sw : ${sw_values}\n rtl: ${rtl_values}")
+20 -31
View File
@@ -1,18 +1,6 @@
// tests/tb_in_ready.v -- the in_ready contract, as a directed test.
//
// in_ready means "a byte handed over this cycle would really be consumed".
// Two historical bugs here, neither of which any tape found:
// * qualified with !in_valid -> deadlock (only a tape that reads input hangs,
// and it shows up as the cycle cap, not as a wrong answer; rtl/README.md 坑 2)
// * not qualified with run/step -> in single-step mode the machine is stopped
// but still says "send me a byte", so a producer that trusts it hands one
// over and loses it; the machine then waits forever on ','
//
// Tape: instruction 0 = ',' (7), instruction 1 = '.' (6), packed into one byte
// (0b001_110_111 = 0x37) -- no assembler, no ROM image needed.
//
// iverilog -g2012 -o tb.vvp rtl/rot8.v tests/tb_in_ready.v && vvp tb.vvp
// Verify input handshaking while paused, running, and halted.
// The test runs an in-memory tape: ',' opcode 7 followed by '.' opcode 6.
// Both opcodes fit in the first packed byte, 0x37.
`timescale 1ns/1ps
`default_nettype none
@@ -48,7 +36,7 @@ module tb_in_ready;
always #5 clk = ~clk;
task expect0(input exp, input got);
task expect_ready(input exp, input got);
begin
if (exp !== got) begin
$display(" expected %0b got %0b -> FAIL", exp, got);
@@ -59,26 +47,26 @@ module tb_in_ready;
endtask
initial begin
mem[0] = 8'h37; // 指令 0 = ',' (7), 指令 1 = '.' (6)
mem[0] = 8'h37;
mem[1] = 8'h00;
rst_n = 0; #20 rst_n = 1; #20;
$display("1. 单步模式停着(run=0):in_ready 必须是低");
$display("1. Ready stays low while paused");
run = 0; step = 0; #30;
expect0(1'b0, in_ready);
expect_ready(1'b0, in_ready);
$display("2. run=0 时给一拍 in_valid:不能出现\"假接受\"(in_ready 全程低)");
$display("2. A valid pulse while paused must leave the cell unchanged");
in_valid = 1; in_data = 8'h41; #10;
expect0(1'b0, in_ready);
expect_ready(1'b0, in_ready);
in_valid = 0; #20;
if (dut.cells[0] !== 8'h00) begin
$display(" cell0 = %02x -> FAIL(机器不该吃)", dut.cells[0]);
$display(" cell0 = %02x -> FAIL (unexpected input transfer)", dut.cells[0]);
errors = errors + 1;
end else
$display(" cell0 仍是 00 -> ok");
$display(" cell0 remains 00 -> ok");
$display("3. 电平式 in_valid 挂在 run=0 上,随后放开 run:必须吃掉");
$display("3. Pending input is accepted when execution resumes");
in_valid = 1; in_data = 8'h43; #20;
run = 1; #45;
if (dut.cells[0] !== 8'h43) begin
@@ -87,9 +75,9 @@ module tb_in_ready;
end else
$display(" cell0 = 43 -> ok");
$display("4. 复位后 run=1 停在 ',' 上:in_ready 必须为高,且交出的字节进格");
$display("4. A running input instruction asserts ready and stores the byte");
rst_n = 0; #20 rst_n = 1; run = 1; in_valid = 0; #25;
expect0(1'b1, in_ready);
expect_ready(1'b1, in_ready);
in_valid = 1; in_data = 8'h42; #10 in_valid = 0; #25;
if (dut.cells[0] !== 8'h42) begin
$display(" cell0 = %02x -> FAIL", dut.cells[0]);
@@ -97,15 +85,16 @@ module tb_in_ready;
end else
$display(" cell0 = 42 -> ok");
$display("5. 停机后(ip >= prog_len):in_ready 必须是低");
$display("5. Ready stays low after halting");
prog_len = 0; #40;
if (!halted) begin
$display(" 没有停机 -> FAIL"); errors = errors + 1;
$display(" Expected the machine to halt -> FAIL"); errors = errors + 1;
end
expect0(1'b0, in_ready);
expect_ready(1'b0, in_ready);
if (errors == 0) $display("ALL OK");
else $display("%0d FAILURES", errors);
if (errors != 0)
$fatal(1, "%0d input handshake checks failed", errors);
$display("ALL OK");
$finish;
end
endmodule
+47 -30
View File
@@ -1,17 +1,6 @@
// tests/tb_state_mix.v -- 跑一张纸带,数周期花在哪:取指 / 括号扫描 / 停机。
//
// 存在的理由:rtl/README.md 只说"和解释器步数一致",那对语义够用,但对**硬件预算**
// 不够 —— 步数不等于拍数。实测(8 位 / 64 格,见 docs/bracket-skip.md):
//
// hello 417 步 / 579 拍 (扫描 27%) 最大栈深 0
// test 100142 步 / (扫描 53%) 最大栈深 4
// calc 166741 步 / 698075 拍 (扫描 76%) 最大栈深 7
//
// iverilog -g2012 -o tb_state_mix.vvp rtl/rot8.v tests/tb_state_mix.v
// vvp tb_state_mix.vvp +HEX=hello.hex +LEN=577
// vvp tb_state_mix.vvp +HEX=calc.hex +LEN=51378 +INFILE=calc_in.txt
// vvp tb_state_mix.vvp +HEX=calc.hex +LEN=51378 +EPROM // 一字节一指令的镜像
// Count cycles in each RTL state and track the peak loop and scan depths.
// Compile with -DEPROM_MODE for one-instruction-per-byte images.
// Use tests/rtl_probe.sh states <image.hex> <instruction count> [input.txt] [eprom].
`timescale 1ns/1ps
`default_nettype none
@@ -22,7 +11,7 @@ module tb_state_mix;
reg [15:0] length = 0;
wire [15:0] prog_addr0, prog_addr1;
reg [7:0] prog_data0, prog_data1;
wire [7:0] prog_data0, prog_data1;
wire in_ready, out_valid, halted;
wire [7:0] out_data;
wire [15:0] ip;
@@ -31,7 +20,10 @@ module tb_state_mix;
reg [7:0] mem [0:65535];
reg [1023:0] hex_path, in_path;
integer in_fd, next_char, i;
integer hex_fd;
integer unsigned requested_length, image_bytes;
integer in_fd = 0;
integer next_char, i;
integer cycles = 0, c_fetch = 0, c_scan = 0, c_halt = 0;
integer n_out = 0, stalls = 0, max_sp = 0, max_scan = 0;
reg in_eof = 0;
@@ -59,24 +51,46 @@ module tb_state_mix;
begin
next_char = $fgetc(in_fd);
if (next_char < 0) begin
in_eof <= 1'b1; in_data <= 8'd0;
in_eof <= 1'b1;
in_data <= 8'd0;
end else
in_data <= next_char[7:0];
end
endtask
initial begin
if (!$value$plusargs("HEX=%s", hex_path)) begin $display("need +HEX="); $finish; end
if (!$value$plusargs("LEN=%d", length)) begin $display("need +LEN="); $finish; end
if ($test$plusargs("EPROM")) begin
// 一字节一指令的镜像里 ip 就是地址,长度也要按"字节数"给;这里不改指针,
// 只提醒调用方用 --eprom --hex 生成的镜像与同样的 +LEN。
if (!$value$plusargs("HEX=%s", hex_path))
$fatal(1, "Pass +HEX=<image>");
if (!$value$plusargs("LEN=%d", requested_length))
$fatal(1, "Pass +LEN=<instruction count>");
if (requested_length > (1 << 16) - 1)
$fatal(1, "Instruction count is too large: %0d", requested_length);
length = requested_length;
image_bytes = EPROM ? requested_length : (3 * requested_length + 7) / 8;
hex_fd = $fopen(hex_path, "rb");
if (hex_fd == 0)
$fatal(1, "Cannot open program image %0s", hex_path);
$fclose(hex_fd);
if (image_bytes != 0) begin
$readmemh(hex_path, mem, 0, image_bytes - 1);
for (i = 0; i < image_bytes; i = i + 1)
if ((^mem[i]) === 1'bx)
$fatal(1, "Missing or invalid byte at offset %0d in %0s", i, hex_path);
end
for (i = 0; i < 65536; i = i + 1) mem[i] = 8'h00;
$readmemh(hex_path, mem);
if ($value$plusargs("INFILE=%s", in_path)) in_fd = $fopen(in_path, "r");
// A packed fetch can read one byte past the image for its fetch window.
mem[image_bytes] = 8'h00;
if ($value$plusargs("INFILE=%s", in_path)) begin
in_fd = $fopen(in_path, "rb");
if (in_fd == 0)
$fatal(1, "Cannot open input file %0s", in_path);
end
#20 rst_n = 1;
if (in_fd != 0) begin in_valid = 1'b1; take_char; end
if (in_fd != 0) begin
in_valid = 1'b1;
take_char;
end
while (!halted && cycles < 200000000) begin
@(posedge clk);
cycles = cycles + 1;
@@ -91,15 +105,18 @@ module tb_state_mix;
if (in_ready && in_valid && in_fd != 0 && !in_eof) take_char;
if (out_valid) n_out = n_out + 1;
end
$display("%s%s", EPROM ? "[EPROM 1 byte/instruction] " : "[packed 3 bit/instruction] ",
halted ? "" : "NO HALT -- ");
if (!halted)
$fatal(1, "No halt after %0d cycles: ip %0d dp %0d, %0d input stalls",
cycles, ip, dp, stalls);
$display("%s", EPROM ? "[EPROM 1 byte/instruction]" : "[packed 3 bit/instruction]");
$display("steps=%0d cycles=%0d outs=%0d stalls=%0d", steps, cycles, n_out, stalls);
if (cycles > 0)
$display(" S_FETCH=%0d (%0d%%) S_SCAN=%0d (%0d%%) S_HALT=%0d",
c_fetch, (100*c_fetch)/cycles, c_scan, (100*c_scan)/cycles, c_halt);
c_fetch, (64'd100*c_fetch)/cycles, c_scan, (64'd100*c_scan)/cycles, c_halt);
if (steps > 0)
$display(" cycles/step = %0d.%02d, max stack depth = %0d, max scan depth = %0d",
cycles/steps, (100*(cycles%steps))/steps, max_sp, max_scan);
cycles/steps, (64'd100*(cycles%steps))/steps, max_sp, max_scan);
$finish;
end
endmodule
+106
View File
@@ -0,0 +1,106 @@
// Check tape bounds and single-step completion for scanning and input.
`timescale 1ns/1ps
`default_nettype none
module tb_step;
reg clk = 0, rst_n = 1, run = 0, step = 0, in_valid = 0;
reg [7:0] in_data = 8'h41;
reg [7:0] length;
reg [7:0] rom [0:255];
wire [7:0] address, ip;
wire ready, halted, out_valid;
wire [7:0] out_data;
wire [31:0] steps;
integer i;
rot8 #(.IPW(8), .EPROM(1)) dut (
.clk(clk), .rst_n(rst_n), .run(run), .step(step),
.prog_addr0(address), .prog_addr1(), .prog_data0(rom[address]),
.prog_data1(8'd0), .prog_len(length), .in_valid(in_valid),
.in_data(in_data), .in_ready(ready), .out_valid(out_valid),
.out_data(out_data), .ip(ip), .dp(), .steps(steps), .halted(halted));
always #5 clk = ~clk;
task reset;
begin
rst_n = 0;
@(negedge clk);
if (ready !== 0)
$fatal(1, "Input advertised while in reset");
rst_n = 1;
end
endtask
task request_step;
begin
step = 1;
@(negedge clk);
step = 0;
end
endtask
initial begin
// A ',' outside the image must not advertise a transfer.
length = 1;
rom[0] = 0;
rom[1] = 7;
run = 1;
reset;
@(negedge clk);
if (ip !== 1 || ready !== 0)
$fatal(1, "Invalid input handshake past program end");
@(negedge clk);
if (halted !== 1)
$fatal(1, "Program failed to halt");
// The scanner must never consume a matching bracket outside the image.
rom[0] = 4;
rom[1] = 5;
reset;
repeat (2) @(negedge clk);
if (ip !== 1 || halted !== 1 || dut.state !== dut.S_HALT)
$fatal(1, "Scanner ran past program end");
// A skipped loop can nest deeper than the active loop stack.
run = 0;
length = 81;
for (i = 0; i < 40; i = i + 1) begin
rom[i] = 4;
rom[40 + i] = 5;
end
rom[80] = 6;
reset;
request_step;
repeat (82) @(negedge clk);
if (ip !== 80 || steps !== 1 || halted !== 0 || out_valid !== 0)
$fatal(1, "Single step failed to finish the skip and pause");
request_step;
if (out_valid !== 1 || steps !== 2)
$fatal(1, "The next step failed to execute OUT");
// An input instruction can receive its byte after the step pulse ends.
length = 2;
rom[0] = 7;
rom[1] = 6;
reset;
request_step;
repeat (3) @(negedge clk);
if (ready !== 1 || ip !== 0 || steps !== 0)
$fatal(1, "Single-step input stopped waiting too early");
in_valid = 1;
@(negedge clk);
in_valid = 0;
repeat (3) @(negedge clk);
if (ready !== 0 || ip !== 1 || steps !== 1 || out_valid !== 0)
$fatal(1, "Single-step input failed to store the byte and pause");
request_step;
if (out_valid !== 1 || out_data !== 8'h41 || steps !== 2)
$fatal(1, "OUT did not return the single-step input byte");
$display("Single-step and tape boundary checks passed");
$finish;
end
endmodule
`default_nettype wire