8 Commits
r1 ... r4
Author SHA1 Message Date
brad ArantandClaude Opus 5.5 fa4752fd7a Assembler in GNU as syntax, objdump-style disassembly, UCASE$ and LCASE$
The monitor's assembler takes GNU as directives (.org, .equ, .byte, .half,
.word, .ascii, .string, .space, .align, .balign ...), # comments, 0x/0b
numbers, '\n' constants, . for the current address, << >> ^ ~, %hi/%lo and
the FP CSR short forms; the old ORG/DB/EQU/0FFH forms remain as aliases. The
disassembler prints lower case and 0x hex as objdump does. The monitor is
built with -msave-restore and puts .rodata first, to fit its ROM.
BASIC gains UCASE$ and LCASE$. Manual, README and tests updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:14:19 -08:00
brad ArantandClaude Opus 5.5 25c8286cf2 BASIC: scientific functions and OPTION ANGLE DEGREES
ASIN, ACOS, ANGLE, SEC, CSC, COT; SINH, COSH, TANH and their inverses;
LOG10, LOG2; IP, FP, CEIL, ROUND, TRUNCATE; MOD; MIN and MAX of any number of
values; FACT; PI, DEG, RAD; OPTION ANGLE DEGREES|RADIANS. Out-of-domain values
give ILLEGAL FUNCTION CALL. basic/test-math.py checks each against Python's
math (within 3 ulp); the manual and README cover them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:39:29 -08:00
brad ArantandClaude Opus 5.5 79aef8ed38 BASIC: DO … LOOP, EXIT, ELSE, block IF and SELECT CASE
DO WHILE/UNTIL … LOOP WHILE/UNTIL, EXIT DO and EXIT FOR; IF … THEN … ELSE on
one line; block IF … ELSEIF … ELSE … END IF; SELECT CASE with values, ranges
and IS comparisons, numeric or string. RENUM also fixes line numbers after
ELSE. basic/test-blocks.py checks them; the manual and README cover them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:09:41 -08:00
brad ArantandClaude Opus 5.5 fd876fd44d Show the start-up screen size in the terminal banner
The banner said 80x32 although the screen starts at 132x64; it now
follows WIDE_BOOT, with the matching terminfo name (basys3-w or basys3).
The testbench checks it in both start-ups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 07:38:22 -08:00
brad ArantandClaude Opus 5.5 2dafda5fe5 Run the CPU at 100 MHz
The FPU picks the FADD/FSUB operands and works out exponents and leading
zeros as it takes them, and finds the back end's leading one a clock
before using it; those were the paths that held the design to 91 MHz.
Add, multiply and the multiply-adds now take 13 clocks, divide and
square root 37, int -> float 9. Setup slack at 100 MHz is +0.286 ns.
On the board: an empty FOR loop 6.4 us (was 8.3), SIN 33 us (was 37).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 07:26:59 -08:00
brad ArantandClaude Opus 5.5 bda9bb67b6 Add a 640x480 two-colour graphics mode; start in white
The graphics memory doubles as 640x480 at a bit a pixel (port 38), four
pixels to an entry, plotted by read-modify-write, in two colours from
port 39 (0 transparent). BASIC gets SCREEN 0 / SCREEN 1 [,set[,clear]];
a plain fill (as every game does) returns to 320x240 and BASIC follows.
The text now starts in white (SW5:4 = 00; 10 is green). The README is
rewritten to stand on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:06:30 -08:00
brad ArantandClaude Opus 5.5 71fd403294 Add a single-precision FPU (the F extension)
rtl/rv32_fpu.v: IEEE 754 single precision with all five rounding modes,
subnormals, the exception flags and the canonical NaN. Multiply-add
(DSPs, exact product, 77-bit sum) with add, subtract and multiply as its
special cases; divide and square root a bit a clock; one normalise-and-
round back end. 12 clocks for add/mul/fma, 36 for div/sqrt. About 3000
LUTs and 2 DSPs; the system still meets 90 MHz.

rv32_cpu.v: float registers, FLW/FSW, OP-FP and the R4 instructions,
fflags/frm/fcsr, mstatus.FS (Initial at reset), misa F.

tools/f32.py is an exact model (checked against x86 hardware) used by
scripts/fputest.sh (random vectors, every instruction and rounding mode)
and by tools/rv32emu.py, which now runs RV32IMF. cputest.sh adds rv32uf.

BASIC and the games are built for rv32imf/ilp32f (BASIC 36.4 -> 28.7 KB,
SIN about twice as fast); setjmp saves fs0-fs11; sqrtf is FSQRT.S. The
monitor saves and restores f0-f31 and fcsr, shows them (F), sets them
(R F1=...), and its disassembler and assembler know every F instruction
(checked against objdump and GNU as). Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:29:08 -08:00
brad ArantandClaude Opus 5.5 19278d1d74 Start the screen at 132x64
The terminal comes up (and resets with ESC c) in DECCOLM's 132x64 mode;
term_ctrl's WIDE_BOOT parameter selects 80x32 instead. Port 0 bit 2 tells
software which width is showing: BASIC's line editor wraps at it, and
the games, which play at 80 columns, put 132 back when they end.

scripts/sim.sh wide checks the start-up; the other checks still start
at 80x32. Manual, README and terminfo updated. send-hex.py is executable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:34:12 -08:00
60 changed files with 19334 additions and 16037 deletions

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ third_party/
*_out.txt
sim_time.txt
out/
sim/fpu/
+157 -43
View File
@@ -1,21 +1,118 @@
# Basys 3 RISC-V Computer
The [Basys 3 Z-80 computer](https://git.barant.com/barant/Basys3Terminal) with
the Z-80 replaced by a RISC-V processor written from scratch in Verilog. The
rest is the same machine: a VT220 terminal with ANSI colour on 1280×1024 VGA,
320×240 graphics in 16 colours with hardware scrolling and 32 sprites, a
three-voice sound chip (PmodAMP2 on JA), the keyboard on the USB host port
(with a keys-held port for games), files in the configuration flash,
Dartmouth-style BASIC, a machine-code monitor and five games.
A complete home computer on a Digilent Basys 3 FPGA board, built around a
RISC-V processor written from scratch in Verilog:
Flip **SW15** up and the terminal is the computer's console. BASIC and the
monitor are described in [docs/basic-manual.md](docs/basic-manual.md); the
terminal itself (SW15 down) works exactly as in the Z-80 project, whose README
covers it.
- **RV32IMF processor at 100 MHz**: integer, multiply/divide and IEEE 754
single-precision floating point in hardware, with traps, interrupts, hardware
breakpoints and single step.
- **VT220 terminal** with ANSI colour on 1280×1024 VGA: 132 × 64 text, or 80 × 32
in a double-size font.
- **Graphics** over the text: 320 × 240 in 16 colours with hardware scrolling,
or 640 × 480 in two colours, plus 32 hardware sprites.
- **Sound**: a three-voice chip with noise and envelopes (PmodAMP2 on JA).
- **USB keyboard** on the board's USB host port, with a keys-held port for
games.
- **Files** saved in the board's configuration flash.
- **Software**: Dartmouth-style BASIC with graphics, sound and files,
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
functions (inverse and hyperbolic trigonometry in radians or degrees,
`LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a
machine-code monitor with a RISC-V disassembler and assembler, and five
original games.
The [BASIC manual](docs/basic-manual.md) ([PDF](docs/basic-manual.pdf))
describes the computer from the user's side: BASIC, graphics, sprites, sound,
files, the monitor and the games.
## Getting started
Download `basys3_terminal.bit` (or `basys3_terminal.mcs` to keep it in the
flash) from the [latest release](https://git.barant.com/barant/Basys3RiscV/releases),
or build it yourself (below).
1. Plug a VGA monitor, a USB keyboard, and optionally a PmodAMP2 into JA.
2. Load the bitstream with Vivado's Hardware Manager, or `scripts/build.sh
program` / `flash` from a checkout.
3. Flip **SW15 up**. The screen shows BASIC's banner and `READY`.
With SW15 down the board is a plain VT220 terminal on its USB serial port, for
a PC. The computer keeps running underneath, waiting at its next character of
output, so flipping back and forth loses nothing.
The games come in the release as `*.ihx` (the program) and `*.bas` (the
loader). From a checkout of this repository, on a PC connected to the board's
serial port:
```bash
tools/send-hex.py keep.ihx --save KEEPGAME --baud 3000000
```
```bash
tools/send-bas.py keep.bas --baud 3000000
```
then `SAVE "KEEP"` in BASIC, and `RUN "KEEP"` from then on.
## Controls
| Control | Function |
|---|---|
| SW1:0 | Serial speed: `00` 115200, `01` 9600, `10` 921600, `11` 3000000 |
| SW2 | Local echo |
| SW3 | Received LF also does CR |
| SW5:4 | Text colour at start-up: `00` white, `01` yellow, `10` green, `11` cyan |
| SW6 | Backspace sends DEL (`7F`) instead of BS (`08`) |
| SW7 | Enter sends CR LF instead of CR |
| SW8 | Smooth scrolling (also `ESC[?4h`) |
| SW9 | Fast smooth scrolling: 15 lines a second instead of 7.5 |
| SW14 | Computer mode: link the PC's serial port too (PC input is typed into BASIC, BASIC's output is copied to the PC) |
| SW15 | Computer mode: the terminal is the computer's console |
| BTNC | Reset everything |
| BTNU | Clear the screen |
| BTND | Restart the computer only (or Ctrl-Alt-Del in computer mode) |
| Pause key | Stop the program in the machine-code monitor |
| LED7:0 | Last byte received |
| LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) |
| LED12–15 | Bell, Caps Lock, serial activity, keyboard activity |
| 7-segment | In computer mode, whatever a program writes to ports 33/32 (`OUT 32,n`); otherwise the last scan code and the last byte sent |
## The terminal
The terminal understands what a VT220 does, plus ANSI colour:
- Cursor movement, save and restore, `IND`/`NEL`/`RI`; insert and delete of
characters and lines, erase, scroll, insert mode.
- Scroll regions, origin mode, deferred auto-wrap, tab stops.
- DEC special graphics (drawn with the CP437 line characters).
- Bold, underline, blink, reverse, concealed; 16 foreground and background
colours (256-colour and RGB codes are mapped to the nearest).
- Cursor and keypad application modes, cursor on/off, smooth scrolling, the
alternate screen, `DECCOLM` (`ESC[?3h` 132 × 64, `ESC[?3l` 80 × 32).
- Replies to `DA`, secondary `DA` and `DSR`/`CPR`; `RIS`, `DECSTR`,
`DECALN`.
- XON/XOFF flow control, so a PC can send at full speed.
For a Linux login on the board, install the terminfo entry and run a getty
on the board's port (the second of its two, usually `/dev/ttyUSB1`):
```bash
tic -x -o ~/.terminfo terminfo/basys3.ti
```
```bash
sudo /usr/sbin/agetty -L 115200 ttyUSB1 basys3-w
```
`basys3-w` is the 132 × 64 entry (`stty rows 64 cols 132`); `basys3` is
80 × 32. Set SW6 up so Backspace sends DEL. Text is drawn as CP437 bytes, with
no UTF-8 decoding, so use `LANG=C` for clean line drawing.
## The processor (`rtl/rv32_cpu.v`)
RV32IM in machine mode: the base integer set, multiply/divide, CSRs, counters
RV32IMF in machine mode: the base integer set, multiply/divide,
single-precision floating point (`rtl/rv32_fpu.v`: IEEE 754 with all five
rounding modes, subnormals and the exception flags), CSRs, counters
(`cycle`, `time`, `instret`), `fence.i`, `ecall`/`ebreak`/`mret`/`wfi`, traps
and interrupts (`mtvec`, `mepc`, `mcause`, `mtval`; software, timer, external
and 16 local interrupt lines), two hardware triggers for execute, load and
@@ -24,9 +121,10 @@ store breakpoints, and a resumable NMI (after the Smrnmi extension: `mnepc`,
It is a multi-cycle design with the next instruction fetched while the current
one decodes: 2 clocks for most instructions, 3 for taken branches, jumps, loads
and stores, 4 for multiplies, 35 for divides; BASIC averages about 2.5. It
runs at 90 MHz (the Z-80's clock) and takes about 2,100 LUTs, 900 flip-flops
and 4 DSP slices.
and stores, 4 for multiplies, 35 for divides; BASIC averages about 2.5.
Floating-point add, subtract, multiply and the fused multiply-adds take 13
clocks, divide and square root 37. It runs at 100 MHz and takes about 5,300
LUTs (3,000 of them the FPU), 1,900 flip-flops and 6 DSP slices.
## The machine (`rtl/rv32_system.v`)
@@ -36,33 +134,48 @@ and 4 DSP slices.
| 0002_0000–0002_7FFF | the monitor's ROM (32 KB of block RAM); the NMI enters at 20000h, traps at 20004h |
| 0002_8000–0002_9FFF | the monitor's RAM (8 KB of distributed RAM, data only) |
| FFFF_FE00–FFFF_FEFF | 32-bit registers: milliseconds, microseconds, the timer interrupt's compare, breakpoints |
| FFFF_FF00–FFFF_FFFF | the Z-80 machine's I/O ports: port *N* at FFFF_FF00 + *N*, one instruction from `x0` (`sb a0,-255(zero)` is `OUT (1),A`) |
| FFFF_FF00–FFFF_FFFF | byte-wide I/O ports: port *N* at FFFF_FF00 + *N*, one instruction from `x0` (`sb a0,-255(zero)` writes port 1) |
The peripherals are the Z-80 machine's, unchanged in function: `term_ctrl.v`,
`text_display.v`, `sprites.v`, `sound.v`, `flash_spi.v`, `uart.v`,
`ps2_keyboard.v`, `sevenseg.v`. To make room in block RAM for the wider
processor's memory, the text screen and the graphics framebuffer are each
split into a power-of-two array and a small one (Vivado builds an array of
16,896 or 76,800 entries as 32K or 96K deep); that saves 10.5 block RAMs and
changes nothing else.
The ports (listed at the top of `rv32_system.v` and in the manual) cover the
console, the millisecond counter, the 7-segment display, graphics, sprites,
sound, the keys held down and the flash. The peripherals are `term_ctrl.v`
(the VT220), `text_display.v` (video), `sprites.v`, `sound.v`,
`flash_spi.v`, `uart.v`, `ps2_keyboard.v` and `sevenseg.v`.
Resources at 90 MHz: see `build/utilization.rpt` and `build/timing.rpt` after a
build.
The graphics memory is 76,800 four-bit entries: 320 × 240 pixels in 16
colours, or, with port 38 set, 640 × 480 pixels at one bit each (four to an
entry; a plot reads the entry and writes it back with one bit changed). To
fit the block RAM, the text screen and the graphics are each split into a
power-of-two array and a small one, because Vivado builds an array of 16,896
or 76,800 entries as 32K or 96K deep. That saves 10.5 block RAMs. The design
uses 49.5 of the XC7A35T's 50.
## Software
All in C (plus a little assembly), compiled with GCC for `rv32im`:
All in C (plus a little assembly), compiled with GCC:
- `basic/` — BASIC, ported from the Z-80 version: the same language, the same
manual. `lib/` has the few C library functions it needs (small string
functions, `setjmp`, and single-precision `sinf` … `sqrtf`), since newlib's
bring in its stdio and malloc. Floating point is IEEE single precision from
libgcc, correctly rounded (the Z-80's SDCC library wasn't, so the last digit
of a result can differ).
- `monitor/` — the machine-code monitor, with a RISC-V disassembler and a
two-pass assembler in place of the Z-80 ones.
- `basic/` — BASIC, with single-precision arithmetic on the FPU (`rv32imf`,
`ilp32f`), correctly rounded, and the structured statements of later
Dartmouth BASIC and True BASIC (`DO … LOOP`, `EXIT`, block `IF`, `SELECT
CASE`). `lib/` has the few C library functions it
needs (small string functions, `setjmp`, and `sinf` … `sqrtf`, `asinf`,
`sinhf`, `atanhf`, `log10f`, an exact `fmodf` and the rest, each within 3
ulp), since
newlib's bring in its stdio and malloc.
- `monitor/` — the machine-code monitor: memory, registers (integer and
floating point), step, breakpoints, a RISC-V disassembler and a two-pass
assembler that both use GNU as syntax (`.org`, `.word`, `.string`,
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
HEX in and out.
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
Cavern, recompiled; they load at A200h (`CALL 41472`).
Cavern; they load at A200h (`CALL 41472`).
| BASIC on the board | |
|---|---|
| `Y = SIN(X)` | 33 µs |
| `Y = EXP(1)` | 33 µs |
| `X = I * 1.5` | 23 µs |
| An empty `FOR` loop, each time round | 6.4 µs |
## Building
@@ -81,18 +194,15 @@ scripts/build.sh
`scripts/build.sh program` loads the bitstream over JTAG; `flash` writes it to
the configuration flash.
Games go onto the board as in the Z-80 project: `tools/send-hex.py
games/keep/keep.ihx --save KEEPGAME --baud 3000000`, then `tools/send-bas.py
games/keep/keep.bas` and `SAVE "KEEP"` in BASIC.
## Tests
| | |
|---|---|
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, graphics, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor. |
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as |
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM and string arrays, and each game, on `tools/rv32emu.py` (a Python RV32IM emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
| `scripts/fputest.sh` | `rtl/rv32_fpu.v` against `tools/f32.py`, an exact model of RISC-V's single precision (itself checked against the PC's FPU), on random vectors: every F instruction, every rounding mode, special values, subnormals and near-cancellations |
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings |
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
| `bench/` | the processor alone with 64 KB of RAM, for timing |
## Toolchain
@@ -101,3 +211,7 @@ games/keep/keep.bas` and `SAVE "KEEP"` in BASIC.
- RISC-V GCC: Vivado ships one for MicroBlaze V (`~/vivado/*/gnu/riscv/lin/bin/riscv64-unknown-elf-gcc`,
GCC 13 with an `rv32im/ilp32` multilib), which `scripts/rv_env.sh` finds
if there is no `riscv64-unknown-elf-gcc` on the PATH. `RV_PREFIX` overrides.
## License
MIT; see [LICENSE](LICENSE).
BIN
View File
Binary file not shown.
+412 -62
View File
@@ -9,8 +9,8 @@
* statement typed without a line number runs at once. Ctrl-C stops a program.
*
* Graphics: 320x240 in 16 colours over the text, origin top left, colour 0
* transparent. CLS COLOR PLOT LINE RECT FILL CIRCLE and POINT(x,y); LOCATE and
* INK place and colour text.
* transparent, or (SCREEN 1) 640x480 in two. CLS COLOR PLOT LINE RECT FILL
* CIRCLE and POINT(x,y); LOCATE and INK place and colour text.
*
* Files: SAVE "NAME", LOAD "NAME", RUN "NAME", DIR, DEL "NAME" keep programs
* in the spare part of the configuration flash (see the file system below).
@@ -33,7 +33,7 @@ typedef uint32_t u32;
/* ------------------------------------------------------------- platform */
#ifdef __riscv
#include "basys3.h"
#define con_stat IO8(0x00) /* bit 0: key waiting, bit 1: can send */
#define con_stat IO8(0x00) /* bit 0: key waiting, bit 1: can send, bit 2: 132 columns */
#define con_data IO8(0x01)
static void out_c(u8 c) { while (!(con_stat & 2)); con_data = c; }
@@ -46,16 +46,22 @@ static void poke(u32 a, u8 v) { *(volatile u8 *)a = v; }
static u8 io_in(u8 p) { return IO8(p); }
static void io_out(u8 p, u8 v) { IO8(p) = v; }
static void bye(void) { }
static u8 scr_width(void) { return con_stat & 4 ? 132 : 80; }
#define gx_lo IO8(0x30)
#define gx_hi IO8(0x31)
#define gy_p IO8(0x32)
#define gpix IO8(0x33) /* write plots and moves right; read gives the colour */
#define gfill IO8(0x34)
static void g_at(u16 x, u8 y) { gx_lo = x; gx_hi = x >> 8; gy_p = y; }
#define gmode IO8(0x38) /* bit 0: 640x480 in two colours (a game's fill ends it) */
#define gcols IO8(0x39) /* its colours: set pixels 3:0, clear ones 7:4 */
static void g_at(u16 x, u16 y) { gx_lo = x; gx_hi = x >> 8 | (y >> 8) << 2; gy_p = y; }
static void g_put(u8 c) { gpix = c; }
static u8 g_get(void) { return gpix; }
static void g_clear(u8 c) { gfill = c; while (gfill & 1); }
/* clear to colour 0, sprites off, scroll to 0; the fill also ends 640x480 mode */
static void g_clear(u8 hi) { gfill = 0; while (gfill & 1); gmode = hi; }
static void g_colours(u8 set, u8 clr) { gcols = set | clr << 4; }
static u8 g_hires(void) { return gmode & 1; }
/* SPI flash: port 40h opens/ends a command (bit 1 reads back "refused"),
41h shifts a byte. The hardware refuses to write below the file area. */
@@ -116,13 +122,15 @@ static u8 io_in(u8 p) { (void)p; return 0xFF; }
static void io_out(u8 p, u8 v) { (void)p; (void)v; }
static void close_all(void);
static void bye(void) { close_all(); exit(0); }
static u8 gmem[240][320];
static u16 hgx;
static u8 hgy;
static void g_at(u16 x, u8 y) { hgx = x; hgy = y; }
static void g_put(u8 c) { if (hgx < 320 && hgy < 240) gmem[hgy][hgx] = c; hgx++; }
static u8 g_get(void) { return hgx < 320 && hgy < 240 ? gmem[hgy][hgx] : 0; }
static void g_clear(u8 c) { memset(gmem, c, sizeof gmem); }
static u8 scr_width(void) { return 80; }
static u8 gmem[480][640];
static u16 hgx, hgy, hgw = 320, hgh = 240;
static void g_at(u16 x, u16 y) { hgx = x; hgy = y; }
static void g_put(u8 c) { if (hgx < hgw && hgy < hgh) gmem[hgy][hgx] = hgw > 320 ? c != 0 : c; hgx++; }
static u8 g_get(void) { return hgx < hgw && hgy < hgh ? gmem[hgy][hgx] : 0; }
static void g_clear(u8 hi) { memset(gmem, 0, sizeof gmem); hgw = hi ? 640 : 320; hgh = hi ? 480 : 240; }
static void g_colours(u8 set, u8 clr) { (void)set; (void)clr; }
static u8 g_hires(void) { return hgw > 320; }
/* flash file area kept in basic-flash.img */
#define HOST_BASE 0x240000UL
@@ -172,25 +180,40 @@ static struct chan ch[NCHAN];
static struct chan *chan_arg(u8 mode);
static u8 chan_line(struct chan *c);
static u8 deg; /* OPTION ANGLE DEGREES */
static u8 ghi; /* 640x480 (SCREEN 1) */
static u16 gw = 320, gh = 240; /* the graphics' size */
/* follow the hardware's mode: a game run with CALL may have ended SCREEN 1 */
static void g_sync(void) { ghi = g_hires(); gw = ghi ? 640 : 320; gh = ghi ? 480 : 240; }
/* ----------------------------------------------------------------- tokens */
enum {
T_LET = 0x80, T_PRINT, T_INPUT, T_IF, T_THEN, T_GOTO, T_GOSUB, T_RETURN, T_FOR,
T_TO, T_STEP, T_NEXT, T_DIM, T_DEF, T_END, T_STOP, T_REM, T_READ, T_DATA,
T_RESTORE, T_ON, T_RANDOMIZE, T_POKE, T_OUT, T_RUN, T_LIST, T_NEW, T_SCRATCH,
T_BYE, T_CLS, T_COLOR, T_PLOT, T_LINE, T_RECT, T_FILL, T_CIRCLE, T_LOCATE, T_INK,
T_BYE, T_CLS, T_COLOR, T_PLOT, T_LINE, T_RECT, T_FILL, T_CIRCLE, T_LOCATE, T_INK, T_SCREEN,
T_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, T_MONITOR, T_CALL, T_BSAVE, T_BLOAD, T_OUTPUT, T_APPEND, T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
T_SQR, T_INT, T_RND, T_SGN, T_FN, T_TAB, T_PEEK, T_INP, T_LEN, T_VAL, T_ASC, T_EOF,
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM, T_LAST
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM,
T_DO, T_LOOP, T_WHILE, T_UNTIL, T_EXIT, T_ELSE, T_SELECT, T_CASE,
T_OPTION, T_PI, T_ANGLE, T_DEG, T_RAD, T_ASIN, T_ACOS, T_SEC, T_CSC, T_COT,
T_SINH, T_COSH, T_TANH, T_ASINH, T_ACOSH, T_ATANH, T_LOG10, T_LOG2, T_CEIL,
T_IP, T_FP, T_ROUND, T_TRUNCATE, T_MOD, T_MIN, T_MAX, T_FACT, T_UCASES, T_LCASES, T_LAST
};
_Static_assert(T_LAST <= 0x100, "too many keywords for a byte");
static const char *const kw[] = {
"LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR",
"TO", "STEP", "NEXT", "DIM", "DEF", "END", "STOP", "REM", "READ", "DATA",
"RESTORE", "ON", "RANDOMIZE", "POKE", "OUT", "RUN", "LIST", "NEW", "SCRATCH",
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK",
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK", "SCREEN",
"SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "MONITOR", "CALL", "BSAVE", "BLOAD", "OUTPUT", "APPEND", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM"
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM",
"DO", "LOOP", "WHILE", "UNTIL", "EXIT", "ELSE", "SELECT", "CASE",
"OPTION", "PI", "ANGLE", "DEG", "RAD", "ASIN", "ACOS", "SEC", "CSC", "COT",
"SINH", "COSH", "TANH", "ASINH", "ACOSH", "ATANH", "LOG10", "LOG2", "CEIL",
"IP", "FP", "ROUND", "TRUNCATE", "MOD", "MIN", "MAX", "FACT", "UCASE$", "LCASE$"
};
/* ----------------------------------------------------------------- memory */
@@ -199,6 +222,7 @@ static const char *const kw[] = {
#define NVARS (26 * 11)
#define FORMAX 16
#define GOSUBMAX 32
#define DOMAX 16
#ifdef __riscv
/* at 8000h (basic.ld), where machine-code programs know to load into it */
@@ -226,6 +250,10 @@ struct subent { u8 *tp, *ln; };
static struct subent subs[GOSUBMAX];
static u8 nsub;
struct doent { u8 *tp, *ln; }; /* tp is the DO itself */
static struct doent dos[DOMAX];
static u8 ndo;
static u8 *tp; /* text pointer */
static u8 *curln; /* line being run, 0 in direct mode */
static u8 *datap; /* next DATA item, 0 = search from the start */
@@ -272,7 +300,8 @@ static void put_u16(u16 v)
enum {
E_SYNTAX, E_LINE, E_RETURN, E_NEXT, E_DATA, E_SUBSCRIPT, E_DIV0, E_MEMORY,
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_NOFILE, E_DISKFULL,
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_BREAK, E_STOP
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_NOLOOP,
E_NODO, E_DODEEP, E_NONEXT, E_ENDIF, E_ENDSEL, E_BREAK, E_STOP
};
static const char *const errmsg[] = {
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
@@ -281,6 +310,8 @@ static const char *const errmsg[] = {
"UNDEFINED FUNCTION", "FOR NESTED TOO DEEPLY", "GOSUB NESTED TOO DEEPLY",
"FILE NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
"FILE TOO BIG", "FILE ALREADY OPEN", "FILE NOT OPEN", "INPUT PAST END",
"DO WITHOUT LOOP", "LOOP WITHOUT DO", "DO NESTED TOO DEEPLY", "FOR WITHOUT NEXT",
"IF WITHOUT END IF", "SELECT WITHOUT END SELECT",
"BREAK", "STOP"
};
@@ -563,8 +594,9 @@ static void clear_vars(void)
memset(arrays, 0, sizeof arrays);
memset(fns, 0, sizeof fns);
arr_low = arena + ARENA;
nfor = nsub = 0;
nfor = nsub = ndo = 0;
datap = 0;
deg = 0;
}
static void new_prog(void)
@@ -620,7 +652,7 @@ static void expect(u8 c)
static u8 at_end(void)
{
u8 c = peekc();
return c == 0 || c == ':';
return c == 0 || c == ':' || c == T_ELSE; /* ELSE ends IF ... THEN's statement */
}
static u16 get_lineno(void)
@@ -652,7 +684,7 @@ static u8 is_str_start(void)
{
u8 c = peekc();
if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS ||
c == T_DATES)
c == T_DATES || c == T_UCASES || c == T_LCASES)
return 1;
return is_alpha(c) && tp[1] == '$';
}
@@ -746,6 +778,106 @@ static float rnd(void)
return (float)((seed >> 8) & 0xFFFFFF) / 16777216.0f;
}
/* ------------------------------------------------- scientific functions */
#define PI_F 3.14159265358979f
/* an angle from an inverse function, in the units OPTION ANGLE chose */
static float ang(float r) { return deg ? r * 180.0f / PI_F : r; }
/* sine (c = 0) or cosine (c = 1). In degrees, the angle is reduced exactly
to within 45 of a multiple of 90 first, so SIN(180) and COS(90) are 0. */
static float sin_cos(float v, u8 c)
{
float r, y;
int k;
if (!deg) return c ? cosf(v) : sinf(v);
r = fmodf(v, 360.0f);
k = (int)floorf(r / 90.0f + 0.5f);
r = (r - 90.0f * (float)k) * (PI_F / 180.0f);
k += c; /* cos x = sin(x + 90) */
y = k & 1 ? cosf(r) : sinf(r);
return (k & 2 ? -y : y) + 0.0f; /* + 0: no -0 */
}
/* x rounded (or truncated) to n decimal places, n < 0 to the left of the
point: INT(x * 10^n + .5) / 10^n, as in True BASIC */
static float round_to(float x, i16 n, u8 rnd)
{
float p = 1, s;
i16 i;
if (n < -38 || n > 38) error(E_FUNC);
for (i = n < 0 ? -n : n; i; i--) p *= 10.0f;
s = n < 0 ? x / p : x * p;
if (s >= 8388608.0f || s <= -8388608.0f) return x; /* nothing to round */
s = rnd ? floorf(s + 0.5f) : s < 0 ? -floorf(-s) : floorf(s);
return (n < 0 ? s * p : s / p) + 0.0f;
}
static float func2(u8 t, float v)
{
float w;
i16 n = 0;
u8 i;
switch (t) {
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
expect(',');
w = expr();
expect(')');
if (v == 0 && w == 0) error(E_FUNC);
return ang(atan2f(w, v));
case T_ROUND: case T_TRUNCATE:
if (t == T_TRUNCATE || peekc() == ',') { expect(','); n = to_int(expr()); }
expect(')');
return round_to(v, n, t == T_ROUND);
case T_MOD: /* the sign of the divisor, like INT */
expect(',');
w = expr();
expect(')');
if (w == 0) error(E_DIV0);
v = fmodf(v, w);
if (v != 0 && (v < 0) != (w < 0)) v += w;
return v + 0.0f;
case T_MIN: case T_MAX:
while (accept(',')) {
w = expr();
if (t == T_MIN ? w < v : w > v) v = w;
}
expect(')');
return v;
}
expect(')');
switch (t) {
case T_DEG: return v * 180.0f / PI_F;
case T_RAD: return v * PI_F / 180.0f;
case T_ASIN: if (v < -1 || v > 1) error(E_FUNC); return ang(asinf(v));
case T_ACOS: if (v < -1 || v > 1) error(E_FUNC); return ang(acosf(v));
case T_SEC: w = sin_cos(v, 1); if (w == 0) error(E_FUNC); return 1 / w;
case T_CSC: w = sin_cos(v, 0); if (w == 0) error(E_FUNC); return 1 / w;
case T_COT:
if (!deg) { w = tanf(v); if (w == 0) error(E_FUNC); return 1 / w; }
w = sin_cos(v, 0);
if (w == 0) error(E_FUNC);
return sin_cos(v, 1) / w;
case T_SINH: return sinhf(v);
case T_COSH: return coshf(v);
case T_TANH: return tanhf(v);
case T_ASINH: return asinhf(v);
case T_ACOSH: if (v < 1) error(E_FUNC); return acoshf(v);
case T_ATANH: if (v <= -1 || v >= 1) error(E_FUNC); return atanhf(v);
case T_LOG10: if (v <= 0) error(E_FUNC); return log10f(v);
case T_LOG2: if (v <= 0) error(E_FUNC); return log2f(v);
case T_CEIL: return -floorf(-v) + 0.0f;
case T_IP: return (v < 0 ? -floorf(-v) : floorf(v)) + 0.0f;
case T_FP: return v - (v < 0 ? -floorf(-v) : floorf(v));
case T_FACT: /* to 34!: 35! is beyond single precision */
if (v < 0 || v > 34 || v != floorf(v)) error(E_FUNC);
for (w = 1, i = 2; i <= v; i++) w *= i; /* exact to 13! */
return w;
}
error(E_SYNTAX);
return 0;
}
static float func(u8 t)
{
char s[STRMAX];
@@ -761,7 +893,8 @@ static float func(u8 t)
expect(',');
y = to_int(expr());
expect(')');
if ((u16)x >= 320 || (u16)y >= 240) return 0;
g_sync();
if ((u16)x >= gw || (u16)y >= gh) return 0;
g_at(x, y);
return g_get();
}
@@ -782,12 +915,19 @@ static float func(u8 t)
return *p ? parse_num(&p) : 0;
}
v = expr();
if (t >= T_ANGLE) return func2(t, v);
expect(')');
switch (t) {
case T_SIN: return sinf(v);
case T_COS: return cosf(v);
case T_TAN: return tanf(v);
case T_ATN: return atanf(v);
case T_SIN: return sin_cos(v, 0);
case T_COS: return sin_cos(v, 1);
case T_TAN:
if (deg) {
float c = sin_cos(v, 1);
if (c == 0) error(E_FUNC);
return sin_cos(v, 0) / c;
}
return tanf(v);
case T_ATN: return ang(atanf(v));
case T_EXP: return expf(v);
case T_LOG: if (v <= 0) error(E_FUNC); return logf(v);
case T_ABS: return v < 0 ? -v : v;
@@ -838,6 +978,8 @@ static float primary(void)
if (is_str_start()) error(E_TYPE);
if (c == T_FN) { tp++; return call_fn(); }
if (c >= T_SIN && c <= T_POINT && c != T_FN && c != T_TAB) { tp++; return func(c); }
if (c == T_PI) { tp++; return PI_F; }
if (c >= T_ANGLE && c <= T_FACT) { tp++; return func(c); }
if (is_alpha(c)) return *num_ref();
error(E_SYNTAX);
return 0;
@@ -965,6 +1107,14 @@ static void str_prim(char *out)
out[0] = to_int(expr());
out[1] = 0;
break;
case T_UCASES: /* only A-Z and a-z change */
case T_LCASES: {
char *p;
sexpr(out);
for (p = out; *p; p++)
if (c == T_UCASES ? *p >= 'a' && *p <= 'z' : *p >= 'A' && *p <= 'Z') *p ^= 32;
break;
}
case T_STRS: {
float v = expr();
out[0] = ' ';
@@ -1037,10 +1187,10 @@ static void check_break(void)
At the end of a line that is only a line number, Right copies that program
line one character at a time and End copies the rest of it; Delete there
skips a character of it. The screen is kept up to date with cursor moves
only, so a line may wrap: ed_sc is the column it starts in, ED_W the
screen width, ed_row the screen row (from the line's first) the
only, so a line may wrap: ed_sc is the column it starts in, ed_w the
screen width (80 or 132, read when the line starts), ed_row the screen row (from the line's first) the
terminal's cursor is on and ed_at the place it is at. */
#define ED_W 80
static u8 ed_w = 80;
static void esc_num(u8 n);
static u8 ed_sc, ed_row, ed_at, ed_pend, ed_n, ed_cur;
static u8 *ed_src; /* the program line being copied, or 0 */
@@ -1055,7 +1205,7 @@ static void ed_csi(u8 n, char f)
static void ed_go(u8 i)
{
u16 p = ed_sc + i;
u8 r = p / ED_W, c = p % ED_W;
u8 r = p / ed_w, c = p % ed_w;
if (i == ed_at && !ed_pend) return;
out_c('\r');
if (r < ed_row) ed_csi(ed_row - r, 'A');
@@ -1073,9 +1223,9 @@ static void ed_show(u8 i, u8 gone)
for (; k < ed_n; k++) out_c(linebuf[k]);
for (; gone; gone--, k++) out_c(' ');
if (k > i) {
ed_row = (ed_sc + k - 1) / ED_W;
ed_row = (ed_sc + k - 1) / ed_w;
ed_at = k;
ed_pend = (ed_sc + k) % ED_W == 0;
ed_pend = (ed_sc + k) % ed_w == 0;
}
ed_go(ed_cur);
}
@@ -1133,7 +1283,8 @@ static void ed_del(void)
static u8 read_line(void)
{
u8 c, k;
ed_sc = col % ED_W;
ed_w = scr_width();
ed_sc = col % ed_w;
ed_row = ed_at = ed_pend = ed_n = ed_cur = 0;
ed_src = 0;
for (;;) {
@@ -1412,6 +1563,181 @@ static void st_read(void)
} while (accept(','));
}
/* ---------------------------------------------------- block structures */
/* Move tp to the start of the next statement, on to the next line if need
be. Returns 0 at the end of the program (or of a direct statement). */
static u8 next_stmt(void)
{
skip_statement();
if (*tp) { tp++; return 1; }
if (!curln || !*(curln + *curln)) return 0;
curln += *curln;
tp = curln + 3;
return 1;
}
/* Does the statement at p end its line with THEN (a block IF)? */
static u8 ends_then(u8 *p)
{
u8 q = 0, last = 0;
for (; *p; p++) {
if (*p == '"') q = !q;
else if (*p != ' ') last = q ? 0 : *p;
}
return last == T_THEN;
}
/* Skip to just past the NEXT that closes the FOR we are in, and its
variables. */
static void find_next(void)
{
u8 depth = 0, c;
for (;;) {
if (!next_stmt()) error(E_NONEXT);
c = peekc();
if (c == T_FOR) depth++;
else if (c == T_NEXT && !depth--) {
tp++;
while (!at_end()) { var_name(); if (!accept(',')) break; }
return;
}
}
}
/* Skip to just past the LOOP that closes the DO we are in, and its
condition. */
static void find_loop(void)
{
u8 depth = 0, c;
for (;;) {
if (!next_stmt()) error(E_NOLOOP);
c = peekc();
if (c == T_DO) depth++;
else if (c == T_LOOP && !depth--) { tp++; skip_statement(); return; }
}
}
/* Skip to just past the END IF or END SELECT (k is T_IF or T_SELECT) that
closes the block we are in. With els, a block IF's condition was false:
stop instead at its ELSE, or at an ELSEIF whose condition is true. */
static void find_end(u8 k, u8 els)
{
u8 depth = 0, c;
for (;;) {
if (!next_stmt()) error(k == T_IF ? E_ENDIF : E_ENDSEL);
c = peekc();
if (c == k && (k == T_SELECT || ends_then(tp))) depth++;
else if (c == T_END) {
tp++;
if (accept(k) && !depth--) break;
} else if (c == T_ELSE && els && !depth) {
tp++;
if (!accept(T_IF)) break; /* ELSE */
c = expr() != 0; /* ELSEIF */
expect(T_THEN);
if (c) break;
}
}
jumped = 1; /* run on from here */
}
static void st_do(void)
{
u8 *at = tp - 1, i, go = 1;
for (i = 0; i < ndo; i++) /* back at a DO left by GOTO: restart it */
if (dos[i].tp == at) { ndo = i; break; }
if (accept(T_WHILE)) go = expr() != 0;
else if (accept(T_UNTIL)) go = expr() == 0;
if (!go) { find_loop(); return; }
if (ndo >= DOMAX) error(E_DODEEP);
dos[ndo].tp = at;
dos[ndo].ln = curln;
ndo++;
}
static void st_loop(void)
{
u8 again = 1;
if (!ndo) error(E_NODO);
if (accept(T_WHILE)) again = expr() != 0;
else if (accept(T_UNTIL)) again = expr() == 0;
ndo--;
if (again) { /* back to the DO, which tests its condition */
tp = dos[ndo].tp;
curln = dos[ndo].ln;
jumped = 1;
}
}
static void st_exit(void)
{
if (accept(T_DO)) {
if (!ndo) error(E_NODO);
ndo--;
find_loop();
} else if (accept(T_FOR)) {
if (!nfor) error(E_NEXT);
nfor--;
find_next();
} else error(E_SYNTAX);
}
/* x compared with the next value: -1, 0 or 1 */
static i16 case_cmp(u8 str, float x, const char *xs)
{
if (str) {
char a[STRMAX];
i16 c;
if (!is_str_start()) error(E_TYPE);
sexpr(a);
c = strcmp(xs, a);
return c < 0 ? -1 : c > 0;
} else {
float a = expr();
return x < a ? -1 : x > a;
}
}
/* One item of a CASE list: value, low TO high, or IS relation value. */
static u8 case_item(u8 str, float x, const char *xs)
{
u8 op;
i16 c;
if (peekc() == 'I' && tp[1] == 'S') tp += 2;
op = relop();
c = case_cmp(str, x, xs);
if (op) return (c < 0 && (op & 1)) || (c == 0 && (op & 2)) || (c > 0 && (op & 4));
if (!accept(T_TO)) return c == 0;
return (c >= 0) & (case_cmp(str, x, xs) <= 0);
}
/* SELECT CASE: find the first CASE that matches and run on from it. */
static void st_select(void)
{
char s[STRMAX];
float x = 0;
u8 str = 0, depth = 0, c, m;
expect(T_CASE);
if (is_str_start()) { sexpr(s); str = 1; }
else x = expr();
for (;;) {
if (!next_stmt()) error(E_ENDSEL);
c = peekc();
if (c == T_SELECT) depth++;
else if (c == T_END) {
tp++;
if (accept(T_SELECT) && !depth--) break;
} else if (c == T_CASE && !depth) {
tp++;
if (accept(T_ELSE)) break;
m = 0;
do m |= case_item(str, x, s); while (accept(','));
if (m) break;
}
}
jumped = 1;
}
static void st_for(void)
{
struct forent *f;
@@ -1432,27 +1758,8 @@ static void st_for(void)
nfor++;
/* skip the body when the loop runs zero times */
if ((f->step >= 0 && vars[v] > f->limit) || (f->step < 0 && vars[v] < f->limit)) {
u8 depth = 0;
nfor--;
for (;;) {
u8 c;
skip_statement();
if (!*tp) {
if (!curln || !*(curln + *curln)) error(E_FOR);
curln += *curln;
tp = curln + 3;
} else tp++;
c = peekc();
if (c == T_FOR) depth++;
else if (c == T_NEXT) {
if (!depth) {
tp++;
while (!at_end()) { var_name(); if (!accept(',')) break; }
return;
}
depth--;
}
}
find_next();
}
}
@@ -1567,16 +1874,16 @@ static void hline(i16 x1, i16 x2, i16 y, u8 c)
{
i16 t;
if (x1 > x2) { t = x1; x1 = x2; x2 = t; }
if ((u16)y >= 240 || x2 < 0 || x1 > 319) return;
if ((u16)y >= gh || x2 < 0 || x1 >= (i16)gw) return;
if (x1 < 0) x1 = 0;
if (x2 > 319) x2 = 319;
if (x2 >= (i16)gw) x2 = gw - 1;
g_at(x1, y);
for (; x1 <= x2; x1++) g_put(c);
}
static void pset(i16 x, i16 y, u8 c)
{
if ((u16)x < 320 && (u16)y < 240) { g_at(x, y); g_put(c); }
if ((u16)x < gw && (u16)y < gh) { g_at(x, y); g_put(c); }
}
static void line(i16 x1, i16 y1, i16 x2, i16 y2, u8 c)
@@ -1620,12 +1927,23 @@ static void graphics(u8 t)
{
i16 a[5];
u8 n, c;
g_sync();
switch (t) {
case T_CLS:
out_c(27); out_c('['); out_c('2'); out_c('J');
out_c(27); out_c('['); out_c('H');
col = 0;
g_clear(0);
g_clear(ghi);
break;
case T_SCREEN: /* SCREEN 0 | SCREEN 1 [, set [, clear]] */
n = int_args(a, 1, 3);
if ((u16)a[0] > 1 || (n > 1 && (u16)a[1] > 15) || (n > 2 && (u16)a[2] > 15))
error(E_FUNC);
ghi = a[0];
gw = ghi ? 640 : 320;
gh = ghi ? 480 : 240;
g_colours(n > 1 ? a[1] : 15, n > 2 ? a[2] : 0);
g_clear(ghi);
break;
case T_COLOR:
int_args(a, 1, 1);
@@ -1655,7 +1973,7 @@ static void graphics(u8 t)
y = a[1] < a[3] ? a[1] : a[3];
y2 = a[1] < a[3] ? a[3] : a[1];
if (y < 0) y = 0;
if (y2 > 239) y2 = 239;
if (y2 >= (i16)gh) y2 = gh - 1;
for (; y <= y2; y++) hline(a[0], a[2], y, c);
break;
}
@@ -2165,7 +2483,7 @@ static void st_renum(void)
rn_put(0); rn_put(n); rn_put(n >> 8);
for (q = p + 3; (t = *q++) != 0; ) {
rn_put(t);
if ((t < T_THEN || t > T_GOSUB) && t != T_RUN) continue; /* THEN GOTO GOSUB */
if ((t < T_THEN || t > T_GOSUB) && t != T_RUN && t != T_ELSE) continue; /* THEN GOTO GOSUB ELSE */
for (want = 1;;) {
while (*q == ' ') rn_put(*q++);
if (want && is_digit(*q)) {
@@ -2203,8 +2521,22 @@ static void statement(void);
static void st_if(void)
{
float c = expr();
u8 depth = 0, q = 0;
if (!accept(T_THEN) && peekc() != T_GOTO) error(E_SYNTAX);
if (!c) { skip_line(); return; }
if (!peekc()) { /* block IF: THEN ends the line */
if (!c && curln) find_end(T_IF, 1);
return;
}
if (!c) { /* on to this IF's ELSE, if it has one */
for (;; tp++) {
if (!*tp) return;
if (*tp == '"') q = !q;
else if (q) continue;
else if (*tp == T_IF) depth++;
else if (*tp == T_ELSE && !depth--) break;
}
tp++;
}
if (is_digit(peekc())) goto_line(get_lineno());
else statement();
}
@@ -2233,7 +2565,24 @@ static void statement(void)
case T_NEXT: st_next(); break;
case T_DIM: st_dim(); break;
case T_DEF: st_def(); break;
case T_END: close_all(); running = 0; break;
case T_END:
if (accept(T_IF) || accept(T_SELECT)) break;
close_all();
running = 0;
break;
case T_DO: st_do(); break;
case T_OPTION: /* OPTION ANGLE DEGREES | RADIANS */
expect(T_ANGLE);
if (accept(T_DEG)) deg = 1;
else if (accept(T_RAD)) deg = 0;
else error(E_SYNTAX);
while (is_alpha(*tp)) tp++; /* the rest of the word */
break;
case T_LOOP: st_loop(); break;
case T_EXIT: st_exit(); break;
case T_SELECT: st_select(); break;
case T_ELSE: find_end(T_IF, 0); break; /* end of the THEN part */
case T_CASE: find_end(T_SELECT, 0); break; /* end of a CASE's part */
case T_STOP: error(E_STOP); break;
case T_REM: skip_line(); break;
case T_DATA: skip_line(); break;
@@ -2308,7 +2657,7 @@ static void statement(void)
graphics(t);
break;
case T_CLS: case T_COLOR: case T_PLOT: case T_RECT:
case T_FILL: case T_CIRCLE: case T_LOCATE: case T_INK:
case T_FILL: case T_CIRCLE: case T_LOCATE: case T_INK: case T_SCREEN:
graphics(t);
break;
default:
@@ -2328,6 +2677,7 @@ static void execute(void)
if (!running) break;
if (jumped) continue;
if (accept(':')) continue;
if (peekc() == T_ELSE) skip_line(); /* IF ... THEN's statement ran */
if (peekc()) error(E_SYNTAX);
if (!curln) break; /* end of a direct statement */
curln += *curln;
@@ -2351,7 +2701,7 @@ int main(void)
newline();
if (setjmp(errjmp)) {
running = 0;
nfor = nsub = 0;
nfor = nsub = ndo = 0;
curln = 0;
}
for (;;) {
+5834 -5834
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -5,13 +5,13 @@ set -e
cd "$(dirname "$0")"
source ../scripts/rv_env.sh
mkdir -p out
CFLAGS="$RV_ARCH -Os -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
CFLAGS="$RV_ARCH_F -ffp-contract=off -Os -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S
${RV_PREFIX}gcc $CFLAGS -c -o out/basic.o basic.c
${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c
${RV_PREFIX}gcc $CFLAGS -c -o out/mathf.o ../lib/mathf.c
${RV_PREFIX}gcc $CFLAGS -c -o out/setjmp.o ../lib/setjmp.S
${RV_PREFIX}gcc $RV_ARCH -nostdlib -nostartfiles -T basic.ld -Wl,--gc-sections -Wl,-Map,out/basic.map \
${RV_PREFIX}gcc $RV_ARCH_F -nostdlib -nostartfiles -T basic.ld -Wl,--gc-sections -Wl,-Map,out/basic.map \
-Wl,--build-id=none -o out/basic.elf out/crt0.o out/basic.o out/string.o out/mathf.o out/setjmp.o -lgcc
${RV_PREFIX}objcopy -O binary -j .text -j .data out/basic.elf basic.bin
${RV_PREFIX}nm -n out/basic.elf > out/basic.sym
+4 -1
View File
@@ -1,6 +1,6 @@
# Start-up for BASIC on the Basys 3 RISC-V computer: at the reset address 0.
# Copy the initialised data from ROM, clear the rest, point traps at the
# monitor and run main.
# monitor, turn the FPU on and run main.
#include "basys3.h"
.section .text.start, "ax"
.globl _start
@@ -12,6 +12,9 @@ _start:
la sp, __stack_top
li t0, MON_TRAP # illegal instructions etc. stop in the monitor
csrw mtvec, t0
li t0, 0x2000 # mstatus.FS: the FPU on (Initial)
csrs mstatus, t0
csrw fcsr, zero # round to nearest, no flags
la a0, __data_start # copy initialised data
la a1, __data_load
la a2, __data_end
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Try BASIC's block structures (DO ... LOOP, EXIT, IF ... ELSE ... END IF,
SELECT CASE) in tools/rv32emu.py, with the screen kept by pyte.
python3 test-blocks.py
"""
import importlib.util
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("te", os.path.join(HERE, "test-edit.py"))
te = importlib.util.module_from_spec(spec)
spec.loader.exec_module(te)
CR = te.CR
def main():
b = te.Basic()
errors = 0
def check(what, ok, out=""):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok:
print(out)
errors += not ok
def screen():
return "\n".join(l.rstrip() for l in b.screen_text().display)
def run(prog):
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for line in prog.strip().splitlines():
b.type(line.encode() + CR)
b.type(b"RUN" + CR)
return screen().split("RUN")[-1]
b.type(b"")
out = run('''
10 I = 0
20 DO WHILE I < 5
30 PRINT I;
40 I = I + 1
50 LOOP
60 PRINT "/";
70 DO
80 I = I - 1: PRINT I;
90 LOOP UNTIL I = 0
100 PRINT "/";
110 DO UNTIL 1: PRINT "NEVER": LOOP
120 DO WHILE 0
130 PRINT "NEVER"
140 LOOP WHILE 1
150 PRINT "END"
''')
check("DO WHILE, LOOP UNTIL, and loops that run no times",
"0 1 2 3 4 / 4 3 2 1 0 /END" in out, out)
out = run('''
10 FOR I = 1 TO 3
20 J = 0
30 DO
40 J = J + 1
50 IF J > I THEN EXIT DO
60 PRINT J;
70 LOOP
80 PRINT ",";
90 NEXT I
100 FOR K = 1 TO 100
110 IF K = 4 THEN EXIT FOR
120 NEXT K
130 PRINT K
''')
check("nested DO in FOR, EXIT DO, EXIT FOR", "1 , 1 2 , 1 2 3 , 4" in out, out)
out = run('''
10 FOR I = 1 TO 4
20 IF I = 1 THEN
30 PRINT "ONE";
40 ELSEIF I = 2 THEN
50 PRINT "TWO";
60 IF I > 0 THEN
70 PRINT "+";
80 ELSE
90 PRINT "NEVER";
100 END IF
110 ELSE IF I = 3 THEN
120 PRINT "THREE";
130 ELSE
140 PRINT "MANY";
150 END IF
160 PRINT ",";
170 NEXT I
''')
check("block IF, ELSEIF, ELSE IF, ELSE, nested, END IF",
"ONE,TWO+,THREE,MANY," in out, out)
out = run('''
10 FOR I = 1 TO 3
20 IF I = 2 THEN PRINT "B"; ELSE PRINT "A";
30 IF I = 1 THEN 50 ELSE PRINT "-";
40 GOTO 60
50 PRINT "*";
60 NEXT I
70 IF 1 THEN IF 0 THEN PRINT "X" ELSE PRINT "Y" ELSE PRINT "Z"
80 IF 0 THEN IF 1 THEN PRINT "X" ELSE PRINT "Y" ELSE PRINT "Z"
90 IF 0 THEN PRINT "ELSE" ELSE PRINT "ELSE OK"
''')
check("one-line IF ... ELSE, with line numbers and nesting",
"A*B-A-Y\nZ\nELSE OK" in out, out)
out = run('''
10 FOR I = 0 TO 7
20 SELECT CASE I * 2
30 CASE 0
40 PRINT "ZERO";
50 CASE 2, 4
60 PRINT "SMALL";
70 CASE 6 TO 9
80 PRINT "MID";
90 CASE IS >= 12
100 PRINT "BIG";
110 CASE ELSE
120 PRINT "OTHER";
130 END SELECT
140 PRINT ",";
150 NEXT I
160 A$ = "PEAR"
170 SELECT CASE A$
180 CASE "APPLE": PRINT "A"
190 CASE "B" TO "Q": PRINT "IN RANGE"
200 END SELECT
210 SELECT CASE 5: CASE 1: PRINT "NO": END SELECT
220 PRINT "DONE"
''')
check("SELECT CASE numbers: values, TO, IS, ELSE",
"ZERO,SMALL,SMALL,MID,MID,OTHER,BIG,BIG," in out, out)
check("SELECT CASE strings, no CASE matching", "IN RANGE\nDONE" in out, out)
out = run('''
10 X = 0
20 DO
30 X = X + 1: PRINT X;
40 IF X < 30 THEN GOTO 20
50 IF X > 40 THEN EXIT DO
60 LOOP
70 PRINT "END"
''')
check("GOTO back to a DO does not fill its stack", " 40 41 END" in out, out)
b.type(b"CLS" + CR)
b.type(b'I=0: DO: I=I+1: LOOP UNTIL I=7: PRINT "DIRECT"; I' + CR)
check("DO ... LOOP in a direct statement", "DIRECT 7" in screen(), screen())
out = run('10 LOOP')
check("LOOP without DO", "LOOP WITHOUT DO" in out, out)
out = run('10 DO WHILE 0\n20 PRINT')
check("DO without LOOP", "DO WITHOUT LOOP" in out, out)
out = run('10 IF 0 THEN\n20 PRINT')
check("IF without END IF", "IF WITHOUT END IF" in out, out)
out = run('10 SELECT CASE 1\n20 PRINT')
check("SELECT without END SELECT", "SELECT WITHOUT END SELECT" in out, out)
out = run('10 FOR I = 2 TO 1\n20 PRINT')
check("FOR without NEXT", "FOR WITHOUT NEXT" in out, out)
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for l in (b"10 IF A THEN 30 ELSE 40", b"30 END IF", b"40 END"):
b.type(l + CR)
b.type(b"RENUM 100" + CR)
b.type(b"LIST" + CR)
check("RENUM follows ELSE's line number", "100 IF A THEN 110 ELSE 120" in screen(), screen())
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""Check BASIC's scientific functions in tools/rv32emu.py.
python3 test-math.py [count]
First the maths library itself: each function in basic.bin (lib/mathf.c) is
called directly in the emulator, on random values across its range and on
the awkward ones, and its result compared bit for bit with Python's math
module (in double precision, so as good as exact here), in units in the last
place of single precision. Then BASIC: the functions as statements see them,
OPTION ANGLE DEGREES, and the errors outside each function's domain.
"""
import importlib.util
import math
import os
import random
import struct
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("te", os.path.join(HERE, "test-edit.py"))
te = importlib.util.module_from_spec(spec)
spec.loader.exec_module(te)
CR = te.CR
RET = 0x12000 # the machine-code area: a return address never run
STACK = 0x12FF0
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def bits(x):
return struct.unpack("<I", struct.pack("<f", x))[0]
def unbits(i):
return struct.unpack("<f", struct.pack("<I", i & 0xFFFFFFFF))[0]
def ulp(x):
"""Single precision's unit in the last place at x."""
x = abs(x)
if x < 2.0 ** -126:
return 2.0 ** -149
return 2.0 ** (math.floor(math.log2(x)) - 23)
def ulps(got, want):
if math.isinf(want):
return 0 if got == want else math.inf
w = f32(want) if abs(want) < 3.4e38 else want
if math.isinf(w):
return 0 if math.isinf(got) and (got > 0) == (want > 0) else math.inf
return abs(got - want) / ulp(want)
def symbols():
s = {}
for line in open(os.path.join(HERE, "out", "basic.sym")):
a, t, n = line.split()
s[n] = int(a, 16)
return s
class Caller:
"""Call a float function in basic.bin, ilp32f: arguments in fa0, fa1."""
def __init__(self, board):
self.b = board
self.sym = symbols()
def __call__(self, name, *args):
b = self.b
x, f, pc = b.x[:], b.f[:], b.pc
for i, a in enumerate(args):
b.f[10 + i] = bits(a)
b.x[1] = RET
b.x[2] = STACK
b.pc = self.sym[name]
n = 0
while b.pc != RET:
b.step()
n += 1
if n > 100000:
raise RuntimeError(name + " did not return")
r = unbits(b.f[10])
b.x[:], b.f[:], b.pc = x, f, pc
return r
def logspace(rng, lo, hi, n, signed=False):
"""n random floats with magnitudes spread evenly in log between lo and hi"""
out = []
for _ in range(n):
v = f32(math.exp(rng.uniform(math.log(lo), math.log(hi))))
out.append(-v if signed and rng.random() < 0.5 else v)
return out
def main():
count = int(sys.argv[1]) if len(sys.argv) > 1 else 1500
rng = random.Random(1)
b = te.Basic()
b.type(b"")
call = Caller(b)
errors = 0
def check(what, ok, out=""):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok and out:
print(out)
errors += not ok
def uni(lo, hi, n):
return [f32(rng.uniform(lo, hi)) for _ in range(n)]
# name, reference, inputs, the most ulps allowed
n = count
tests = [
("asinf", math.asin, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True) + [1, -1, 0.5, 1 - 2 ** -24], 3),
("acosf", math.acos, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True) + [1, -1, 0, 1 - 2 ** -24, -1 + 2 ** -24], 3),
("sinhf", math.sinh, uni(-12, 12, n) + logspace(rng, 1e-30, 89, n, True) + [1, -1, 10, 89.4], 3),
("coshf", math.cosh, uni(-12, 12, n) + logspace(rng, 1e-30, 89, n, True) + [0, 1, 10, 89.4], 3),
("tanhf", math.tanh, uni(-12, 12, n) + logspace(rng, 1e-30, 30, n, True) + [0, 1, 10, -10], 3),
("asinhf", math.asinh, uni(-10, 10, n) + logspace(rng, 1e-30, 3e38, n, True) + [0, 1, 1e9, 2e9], 3),
("acoshf", math.acosh, [1 + abs(v) for v in uni(0, 10, n)] + logspace(rng, 1, 3e38, n)
+ [1 + 2 ** -23 * k for k in range(1, 40)] + [1, 1e9, 2e9], 3),
("atanhf", math.atanh, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True)
+ [1 - 2 ** -24 * k for k in range(1, 40)] + [0, 0.5], 3),
("log1pf", math.log1p, logspace(rng, 1e-30, 1e30, n) + uni(-0.999, 1, n), 3),
("log10f", math.log10, logspace(rng, 1e-45, 3e38, n) + uni(0.5, 2, n) + [10.0 ** k for k in range(-37, 39)], 2),
("log2f", math.log2, logspace(rng, 1e-45, 3e38, n) + uni(0.5, 2, n), 2),
]
for name, ref, xs, most in tests:
worst, at = 0, None
for x in xs:
x = f32(x)
try:
want = ref(x)
except (ValueError, OverflowError):
want = math.inf if name in ("sinhf", "coshf") else None
if name == "sinhf":
want = math.copysign(math.inf, x)
if want is None:
continue
e = ulps(call(name, x), want)
if e > worst:
worst, at = e, x
check(f"{name}: {len(xs)} values, worst {worst:.2f} ulp (at {at!r}), "
f"allowed {most}", worst <= most)
# exact cases
check("log2f exact at powers of 2", all(call("log2f", 2.0 ** k) == k for k in range(-149, 128)))
check("asinf(1), acosf(-1), acosf(1) exact",
call("asinf", 1.0) == f32(math.pi / 2) and call("acosf", -1.0) == f32(math.pi)
and call("acosf", 1.0) == 0)
# atan2f
worst, at = 0, None
for _ in range(4 * n):
y, x = f32(rng.uniform(-10, 10)), f32(rng.uniform(-10, 10))
if rng.random() < 0.3:
y = f32(y * 10 ** rng.uniform(-20, 20))
e = ulps(call("atan2f", y, x), math.atan2(y, x))
if e > worst:
worst, at = e, (y, x)
axes = all(call("atan2f", y, x) == f32(math.atan2(y, x))
for y, x in [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1)])
check(f"atan2f: {4 * n} values, worst {worst:.2f} ulp (at {at!r}), allowed 3; axes exact",
worst <= 3 and axes)
# fmodf must be exact
bad = []
for _ in range(4 * n):
x = f32(rng.choice([-1, 1]) * 10 ** rng.uniform(-10, 30))
y = f32(rng.choice([-1, 1]) * 10 ** rng.uniform(-10, 10))
if call("fmodf", x, y) != f32(math.fmod(x, y)):
bad.append((x, y))
check(f"fmodf exact on {4 * n} values", not bad, repr(bad[:5]))
# ---------------------------------------------------------------- BASIC
def screen():
return "\n".join(l.rstrip() for l in b.screen_text().display)
def run(prog):
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for line in prog.strip().splitlines():
b.type(line.encode() + CR)
b.type(b"RUN" + CR)
return screen().split("RUN")[-1]
def rows(out):
return [l.strip() for l in out.splitlines() if l.strip() and l.strip() != "READY"]
out = run('''
10 PRINT PI; DEG(PI); RAD(180); ATN(1) * 4
20 PRINT ASIN(.5); ACOS(-1); ANGLE(-1, 0); ANGLE(0, -2)
30 PRINT SINH(1); COSH(1); TANH(.5); ASINH(1); ACOSH(2); ATANH(.5)
40 PRINT LOG10(1000); LOG2(1024); LOG10(2); LOG(EXP(2))
50 PRINT SEC(0); CSC(PI / 2); COT(PI / 4)
''')
got = rows(out)
want = ["3.14159 180 3.14159 3.14159",
".523599 3.14159 3.14159 -1.5708",
"1.1752 1.54308 .462117 .881374 1.31696 .549306",
"3 10 .30103 2",
"1 1 1"]
check("PI, DEG, RAD, the inverse trig functions, ANGLE", got[:2] == want[:2], out)
check("hyperbolic functions and their inverses", got[2:3] == want[2:3], out)
check("LOG10, LOG2", got[3:4] == want[3:4], out)
check("SEC, CSC, COT", got[4:5] == want[4:5], out)
out = run('''
10 PRINT ROUND(2.567, 2); ROUND(2.5); ROUND(-2.5); ROUND(1250, -2); ROUND(-1.25, 1)
20 PRINT TRUNCATE(2.567, 1); TRUNCATE(-2.567, 1); TRUNCATE(1299, -2)
30 PRINT IP(3.7); IP(-3.7); FP(3.75); FP(-3.75); CEIL(3.2); CEIL(-3.2); CEIL(4)
40 PRINT MOD(7, 3); MOD(-7, 3); MOD(7, -3); MOD(-7, -3); MOD(7.5, 2); MOD(6, 3)
50 PRINT MIN(3, 1, 2); MAX(3, 1, 2); MIN(-1, -5); MAX(4)
60 PRINT FACT(0); FACT(5); FACT(10); FACT(13); FACT(34)
''')
got = rows(out)
want = ["2.57 3 -2 1300 -1.2",
"2.5 -2.5 1200",
"3 -3 .75 -.75 4 -3 4",
"1 2 -2 -1 1.5 0",
"1 3 -5 4",
"1 120 3.6288E+06 6.22702E+09 2.95233E+38"]
for w, g, what in zip(want, got + [""] * 6,
["ROUND", "TRUNCATE", "IP, FP, CEIL", "MOD", "MIN, MAX", "FACT"]):
check(what, g == w, f"got {g!r}, want {w!r}")
out = run('''
10 OPTION ANGLE DEGREES
20 PRINT SIN(30); SIN(180); COS(90); COS(60); TAN(45); SIN(-90); COS(720)
30 PRINT ASIN(1); ACOS(0); ATN(1); ANGLE(-1, -1); SEC(60); COT(45); CSC(30)
40 PRINT SIN(1E6); COS(-123.5)
50 OPTION ANGLE RADIANS
60 PRINT SIN(PI / 6); ATN(1)
''')
got = rows(out)
check("OPTION ANGLE DEGREES: exact at multiples of 30 and 45",
got[:2] == [".5 0 0 .5 1 -1 1", "90 90 45 -135 2 1 2"], out)
try:
big = [float(v) for v in got[2].split()]
except (IndexError, ValueError):
big = []
check("degrees: large and negative angles",
len(big) == 2 and abs(big[0] - math.sin(math.radians(1e6))) < 2e-6
and abs(big[1] - math.cos(math.radians(-123.5))) < 2e-6, out)
check("OPTION ANGLE RADIANS goes back", got[3:4] == [".5 .785398"], out)
out = run('10 PRINT SIN(90)')
check("RUN starts in radians again", rows(out) == [".893997"], out)
for expr, msg in [("ASIN(1.5)", "ILLEGAL"), ("ACOS(-2)", "ILLEGAL"), ("ACOSH(.5)", "ILLEGAL"),
("ATANH(1)", "ILLEGAL"), ("ATANH(-1)", "ILLEGAL"), ("LOG10(0)", "ILLEGAL"),
("LOG2(-1)", "ILLEGAL"), ("FACT(-1)", "ILLEGAL"), ("FACT(2.5)", "ILLEGAL"),
("FACT(35)", "ILLEGAL"), ("ANGLE(0, 0)", "ILLEGAL"), ("MOD(1, 0)", "DIVISION BY ZERO"),
("ROUND(1, 39)", "ILLEGAL"), ("CSC(0)", "ILLEGAL"), ("COT(0)", "ILLEGAL")]:
out = run(f"10 PRINT {expr}")
check(f"{expr} is an error", msg in out, out)
out = run("10 OPTION ANGLE DEGREES: PRINT TAN(90)")
check("TAN(90) in degrees is an error", "ILLEGAL" in out, out)
out = run("10 OPTION ANGLE DEGREES: PRINT SEC(90)")
check("SEC(90) in degrees is an error", "ILLEGAL" in out, out)
out = run("10 OPTION ANGLE GRADS")
check("OPTION ANGLE wants DEGREES or RADIANS", "SYNTAX" in out, out)
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
b.type(b"10 OPTION ANGLE DEGREES: X = TRUNCATE(PI, 3)" + CR)
b.type(b"LIST" + CR)
check("LIST spells the new words as typed",
"10 OPTION ANGLE DEGREES: X = TRUNCATE(PI, 3)" in screen(), screen())
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""BASIC's graphics modes in tools/rv32emu.py (tools/boardemu.py models the
graphics): SCREEN 1 (640x480 in two colours) and back to SCREEN 0.
python3 test-screen.py
Needs pyte.
"""
import importlib.util
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("test_edit", os.path.join(HERE, "test-edit.py"))
te = importlib.util.module_from_spec(spec)
spec.loader.exec_module(te)
def main():
b = te.Basic()
errors = 0
def check(what, ok):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
errors += not ok
def last():
rows = [l.rstrip() for l in b.screen_text().display if l.strip()]
return rows[-2] if rows and rows[-1] == "READY" else rows[-1:]
CR = b"\r"
b.type(b"")
b.type(b"SCREEN 1,14,1" + CR)
check("SCREEN 1 turns on 640x480 with its colours", b.g_hires == 1 and b.g_cols == 0x1E)
b.type(b"LINE 0,0,639,479:CIRCLE 320,240,200:PLOT 600,470,0:PRINT POINT(639,479);POINT(320,40);POINT(1,0);POINT(700,10)" + CR)
check("POINT reads pixels past 320x240", last() == " 1 1 0 0")
h = b.hgfx
check("the line reaches the corner", h[0] == 1 and h[479 * 640 + 639] == 1 and h[240 * 640 + 320] == 1)
check("the circle is in the 640x480 plane", h[240 * 640 + 520] == 1 and h[440 * 640 + 320] == 1)
check("the 320x240 plane is untouched", not any(b.gfx))
b.type(b"FILL 600,460,639,479:PLOT 639,479,0:PRINT POINT(600,460);POINT(639,479)" + CR)
check("FILL and erasing with colour 0", last() == " 1 0")
b.type(b"CLS:PRINT POINT(320,40)" + CR)
check("CLS clears but stays in 640x480", b.g_hires == 1 and not any(b.hgfx) and last() == " 0")
b.type(b"SCREEN 0:PLOT 319,239,9:PRINT POINT(319,239);POINT(320,40)" + CR)
check("SCREEN 0 goes back to 320x240 in 16 colours", b.g_hires == 0 and last() == " 9 0")
b.type(b"SCREEN 2" + CR)
check("SCREEN 2 is an error", "?" in "".join(b.screen_text().display) or "ERROR" in "".join(b.screen_text().display))
# a game's fill ends 640x480 mode; BASIC follows the hardware
b.type(b"SCREEN 1:OUT 52,0:PLOT 319,239,5:PRINT POINT(319,239)" + CR)
check("after a plain fill BASIC is back in 320x240", b.g_hires == 0 and last() == " 5")
print("%d error(s)" % errors)
sys.exit(1 if errors else 0)
main()
+18 -1
View File
@@ -18,9 +18,11 @@ def main():
b = te.Basic()
errors = 0
def check(what, ok):
def check(what, ok, out=""):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok and out:
print(out)
errors += not ok
def run(prog):
@@ -64,6 +66,21 @@ def main():
b.type(b"A, B" + CR)
check("LINE INPUT into an element", "<A, B>" in "\n".join(l.rstrip() for l in b.screen_text().display))
out = run('''
10 A$ = "Hello, World! 123"
20 PRINT UCASE$(A$); "|"; LCASE$(A$); "|"; LCASE$(UCASE$("mIxEd"))
30 B$ = CHR$(64) + CHR$(91) + CHR$(96) + CHR$(123) + CHR$(224)
40 PRINT (UCASE$(B$) = B$); (LCASE$(B$) = B$); LEN(UCASE$("")); ASC(LCASE$("Z"))
50 DIM N$(1): N$(1) = "abc": PRINT UCASE$(N$(1) + "d")
''')
check("UCASE$ and LCASE$", "HELLO, WORLD! 123|hello, world! 123|mixed" in out, out)
check("only A-Z and a-z change", "-1 -1 0 122" in out, out)
check("UCASE$ of an expression", "ABCD" in out, out)
b.type(b"LIST 20" + CR)
check("LIST spells UCASE$ and LCASE$",
'20 PRINT UCASE$(A$); "|"; LCASE$(A$); "|"; LCASE$(UCASE$("mIxEd"))' in
"\n".join(l.rstrip() for l in b.screen_text().display))
out = run('10 DIM Q$(2): Q$(3) = "X"')
check("subscript out of range", "SUBSCRIPT" in out.upper())
out = run('10 DIM Z$(300)')
+1 -1
View File
@@ -7,7 +7,7 @@ set mult [expr {[info exists ::env(MULT)] ? $::env(MULT) : 9.0}]
set div [expr {[info exists ::env(DIV)] ? $::env(DIV) : 10.0}]
puts "CPU clock: [expr {100.0 * $mult / $div}] MHz"
read_verilog $root/rtl/rv32_cpu.v $root/bench/cpu_bench.v
read_verilog $root/rtl/rv32_cpu.v $root/rtl/rv32_fpu.v $root/bench/cpu_bench.v
read_mem $root/bench/bench.mem
read_xdc $root/bench/bench.xdc
synth_design -top cpu_bench -part xc7a35tcpg236-1 -generic MULT=$mult -generic DIV=$div
+333 -92
View File
@@ -99,7 +99,7 @@ L End Enter now it is 10 PRINT "HELLO"
`RENUM` gives the lines new numbers, starting at 10 (or the first number
given) and going up in tens (or the second). It also changes the line numbers
after `GOTO`, `GOSUB`, `THEN`, `RUN` and `ON … GOTO`/`GOSUB` so the program
after `GOTO`, `GOSUB`, `THEN`, `ELSE`, `RUN` and `ON … GOTO`/`GOSUB` so the program
runs as before. A number that isn't a line in the program is left alone.
Numbers inside quotes, `REM` and `DATA` are left as they are, and so is a
line number worked out at run time. If the new numbers would pass 65535, or
@@ -270,6 +270,37 @@ by statements to run. When it is false, the rest of the line is skipped, so
statements after the colon run only when the condition is true. Any non-zero
value counts as true.
`ELSE` gives the line a second part, run only when the condition is false:
```
IF X > 100 THEN 500 ELSE 600
IF A$ = "YES" THEN PRINT "OK": GOTO 20 ELSE PRINT "NO"
IF A THEN IF B THEN PRINT "BOTH" ELSE PRINT "A ONLY" ELSE PRINT "NOT A"
```
An `ELSE` belongs to the nearest `IF` before it that has none yet.
**Block IF.** When `THEN` is the last thing on its line, the statements that
follow, down to `END IF`, are the `THEN` part, and the block can have
`ELSEIF` and `ELSE` parts too:
```
10 IF T < 0 THEN
20 PRINT "FREEZING"
30 C = 1
40 ELSEIF T < 20 THEN
50 PRINT "COOL"
60 ELSE
70 PRINT "WARM"
80 END IF
```
Only the first part whose condition is true runs (or `ELSE`'s, if none is);
then the program carries on after `END IF`. Blocks nest inside each other and
inside loops. `ELSEIF` may be written `ELSE IF`, and `END IF` `ENDIF`. Each
`ELSEIF` must end its line with `THEN`. Block IFs work in a program, not in
a direct statement.
### GOTO, GOSUB, RETURN, ON
```
@@ -304,6 +335,56 @@ NEXT J, I
- Loops nest 16 deep.
- Jumping out of a loop with `GOTO` is allowed. Starting a new `FOR` with the
same variable discards the old loop.
- `EXIT FOR` leaves the innermost loop at once, carrying on after its `NEXT`;
the variable keeps the value it had.
### DO … LOOP — loops on a condition
```
10 DO WHILE I < 10
20 I = I + 1
30 LOOP
10 DO
20 INPUT "GUESS"; G
30 LOOP UNTIL G = 7
```
- `DO WHILE` *condition* runs the loop while the condition is true, testing it
before each time round, so the body may not run at all. `DO UNTIL`
*condition* runs it until the condition is true.
- `LOOP WHILE` and `LOOP UNTIL` test at the end instead, so the body always
runs at least once.
- A plain `DO` … `LOOP` goes round for ever, until `EXIT DO` (or `GOTO`, `END`
or Ctrl-C) leaves it. `EXIT DO` carries on after the `LOOP`.
- Loops nest 16 deep, with `FOR` loops inside and out. A whole loop can be on
one line, or in a direct statement:
`I = 0: DO: I = I + 1: PRINT I: LOOP UNTIL I = 5`.
### SELECT CASE — choosing by value
```
10 SELECT CASE N
20 CASE 0
30 PRINT "NONE"
40 CASE 1, 2, 3
50 PRINT "A FEW"
60 CASE 4 TO 9
70 PRINT "SEVERAL"
80 CASE IS >= 10
90 PRINT "LOTS"
100 CASE ELSE
110 PRINT "LESS THAN NONE"
120 END SELECT
```
`SELECT CASE` works out its value once, then runs the statements under the
first `CASE` that matches it and carries on after `END SELECT`. A `CASE` lists
values, ranges (*low* `TO` *high*) and comparisons (`IS` followed by `<`,
`<=`, `=`, `<>`, `>=` or `>` and a value), separated by commas; any one of
them matching is enough. `CASE ELSE` matches anything, so it goes last. When
no `CASE` matches, nothing runs. The value may be a string, with strings in
the `CASE`s: `CASE "A" TO "M"` compares in alphabetical order, as `<` does.
### DIM — arrays
@@ -338,6 +419,16 @@ in its formula are the program's ordinary variables.
the program. A `DATA` statement takes up the rest of its line. `RESTORE` starts
again from the first item.
### OPTION ANGLE
```
OPTION ANGLE DEGREES
OPTION ANGLE RADIANS
```
Chooses the units of the trigonometric functions (section 6). Radians are
the default, and `RUN` goes back to them.
### END, STOP, REM
- `END` stops the program quietly.
@@ -360,14 +451,15 @@ MONITOR
```
`CALL` runs machine code at *address* as a subroutine, called the standard
RISC-V way: it must end with `RET` and leave `SP`, `GP`, `TP` and `S0`–`S11` as
it found them (`A0`–`A7` and `T0`–`T6` are free to use). `MONITOR` stops BASIC in the
RISC-V way: it must end with `RET` and leave `SP`, `GP`, `TP`, `S0`–`S11` and
the float registers `FS0`–`FS11` as it found them (`A0`–`A7`, `T0`–`T6` and the
other float registers are free to use). `MONITOR` stops BASIC in the
machine-code monitor (section 10). See section 9 for memory and ports.
### Graphics and text placement
`CLS`, `COLOR`, `PLOT`, `LINE`, `RECT`, `FILL`, `CIRCLE`, `LOCATE` and `INK`
are described in sections 7 and 8.
`CLS`, `SCREEN`, `COLOR`, `PLOT`, `LINE`, `RECT`, `FILL`, `CIRCLE`, `LOCATE`
and `INK` are described in sections 7 and 8.
## 6. Functions
@@ -378,16 +470,74 @@ are described in sections 7 and 8.
| `ABS(X)` | Absolute value |
| `SGN(X)` | -1, 0 or 1 |
| `INT(X)` | Largest whole number not above *X*: `INT(-2.5)` is -3 |
| `IP(X)` | The whole-number part, towards 0: `IP(-2.5)` is -2 |
| `FP(X)` | The fraction part, `X - IP(X)`: `FP(-2.5)` is -.5 |
| `CEIL(X)` | Smallest whole number not below *X*: `CEIL(2.1)` is 3 |
| `ROUND(X [, N])` | *X* rounded to *N* decimal places (0 if left out); a negative *N* rounds to tens, hundreds…: `ROUND(2.567, 2)` is 2.57, `ROUND(1250, -2)` is 1300. Halves go up, as `INT(X + .5)` does: `ROUND(-2.5)` is -2 |
| `TRUNCATE(X, N)` | *X* cut short after *N* decimal places: `TRUNCATE(-2.567, 1)` is -2.5 |
| `MOD(A, B)` | Remainder of *A* divided by *B*, with the sign of *B*: `A - B * INT(A / B)`, but exact. `MOD(-7, 3)` is 2 |
| `MIN(A, B, …)`, `MAX(A, B, …)` | Smallest or largest of any number of values |
| `FACT(N)` | *N* factorial, for whole numbers 0 to 34 |
| `SQR(X)` | Square root |
| `EXP(X)` | e to the power *X* |
| `LOG(X)` | Natural logarithm |
| `SIN(X)`, `COS(X)`, `TAN(X)` | Trigonometry, in radians |
| `ATN(X)` | Arctangent, in radians; `4*ATN(1)` is pi |
| `LOG10(X)`, `LOG2(X)` | Logarithm to base 10 or 2 (`LOG2` is exact for powers of 2); powers of 10 are `10 ^ X` |
| `PI` | 3.14159265 (no brackets) |
| `RND` or `RND(X)` | Random number from 0 up to (not including) 1; *X* is ignored |
| `FNx(X)` | A function made with `DEF` |
A whole number from 1 to 6: `1 + INT(RND * 6)`.
### Trigonometry
| Function | Result |
|---|---|
| `SIN(X)`, `COS(X)`, `TAN(X)` | Sine, cosine, tangent |
| `SEC(X)`, `CSC(X)`, `COT(X)` | Secant, cosecant, cotangent: `1/COS(X)`, `1/SIN(X)`, `1/TAN(X)` |
| `ATN(X)` | Arctangent, from -90° to 90° (-π/2 to π/2) |
| `ASIN(X)`, `ACOS(X)` | Arcsine (-90° to 90°) and arccosine (0° to 180°), for *X* from -1 to 1 |
| `ANGLE(X, Y)` | The direction of the point (*X*, *Y*) from the origin, from -180° to 180°, measured anticlockwise from the X axis; it gets the quarter right, as `ATN(Y / X)` can't (other languages call it `ATAN2(Y, X)`) |
| `DEG(X)`, `RAD(X)` | Radians to degrees, degrees to radians |
| `SINH(X)`, `COSH(X)`, `TANH(X)` | Hyperbolic sine, cosine, tangent |
| `ASINH(X)`, `ACOSH(X)`, `ATANH(X)` | Their inverses: `ACOSH` for *X* ≥ 1, `ATANH` for *X* between -1 and 1 |
Angles are in radians until a program says `OPTION ANGLE DEGREES`; from
then on the trigonometric functions take degrees and the inverse ones
(`ATN`, `ASIN`, `ACOS`, `ANGLE`) give degrees. `OPTION ANGLE RADIANS` goes
back, and so does `RUN`. In degrees, `SIN`, `COS` and the rest are exact at
multiples of 90, so `SIN(180)` is 0, not a tiny remainder.
A value outside a function's range, such as `ASIN(2)`, `LOG10(0)`,
`ACOSH(0)`, `FACT(2.5)`, `ANGLE(0, 0)` or, in degrees, `TAN(90)`, stops
the program with `ILLEGAL FUNCTION CALL`; `MOD(A, 0)` is
`DIVISION BY ZERO`. Every function is correct to within 3 units in the last
place of single precision (about 1 part in 3 million), checked against a
PC's double-precision maths by `basic/test-math.py`.
```
10 OPTION ANGLE DEGREES
20 FOR A = 0 TO 75 STEP 15
30 PRINT A, ROUND(SIN(A), 4), ROUND(COS(A), 4), ROUND(TAN(A), 4)
40 NEXT A
50 PRINT "BEARING OF (3, 4):"; ROUND(ANGLE(3, 4), 2); "DEGREES"
60 PRINT "ITS HYPOTENUSE:"; SQR(3^2 + 4^2)
70 PRINT "ACOS(-1) ="; ACOS(-1); " 20! ="; FACT(20)
```
prints
```
0 0 1 0
15 .2588 .9659 .2679
30 .5 .866 .5774
45 .7071 .7071 1
60 .866 .5 1.7321
75 .9659 .2588 3.7321
BEARING OF (3, 4): 53.13 DEGREES
ITS HYPOTENUSE: 5
ACOS(-1) = 180 20! = 2.4329E+18
```
### Strings
| Function | Result |
@@ -400,6 +550,20 @@ A whole number from 1 to 6: `1 + INT(RND * 6)`.
| `LEFT$(A$, N)` | First *N* characters |
| `RIGHT$(A$, N)` | Last *N* characters |
| `MID$(A$, S [, N])` | *N* characters (or the rest) starting at position *S* (from 1) |
| `UCASE$(A$)` | The string in capitals: only `a`–`z` change |
| `LCASE$(A$)` | The string in small letters: only `A`–`Z` change |
BASIC turns what you type into capitals outside quotes, but text that comes
from `INPUT`, a file or `CHR$` keeps its case. `UCASE$` is the way to compare
an answer whatever case it was typed in, `IF UCASE$(A$) = "YES" THEN …`, and
the two together tidy a name:
```
10 INPUT "YOUR NAME"; N$
20 PRINT "HELLO, "; UCASE$(LEFT$(N$, 1)); LCASE$(MID$(N$, 2))
```
typed `aDA LOVELACE`, prints `HELLO, Ada lovelace`.
### Machine and screen
@@ -408,7 +572,7 @@ A whole number from 1 to 6: `1 + INT(RND * 6)`.
| `TIM` | Seconds since the computer was reset, to the millisecond |
| `DATE$` | The date and time as `"2026-11-28 09:30:15"`, or `""` if not set (section 11) |
| `EOF(N)` | -1 (true) when file *N* has been read to the end, else 0 (section 11) |
| `POINT(X, Y)` | Colour of the graphics pixel at *X, Y* (0 off screen) |
| `POINT(X, Y)` | Colour of the graphics pixel at *X, Y* (0 off screen; 0 or 1 in `SCREEN 1`) |
| `PEEK(A)` | Byte at memory address *A* |
| `INP(P)` | Byte from I/O port *P* |
@@ -421,11 +585,12 @@ A whole number from 1 to 6: `1 + INT(RND * 6)`.
## 7. Graphics
The screen has a graphics layer **320 pixels wide and 240 high in 16 colours**.
It is mixed with the 80×30 text:
The screen has a graphics layer **320 pixels wide and 240 high in 16 colours**,
or, after `SCREEN 1`, **640 by 480 in two** (see below). It is mixed with the
text:
- **Coordinates:** *X* runs from 0 at the left to 319, and *Y* from 0 at the
top to 239. Each graphics pixel is a 2×2 block on the monitor.
top to 239. Each graphics pixel is a 4×4 block on the monitor.
- **Mixing with text:** text characters are drawn on top of the graphics. The
graphics show through wherever the text screen is blank.
- **Colour 0** is "no graphics": it shows the text background, normally black.
@@ -477,6 +642,34 @@ by `COLOR` is used, initially 15 (white).
70 RECT 20, 120, 300, 230, 7
```
### 640 × 480 in two colours
The same graphics memory holds 640 × 480 pixels at one bit each, twice the
detail across and down in two colours:
| Statement | |
|---|---|
| `SCREEN 1 [, S [, C]]` | 640 × 480: *X* 0–639, *Y* 0–479, each pixel a 2×2 block on the monitor. Set pixels show in colour *S* (15, white, if left out), clear ones in *C* (0, transparent, if left out) |
| `SCREEN 0` | Back to 320 × 240 in 16 colours (the mode at power-up) |
Both clear the graphics. In `SCREEN 1` every drawing statement sets pixels
in any colour but 0 and clears them in colour 0, so `COLOR`, `PLOT`, `LINE`,
`RECT`, `FILL` and `CIRCLE` work unchanged; `POINT` gives 1 or 0. `CLS` clears
the graphics and stays in the mode. With a clear colour other than 0 the whole
picture area is that colour, under the text.
```
10 SCREEN 1, 10
20 FOR A = 0 TO 6.28 STEP .02
30 LINE 320, 240, 320 + 300*COS(A), 240 + 230*SIN(3*A)
40 NEXT A
```
The mode doesn't scroll (the scroll registers and the border are ignored).
Sprites still work, on the 320 × 240 grid, and a sprite counts as touching
the graphics where a set pixel is within the 4 × 1 group of pixels under it. A
game started with `CALL` goes back to 320 × 240; BASIC notices.
### Animation
Erase something by drawing it again in colour 0, then draw it in its new
@@ -596,9 +789,11 @@ the numbers (see section 9).
## 8. The text screen
The text screen is 80 columns by 32 rows; `PRINT CHR$(27);"[?3h"` switches to
132 columns by 64 rows in a smaller font (and clears it), `CHR$(27);"[?3l"`
back. Two statements place and colour text:
The text screen starts at 132 columns by 64 rows in the 8×16 font.
`PRINT CHR$(27);"[?3l"` switches to 80 columns by 32 rows in a font twice the
size (and clears it), `CHR$(27);"[?3h"` back to 132; `INP(0) AND 4` is 4 at
132 columns. The line editor follows the change, and the games play at 80
columns and put the screen back as they found it. Two statements place and colour text:
| Statement | Does |
|---|---|
@@ -654,15 +849,17 @@ compare value, 10h and 14h the monitor's breakpoint addresses.
| Port | `INP` | `OUT` |
|---|---|---|
| 0 | bit 0: a key is waiting; bit 1: the screen can take a character | — |
| 0 | bit 0: a key is waiting; bit 1: the screen can take a character; bit 2: the screen is 132 columns wide | — |
| 1 | the waiting key | a character to the screen |
| 16–19 | the millisecond counter, low byte first (reading 16 freezes the other three) | — |
| 32 | — | right two digits of the 7-segment display (hex) |
| 33 | — | left two digits of the 7-segment display |
| 48, 49, 50 | — | graphics X (low byte, high bit), Y |
| 51 | colour at X, Y | plot a pixel at X, Y and move right |
| 52 | bit 0: screen fill in progress | fill the whole graphics layer with a colour; also hides the sprites and resets the scroll, unless 128 is added |
| 48, 49, 50 | — | graphics X low byte; X bits 8–9 (1, 2) and Y bit 8 (4); Y low byte |
| 51 | colour at X, Y (0 or 1 in 640 × 480) | plot a pixel at X, Y and move right (in 640 × 480 any colour but 0 sets it) |
| 52 | bit 0: screen fill in progress | fill the whole graphics layer with a colour; also hides the sprites, resets the scroll and goes back to 320 × 240, unless 128 is added |
| 53, 54, 55 | — | graphics scroll and border (section 7) |
| 56 | bit 0: 640 × 480 mode | 1: 640 × 480 in two colours, 0: 320 × 240 in 16 |
| 57 | — | 640 × 480 colours: set pixels' colour + 16 × clear pixels' colour |
| 64 | bit 0: flash byte in progress; bit 1: last flash command refused | 1 selects the flash and starts a command, 0 ends it |
| 65 | the byte the flash sent back during the last `OUT 65` | a byte to the flash |
| 96 | why the monitor was entered (used by the monitor) | single step (used by the monitor) |
@@ -761,19 +958,21 @@ each voice, so a note or a bang fades away by itself.
### Speed
The processor is a 32-bit RISC-V (RV32IM: the base instructions plus
multiply and divide) running at 90 MHz. Most instructions take 2 clocks; loads,
stores, jumps and taken branches 3, a multiply 4 and a divide 35, which comes to
about 2.5 clocks per instruction in BASIC, some 36 million instructions a
second. BASIC does its floating-point arithmetic in software, so in round
numbers:
The processor is a 32-bit RISC-V (RV32IMF: the base instructions, multiply
and divide, and single-precision floating point) running at 100 MHz. Most
instructions take 2 clocks; loads, stores, jumps and taken branches 3, a
multiply 4 and a divide 35, which comes to about 2.5 clocks per instruction in
BASIC, some 40 million instructions a second. Its floating-point unit adds,
subtracts and multiplies in 13 clocks and divides or takes a square root in 37,
correctly rounded. In round numbers:
| Operation | Time |
|---|---|
| One pass of an empty `FOR … NEXT` loop | 9 µs (about 100,000 a second) |
| `X = I * 1.5` | 43 µs |
| `Y = SIN(X)` | 85 µs |
| `LINE` right across the screen | 0.2 ms |
| One pass of an empty `FOR … NEXT` loop | 6.4 µs (about 150,000 a second) |
| `X = I * 1.5` | 23 µs |
| `Y = SIN(X)` | 33 µs |
| `Y = EXP(1)` | 33 µs |
| `LINE` right across the screen | 0.12 ms |
Constants in a program are converted from text every time they are used, so a
loop runs a little faster if a constant used inside it is put into a variable
@@ -807,9 +1006,9 @@ graphics come back exactly as they were.
T1 00000000 T2 00000000 S0 00013FB0 S1 0000A01E A0 00000000 A1 00012000
...
ADDR WORD INSTRUCTION STACK
>*12000 04100513 LI A0,65 13F70 00000000
12004 F0A000A3 SB A0,-255(ZERO) 13F74 0000A01E
12008 00008067 RET ...
>*12000 04100513 li a0,65 13F70 00000000
12004 F0A000A3 sb a0,-255(zero) 13F74 0000A01E
12008 00008067 ret ...
MEMORY
12000 13 05 10 04 A3 00 A0 F0-67 80 00 00 00 00 00 00 ....g...........
```
@@ -822,7 +1021,8 @@ graphics come back exactly as they were.
### Commands
Type a command on the bottom line and press Enter. Numbers are in hex.
Type a command on the bottom line and press Enter. Numbers are in hex, with
or without `0x`.
| Command | Does |
|---|---|
@@ -835,10 +1035,11 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
| `D addr` | Show the disassembly from *addr* (`D` alone: from PC) |
| `M addr` | Show memory from *addr* |
| `E addr bytes…` | Write bytes into memory: `E 12000 13 05 10 04` |
| `R reg=value` | Set PC or a register, by name or number: `R A0=1234`, `R X10=1234` |
| `R reg=value` | Set PC or a register, by name or number: `R A0=1234`, `R X10=1234`; a float register as its bit pattern: `R F1=3FC00000` (1.5), or `R FCSR=0` |
| `F` | Show the float registers F0–F31 and FCSR, as bit patterns, in the memory window (`M` brings the memory back) |
| `SAVE "NAME" start end` | Save memory *start* to *end* (inclusive) to a file in flash |
| `LOAD "NAME"` | Load a memory file back to where it was saved from |
| `LOAD "NAME" addr` | Load it at *addr* instead (0A000h or above) |
| `LOAD "NAME" addr` | Load it at *addr* instead (A000 or above) |
| `DIR` | List the files in flash in the memory window (`M` brings the memory back) |
| `ASM "NAME"` | Assemble a source file into memory (see the assembler, below) |
| `A addr` | Assemble lines as you type them, from *addr*; an empty line ends |
@@ -854,10 +1055,14 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
itself, the monitor first steps past it.
- **Memory below 0A000h** is BASIC's ROM and can be viewed but not changed. `E`
says so if you try.
- **The disassembler** shows every RV32IM instruction and the CSR and system
instructions, using the usual short forms where they apply (`LI`, `MV`, `J`,
`RET`, `BEQZ`, `CSRR` and so on), with hex numbers like `1F0H` and `0A200H`;
anything else is shown as `DW` and its value.
- **The float registers** are saved and put back like the others, while the
FPU is on (`mstatus.FS`, which BASIC turns on); `F` says when it is off.
- **The disassembler** shows every RV32IMF instruction and the CSR and system
instructions the way GNU `objdump` does: in lower case, with the usual
short forms where they apply (`li`, `mv`, `j`, `ret`, `beqz`, `csrr` and so
on), hex numbers like `0x1f0`, and the float registers by their ABI names
(`fa0`, `ft1`). Anything else is shown as `.word` and its value. What it
shows, the assembler reads back.
### A machine-code example
@@ -868,8 +1073,8 @@ RUN
MONITOR
```
The `POKE`s put `LI A0,65 : SB A0,-255(ZERO) : RET` at 12000h; it prints an
`A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`.
The `POKE`s put `li a0,65`, `sb a0,-255(zero)` and `ret` at 0x12000; it
prints an `A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`.
Back in BASIC, `CALL 73728` stops at the breakpoint. Press Enter to step
through each instruction, or `X` to let it finish.
@@ -878,80 +1083,110 @@ through each instruction, or `X` to let it finish.
The monitor can assemble RISC-V source code into memory, either a whole file
or one line at a time.
**Writing source.** Type it into BASIC as numbered lines, just like a
program, and save it. BASIC doesn't run it; it just keeps the lines. The
assembler ignores the line numbers, and uses them in its error messages.
**Writing source.** The assembler reads the GNU assembler's RISC-V syntax,
as in the RISC-V manuals and `gcc -S` output. Type the source into BASIC as
numbered lines, just like a program, and save it. BASIC doesn't run it; it
just keeps the lines. The assembler ignores the line numbers, and uses them
in its error messages.
```
NEW
10 ; PRINT A MESSAGE
20 ORG 12000H
30 START: LA A1,MSG
40 LOOP: LBU A0,0(A1)
50 BEQZ A0,DONE
60 WAIT: LBU T0,-256(ZERO) ; CAN THE SCREEN TAKE A CHARACTER?
70 ANDI T0,T0,2
80 BEQZ T0,WAIT
90 SB A0,-255(ZERO)
100 ADDI A1,A1,1
110 J LOOP
120 DONE: RET
130 MSG: DB "HELLO FROM ASSEMBLY",13,10,0
10 # print a message
20 .org 0x12000
30 start: la a1, msg
40 loop: lbu a0, 0(a1)
50 beqz a0, done
60 wait: lbu t0, -256(zero) # can the screen take a character?
70 andi t0, t0, 2
80 beqz t0, wait
90 sb a0, -255(zero)
100 addi a1, a1, 1
110 j loop
120 done: ret
130 msg: .string "Hello from assembly\r\n"
SAVE "HELLO"
```
A text file sent from the PC with `tools/send-bas.py` works the same way, as
long as each line starts with a number.
BASIC stores what you type in capitals, except inside double quotes, so
`LIST` shows `30 START: LA A1, MSG`. The assembler doesn't mind either way,
but a character constant changes: `'a'` becomes `'A'`. BASIC also drops the
spaces after the line number, so a label needs its colon. And BASIC knows
nothing of `\"`, so a string can't contain a double quote; use `.byte 34`.
**Assembling.** `MONITOR`, then `ASM "HELLO"`. The monitor says
`ASSEMBLED 12000-12041` and shows the code; errors are listed in the memory
window with their line numbers. Back in BASIC (`X`), `CALL 73728` runs it.
Or set a breakpoint first and step through it.
**One line at a time.** `A 12100` starts the line assembler at 12100h: type
**One line at a time.** `A 12100` starts the line assembler at 0x12100: type
an instruction, press Enter, and it is assembled and shown, then the next
address is offered. An empty line ends. Labels from the last `ASM` can be used.
**Syntax**: as the disassembler shows it.
**Syntax**: GNU as's, which is also what the disassembler shows.
| | |
|---|---|
| Labels | `NAME:` before an instruction, up to 8 letters and digits; `NAME EQU value` for constants |
| Numbers | `123`, `0FFH`, `$FF`, `0x1F`, `1010B`, `'A'`; `$` alone is the current address |
| Expressions | `+ - * / & |` and brackets: `LI A0,END-START`, `LI A1,'Z'-1` |
| Registers | `X0`–`X31` or `ZERO RA SP GP TP T0`–`T6 S0`–`S11 FP A0`–`A7` |
| Memory operands | *offset*`(`*register*`)`: `LW A0,8(SP)`, `SB A0,-255(ZERO)`, `LBU T0,(A1)` |
| CSRs | by name (`MSTATUS`, `MEPC`, `MCAUSE`, `CYCLE`, `TIME`, `INSTRET`, …) or number |
| `ORG addr` | assemble from *addr* (12000h if there is no `ORG`) |
| `DB` / `DEFB` / `DEFM` | bytes and `"strings"`: `DB "HI",13,10,0` |
| `DH` | 16-bit halfwords, low byte first |
| `DW` / `DEFW` | 32-bit words, low byte first |
| `DS n` / `DEFS n` | skip *n* bytes |
| `ALIGN n` | skip to a multiple of *n* (instructions must be on a multiple of 4) |
| `END` | stop here |
| `;` | comment to the end of the line |
| Labels | `name:` before an instruction, or on a line of its own; letters, digits, `_` and `.`, of which the first 8 count |
| Constants | `.equ name, value`, `.set name, value` or `name = value` |
| Numbers | `123`, `0x1f`, `0b1010`, `'A'`, `'\n'`; `.` is the current address |
| Expressions | <code>+ - * / &amp; &#124; ^ &lt;&lt; &gt;&gt; ~</code> and brackets: `li a0, end - start`, `li a1, 'Z' - 1`; `%hi(x)` and `%lo(x)` split an address for `lui` and `addi`, or a load or store: `lui a5, %hi(table)` then `lw a0, %lo(table)(a5)` |
| Registers | `x0`–`x31` or `zero ra sp gp tp t0`–`t6 s0`–`s11 fp a0`–`a7` |
| Memory operands | *offset*`(`*register*`)`: `lw a0, 8(sp)`, `sb a0, -255(zero)`, `lbu t0, (a1)` |
| CSRs | by name (`mstatus`, `mepc`, `mcause`, `cycle`, `time`, `instret`, …) or number |
| `.org addr` | assemble from *addr* (0x12000 if there is no `.org`) |
| `.byte` | bytes: `.byte 13, 10, 'A'` |
| `.half` / `.short` | 16-bit halfwords, low byte first |
| `.word` / `.long` | 32-bit words, low byte first: `.word start, 0x12345678` |
| `.ascii "text"` | the characters of the text; `\n`, `\r`, `\t`, `\0`, `\\` and `\"` stand for a line feed, return, tab, 0, `\` and `"` |
| `.string "text"` / `.asciz "text"` | the same with a 0 after it |
| `.space n` / `.skip n` / `.zero n` | *n* bytes of 0, or of *fill* with `.space n, fill` |
| `.align n` / `.p2align n` | to a multiple of 2*ⁿ*: `.align 2` for a word. The gap is filled with zeros up to a word, then `nop`s, so code can run through it; `.align n, fill` fills it with *fill* |
| `.balign n` | to a multiple of *n* bytes |
| `.end` | stop here |
| `.text`, `.data`, `.section`, `.globl`, `.global`, `.option`, `.type` | accepted and ignored, so code written for GNU as needn't be changed |
| `#` or `;` | comment to the end of the line |
- **Instructions:** all of RV32I and M, `CSRRW`…`CSRRCI`, `ECALL`, `EBREAK`,
`MRET`, `MNRET`, `WFI`, `FENCE`, `FENCE.I`, and the short forms `NOP`, `LI`,
`LA`, `MV`, `NOT`, `NEG`, `SEQZ`, `SNEZ`, `SLTZ`, `SGTZ`, `J`, `JR`, `JAL`
*target* (saving RA), `JALR` *register*, `RET`, `CALL`, `BEQZ`, `BNEZ`,
`BLEZ`, `BGEZ`, `BLTZ`, `BGTZ`, `BGT`, `BLE`, `BGTU`, `BLEU`, `CSRR`, `CSRW`,
`CSRS`, `CSRC`, `CSRWI`, `CSRSI`, `CSRCI`.
- **`LI`** is one instruction (`ADDI`) for a value from −2048 to 2047 that is
known by then, otherwise two (`LUI`, `ADDI`); **`LA`** is always two
(`AUIPC`, `ADDI`); **`CALL`** is `JAL RA`, which reaches 1 MB either way.
- **Where code can go:** RAM from 0A000h up. 12000h–12FFFh is the safe place,
since BASIC doesn't use it.
The assembler of earlier versions used other spellings, and sources written
for it still assemble: `ORG`, `NAME EQU value`, `DB`/`DEFB`/`DEFM` (with
strings taken as they are, no escapes), `DH`, `DW`/`DEFW`, `DS n`/`DEFS n`
(skip *n* bytes), `ALIGN n` (to a multiple of *n*), `END`, numbers like
`0FFH`, `$FF` and `1010B`, and `$` for the current address.
- **Instructions:** all of RV32I and M, `csrrw`…`csrrci`, `ecall`, `ebreak`,
`mret`, `mnret`, `wfi`, `fence`, `fence.i`, and the short forms `nop`, `li`,
`la`, `mv`, `not`, `neg`, `seqz`, `snez`, `sltz`, `sgtz`, `j`, `jr`, `jal`
*target* (saving `ra`), `jalr` *register*, `ret`, `call`, `beqz`, `bnez`,
`blez`, `bgez`, `bltz`, `bgtz`, `bgt`, `ble`, `bgtu`, `bleu`, `csrr`,
`csrw`, `csrs`, `csrc`, `csrwi`, `csrsi`, `csrci`.
- **Floating point:** `flw`, `fsw`, `fadd.s`, `fsub.s`, `fmul.s`, `fdiv.s`,
`fsqrt.s`, `fmadd.s`, `fmsub.s`, `fnmsub.s`, `fnmadd.s`, `fmin.s`, `fmax.s`,
`fsgnj.s`, `fsgnjn.s`, `fsgnjx.s` (and `fmv.s`, `fneg.s`, `fabs.s`),
`feq.s`, `flt.s`, `fle.s`, `fcvt.w.s`, `fcvt.wu.s`, `fcvt.s.w`, `fcvt.s.wu`,
`fmv.x.w`, `fmv.w.x`, `fclass.s`. Float registers are `f0`–`f31` or
`ft0`–`ft11`, `fs0`–`fs11`, `fa0`–`fa7`; a rounding mode (`rne`, `rtz`,
`rdn`, `rup`, `rmm`) may follow the operands, `fadd.s fa0, fa1, fa2, rtz`,
and without one the instruction uses FCSR's (round to nearest unless
changed). CSRs `fflags`, `frm` and `fcsr`, and the short forms `frcsr`,
`fscsr`, `frrm`, `fsrm`, `frflags`, `fsflags`.
- **`li`** is one instruction (`addi`) for a value from −2048 to 2047 that is
known by then, `lui` alone for one whose low 12 bits are 0, otherwise two
(`lui`, `addi`); **`la`** is always two (`auipc`, `addi`). **`call`** is
`jal ra`, which reaches 1 MB either way (GNU as makes it `auipc` and
`jalr`, 8 bytes, to reach anywhere).
- **Where code can go:** RAM from 0xA000 up. 0x12000–0x12FFF is the safe
place, since BASIC doesn't use it.
- **Labels:** up to 200.
- **Typing source into BASIC:** BASIC turns lower case to upper case (except
inside double quotes), so `'a'` becomes `'A'`. Indentation after the line
number isn't kept, so labels need their colon.
**Errors:** `UNKNOWN INSTRUCTION`, `BAD REGISTER`, `MISSING OPERAND`, `TOO
MANY OPERANDS`, `OFFSET(REGISTER)`, `UNDEFINED LABEL`, `DUPLICATE LABEL`,
`VALUE OUT OF RANGE` (an immediate, offset or `LUI` value that doesn't fit),
`VALUE OUT OF RANGE` (an immediate, offset or `lui` value that doesn't fit),
`BRANCH TOO FAR` (beyond ±4 KB), `JUMP TOO FAR` (beyond ±1 MB), `NOT ON A
WORD: USE ALIGN 4`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`.
WORD: USE .ALIGN 2`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`,
`BAD STRING` (`.ascii` or `.string` without a string), `ALIGN TO A POWER OF
2`, `EQU NEEDS A NAME`.
### How it works
@@ -1174,13 +1409,19 @@ An error stops the program and reports the line, for example
| `NEXT WITHOUT FOR` | `NEXT` with no loop open (or the wrong variable) |
| `OUT OF DATA` | `READ` after the last `DATA` item |
| `SUBSCRIPT OUT OF RANGE` | An array subscript below 0 or beyond its `DIM` |
| `DIVISION BY ZERO` | Dividing by 0 |
| `DIVISION BY ZERO` | Dividing by 0, or `MOD(A, 0)` |
| `OUT OF MEMORY` | The program and arrays don't fit |
| `TYPE MISMATCH` | A string where a number belongs, or the other way round |
| `STRING TOO LONG` | A string over 79 characters, or a program line too long to store (also from `RENUM`) |
| `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE`, a `RENUM` past 65535 or with a step of 0 |
| `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, `ASIN(2)`, `FACT(-1)` (section 6), a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE`, a `RENUM` past 65535 or with a step of 0 |
| `UNDEFINED FUNCTION` | `FNx` used before its `DEF` |
| `FOR NESTED TOO DEEPLY` | More than 16 loops open |
| `FOR NESTED TOO DEEPLY` | More than 16 `FOR` loops open |
| `DO NESTED TOO DEEPLY` | More than 16 `DO` loops open |
| `FOR WITHOUT NEXT` | A `FOR` that runs no times, or `EXIT FOR`, with no `NEXT` after it |
| `DO WITHOUT LOOP` | A `DO` whose condition fails, or `EXIT DO`, with no `LOOP` after it |
| `LOOP WITHOUT DO` | `LOOP` or `EXIT DO` with no `DO` loop open |
| `IF WITHOUT END IF` | A block `IF` (or its `ELSE`) with no `END IF` after it |
| `SELECT WITHOUT END SELECT` | A `SELECT CASE` (or its `CASE`) with no `END SELECT` after it |
| `GOSUB NESTED TOO DEEPLY` | More than 32 subroutines in progress |
| `FILE NOT FOUND` | `LOAD`, `RUN` or `DEL` of a name not in `DIR` |
| `BAD FILE NAME` | A name that is empty, longer than 8 or not just letters and digits |
@@ -1391,7 +1632,7 @@ while keeping the cave connected, mirrored and free of dead ends
| Arrays | A–Z, 1 or 2 subscripts, up to 6000 elements each |
| User functions | FNA–FNZ, one argument each |
| FOR nesting / GOSUB nesting | 16 / 32 |
| Graphics | 320 × 240, 16 colours |
| Graphics | 320 × 240 in 16 colours, or 640 × 480 in 2 |
| Sprites | 32 on screen, 64 shapes, 16 × 16 pixels each |
| Text | 80 × 32, or 132 × 64 |
| Files in flash | 64, 1,784 KB in all, 32 KB each |
Binary file not shown.
+2 -2
View File
@@ -8,11 +8,11 @@ source ../scripts/rv_env.sh
G=$1
mkdir -p $G/out
python3 $G/gen.py $G/out/data.h
CFLAGS="$RV_ARCH -Os -mno-relax -ffunction-sections -fdata-sections -fno-common -Wall -I../include -I$G/out"
CFLAGS="$RV_ARCH_F -ffp-contract=off -Os -mno-relax -ffunction-sections -fdata-sections -fno-common -Wall -I../include -I$G/out"
${RV_PREFIX}gcc $CFLAGS -c -o $G/out/crt0.o crt0.S
${RV_PREFIX}gcc $CFLAGS -c -o $G/out/$G.o $G/$G.c
${RV_PREFIX}gcc $CFLAGS -c -o $G/out/string.o ../lib/string.c
${RV_PREFIX}gcc $RV_ARCH -nostdlib -nostartfiles -T game.ld -Wl,--no-relax -Wl,--gc-sections \
${RV_PREFIX}gcc $RV_ARCH_F -nostdlib -nostartfiles -T game.ld -Wl,--no-relax -Wl,--gc-sections \
-Wl,--build-id=none -Wl,--no-warn-rwx-segments -Wl,-Map,$G/out/$G.map -o $G/out/$G.elf $G/out/crt0.o $G/out/$G.o $G/out/string.o -lgcc
${RV_PREFIX}objcopy -O ihex -j .text -j .data $G/out/$G.elf $G/$G.ihx
${RV_PREFIX}nm -n $G/out/$G.elf > $G/out/$G.sym
+3 -1
View File
@@ -637,6 +637,7 @@ int main(void)
{
rnd_state = 0x1980 ^ frame_ctr;
last_frame = frame_ctr;
u8 was_wide = con_stat & 4; /* 132 columns before the game? */
puts_("\033[?3l\033[?25l");
load_shapes();
quit = 0;
@@ -645,6 +646,7 @@ int main(void)
play();
}
clear_all();
puts_("\033[0m\033[2J\033[H\033[?25h");
puts_(was_wide ? "\033[0m\033[?3h\033[?25h" /* back to 132 columns (this clears) */
: "\033[0m\033[2J\033[H\033[?25h");
while (con_stat & 1) (void)con_data;
}
+590 -587
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -5,7 +5,7 @@
python3 test-cavern.py [--shots DIR] [--play]
It checks the title screen, measures the Z-80 instructions each frame takes
(a 60 Hz frame has about 550,000 at 90 MHz), checks that walls stop the miner,
(a 60 Hz frame has about 610,000 at 100 MHz), checks that walls stop the miner,
that crystals score and that the bats leave the roost, and with --play lets
an autopilot gather every crystal in the cave by breadth-first search. The
autopilot can't be caught (it keeps the miner shielded), so this checks the
+3 -1
View File
@@ -632,6 +632,7 @@ int main(void)
{
rnd_state = 0xACE1 ^ frame_ctr;
last_frame = frame_ctr;
u8 was_wide = con_stat & 4; /* 132 columns before the game? */
puts_("\033[?3l\033[?25l"); /* 80 columns (this clears), no cursor */
load_shapes();
quit = 0;
@@ -642,6 +643,7 @@ int main(void)
if (!end_screen()) break;
}
clear_gfx();
puts_("\033[0m\033[2J\033[H\033[?25h");
puts_(was_wide ? "\033[0m\033[?3h\033[?25h" /* back to 132 columns (this clears) */
: "\033[0m\033[2J\033[H\033[?25h");
while (con_stat & 1) (void)con_data;
}
+812 -809
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -683,6 +683,7 @@ int main(void)
{
rnd_state = 0xBEEF ^ frame_ctr;
last_frame = frame_ctr;
u8 was_wide = con_stat & 4; /* 132 columns before the game? */
puts_("\033[?3l\033[?25l");
load_shapes();
quit = 0;
@@ -691,6 +692,7 @@ int main(void)
play();
}
clear_all();
puts_("\033[0m\033[2J\033[H\033[?25h");
puts_(was_wide ? "\033[0m\033[?3h\033[?25h" /* back to 132 columns (this clears) */
: "\033[0m\033[2J\033[H\033[?25h");
while (con_stat & 1) (void)con_data;
}
+597 -594
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -5,7 +5,7 @@ and take screenshots.
python3 test-raid.py [--shots DIR] [--play]
It checks the title screen, measures the Z-80 instructions each frame takes
(a 60 Hz frame has about 550,000 at 90 MHz), flies into the fortress, and with
(a 60 Hz frame has about 610,000 at 100 MHz), flies into the fortress, and with
--play lets an autopilot fly the whole level: it steers through every doorway
at the right height, climbs over low walls and shoots ahead. The autopilot
can't be hit by shells or fighters (it keeps the ship invulnerable), so this
@@ -57,7 +57,7 @@ def main():
c0 = b.steps
b.run_frames(60)
per = (b.steps - c0) / 60
print("%.0f instructions a frame (%.0f%% of a 60 Hz frame at 90 MHz)" % (per, per / 5500))
print("%.0f instructions a frame (%.0f%% of a 60 Hz frame at 100 MHz)" % (per, per / 6100))
check("a frame fits in a 60th of a second", per < 500000)
if a.shots: b.shot(os.path.join(a.shots, "2-approach.png"), font)
alt0 = b.m[sym["_alt"]]
+3 -1
View File
@@ -641,6 +641,7 @@ int main(void)
u8 i;
rnd_state = 0x1979 ^ frame_ctr;
last_frame = frame_ctr;
u8 was_wide = con_stat & 4; /* 132 columns before the game? */
puts_("\033[?3l\033[?25l");
load_shapes();
for (i = 0; i < NST; i++) { st_x[i] = rnd() % 304; st_y[i] = rnd() % 240; st_v[i] = 1 + (i & 1); }
@@ -650,6 +651,7 @@ int main(void)
play();
}
clear_all();
puts_("\033[0m\033[2J\033[H\033[?25h");
puts_(was_wide ? "\033[0m\033[?3h\033[?25h" /* back to 132 columns (this clears) */
: "\033[0m\033[2J\033[H\033[?25h");
while (con_stat & 1) (void)con_data;
}
+550 -548
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -5,7 +5,7 @@ and take screenshots.
python3 test-swarm.py [--shots DIR] [--play]
It checks the title screen, measures the Z-80 instructions each frame takes
(a 60 Hz frame has about 550,000 at 90 MHz), checks that the formation sways
(a 60 Hz frame has about 610,000 at 100 MHz), checks that the formation sways
and that aliens dive, shoots one out of the formation, and with --play lets an
autopilot clear the whole swarm. The autopilot can't be killed (it keeps the
ship shielded), so this checks the rules and the waves, not its skill.
+1 -1
View File
@@ -5,7 +5,7 @@ and take screenshots.
python3 test-warden.py [--shots DIR] [--play]
It checks the title screen, measures the Z-80 instructions each frame takes
(a 60 Hz frame has about 550,000 at 90 MHz), flies along the planet checking
(a 60 Hz frame has about 610,000 at 100 MHz), flies along the planet checking
that the picture scrolls and the scanner fills in, and with --play lets an
autopilot hunt down every enemy until the wave is cleared. The autopilot
can't be killed (it keeps the ship shielded), so this checks the rules and the
+3 -1
View File
@@ -803,6 +803,7 @@ int main(void)
{
rnd_state = 0x2084 ^ frame_ctr;
last_frame = frame_ctr;
u8 was_wide = con_stat & 4; /* 132 columns before the game? */
puts_("\033[?3l\033[?25l");
load_shapes();
quit = 0;
@@ -811,6 +812,7 @@ int main(void)
play();
}
clear_all();
puts_("\033[0m\033[2J\033[H\033[?25h");
puts_(was_wide ? "\033[0m\033[?3h\033[?25h" /* back to 132 columns (this clears) */
: "\033[0m\033[2J\033[H\033[?25h");
while (con_stat & 1) (void)con_data;
}
+757 -755
View File
File diff suppressed because it is too large. Load diff
+140 -2
View File
@@ -1,7 +1,9 @@
/* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf
floorf. Range reduction by Cody and Waite, minimax polynomials as in the
floorf, and from them asinf acosf atan2f sinhf coshf tanhf asinhf acoshf
atanhf log1pf log10f log2f and an exact fmodf. Range reduction by Cody and Waite, minimax polynomials as in the
Cephes library; good to an ulp or two, which BASIC's 6-7 printed digits
don't show. sqrtf and floorf are exact. (newlib's versions are larger and
don't show. sqrtf (the FPU's FSQRT.S when there is one) and floorf are
exact. (newlib's versions are larger and
bring in errno, stdio and malloc.) */
#include <math.h>
#include <stdint.h>
@@ -141,6 +143,10 @@ float logf(float x)
/* exact: one bit at a time (after fdlibm) */
float sqrtf(float x)
{
#ifdef __riscv_flen
__asm__("fsqrt.s %0, %1" : "=f"(x) : "f"(x)); /* the FPU's, correctly rounded */
return x;
#else
fbits u = { x };
int32_t ix = (int32_t)u.i, m, i;
uint32_t q, s, r, t;
@@ -167,6 +173,7 @@ float sqrtf(float x)
if (ix) q += q & 1;
u.i = (q >> 1) + 0x3F000000 + ((uint32_t)m << 23);
return u.f;
#endif
}
float floorf(float x)
@@ -184,3 +191,134 @@ float floorf(float x)
else if (u.i << 1) u.f = -1.0f;
return u.f;
}
/* ------------------------------------------------- built on the above */
static const float PI_F = 3.14159265358979f, LN2_F = 0.693147180559945f;
/* log(1 + u), accurate for small u: Goldberg's trick, since w - 1 is exact */
float log1pf(float u)
{
float w = 1.0f + u;
if (w == 1.0f) return u;
return logf(w) * (u / (w - 1.0f));
}
float asinf(float x) /* |x| <= 1 */
{
return atanf(x / sqrtf((1.0f - x) * (1.0f + x)));
}
float acosf(float x) /* |x| <= 1 */
{
return 2.0f * atanf(sqrtf((1.0f - x) / (1.0f + x)));
}
float atan2f(float y, float x)
{
float a;
if (x == 0.0f) return y > 0 ? PI_F / 2 : y < 0 ? -PI_F / 2 : 0.0f;
a = atanf(y / x);
if (x < 0) a += y < 0 ? -PI_F : PI_F;
return a;
}
/* e^|x| / 2 for large |x|, without overflowing on the way */
static float half_exp(float a)
{
float h = expf(0.5f * a);
return (0.5f * h) * h;
}
float sinhf(float x)
{
float a = x < 0 ? -x : x, r, z, e;
if (a < 1.0f) { /* the series: no cancellation */
z = a * a;
r = a + a * z * (1.6666667163e-1f + z * (8.3333337680e-3f + z * (1.9841270114e-4f
+ z * (2.7557318845e-6f + z * 2.5052108385e-8f))));
} else if (a < 10.0f) {
e = expf(a);
r = 0.5f * (e - 1.0f / e);
} else r = half_exp(a);
return x < 0 ? -r : r;
}
float coshf(float x)
{
float a = x < 0 ? -x : x, e;
if (a >= 10.0f) return half_exp(a);
e = expf(a);
return 0.5f * (e + 1.0f / e);
}
float tanhf(float x)
{
float a = x < 0 ? -x : x, r;
r = a >= 10.0f ? 1.0f : sinhf(a) / coshf(a);
return x < 0 ? -r : r;
}
float asinhf(float x)
{
float a = x < 0 ? -x : x, r;
if (a > 1e9f) r = logf(a) + LN2_F;
else r = log1pf(a + a * a / (1.0f + sqrtf(1.0f + a * a)));
return x < 0 ? -r : r;
}
float acoshf(float x) /* x >= 1 */
{
float t;
if (x > 1e9f) return logf(x) + LN2_F;
t = x - 1.0f;
return log1pf(t + sqrtf(2.0f * t + t * t));
}
float atanhf(float x) /* |x| < 1 */
{
float a = x < 0 ? -x : x, r;
r = 0.5f * log1pf(2.0f * a / (1.0f - a));
return x < 0 ? -r : r;
}
/* log of x = m * 2^e, m in [sqrt(1/2), sqrt(2)): returns log(m), sets e */
static float log_split(float x, int *e)
{
fbits u = { x };
int k = 0;
if (u.i < 0x00800000) { u.f *= 16777216.0f; k = -24; } /* subnormal */
k += (int)(u.i >> 23) - 127;
u.i = (u.i & 0x007FFFFF) | 0x3F800000; /* [1, 2) */
if (u.f > 1.41421356f) { u.f *= 0.5f; k++; }
*e = k;
return logf(u.f);
}
float log2f(float x) /* x > 0: exact for powers of 2 */
{
int e;
float y = log_split(x, &e);
return y * 1.44269504088896341f + (float)e;
}
float log10f(float x) /* x > 0 */
{
int e;
float y = log_split(x, &e), f = (float)e;
/* log10(2) and log10(e) each split in two, as in Cephes */
return ((f * 2.48745663981195213739e-4f + y * 7.00731903251827651129e-4f)
+ y * 4.3359375e-1f) + f * 3.0078125e-1f;
}
/* exactly x - n*y, n = x/y truncated, by binary long division: each step
subtracts t from r with t <= r < 2t, which is exact */
float fmodf(float x, float y)
{
float r = x < 0 ? -x : x, d = y < 0 ? -y : y, t;
if (d == 0.0f || r < d) return x;
t = d;
while (t <= 0.5f * r) t += t;
for (; t >= d; t *= 0.5f)
if (r >= t) r -= t;
return x < 0 ? -r : r;
}
+30 -1
View File
@@ -1,4 +1,5 @@
# setjmp/longjmp: ra, sp and s0-s11 (newlib's jmp_buf has room).
# setjmp/longjmp: ra, sp and s0-s11, and fs0-fs11 when compiled for the FPU
# (newlib's jmp_buf has room for both).
.text
.globl setjmp, longjmp
setjmp:
@@ -16,6 +17,20 @@ setjmp:
sw s9, 44(a0)
sw s10, 48(a0)
sw s11, 52(a0)
#ifdef __riscv_flen
fsw fs0, 56(a0)
fsw fs1, 60(a0)
fsw fs2, 64(a0)
fsw fs3, 68(a0)
fsw fs4, 72(a0)
fsw fs5, 76(a0)
fsw fs6, 80(a0)
fsw fs7, 84(a0)
fsw fs8, 88(a0)
fsw fs9, 92(a0)
fsw fs10, 96(a0)
fsw fs11, 100(a0)
#endif
li a0, 0
ret
longjmp:
@@ -33,6 +48,20 @@ longjmp:
lw s9, 44(a0)
lw s10, 48(a0)
lw s11, 52(a0)
#ifdef __riscv_flen
flw fs0, 56(a0)
flw fs1, 60(a0)
flw fs2, 64(a0)
flw fs3, 68(a0)
flw fs4, 72(a0)
flw fs5, 76(a0)
flw fs6, 80(a0)
flw fs7, 84(a0)
flw fs8, 88(a0)
flw fs9, 92(a0)
flw fs10, 96(a0)
flw fs11, 100(a0)
#endif
seqz a0, a1
add a0, a0, a1 # 0 becomes 1
ret
+271 -51
View File
@@ -1,21 +1,37 @@
/* RISC-V assembler for the monitor (included by monitor.c).
*
* The syntax the disassembler prints. A line is
* [line number] [label:] [instruction or directive] [; comment]
* (the line number is there when the source was typed into BASIC). Numbers:
* 123, 0FFH, $FF, 0x1F, 1010B, 'A'; $ alone is the current address.
* Expressions use + - * / & | and parentheses. Registers are X0-X31 or their
* ABI names (ZERO RA SP GP TP T0-T6 S0-S11 FP A0-A7); memory operands are
* offset(register). CSRs by name (MSTATUS, MEPC, CYCLE...) or number.
* GNU as syntax, as the disassembler prints it. A line is
* [line number] [label:] [instruction or directive] [# comment]
* (the line number is there when the source was typed into BASIC; ; also
* starts a comment). Case doesn't matter: lines are upper-cased outside
* quotes before they are read. Numbers: 123, 0x1F, 0b1010, 'A', '\n'; . is
* the current address. Expressions use + - * / & | ^ << >> ~ and parentheses,
* and %hi(x) and %lo(x), the LUI/AUIPC and ADDI parts of x. Registers are
* x0-x31 or their ABI names (zero ra sp gp tp t0-t6 s0-s11 fp a0-a7); memory
* operands are offset(register). CSRs by name (mstatus, mepc, cycle...) or
* number.
*
* Instructions: RV32I and M, CSRRW..CSRRCI, ECALL EBREAK MRET MNRET WFI FENCE
* FENCE.I, and the usual short forms: NOP LI LA MV NOT NEG SEQZ SNEZ SLTZ SGTZ
* J JR JAL target RET CALL BEQZ BNEZ BLEZ BGEZ BLTZ BGTZ BGT BLE BGTU BLEU CSRR
* CSRW CSRS CSRC CSRWI CSRSI CSRCI. LI is one instruction for a constant of
* -2048..2047 known by then, else LUI and ADDI; LA is AUIPC and ADDI.
* Directives: ORG, EQU (NAME EQU value), DB/DEFB/DEFM (numbers and "strings"),
* DH (16 bits), DW/DEFW (32 bits), DS/DEFS n, ALIGN n, END. Instructions must
* be on a 4-byte boundary. Labels are up to 8 characters.
* Instructions: RV32I and M, csrrw..csrrci, ecall ebreak mret mnret wfi fence
* fence.i, and the usual short forms: nop li la mv not neg seqz snez sltz sgtz
* j jr jal target ret call beqz bnez blez bgez bltz bgtz bgt ble bgtu bleu
* csrr csrw csrs csrc csrwi csrsi csrci.
* F: flw fsw fmadd.s fmsub.s fnmsub.s fnmadd.s fadd.s fsub.s fmul.s fdiv.s
* fsqrt.s fsgnj.s fsgnjn.s fsgnjx.s fmin.s fmax.s feq.s flt.s fle.s fcvt.w.s
* fcvt.wu.s fcvt.s.w fcvt.s.wu fmv.x.w fmv.w.x fclass.s and fmv.s fneg.s
* fabs.s; float registers f0-f31 or ft0-ft11 fs0-fs11 fa0-fa7; a rounding
* mode (rne rtz rdn rup rmm dyn) may follow the operands, dyn if not. li is
* one instruction for a constant of -2048..2047 known by then, else lui and
* addi; la is auipc and addi.
* Directives: .org, .equ/.set name, value (or name = value), .byte, .half
* (.short .2byte), .word (.long .4byte), .ascii, .string/.asciz (a 0 after
* each string; \n \r \t \0 \\ \" escapes), .space/.skip/.zero n, .align n
* and .p2align n (to 2^n), .balign n (to n), .end; .text .data .section .globl
* .global .option and .type are accepted and ignored. Instructions must be on
* a 4-byte boundary. Labels are up to 8 characters (more are allowed; the
* first 8 count).
* The older forms still work: ORG, NAME EQU value, DB/DEFB/DEFM (no escapes),
* DH, DW/DEFW, DS/DEFS n, ALIGN n (to n), END; numbers 0FFH, $FF, 1010B; $
* for the current address.
*/
#define MAXSYM 200
struct sym { char name[8]; u32 val; u16 line; };
@@ -37,6 +53,28 @@ static void a_sp(void) { while (*ap == ' ' || *ap == '\t') ap++; }
static u8 a_alpha(char c) { return (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; }
static u8 a_alnum(char c) { return a_alpha(c) || (c >= '0' && c <= '9'); }
/* the length of the character constant at p ('A' or '\N'), 0 if none */
static u8 a_chlen(const char *p)
{
if (p[0] != '\'') return 0;
if (p[1] == '\\' && p[2] && p[3] == '\'') return 4;
if (p[1] && p[2] == '\'') return 3;
return 0;
}
/* the character an escape stands for: \N \R \T \0 \E, else itself */
static u8 a_esc(char c)
{
switch (c) {
case 'n': case 'N': return 10;
case 'r': case 'R': return 13;
case 't': case 'T': return 9;
case '0': return 0;
case 'e': case 'E': return 27;
}
return c;
}
static void a_emit(u8 b)
{
if (a_pass == 2) {
@@ -80,15 +118,19 @@ static void a_name(char *n)
/* ---------------------------------------------------------- expressions */
static u32 a_expr(void);
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
static u32 a_number(void)
{
const char *s = ap;
u32 v = 0;
u8 base = 10, n = 0;
while (a_alnum(s[n])) n++;
if (s[0] == '0' && s[1] == 'X') { base = 16; s += 2; }
else if (s[0] == '0' && s[1] == 'B' && s[n - 1] != 'H') { base = 2; s += 2; }
else {
while (a_alnum(s[n])) n++;
if (s[n - 1] == 'H') base = 16;
else if (s[n - 1] == 'B') {
u8 k;
@@ -99,7 +141,7 @@ static u32 a_number(void)
for (; a_alnum(*s); s++) {
char c = *s;
u8 d = c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : 99;
if ((c == 'H' && base == 16) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; }
if ((c == 'H' && base == 16 && !a_alnum(s[1])) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; }
if (d >= base) { a_fail("BAD NUMBER"); break; }
v = v * base + d;
}
@@ -113,6 +155,15 @@ static u32 a_factor(void)
a_sp();
if (*ap == '-') { ap++; return -a_factor(); }
if (*ap == '+') { ap++; return a_factor(); }
if (*ap == '~') { ap++; return ~a_factor(); }
if (*ap == '%') { /* %HI(x), %LO(x) */
u8 hi = !strncmp(ap + 1, "HI(", 3);
if (!hi && strncmp(ap + 1, "LO(", 3)) { a_fail("BAD EXPRESSION"); return 0; }
ap += 3;
v = a_factor();
return hi ? hi20(v) : (u32)lo12(v);
}
if (*ap == '.' && !a_alnum(ap[1])) { ap++; return a_pc; }
if (*ap == '(') {
ap++;
v = a_expr();
@@ -120,7 +171,8 @@ static u32 a_factor(void)
if (*ap == ')') ap++; else a_fail("MISSING )");
return v;
}
if (*ap == '\'' && ap[1] && ap[2] == '\'') { v = (u8)ap[1]; ap += 3; return v; }
if (a_chlen(ap) == 4) { v = a_esc(ap[2]); ap += 4; return v; }
if (a_chlen(ap) == 3) { v = (u8)ap[1]; ap += 3; return v; }
if (*ap == '$') {
ap++;
if ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F')) {
@@ -169,12 +221,15 @@ static u32 a_expr(void)
else if (*ap == '-') { ap++; v -= a_term(); }
else if (*ap == '&') { ap++; v &= a_term(); }
else if (*ap == '|') { ap++; v |= a_term(); }
else if (*ap == '^') { ap++; v ^= a_term(); }
else if (*ap == '<' && ap[1] == '<') { ap += 2; v <<= a_term(); }
else if (*ap == '>' && ap[1] == '>') { ap += 2; v >>= a_term(); }
else return v;
}
}
/* ------------------------------------------------------------- operands */
#define MAXOP 3
#define MAXOP 5
static char a_ops[MAXOP][40];
static u8 a_nops;
@@ -187,7 +242,8 @@ static void a_split(void)
const char *s = ap;
u8 d = 0, q = 0, len;
while (*ap && (d || q || *ap != ',')) {
if (*ap == '\'' && !q && ap[1] && ap[2] == '\'') ap += 2;
if (!q && a_chlen(ap)) ap += a_chlen(ap) - 1;
else if (q && *ap == '\\' && ap[1]) ap++;
else if (*ap == '"') q = !q;
else if (*ap == '(') d++;
else if (*ap == ')' && d) d--;
@@ -310,15 +366,102 @@ static u32 enc_u(u32 base, u8 rd, u32 imm)
if (a_pass == 2 && imm > 0xFFFFF) a_fail("VALUE OUT OF RANGE");
return base | rd << 7 | (imm & 0xFFFFF) << 12;
}
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
/* ----------------------------------------------------------------- F */
static void a_need(u8 n);
/* a float register name, the whole of s; 0xFF if it isn't one */
static u8 a_fregname(const char *s)
{
u8 k = 0, base, lim;
const char *d;
if (s[0] != 'F') return 0xFF;
if (s[1] >= '0' && s[1] <= '9') { d = s + 1; base = 0; lim = 32; }
else if (s[1] == 'T') { d = s + 2; base = 100; lim = 12; } /* FT0-7: 0-7, FT8-11: 28-31 */
else if (s[1] == 'S') { d = s + 2; base = 200; lim = 12; } /* FS0-1: 8-9, FS2-11: 18-27 */
else if (s[1] == 'A') { d = s + 2; base = 10; lim = 8; } /* FA0-7: 10-17 */
else return 0xFF;
if (*d < '0' || *d > '9') return 0xFF;
k = *d++ - '0';
if (*d >= '0' && *d <= '9') k = k * 10 + (*d++ - '0');
if (*d || k >= lim) return 0xFF;
if (base == 100) return k < 8 ? k : k + 20;
if (base == 200) return k < 2 ? k + 8 : k + 16;
return base + k;
}
static u8 a_freg(u8 i)
{
u8 r = i < a_nops ? a_fregname(a_ops[i]) : 0xFF;
if (r == 0xFF) a_fail("BAD FLOAT REGISTER");
return r & 31;
}
/* the rounding mode in operand i, DYN (7) if there is none */
static u32 a_rm(u8 i)
{
static const char *const m[8] = { "RNE", "RTZ", "RDN", "RUP", "RMM", "", "", "DYN" };
u8 k;
if (i >= a_nops) return 7;
for (k = 0; k < 8; k++) if (m[k][0] && !strcmp(a_ops[i], m[k])) return k;
a_fail("BAD ROUNDING MODE");
return 7;
}
enum { G_LD, G_ST, G_R4, G_R3RM, G_R2RM, G_R3, G_XFF, G_XFRM, G_FXRM, G_XF, G_FX, G_P2 };
struct fins { char name[10]; u8 f; u32 base; };
static const struct fins ftab[] = {
{ "FLW", G_LD, 0x00002007 }, { "FSW", G_ST, 0x00002027 },
{ "FMADD.S", G_R4, 0x43 }, { "FMSUB.S", G_R4, 0x47 }, { "FNMSUB.S", G_R4, 0x4B },
{ "FNMADD.S", G_R4, 0x4F },
{ "FADD.S", G_R3RM, 0x00000053 }, { "FSUB.S", G_R3RM, 0x08000053 },
{ "FMUL.S", G_R3RM, 0x10000053 }, { "FDIV.S", G_R3RM, 0x18000053 },
{ "FSQRT.S", G_R2RM, 0x58000053 },
{ "FSGNJ.S", G_R3, 0x20000053 }, { "FSGNJN.S", G_R3, 0x20001053 },
{ "FSGNJX.S", G_R3, 0x20002053 }, { "FMIN.S", G_R3, 0x28000053 }, { "FMAX.S", G_R3, 0x28001053 },
{ "FEQ.S", G_XFF, 0xA0002053 }, { "FLT.S", G_XFF, 0xA0001053 }, { "FLE.S", G_XFF, 0xA0000053 },
{ "FCVT.W.S", G_XFRM, 0xC0000053 }, { "FCVT.WU.S", G_XFRM, 0xC0100053 },
{ "FCVT.S.W", G_FXRM, 0xD0000053 }, { "FCVT.S.WU", G_FXRM, 0xD0100053 },
{ "FMV.X.W", G_XF, 0xE0000053 }, { "FMV.X.S", G_XF, 0xE0000053 },
{ "FCLASS.S", G_XF, 0xE0001053 },
{ "FMV.W.X", G_FX, 0xF0000053 }, { "FMV.S.X", G_FX, 0xF0000053 },
{ "FMV.S", G_P2, 0x20000053 }, { "FNEG.S", G_P2, 0x20001053 }, { "FABS.S", G_P2, 0x20002053 },
};
#define NFINS (sizeof ftab / sizeof ftab[0])
/* the operand count of a form with an optional rounding mode */
static void a_need2(u8 n) { if (a_nops != n && a_nops != n + 1) a_need(n); }
static void a_finstr(const struct fins *t)
{
u32 b = t->base;
i32 off;
u8 r, s;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE .ALIGN 2"); return; }
switch (t->f) {
case G_LD: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_i(b, r, s, off)); return;
case G_ST: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_s(b, s, r, off)); return;
case G_R4:
a_need2(4);
a_emit32(b | a_freg(0) << 7 | a_freg(1) << 15 | a_freg(2) << 20 | (u32)a_freg(3) << 27 |
a_rm(4) << 12);
return;
case G_R3RM:
a_need2(3);
a_emit32(b | a_freg(0) << 7 | a_freg(1) << 15 | a_freg(2) << 20 | a_rm(3) << 12);
return;
case G_R2RM: a_need2(2); a_emit32(b | a_freg(0) << 7 | a_freg(1) << 15 | a_rm(2) << 12); return;
case G_R3: a_need(3); a_emit32(b | a_freg(0) << 7 | a_freg(1) << 15 | a_freg(2) << 20); return;
case G_XFF: a_need(3); a_emit32(b | a_reg(0) << 7 | a_freg(1) << 15 | a_freg(2) << 20); return;
case G_XFRM: a_need2(2); a_emit32(b | a_reg(0) << 7 | a_freg(1) << 15 | a_rm(2) << 12); return;
case G_FXRM: a_need2(2); a_emit32(b | a_freg(0) << 7 | a_reg(1) << 15 | a_rm(2) << 12); return;
case G_XF: a_need(2); a_emit32(b | a_reg(0) << 7 | a_freg(1) << 15); return;
case G_FX: a_need(2); a_emit32(b | a_freg(0) << 7 | a_reg(1) << 15); return;
case G_P2: a_need(2); r = a_freg(1); a_emit32(b | a_freg(0) << 7 | r << 15 | r << 20); return;
}
}
/* --------------------------------------------------------- instructions */
enum {
F_R, F_I, F_SH, F_LD, F_ST, F_B, F_U, F_JAL, F_JALR, F_CSR, F_CSRI, F_FIX,
P_LI, P_LA, P_MV, P_NOT, P_NEG, P_SEQZ, P_SNEZ, P_SLTZ, P_SGTZ, P_J, P_JR, P_RET,
P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI
P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI, P_FR, P_FS
};
struct ins { char name[8]; u8 f; u32 base; };
static const struct ins itab[] = {
@@ -355,6 +498,9 @@ static const struct ins itab[] = {
{ "CSRR", P_CSRR, 0 }, { "CSRW", P_CSRW, 0x00001073 }, { "CSRS", P_CSRW, 0x00002073 },
{ "CSRC", P_CSRW, 0x00003073 }, { "CSRWI", P_CSRWI, 0x00005073 },
{ "CSRSI", P_CSRWI, 0x00006073 }, { "CSRCI", P_CSRWI, 0x00007073 },
/* the float CSRs: read (CSRR), and write ([rd,] rs: CSRRW) */
{ "FRFLAGS", P_FR, 0x00102073 }, { "FRRM", P_FR, 0x00202073 }, { "FRCSR", P_FR, 0x00302073 },
{ "FSFLAGS", P_FS, 0x00101073 }, { "FSRM", P_FS, 0x00201073 }, { "FSCSR", P_FS, 0x00301073 },
};
#define NINS (sizeof itab / sizeof itab[0])
@@ -365,7 +511,7 @@ static void a_instr(const struct ins *t)
u32 b = t->base, v;
i32 off;
u8 rd, rs;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE ALIGN 4"); return; }
if (a_pc & 3) { a_fail("NOT ON A WORD: USE .ALIGN 2"); return; }
switch (t->f) {
case F_R: a_need(3); a_emit32(enc_r(b, a_reg(0), a_reg(1), a_reg(2))); return;
case F_I: a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return;
@@ -401,6 +547,8 @@ static void a_instr(const struct ins *t)
v = a_imm(1);
if (!a_undef && !a_fwd && (i32)v >= -2048 && (i32)v <= 2047) {
a_emit32(enc_i(0x13, rd, 0, (i32)v));
} else if (!a_undef && !a_fwd && !(v & 0xFFF)) {
a_emit32(enc_u(0x37, rd, v >> 12)); /* LUI alone, as GNU as does */
} else {
a_emit32(enc_u(0x37, rd, hi20(v)));
a_emit32(enc_i(0x13, rd, rd, lo12(v)));
@@ -429,6 +577,10 @@ static void a_instr(const struct ins *t)
case P_BSW: a_need(3); rs = a_reg(0); a_emit32(enc_b(b, a_reg(1), rs, a_imm(2))); return;
case P_CSRR: a_need(2); a_emit32(0x2073 | a_reg(0) << 7 | (u32)a_csr(1) << 20); return;
case P_CSRW: a_need(2); a_emit32(b | a_reg(1) << 15 | (u32)a_csr(0) << 20); return;
case P_FR: a_need(1); a_emit32(b | a_reg(0) << 7); return;
case P_FS:
if (a_nops == 1) { a_emit32(b | a_reg(0) << 15); return; }
a_need(2); a_emit32(b | a_reg(0) << 7 | a_reg(1) << 15); return;
case P_CSRWI:
a_need(2);
v = a_imm(1);
@@ -438,15 +590,24 @@ static void a_instr(const struct ins *t)
}
}
/* DB/DH/DW items: numbers and (for DB) strings */
static void a_data(u8 size)
/* data items: numbers, and for bytes "strings". str: 1 strings with
escapes (.ascii), 2 the same with a 0 after each (.string); 0 DB's, kept
as they are. */
static void a_data(u8 size, u8 str)
{
for (;;) {
a_sp();
if (*ap == '"' && size == 1) {
ap++;
while (*ap && *ap != '"') a_emit(*ap++);
while (*ap && *ap != '"') {
if (str && *ap == '\\' && ap[1]) { a_emit(a_esc(ap[1])); ap += 2; }
else a_emit(*ap++);
}
if (*ap) ap++;
if (str == 2) a_emit(0);
} else if (str) {
a_fail("BAD STRING");
return;
} else {
u32 v = a_expr();
u8 k;
@@ -461,19 +622,37 @@ static void a_data(u8 size)
static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); }
/* directives, and the old names that mean the same */
enum { D_EQU = 1, D_SET, D_ORG, D_END, D_DB, D_ASCII, D_STRING, D_DH, D_DW, D_DS, D_SPACE,
D_ALIGN, D_P2ALIGN, D_IGNORE };
static const struct { char n[8]; u8 d; } dtab[] = {
{ "EQU", D_EQU }, { ".EQU", D_SET }, { ".SET", D_SET }, { "ORG", D_ORG }, { ".ORG", D_ORG },
{ "END", D_END }, { ".END", D_END }, { "DB", D_DB }, { "DEFB", D_DB }, { "DEFM", D_DB },
{ ".BYTE", D_DB }, { ".ASCII", D_ASCII }, { ".STRING", D_STRING }, { ".ASCIZ", D_STRING },
{ "DH", D_DH }, { ".HALF", D_DH }, { ".SHORT", D_DH }, { ".2BYTE", D_DH }, { "DW", D_DW },
{ "DEFW", D_DW }, { ".WORD", D_DW }, { ".LONG", D_DW }, { ".4BYTE", D_DW }, { "DS", D_DS },
{ "DEFS", D_DS }, { ".SPACE", D_SPACE }, { ".SKIP", D_SPACE }, { ".ZERO", D_SPACE },
{ "ALIGN", D_ALIGN }, { ".BALIGN", D_ALIGN }, { ".ALIGN", D_P2ALIGN }, { ".P2ALIGN", D_P2ALIGN },
{ ".TEXT", D_IGNORE }, { ".DATA", D_IGNORE }, { ".SECTION", D_IGNORE }, { ".GLOBL", D_IGNORE },
{ ".GLOBAL", D_IGNORE }, { ".OPTION", D_IGNORE }, { ".TYPE", D_IGNORE }, { "", 0 }
};
/* Assemble one source line (uppercase except in quotes). */
static void a_line(char *s)
{
char w[8], lab[8];
u8 has_lab = 0, q = 0;
char w[8], lab[8], fm[12];
const char *mn;
u8 has_lab = 0, q = 0, d;
u16 m;
u32 n, f;
char *c;
a_err = 0;
/* cut the comment */
for (c = s; *c; c++) {
if (*c == '"') q = !q;
else if (*c == '\'' && !q && c[1] && c[2] == '\'') c += 2;
else if (*c == ';' && !q) { *c = 0; break; }
if (q && *c == '\\' && c[1]) c++;
else if (*c == '"') q = !q;
else if (!q && a_chlen(c)) c += a_chlen(c) - 1;
else if ((*c == ';' || *c == '#') && !q) { *c = 0; break; }
}
ap = s;
a_sp();
@@ -485,6 +664,7 @@ static void a_line(char *s)
a_sp();
if (!*ap) return;
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
mn = ap;
a_name(w);
a_sp();
if (*ap == ':') { /* LABEL: */
@@ -493,33 +673,72 @@ static void a_line(char *s)
a_sp();
if (!*ap) { sym_def(lab, a_pc); return; }
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
mn = ap;
a_name(w);
a_sp();
} else if (!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) {
memcpy(lab, w, 8); has_lab = 1;
} else if ((!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) || (*ap == '=' && w[0] != '.')) {
memcpy(lab, w, 8); has_lab = 1; /* NAME EQU value, NAME = value */
ap += *ap == '=' ? 1 : 3;
memcpy(w, "EQU\0\0\0\0\0", 8);
ap += 3;
}
if (is_w(w, "EQU")) {
u32 v = a_expr();
for (m = 0; dtab[m].d && !is_w(w, dtab[m].n); m++);
d = dtab[m].d;
if (d == D_SET) { /* .EQU NAME, value */
if (!a_alpha(*ap)) { a_fail("EQU NEEDS A NAME"); return; }
a_name(lab); has_lab = 1;
a_sp();
if (*ap == ',') ap++;
d = D_EQU;
}
if (d == D_EQU) {
n = a_expr();
if (!has_lab) a_fail("EQU NEEDS A NAME");
else if (a_undef && a_pass == 1) a_fail("EQU BEFORE ITS VALUE");
else sym_def(lab, v);
else sym_def(lab, n);
return;
}
if (has_lab) sym_def(lab, a_pc);
if (is_w(w, "ORG")) { a_pc = a_expr(); return; }
if (is_w(w, "END")) { a_end = 1; return; }
if (is_w(w, "DB") || is_w(w, "DEFB") || is_w(w, "DEFM")) { a_data(1); return; }
if (is_w(w, "DH")) { a_data(2); return; }
if (is_w(w, "DW") || is_w(w, "DEFW")) { a_data(4); return; }
if (is_w(w, "DS") || is_w(w, "DEFS")) { a_pc += a_expr(); return; }
if (is_w(w, "ALIGN")) {
u32 n = a_expr();
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2");
else while (a_pc & (n - 1)) a_emit(0);
switch (d) {
case D_ORG: a_pc = a_expr(); return;
case D_END: a_end = 1; return;
case D_DB: a_data(1, 0); return;
case D_ASCII: a_data(1, 1); return;
case D_STRING: a_data(1, 2); return;
case D_DH: a_data(2, 0); return;
case D_DW: a_data(4, 0); return;
case D_DS: a_pc += a_expr(); return;
case D_SPACE: /* n [, fill] */
n = a_expr(); f = 0;
a_sp();
if (*ap == ',') { ap++; f = a_expr(); }
while (n--) a_emit(f);
return;
case D_ALIGN: case D_P2ALIGN:
n = a_expr();
if (d == D_P2ALIGN) n = n < 32 ? 1u << n : 0; /* .ALIGN, .P2ALIGN: to 2^n */
a_sp();
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2");
else if (*ap == ',') { /* n, fill */
ap++;
f = a_expr();
while (a_pc & (n - 1)) a_emit(f);
} else { /* zeros to a word, then NOPs */
while (a_pc & (n - 1) & 3) a_emit(0);
while (a_pc & (n - 1)) a_emit32(0x13);
}
return;
case D_IGNORE: return;
}
/* F instructions, whose names can be longer than 8 */
for (m = 0; m < 11 && a_alnum(mn[m]); m++) fm[m] = mn[m];
fm[m] = 0;
if (!a_alnum(mn[m]))
for (m = 0; m < NFINS; m++)
if (!strcmp(fm, ftab[m].name)) {
a_split();
if (!a_err) a_finstr(&ftab[m]);
return;
}
for (m = 0; m < NINS; m++)
if (!strncmp(w, itab[m].name, 8)) break;
if (m == NINS) { a_fail("UNKNOWN INSTRUCTION"); return; }
@@ -533,8 +752,9 @@ static void a_upper(char *s)
{
u8 q = 0;
for (; *s; s++) {
if (*s == '"') q = !q;
else if (*s == '\'' && !q && s[1] && s[2] == '\'') s += 2;
if (q && *s == '\\' && s[1]) s++;
else if (*s == '"') q = !q;
else if (!q && a_chlen(s)) s += a_chlen(s) - 1;
else if (!q && *s >= 'a' && *s <= 'z') *s -= 32;
if (*s == '\t') *s = ' ';
}
+3 -2
View File
@@ -5,12 +5,13 @@ set -e
cd "$(dirname "$0")"
source ../scripts/rv_env.sh
mkdir -p out
CFLAGS="$RV_ARCH -Os -mno-relax -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
# -msave-restore: shared register saving, 2 KB smaller (the ROM is 32 KB)
CFLAGS="$RV_ARCH -Os -msave-restore -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S
${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c
${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c
${RV_PREFIX}gcc $CFLAGS -c -o out/setjmp.o ../lib/setjmp.S
${RV_PREFIX}gcc $RV_ARCH -nostdlib -nostartfiles -T monitor.ld -Wl,--no-relax -Wl,--gc-sections \
${RV_PREFIX}gcc $RV_ARCH -nostdlib -nostartfiles -T monitor.ld -Wl,--gc-sections \
-Wl,--build-id=none -Wl,-Map,out/monitor.map -o out/monitor.elf \
out/crt0.o out/monitor.o out/string.o out/setjmp.o -lgcc
${RV_PREFIX}objcopy -O binary -j .text -j .data out/monitor.elf monitor.bin
+35 -2
View File
@@ -4,13 +4,20 @@
# instruction, a misaligned access, ebreak, ecall, an unhandled interrupt).
# The program's registers go to u (struct regs in monitor.c), the monitor runs,
# and mnret takes the program back to u.pc with its registers as u has them.
.equ U, 0x29F00 # struct regs, below RAM's last 256 bytes
# The float registers and fcsr are saved too, when mstatus.FS is on (Off: the
# F instructions would trap), and FS is put back as it was.
.option arch, +f
.option norelax
.equ U, 0x29E80 # struct regs, below RAM's last 384 bytes
.equ INITED, 0x29FFC # C data is set up once, then kept
.equ U_PC, 128
.equ U_HOW, 132 # 0 NMI, 1 trap
.equ U_CAUSE, 136
.equ U_TVAL, 140
.equ U_STATUS, 144
.equ U_F, 148 # f0-f31
.equ U_FCSR, 276
.equ U_FS, 280 # mstatus.FS on entry; 0: f not saved
.section .text.start, "ax"
.globl _start, u
@@ -56,6 +63,21 @@ trap_entry:
common:
li sp, U # the monitor's stack, below u
.option push
.option norelax
la gp, __global_pointer$ # the monitor's (the program's is in u)
.option pop
csrr t0, mstatus
srli t0, t0, 13
andi t0, t0, 3
sw t0, U_FS(sp)
beqz t0, 5f
.irp n, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
fsw f\n, U_F+4*\n(sp)
.endr
csrr t0, fcsr
sw t0, U_FCSR(sp)
5:
li t0, INITED
lw t1, 0(t0)
li t2, 0xA5A5
@@ -79,7 +101,18 @@ common:
3: call mon_main
li sp, U
lw t0, U_PC(sp)
lw t0, U_FS(sp)
beqz t0, 6f
.irp n, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
flw f\n, U_F+4*\n(sp)
.endr
lw t1, U_FCSR(sp)
csrw fcsr, t1
li t1, 0x6000 # FS as it was (loading f made it Dirty)
csrc mstatus, t1
slli t0, t0, 13
csrs mstatus, t0
6: lw t0, U_PC(sp)
csrw 0x741, t0 # mnepc
lw t0, U_HOW(sp)
beqz t0, 4f
Binary file not shown.
+158 -11
View File
@@ -27,12 +27,15 @@ typedef int32_t i32;
#define fl_ctl IO8(0x40)
#define fl_dat IO8(0x41)
/* saved by crt0.S at 29F00h */
/* saved by crt0.S at 29E80h */
struct regs {
u32 x[32]; /* x[0] is 0 */
u32 pc;
u32 how; /* 0 NMI, 1 trap */
u32 cause, tval, status; /* for a trap */
u32 f[32]; /* float registers (bit patterns) */
u32 fcsr;
u32 fs; /* mstatus.FS on entry; 0: f and fcsr not saved */
};
extern struct regs u;
@@ -77,14 +80,13 @@ static void s_udec(u32 v)
s_str(q);
}
static void s_dec(i32 v) { if (v < 0) { s_ch('-'); v = -v; } s_udec((u32)v); }
/* assembler style: 1F0H, 0A200H (a leading 0 when it starts with a letter) */
/* GNU style: 0x1f0 (disasm() lower-cases it) */
static void s_lit(u32 v)
{
u8 n = 1;
while (n < 8 && v >> (4 * n)) n++;
if ((v >> (4 * (n - 1)) & 15) >= 10) s_ch('0');
s_str("0X");
s_hex(v, n);
s_ch('H');
}
/* ---------------------------------------------------------- disassembler */
@@ -101,6 +103,7 @@ static const struct csrn csrs[] = {
{ 0x7A5, "TCONTROL" }, { 0xB00, "MCYCLE" }, { 0xB02, "MINSTRET" }, { 0xB80, "MCYCLEH" },
{ 0xB82, "MINSTRETH" }, { 0xC00, "CYCLE" }, { 0xC01, "TIME" }, { 0xC02, "INSTRET" },
{ 0xC80, "CYCLEH" }, { 0xC81, "TIMEH" }, { 0xC82, "INSTRETH" }, { 0xF14, "MHARTID" },
{ 0x001, "FFLAGS" }, { 0x002, "FRM" }, { 0x003, "FCSR" },
{ 0, 0 }
};
@@ -123,8 +126,85 @@ static const char *const opn[8] = { "ADD", "SLL", "SLT", "SLTU", "XOR", "SRL", "
static const char *const muln[8] = { "MUL", "MULH", "MULHSU", "MULHU", "DIV", "DIVU", "REM", "REMU" };
static const char *const csrin[8] = { 0, "CSRRW", "CSRRS", "CSRRC", 0, "CSRRWI", "CSRRSI", "CSRRCI" };
/* One instruction at a into line (at lp); returns its length, 4. */
static u8 disasm(u32 a)
/* F: registers F0-F31, the rounding mode after the operands unless DYN */
static const char *const rmn[8] = { "RNE", "RTZ", "RDN", "RUP", "RMM", 0, 0, "DYN" };
/* float registers by their ABI names, as objdump shows them: ft0-7 fs0-1
fa0-7 fs2-11 ft8-11 */
static void s_freg(u8 r)
{
s_ch('F');
if (r < 8) { s_ch('T'); s_udec(r); }
else if (r < 10) { s_ch('S'); s_udec(r - 8); }
else if (r < 18) { s_ch('A'); s_udec(r - 10); }
else if (r < 28) { s_ch('S'); s_udec(r - 16); }
else { s_ch('T'); s_udec(r - 20); }
}
static void s_rm(u8 m) { if (m != 7) { s_c(); s_str(rmn[m]); } }
/* An F instruction (not FLW/FSW); 0 if it isn't one */
static u8 dis_f(u32 w)
{
u8 op = w & 0x7F, rd = w >> 7 & 31, f3 = w >> 12 & 7, rs1 = w >> 15 & 31, rs2 = w >> 20 & 31;
u8 f5 = w >> 27;
if (w >> 25 & 3) return 0;
if (op != 0x53) { /* FMADD.S FMSUB.S FNMSUB.S FNMADD.S */
static const char *const r4[4] = { "FMADD.S", "FMSUB.S", "FNMSUB.S", "FNMADD.S" };
if (!rmn[f3]) return 0;
s_mn(r4[op >> 2 & 3]); s_freg(rd); s_c(); s_freg(rs1); s_c(); s_freg(rs2); s_c();
s_freg(w >> 27); s_rm(f3);
return 1;
}
switch (f5) {
case 0x00: case 0x01: case 0x02: case 0x03: {
static const char *const ar[4] = { "FADD.S", "FSUB.S", "FMUL.S", "FDIV.S" };
if (!rmn[f3]) return 0;
s_mn(ar[f5]); s_freg(rd); s_c(); s_freg(rs1); s_c(); s_freg(rs2); s_rm(f3);
return 1;
}
case 0x0B:
if (rs2 || !rmn[f3]) return 0;
s_mn("FSQRT.S"); s_freg(rd); s_c(); s_freg(rs1); s_rm(f3);
return 1;
case 0x04: {
static const char *const sj[3] = { "FSGNJ.S", "FSGNJN.S", "FSGNJX.S" };
static const char *const sp[3] = { "FMV.S", "FNEG.S", "FABS.S" };
if (f3 > 2) return 0;
if (rs1 == rs2) { s_mn(sp[f3]); s_freg(rd); s_c(); s_freg(rs1); return 1; }
s_mn(sj[f3]); s_freg(rd); s_c(); s_freg(rs1); s_c(); s_freg(rs2);
return 1;
}
case 0x05:
if (f3 > 1) return 0;
s_mn(f3 ? "FMAX.S" : "FMIN.S"); s_freg(rd); s_c(); s_freg(rs1); s_c(); s_freg(rs2);
return 1;
case 0x14: {
static const char *const cm[3] = { "FLE.S", "FLT.S", "FEQ.S" };
if (f3 > 2) return 0;
s_mn(cm[f3]); s_reg(rd); s_c(); s_freg(rs1); s_c(); s_freg(rs2);
return 1;
}
case 0x18:
if (rs2 > 1 || !rmn[f3]) return 0;
s_mn(rs2 ? "FCVT.WU.S" : "FCVT.W.S"); s_reg(rd); s_c(); s_freg(rs1); s_rm(f3);
return 1;
case 0x1A:
if (rs2 > 1 || !rmn[f3]) return 0;
s_mn(rs2 ? "FCVT.S.WU" : "FCVT.S.W"); s_freg(rd); s_c(); s_reg(rs1); s_rm(f3);
return 1;
case 0x1C:
if (rs2 || f3 > 1) return 0;
s_mn(f3 ? "FCLASS.S" : "FMV.X.W"); s_reg(rd); s_c(); s_freg(rs1);
return 1;
case 0x1E:
if (rs2 || f3) return 0;
s_mn("FMV.W.X"); s_freg(rd); s_c(); s_reg(rs1);
return 1;
}
return 0;
}
/* One instruction at a into line (at lp), in capitals; returns its length, 4. */
static u8 dis_up(u32 a)
{
u32 w = rd32(a);
u8 op = w & 0x7F, rd = w >> 7 & 31, f3 = w >> 12 & 7, rs1 = w >> 15 & 31, rs2 = w >> 20 & 31;
@@ -199,6 +279,18 @@ static u8 disasm(u32 a)
else break;
s_reg(rd); s_c(); s_reg(rs1); s_c(); s_reg(rs2);
return 4;
case 0x07:
if (f3 != 2) break;
s_mn("FLW"); s_freg(rd); s_c(); s_dec(ii); s_ch('('); s_reg(rs1); s_ch(')');
return 4;
case 0x27:
if (f3 != 2) break;
s_mn("FSW"); s_freg(rs2); s_c(); s_dec(sx((w >> 25) << 5 | rd, 12));
s_ch('('); s_reg(rs1); s_ch(')');
return 4;
case 0x43: case 0x47: case 0x4B: case 0x4F: case 0x53:
if (dis_f(w)) return 4;
break;
case 0x0F:
if (f3 == 0) { s_str("FENCE"); return 4; }
if (f3 == 1) { s_str("FENCE.I"); return 4; }
@@ -223,10 +315,20 @@ static u8 disasm(u32 a)
return 4;
}
}
s_mn("DW"); s_lit(w);
s_mn(".WORD"); s_lit(w);
return 4;
}
/* One instruction at a into line (at lp), in lower case as GNU tools show
it; returns its length, 4. */
static u8 disasm(u32 a)
{
char *s = lp;
u8 n = dis_up(a);
for (; s < lp; s++) if (*s >= 'A' && *s <= 'Z') *s += 32;
return n;
}
#ifndef __riscv
#include "asm.c"
@@ -340,6 +442,7 @@ static char cmd[80];
static u8 msg_err;
static const char *msg;
static u8 why_in; /* why the monitor was entered */
static u8 show_f; /* the float registers in the memory window */
static char load_msg[32];
/* ------------------------------------------------------------- drawing */
@@ -398,10 +501,33 @@ static void draw_stack(void)
}
}
/* the float registers and fcsr, where the memory window goes */
static void draw_fregs(void)
{
u8 r, i;
at(MEM_TOP - 1, 0); sgr("36"); puts_(" FLOAT REGISTERS"); sgr("0"); clr_eol();
for (r = 0; r < MEM_ROWS; r++) {
lp = line;
if (!u.fs) { if (r == 0) s_str(" THE FPU IS OFF (MSTATUS.FS = 0)"); }
else for (i = 0; i < 6; i++) {
u8 k = r * 6 + i;
char n[4];
if (k < 32) {
n[0] = 'F'; n[1] = k < 10 ? '0' + k : '0' + k / 10;
n[2] = k < 10 ? 0 : '0' + k % 10; n[3] = 0;
s_rv(n, u.f[k]);
} else if (k == 32) s_rv("FCSR", u.fcsr);
}
at(MEM_TOP + r, 0); flush_line(); clr_eol();
}
}
static void draw_mem(void)
{
u32 a = mem_a;
u8 r, j, c;
if (show_f) { draw_fregs(); return; }
at(MEM_TOP - 1, 0); sgr("36"); puts_(" MEMORY"); sgr("0"); clr_eol();
for (r = 0; r < MEM_ROWS; r++) {
lp = line;
s_ch(' '); s_hex(a, 5); s_str(" ");
@@ -456,10 +582,9 @@ static void draw_all(void)
at(DIS_TOP - 1, 0); sgr("36"); puts_(" ADDR WORD INSTRUCTION"); sgr("0");
draw_dis();
draw_stack();
at(MEM_TOP - 1, 0); sgr("36"); puts_(" MEMORY"); sgr("0");
draw_mem();
at(28, 0); sgr("36");
puts_(" ENTER step O over G go X exit B bp D/M addr E edit R reg ? help");
puts_(" ENTER step O over G go X exit B bp D/M addr E edit R reg F fp ? help");
sgr("0");
}
@@ -474,6 +599,7 @@ static u8 get_hex(u32 *v)
u8 n = 0;
skip_sp();
*v = 0;
if (cp[0] == '0' && (cp[1] == 'X' || cp[1] == 'x') && is_hex(cp[2])) cp += 2; /* 0x is optional */
while (is_hex(*cp)) {
*v = *v << 4 | (*cp <= '9' ? *cp - '0' : *cp - 'A' + 10);
cp++; n++;
@@ -927,6 +1053,21 @@ static u8 set_reg(void)
u8 r;
u32 v;
skip_sp();
if (cp[0] == 'F' && ((cp[1] >= '0' && cp[1] <= '9') || !memcmp(cp, "FCSR", 4))) {
if (!u.fs) return 0; /* not saved: the FPU is off */
if (cp[1] == 'C') { cp += 4; r = 32; }
else {
r = *++cp - '0';
if (*++cp >= '0' && *cp <= '9') r = r * 10 + (*cp++ - '0');
if (r > 31) return 0;
}
skip_sp();
if (*cp == '=') cp++;
if (!get_hex(&v)) return 0;
if (r == 32) u.fcsr = v & 0xFF; else u.f[r] = v;
show_f = 1;
return 1;
}
if (cp[0] == 'P' && cp[1] == 'C') { cp += 2; r = 32; }
else if ((r = reg_num()) == 0xFF || r == 0) return 0;
skip_sp();
@@ -1052,6 +1193,7 @@ static u8 command(void)
return 0;
case 'M':
if (get_hex(&v)) mem_a = v;
show_f = 0;
draw_mem();
return 0;
case 'E': /* E addr bytes... */
@@ -1060,9 +1202,14 @@ static u8 command(void)
if (!wr(a++, v)) { msg = "ROM: NOT CHANGED"; msg_err = 1; break; }
draw_all();
return 0;
case 'F':
show_f = 1;
draw_mem();
msg = "M TO SHOW MEMORY AGAIN";
return 0;
case 'R':
if (!set_reg()) { msg = "R PC|X1-X31|RA|SP|A0... = VALUE"; msg_err = 1; return 0; }
draw_regs(); draw_dis(); draw_stack();
if (!set_reg()) { msg = "R PC|X1-X31|RA|SP|A0...|F0-F31|FCSR = VALUE"; msg_err = 1; return 0; }
draw_regs(); draw_dis(); draw_stack(); draw_mem();
return 0;
case '?':
case 'H':
+9 -2
View File
@@ -1,5 +1,5 @@
/* The monitor: ROM 20000-27FFF (writes ignored), RAM 28000-29FFF (data only)
with the saved registers at 29F00h (crt0.S) and the stack below them. */
with the saved registers at 29E80h (crt0.S) and the stack below them. */
OUTPUT_ARCH("riscv")
ENTRY(_start)
MEMORY
@@ -11,8 +11,12 @@ SECTIONS
{
.text : {
KEEP(*(.text.start))
*(.text .text.*)
/* the constants before the code: they are reached by LUI and ADDI,
and relaxation must never take them for gp-relative data, which
it would if the code (larger before relaxing) pushed them past
28000h */
*(.rodata .rodata.* .srodata .srodata.*)
*(.text .text.*)
. = ALIGN(4);
} > ROM
.data : ALIGN(4) {
@@ -22,6 +26,9 @@ SECTIONS
__data_end = .;
} > RAM AT > ROM
__data_load = LOADADDR(.data);
/* the monitor's gp (set in crt0.S): its variables in one instruction */
/* (0xC00, not 0x800: before relaxing, the ROM overflows into 28000h) */
__global_pointer$ = ORIGIN(RAM) + 0xC00;
.bss (NOLOAD) : ALIGN(4) {
__bss_start = .;
*(.sbss .sbss.* .bss .bss.* COMMON)
+6508 -6508
View File
File diff suppressed because it is too large. Load diff
+145 -23
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""Assemble a test program with the monitor's assembler (out/monitor-host)
and with GNU as, and check the bytes are the same.
"""Assemble test programs with the monitor's assembler (out/monitor-host)
and with GNU as, and check the bytes are the same: one in GNU syntax, given
to both as it is, and one in the older forms the monitor still takes.
python3 test-asm.py
"""
@@ -12,7 +13,72 @@ import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
# the monitor's syntax; to_gnu() below turns it into GNU as's
# GNU syntax: both assemblers read this text (GNU as without the .org)
GNU_SRC = r"""
.org 0x12000
.text
.option norvc
.globl _start
.equ count, 10
.set mask, 0b1010 << 4 | 1 # 161
width = (count * 3) ^ ~0xf # mixed operators
big = 0x12345
_start: la a1, message # auipc and addi
li a2, count
li a3, 0x12000 # lui alone
li a4, 0x12345 # lui and addi
li a5, -1
li t0, mask
li t1, width & 0x7ff
lui a6, %hi(big)
addi a6, a6, %lo(big)
lui a7, %hi(table)
lw a7, %lo(table)(a7)
sw zero, %lo(table)(a7)
print_char:
lbu a0, 0(a1)
beqz a0, finish
wait: lbu t0, -256(zero)
andi t0, t0, 2
beqz t0, wait
sb a0, -255(zero)
addi a1, a1, 1
j print_char
finish: li a0, '\n'
li a1, 'Z' - 1
csrr a2, mstatus
csrw mscratch, a2
csrrs a3, cycle, zero
frrm a4
fadd.s fa0, fa1, fa2, rtz
fmadd.s ft0, ft1, ft2, ft3
flw fs0, 4(sp)
fsw ft11, -8(sp)
fcvt.w.s t2, fa0, rtz
jal print_char
jalr t0
ret
.align 4 # NOPs from a word
message:
.string "hello, \"world\"\n", "two"
.ascii "tab\there"
.asciz "back\\slash"
.p2align 2, 0 # GNU leaves bytes unaligned without a fill
table: .word _start, finish, . - _start, 0x12345678
.long -1
.4byte 'A'
.half 1234, 0xffff
.short 7
.2byte -2
.byte 1, 2, 0x7f, 'X', '\t' # (GNU reads '\0' as '0')
.space 3, 0xaa
.zero 2
.skip 1
.balign 8
.byte 0xee
"""
# the older forms; to_gnu() below turns them into GNU as's
SRC = r"""
ORG 12000H
COUNT EQU 10
@@ -68,6 +134,33 @@ DONE: ADDI A2,A2,-1
FENCE
FENCE.I
NOP
FLW FA0,8(SP)
FSW F31,-12(A0)
FADD.S FA0,FA1,FA2
FSUB.S F1,F2,F3,RTZ
FMUL.S FT0,FT11,FS0
FDIV.S FS11,FS1,FS2,RMM
FSQRT.S F4,F5,DYN
FMADD.S F1,F2,F3,F4
FNMSUB.S F1,F2,F3,F4,RUP
FSGNJX.S F6,F7,F8
FMV.S F9,F10
FNEG.S F9,F10
FABS.S F9,F10
FMIN.S F11,F12,F13
FMAX.S F11,F12,F13
FEQ.S A0,F1,F2
FLT.S A1,F1,F2
FLE.S A2,F1,F2
FCVT.W.S A3,F4,RTZ
FCVT.WU.S A4,F4
FCVT.S.W F5,A5
FCVT.S.WU F6,A6,RDN
FMV.X.W T0,F7
FMV.W.X F8,T1
FCLASS.S T2,F9
CSRR A0,FCSR
CSRW FRM,A1
RET
MSG: DB "HI",13,10,0
ALIGN 4
@@ -103,36 +196,65 @@ def to_gnu(src):
return "\n".join(out) + "\n"
def main():
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
capture_output=True, text=True).stdout.strip()
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=SRC,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL the monitor's assembler: " + ours)
sys.exit(1)
start, ours = ours.split()
tmp = tempfile.mkdtemp()
open(os.path.join(tmp, "t.s"), "w").write(to_gnu(SRC))
subprocess.run([pre + "as", "-march=rv32im_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"),
def assemble_gnu(pre, text, tmp):
open(os.path.join(tmp, "t.s"), "w").write(text)
subprocess.run([pre + "as", "-march=rv32imf_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"),
os.path.join(tmp, "t.s")], check=True)
subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o", os.path.join(tmp, "t.elf"),
os.path.join(tmp, "t.o")], check=True)
subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o",
os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.o")], check=True)
subprocess.run([pre + "objcopy", "-O", "binary", os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.bin")],
check=True)
gnu = open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper()
# GNU pads the section's end to a word
if len(gnu) > len(ours) and set(gnu[len(ours):]) <= {"0"}:
return open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper()
def compare(what, src, gnu_text, pre):
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=src,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL %s: the monitor's assembler says %s" % (what, ours))
return False
start, ours = ours.split()
gnu = assemble_gnu(pre, gnu_text, tempfile.mkdtemp())
if 0 < len(gnu) - len(ours) < 32: # GNU pads the section's end to 16 bytes
gnu = gnu[:len(ours)]
ok = start == "12000" and ours == gnu
if not ok:
for i in range(0, max(len(ours), len(gnu)), 8):
if ours[i:i + 8] != gnu[i:i + 8]:
print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8], gnu[i:i + 8]))
print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8],
gnu[i:i + 8]))
break
print("lengths: monitor %d bytes, GNU %d" % (len(ours) // 2, len(gnu) // 2))
print(("PASS" if ok else "FAIL") + " %d bytes from 12000h the same as GNU as" % (len(ours) // 2))
sys.exit(0 if ok else 1)
print(("PASS" if ok else "FAIL") + " %s: %d bytes from 12000h the same as GNU as" % (what, len(ours) // 2))
return ok
def host(cmd, text):
return subprocess.run([os.path.join(HERE, "out", "monitor-host"), cmd], input=text,
capture_output=True, text=True).stdout
def main():
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
capture_output=True, text=True).stdout.strip()
ok = compare("GNU syntax", GNU_SRC, GNU_SRC.replace(".org 0x12000", ""), pre)
ok &= compare("the older forms", SRC, to_gnu(SRC), pre)
# the same lines as BASIC stores them, in capitals outside double quotes
# (BASIC knows nothing of \" in a string, so that line is left out), and
# with ; comments
plain = "\n".join(l for l in GNU_SRC.splitlines() if '\\"' not in l)
upper = re.sub(r'("[^"]*")|[a-z]', lambda m: m.group(1) or m.group(0).upper(), plain)
upper = upper.replace("#", ";")
want = host("asmbin", plain)
same = host("asmbin", upper) == want and "ERROR" not in want
print(("PASS" if same else "FAIL") + " the same in capitals, with ; comments")
ok &= same
# errors
errs = {".align 33": "ALIGN", ".equ 5": "NAME", "li a0, %mid(5)": "BAD EXPRESSION",
".ascii 5": "BAD STRING", "lw a0, 0(q9)": "REGISTER", ".byte 0b102": "BAD NUMBER"}
bad = [k for k, v in errs.items() if v not in host("asm", k + "\n")]
print(("PASS" if not bad else "FAIL %s" % bad) + " errors")
sys.exit(0 if ok and not bad else 1)
if __name__ == "__main__":
+44 -3
View File
@@ -66,6 +66,27 @@ def words():
ws.append(0x13 | r() << 7 | 0 << 15 | imm << 20) # li
ws.append(0x13 | r() << 7 | r() << 15) # mv
ws.append(0x00008067) # ret
# F
rms = [0, 1, 2, 3, 4, 7]
for _ in range(N):
imm = random.randrange(4096)
ws.append(0x07 | 2 << 12 | r() << 7 | r() << 15 | imm << 20) # flw
ws.append(0x27 | 2 << 12 | (imm & 31) << 7 | r() << 15 | r() << 20 | (imm >> 5) << 25)
ws.append(random.choice([0x43, 0x47, 0x4B, 0x4F]) | random.choice(rms) << 12 | r() << 7 |
r() << 15 | r() << 20 | r() << 27)
f5, f3 = random.choice([(0, None), (1, None), (2, None), (3, None), (4, 0), (4, 1), (4, 2),
(5, 0), (5, 1), (0x14, 0), (0x14, 1), (0x14, 2)])
ws.append(0x53 | f5 << 27 | (random.choice(rms) if f3 is None else f3) << 12 | r() << 7 |
r() << 15 | r() << 20)
rr = r()
ws.append(0x53 | 4 << 27 | random.randrange(3) << 12 | r() << 7 | rr << 15 | rr << 20) # fmv.s ...
ws.append(0x53 | 0x0B << 27 | random.choice(rms) << 12 | r() << 7 | r() << 15) # fsqrt
ws.append(0x53 | random.choice([0x18, 0x1A]) << 27 | random.randrange(2) << 20 |
random.choice(rms) << 12 | r() << 7 | r() << 15) # fcvt
ws.append(0x53 | 0x1C << 27 | random.randrange(2) << 12 | r() << 7 | r() << 15) # fmv.x.w fclass
ws.append(0x53 | 0x1E << 27 | r() << 7 | r() << 15) # fmv.w.x
ws.append(0x73 | random.choice([1, 2, 3, 5, 6, 7]) << 12 | r() << 7 | r() << 15 |
random.choice([1, 2, 3]) << 20) # fcsr
ws += [0x13, 0x73, 0x00100073, 0x30200073, 0x70200073, 0x10500073, 0x0FF0000F, 0x100F]
return ws
@@ -95,10 +116,22 @@ CSRN = {"MSTATUS": 0x300, "MISA": 0x301, "MIE": 0x304, "MTVEC": 0x305, "MSCRATCH
"MNEPC": 0x741, "MNCAUSE": 0x742, "MNSTATUS": 0x744, "TSELECT": 0x7A0, "TDATA1": 0x7A1,
"TDATA2": 0x7A2, "TCONTROL": 0x7A5, "MCYCLE": 0xB00, "MINSTRET": 0xB02, "MCYCLEH": 0xB80,
"MINSTRETH": 0xB82, "CYCLE": 0xC00, "TIME": 0xC01, "INSTRET": 0xC02, "CYCLEH": 0xC80,
"TIMEH": 0xC81, "INSTRETH": 0xC82, "MHARTID": 0xF14}
"TIMEH": 0xC81, "INSTRETH": 0xC82, "MHARTID": 0xF14,
"FFLAGS": 1, "FRM": 2, "FCSR": 3}
# objdump's short forms for the float CSRs: read, write, write immediate
FCSR_ALIAS = {"FRCSR": ("FCSR", "R"), "FRRM": ("FRM", "R"), "FRFLAGS": ("FFLAGS", "R"),
"FSCSR": ("FCSR", ""), "FSRM": ("FRM", ""), "FSFLAGS": ("FFLAGS", ""),
"FSRMI": ("FRM", "I"), "FSFLAGSI": ("FFLAGS", "I")}
FABI = ["FT%d" % i for i in range(8)] + ["FS0", "FS1"] + ["FA%d" % i for i in range(8)] + \
["FS%d" % i for i in range(2, 12)] + ["FT%d" % i for i in range(8, 12)]
def same(gnu_mn, gnu_ops, our):
# ours is in lower case, with float registers by ABI name: objdump -M
# numeric's f0-f31
our = re.sub(r"\bF[TSA]\d+\b", lambda q: "F%d" % FABI.index(q.group(0)), our.upper())
m = our.split(None, 1)
mn = m[0]
ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else []
@@ -109,9 +142,17 @@ def same(gnu_mn, gnu_ops, our):
gnu_ops = ["RA"] + gnu_ops
elif gnu_mn.startswith("RD") and gnu_mn[2:] in CSRN:
gnu_mn, gnu_ops = "CSRR", gnu_ops + [gnu_mn[2:]]
elif gnu_mn in FCSR_ALIAS:
csr, kind = FCSR_ALIAS[gnu_mn]
if kind == "R":
gnu_mn, gnu_ops = "CSRR", gnu_ops + [csr]
elif len(gnu_ops) == 2:
gnu_mn, gnu_ops = "CSRRW" + kind, [gnu_ops[0], csr, gnu_ops[1]]
else:
gnu_mn, gnu_ops = "CSRW" + kind, [csr] + gnu_ops
gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops]
ops = [str(CSRN[o]) if o in CSRN else o for o in ops]
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"}
alias = {"FENCE.I": "FENCE.I", "UNIMP": ".WORD"}
if alias.get(gnu_mn, gnu_mn) != mn:
return False
# objdump writes "fence iorw,iorw"
@@ -174,7 +215,7 @@ def main():
print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o))
# round trip through the monitor's assembler, one instruction at 1000h each
bad_asm = 0
back = subprocess.run([HOST, "asm"], input="".join("ORG 1000H\n%s\n" % o for o in ours),
back = subprocess.run([HOST, "asm"], input="".join(".org 0x1000\n%s\n" % o for o in ours),
capture_output=True, text=True).stdout.splitlines()
for w, o, b in zip(ws, ours, back):
want = 0x0FF0000F if (w & 0x707F) == 0x0F else w
+19 -13
View File
@@ -2,13 +2,13 @@
// Basys 3 VT220 terminal with ANSI colour, and a RISC-V computer running BASIC.
// SW15 down: keyboard (USB HID port) -> UART TX (USB-UART port),
// UART RX -> 80x30 colour text on VGA
// UART RX -> 132x64 (or 80x32) colour text on VGA
// SW15 up: the terminal is the computer's console
//
// SW1:0 baud rate: 00 115200, 01 9600, 10 921600, 11 3000000 (8N1)
// SW2 local echo
// SW3 received LF also does CR
// SW5:4 default text colour: 00 green, 01 yellow, 10 white, 11 cyan
// SW5:4 default text colour: 00 white, 01 yellow, 10 green, 11 cyan
// SW6 Backspace sends DEL (7F) instead of BS (08)
// SW7 Enter sends CR LF instead of CR
// SW8 smooth scrolling (also turned on by ESC [ ? 4 h)
@@ -30,10 +30,11 @@ module basys3_terminal #(
parameter MEM_FILE = "basic.mem",
parameter MEM_HI_FILE = "basic-hi.mem",
parameter MON_FILE = "monitor.mem",
parameter WIDE_BOOT = 1, // the screen starts at 132x64 (0: 80x32)
parameter CLK_HZ = 100_000_000,
parameter real CPU_MULT = 9.0, // CPU clock = 100 MHz * CPU_MULT / CPU_DIV
parameter real CPU_MULT = 10.0, // CPU clock = 100 MHz * CPU_MULT / CPU_DIV
parameter real CPU_DIV = 10.0,
parameter CPU_HZ = 90_000_000,
parameter CPU_HZ = 100_000_000,
parameter ROM_TOP = 32'h0000_A000 // BASIC's code is below; writes there are ignored
) (
input clk,
@@ -93,9 +94,9 @@ module basys3_terminal #(
reg [3:0] def_fg;
always @(posedge clk)
case (sw_r[5:4])
2'b00: def_fg <= 4'd10; // bright green
2'b00: def_fg <= 4'd15; // white
2'b01: def_fg <= 4'd11; // yellow
2'b10: def_fg <= 4'd7; // white
2'b10: def_fg <= 4'd10; // bright green
2'b11: def_fg <= 4'd14; // bright cyan
endcase
@@ -246,10 +247,11 @@ module basys3_terminal #(
// Start-up banner, fed in like received text. Bytes are read from the
// high end of the string; the unused high bytes are zero and skipped.
localparam [8*200-1:0] BANNER = {
"\033[1mBasys 3 VT220 Terminal\033[0m 80x32 ",
"\033[1mBasys 3 VT220 Terminal\033[0m ", WIDE_BOOT ? "132x64" : "80x32 ", " ",
"\033[31mc\033[33mo\033[32ml\033[36mo\033[34mu\033[35mr\033[0m ",
"\033[4munderline\033[0m\015\012",
"UART RX -> screen, keyboard -> UART TX TERM=basys3 or vt220\015\012\012"};
"UART RX -> screen, keyboard -> UART TX TERM=vt220 or ",
WIDE_BOOT ? "basys3-w" : "basys3 ", "\015\012\012"};
// (not shown in computer mode, where BASIC prints its own)
reg [7:0] ban_i;
wire [7:0] ban_c = BANNER[ban_i*8 +: 8];
@@ -331,7 +333,8 @@ module basys3_terminal #(
wire sp_go, sp_buf, sp_on, pix_frame;
wire [8:0] scroll_x;
wire [7:0] scroll_y;
wire g_border;
wire g_border, g_hires;
wire [7:0] g_cols;
wire [7:0] sp_line;
wire [8:0] sp_x;
wire [3:0] sp_pix;
@@ -343,13 +346,15 @@ module basys3_terminal #(
(* ASYNC_REG = "TRUE" *) reg [2:0] brk_s = 3'd0;
always @(posedge cpu_clk) brk_s <= {brk_s[1:0], brk_t};
wire wide; // DECCOLM from the terminal (term_ctrl below)
rv32_system #(.MEM_FILE(MEM_FILE), .MEM_HI_FILE(MEM_HI_FILE), .MON_FILE(MON_FILE), .CPU_HZ(CPU_HZ), .ROM_TOP(ROM_TOP)) sys (
.clk(cpu_clk), .rst(cpu_rst_s[2]),
.rx_req(zrx_req), .rx_data(zrx_data), .rx_ack(zrx_ack),
.tx_req(ztx_req), .tx_data(ztx_data), .tx_ack(ztx_ack),
.tx_req(ztx_req), .tx_data(ztx_data), .tx_ack(ztx_ack), .wide(wide),
.seg_val(rv_seg), .halted(), .brk_key(brk_s[2] ^ brk_s[1]),
.vclk(pix_clk), .gfx_vaddr(gfx_addr), .gfx_vpix(gfx_pix),
.scroll_x(scroll_x), .scroll_y(scroll_y), .g_border(g_border),
.g_hires(g_hires), .g_cols(g_cols),
.sp_go(sp_go), .sp_line(sp_line), .sp_buf(sp_buf), .sp_x(sp_x), .sp_on(sp_on),
.sp_pix(sp_pix), .sp_ftick(pix_frame), .keys(keys_down),
.fl_cs_n(QspiCSn), .fl_sck(fl_sck), .fl_mosi(QspiDB[0]), .fl_miso(QspiDB[1]),
@@ -425,7 +430,7 @@ module basys3_terminal #(
// ------------------------------------------------------------- terminal
wire [13:0] t_addr;
wire alt_scr, wide;
wire alt_scr;
wire t_we;
wire [17:0] t_wdata, t_rdata;
wire [5:0] cur_row, stop, sbot;
@@ -443,7 +448,7 @@ module basys3_terminal #(
always @(posedge clk) frame_s <= {frame_s[1:0], frame_t};
assign frame_tick = frame_s[2] ^ frame_s[1];
term_ctrl term (
term_ctrl #(.WIDE_BOOT(WIDE_BOOT)) term (
.clk(clk), .rst(rst), .in_byte(tq), .in_empty(tq_empty), .in_rd(tq_rd),
.lf_cr(sw_r[3]), .clear_req(clr_sync[1]), .def_fg(def_fg),
.smooth_sw(sw_r[8]), .smooth_fast(sw_r[9]), .frame_tick(frame_tick),
@@ -471,8 +476,9 @@ module basys3_terminal #(
.clk(pix_clk), .rst(pix_rst_s[1]), .wide(wide),
.cur_row(cur_row), .cur_col(cur_col), .cur_vis(cur_vis),
.stop(stop), .sbot(sbot), .sm_on(sm_on), .sm_dir(sm_dir), .sm_off(sm_off),
.ram_addr(v_addr), .ram_data(v_data), .gfx_addr(gfx_addr), .gfx_pix(alt_scr ? 4'd0 : gfx_pix),
.ram_addr(v_addr), .ram_data(v_data), .gfx_addr(gfx_addr), .gfx_pix(gfx_pix),
.scroll_x(scroll_x), .scroll_y(scroll_y), .g_border(g_border),
.g_hires(g_hires), .g_cols(g_cols), .g_show(!alt_scr),
.sp_go(sp_go), .sp_line(sp_line), .sp_buf(sp_buf), .sp_x(sp_x), .sp_on(sp_on),
.sp_pix(alt_scr ? 4'd0 : sp_pix),
.red(vgaRed), .green(vgaGreen), .blue(vgaBlue), .hsync(Hsync), .vsync(Vsync),
+108 -20
View File
@@ -1,12 +1,16 @@
`timescale 1ns / 1ps
// RV32IM processor, machine mode only.
// RV32IMF processor, machine mode only.
//
// A multi-cycle core with one instruction in flight. Each instruction is
// decoded in one cycle (D) and executed in the next (E); the decode cycle
// fetches the following word, so straight-line code takes 2 clocks per
// instruction. Taken branches and jumps take 3, loads and stores 3 (more if
// the bus waits), multiplies 4 and divides 35.
// the bus waits), multiplies 4 and divides 35. Floating-point operations run
// in rv32_fpu.v: 4 clocks for moves, sign injection, compares, min/max and
// class, 5 for float -> int, 9 for int -> float, 13 for add, subtract,
// multiply and the multiply-adds (4 if an operand is infinite, NaN or zero),
// 37 for divide and square root; float loads and stores as integer ones.
//
// Instruction port: synchronous read. i_rdata is the word at the i_addr given
// in the last cycle with i_en high, and must hold while i_en is low.
@@ -25,10 +29,12 @@
// breakpoint) are raised one cycle late, from registers, to keep the long
// paths out of the trap logic; the instruction has no effect either way.
//
// Speed: 90 MHz with 1.5 ns to spare on the XC7A35T-1 (bench/), about 2100
// LUTs, 900 flip-flops and 4 DSP slices.
// Speed: 100 MHz in the full design on the XC7A35T-1. The integer core
// alone (bench/) is about 2100 LUTs, 900 flip-flops and 4 DSP slices.
//
// Implemented: RV32I, M, Zicsr, Zicntr (cycle, time = cycle, instret), Zifencei,
// Implemented: RV32I, M, F (rv32_fpu.v; fflags, frm, fcsr; mstatus.FS, which
// resets to Initial: F instructions and CSRs are illegal while it is Off,
// and any F instruction or F CSR write makes it Dirty), Zicsr, Zicntr (cycle, time = cycle, instret), Zifencei,
// mret and wfi (a no-op). Machine-mode CSRs: mstatus (MIE, MPIE; MPP reads 3),
// misa, mie, mip, mtvec (direct mode), mscratch, mepc, mcause, mtval, mcycle,
// minstret, mhartid etc. (read 0), and two Sdtrig match triggers (tselect,
@@ -74,9 +80,9 @@ module rv32_cpu #(
output dbg_decode, // high in an instruction's first cycle
output reg retire // pulse: an instruction completed
);
localparam S_IF = 3'd0, S_D = 3'd1, S_E = 3'd2, S_MEM = 3'd3,
S_MUL = 3'd4, S_DIV = 3'd5, S_DIVF = 3'd6, S_XT = 3'd7;
reg [2:0] state;
localparam S_IF = 4'd0, S_D = 4'd1, S_E = 4'd2, S_MEM = 4'd3,
S_MUL = 4'd4, S_DIV = 4'd5, S_DIVF = 4'd6, S_XT = 4'd7, S_FP = 4'd8;
reg [3:0] state;
reg [31:0] pc;
assign i_en = state == S_IF || state == S_D;
@@ -94,6 +100,15 @@ module rv32_cpu #(
reg [31:0] rf_wd;
always @(posedge clk) if (rf_we && rf_wa != 5'd0) rf[rf_wa] <= rf_wd;
// Floating-point registers: distributed RAM, three read ports.
reg [31:0] frf [0:31];
initial for (k = 0; k < 32; k = k + 1) frf[k] = 32'd0;
reg frf_we;
reg [31:0] frf_wd;
reg [1:0] fs; // mstatus.FS
reg [4:0] fflags;
reg [2:0] frm;
// ------------------------------------------------------------------
// Decode (state D): inst is the fetched word.
wire [31:0] inst = i_rdata;
@@ -103,6 +118,8 @@ module rv32_cpu #(
wire [4:0] rs1 = inst[19:15], rs2 = inst[24:20];
wire [31:0] rv1 = rs1 == 5'd0 ? 32'd0 : rf[rs1];
wire [31:0] rv2 = rs2 == 5'd0 ? 32'd0 : rf[rs2];
wire [4:0] rs3 = inst[31:27];
wire [31:0] fv1 = frf[rs1], fv2 = frf[rs2], fv3 = frf[rs3];
wire [31:0] imm_i = {{20{inst[31]}}, inst[31:20]};
wire [31:0] imm_s = {{20{inst[31]}}, inst[31:25], inst[11:7]};
@@ -133,9 +150,31 @@ module rv32_cpu #(
wire is_mret = inst == 32'h3020_0073;
wire is_wfi = inst == 32'h1050_0073;
wire is_mnret = inst == 32'h7020_0073;
// F: loads, stores, the multiply-adds and OP-FP
wire fp_on = fs != 2'b00;
wire [2:0] rm_d = f3 == 3'd7 ? frm : f3;
wire rm_ok = rm_d <= 3'd4;
wire [4:0] f5 = inst[31:27];
wire is_flw = opc == 7'b0000111 && f3 == 3'd2;
wire is_fsw = opc == 7'b0100111 && f3 == 3'd2;
wire is_fr4 = opc[6:4] == 3'b100 && opc[1:0] == 2'b11 && inst[26:25] == 2'b00 && rm_ok;
wire is_fop = opc == 7'b1010011 && inst[26:25] == 2'b00 &&
((f5 <= 5'h03 && rm_ok) || // add sub mul div
(f5 == 5'h0B && rs2 == 5'd0 && rm_ok) || // sqrt
(f5 == 5'h04 && f3 <= 3'd2) || // sgnj
(f5 == 5'h05 && f3 <= 3'd1) || // min max
(f5 == 5'h14 && f3 <= 3'd2) || // le lt eq
(f5 == 5'h18 && rs2[4:1] == 4'd0 && rm_ok) || // fcvt.w[u].s
(f5 == 5'h1A && rs2[4:1] == 4'd0 && rm_ok) || // fcvt.s.w[u]
(f5 == 5'h1C && rs2 == 5'd0 && f3 <= 3'd1) || // fmv.x.w fclass
(f5 == 5'h1E && rs2 == 5'd0 && f3 == 3'd0)); // fmv.w.x
wire fp_toint = opc == 7'b1010011 && (f5 == 5'h18 || f5 == 5'h1C || f5 == 5'h14);
wire fp_frint = opc == 7'b1010011 && (f5 == 5'h1A || f5 == 5'h1E);
wire is_fp = fp_on && (is_fr4 || is_fop);
wire legal = is_lui | is_auipc | is_jal | is_jalr | is_br | is_ld | is_st |
is_opi | is_op | is_mdv | is_fence | is_fencei | is_csr |
is_ecall | is_ebrk | is_mret | is_wfi | is_mnret;
is_ecall | is_ebrk | is_mret | is_wfi | is_mnret |
(fp_on && (is_flw || is_fsw)) | is_fp;
// ------------------------------------------------------------------
// Execute-stage registers, loaded at the end of D.
@@ -148,7 +187,10 @@ module rv32_cpu #(
reg x_trap; // the deferred trap, below
reg [31:0] x_cause, x_val;
reg e_alu, e_sub, e_jal, e_jalr, e_br, e_ld, e_st, e_mul, e_div,
e_csr, e_ecall, e_ebrk, e_mret, e_mnret, e_fencei, e_ill;
e_csr, e_ecall, e_ebrk, e_mret, e_mnret, e_fencei, e_ill,
e_fp, e_fpint, e_fd; // F operation, its result to x, a load to f
reg [31:0] fa, fb, fc; // F operands
reg [2:0] e_rm;
wire [2:0] e_f3 = ir[14:12];
wire [4:0] e_rd = ir[11:7];
reg [2:0] alu_fn;
@@ -221,8 +263,11 @@ module rv32_cpu #(
always @* begin
csr_ok = 1'b1;
case (csr_a)
12'h300: csr_rd = {19'd0, 2'b11, 3'd0, mpie_b, 3'd0, mie_b, 3'd0};
12'h301: csr_rd = 32'h4000_1100; // RV32 I M
12'h001: begin csr_rd = {27'd0, fflags}; csr_ok = fp_on; end
12'h002: begin csr_rd = {29'd0, frm}; csr_ok = fp_on; end
12'h003: begin csr_rd = {24'd0, frm, fflags}; csr_ok = fp_on; end
12'h300: csr_rd = {fs == 2'b11, 16'd0, fs, 2'b11, 3'd0, mpie_b, 3'd0, mie_b, 3'd0};
12'h301: csr_rd = 32'h4000_1120; // RV32 I M F
12'h304: csr_rd = mie_r;
12'h305: csr_rd = mtvec;
12'h310: csr_rd = 32'd0; // mstatush
@@ -346,16 +391,34 @@ module rv32_cpu #(
end
end
// floating point
wire fpu_done;
wire [31:0] fpu_res;
wire [4:0] fpu_flags;
rv32_fpu fpu (
.clk(clk), .rst(rst), .start(state == S_E && e_fp && !trap),
.ins(ir), .rm(e_rm), .a(fa), .b(fb), .c(fc),
.done(fpu_done), .result(fpu_res), .flags(fpu_flags)
);
// ------------------------------------------------------------------
// Register write-back
always @* begin
rf_we = 1'b0; rf_wa = e_rd; rf_wd = alu_out;
frf_we = 1'b0; frf_wd = fpu_res;
case (state)
S_E: begin
rf_we = !trap && (e_alu || e_jal || e_jalr || e_csr);
rf_wd = e_csr ? csr_rd : (e_jal || e_jalr) ? pc4 : alu_out;
end
S_MEM: begin rf_we = d_ack && e_ld; rf_wd = ld_val; end
S_MEM: begin
rf_we = d_ack && e_ld && !e_fd; rf_wd = ld_val;
frf_we = d_ack && e_fd; frf_wd = d_rdata;
end
S_FP: begin
rf_we = fpu_done && e_fpint; rf_wd = fpu_res;
frf_we = fpu_done && !e_fpint;
end
S_MUL: begin rf_we = m_cnt; rf_wd = m_hi ? m_p2[63:32] : m_p2[31:0]; end
S_DIVF: begin
rf_we = 1'b1;
@@ -368,9 +431,12 @@ module rv32_cpu #(
endcase
end
always @(posedge clk) if (frf_we) frf[e_rd] <= frf_wd;
// an instruction completes (counted by instret unless it writes instret)
reg count_i;
wire done = (state == S_E && !trap && !e_ld && !e_st && !e_mul && !e_div) ||
wire done = (state == S_E && !trap && !e_ld && !e_st && !e_mul && !e_div && !e_fp) ||
(state == S_FP && fpu_done) ||
(state == S_MEM && d_ack) || (state == S_MUL && m_cnt) ||
state == S_DIVF || (state == S_XT && !x_trap);
@@ -387,7 +453,10 @@ module rv32_cpu #(
if (csr_go) begin
case (csr_a)
12'h300: begin mie_b <= csr_wv[3]; mpie_b <= csr_wv[7]; end
12'h001: begin fflags <= csr_wv[4:0]; fs <= 2'b11; end
12'h002: begin frm <= csr_wv[2:0]; fs <= 2'b11; end
12'h003: begin {frm, fflags} <= csr_wv[7:0]; fs <= 2'b11; end
12'h300: begin mie_b <= csr_wv[3]; mpie_b <= csr_wv[7]; fs <= csr_wv[14:13]; end
12'h304: mie_r <= csr_wv & MIE_MASK;
12'h305: mtvec <= {csr_wv[31:2], 2'b00};
12'h340: mscratch <= csr_wv;
@@ -421,9 +490,16 @@ module rv32_cpu #(
pc4 <= pc + 32'd4;
tgt <= pc + (is_jal ? imm_j : imm_b);
a <= is_lui ? 32'd0 : (is_auipc || is_jal) ? pc : rv1;
b <= (is_lui || is_auipc) ? imm_u : is_st ? imm_s :
b <= (is_lui || is_auipc) ? imm_u : (is_st || is_fsw) ? imm_s :
(is_op || is_br || is_mdv) ? rv2 : imm_i;
sv <= rv2;
sv <= is_fsw ? fv2 : rv2;
fa <= fp_frint ? rv1 : fv1;
fb <= fv2;
fc <= fv3;
e_rm <= rm_d;
e_fp <= is_fp;
e_fpint <= fp_toint;
e_fd <= is_flw && fp_on;
alu_fn <= (is_lui || is_auipc) ? 3'd0 : f3;
alu_alt <= inst[30];
e_alu <= is_lui | is_auipc | is_opi | is_op;
@@ -432,8 +508,8 @@ module rv32_cpu #(
e_jalr <= is_jalr;
e_br <= is_br;
e_tmis <= is_jal ? inst[21] : inst[8];
e_ld <= is_ld;
e_st <= is_st;
e_ld <= is_ld || (is_flw && fp_on);
e_st <= is_st || (is_fsw && fp_on);
e_mul <= is_mdv & !f3[2];
e_div <= is_mdv & f3[2];
e_csr <= is_csr;
@@ -471,6 +547,8 @@ module rv32_cpu #(
state <= S_MUL;
else if (e_div)
state <= S_DIV;
else if (e_fp)
state <= S_FP;
else if (e_br && e_tmis)
state <= S_XT;
else if (e_mret) begin
@@ -492,7 +570,16 @@ module rv32_cpu #(
end
end
S_MEM: if (d_ack) begin pc <= pc4; state <= S_D; end
S_MEM: if (d_ack) begin
pc <= pc4; state <= S_D;
if (e_fd) fs <= 2'b11;
end
S_FP: if (fpu_done) begin
pc <= pc4; state <= S_D;
fflags <= fflags | fpu_flags;
fs <= 2'b11;
end
S_MUL: begin
m_cnt <= 1'b1;
@@ -546,6 +633,7 @@ module rv32_cpu #(
mcycle <= 64'd0; minstret <= 64'd0;
retire <= 1'b0; count_i <= 1'b0;
nmie <= 1'b1; stepped <= 1'b0; nmi_taken <= 1'b0;
fs <= 2'b01; fflags <= 5'd0; frm <= 3'd0;
end
end
endmodule
+499
View File
@@ -0,0 +1,499 @@
`timescale 1ns / 1ps
// Single-precision floating point for rv32_cpu (the F extension), IEEE 754
// with all five rounding modes, subnormals, the five exception flags and
// RISC-V's canonical NaN. tools/f32.py is the reference it is tested against
// (scripts/fputest.sh).
//
// One operation at a time: `start` (one cycle) with the instruction word, the
// resolved rounding mode and the operands; `done` pulses with the result and
// the flags. a is the integer register for FMV.W.X and FCVT.S.W[U].
//
// Every arithmetic operation ends in the same normalise-and-round back end,
// which takes an unrounded value as sign, a 77-bit significand X and the
// exponent ex the value would have with X's top bit set (X * 2^(ex-127-76)).
// multiply-add a*b (DSPs, exact) and c aligned to it, added in 77 bits:
// add, subtract and multiply are a*1+c, a*1-c and a*b alone
// divide 27 quotient bits, one a clock, and a remainder sticky bit
// square root 27 root bits, one a clock, and a remainder sticky bit
// int -> float the integer itself
// The rest (sign injection, min/max, compares, class, moves, float -> int)
// finish without it.
//
// Clocks from start to done: multiply-add family 11 (2 when an operand is
// infinite, NaN or zero), divide and square root 35, int -> float 7,
// float -> int 3, the rest 2. (Exponents, leading zeros and the FADD/FSUB
// operand swap are worked out as the operands are taken, and the back end
// finds the leading one a clock before using it, for 100 MHz.)
module rv32_fpu (
input clk,
input rst,
input start,
input [31:0] ins,
input [2:0] rm,
input [31:0] a, b, c,
output reg done,
output reg [31:0] result,
output reg [4:0] flags // NV DZ OF UF NX
);
localparam NV = 5'b10000, DZ = 5'b01000, OF = 5'b00100, UF = 5'b00010, NX = 5'b00001;
localparam [31:0] QNAN = 32'h7FC0_0000;
localparam S_IDLE = 4'd0, S_U = 4'd1, S_M1 = 4'd2, S_M2 = 4'd3, S_ADD = 4'd4,
S_ABS = 4'd5, S_N1 = 4'd6, S_N2 = 4'd7, S_R1 = 4'd8, S_R2 = 4'd9,
S_DIV = 4'd10, S_SQRT = 4'd11, S_CW = 4'd12, S_DIVF = 4'd13,
S_SQRTF = 4'd14, S_NZ = 4'd15;
reg [3:0] st;
// ------------------------------------------------------------ operands
reg [31:0] ra, rb, rc, ri;
reg [2:0] rrm;
wire [6:0] opc = ri[6:0];
wire [2:0] f3 = ri[14:12];
wire [4:0] f5 = ri[31:27];
wire r4 = opc[6:4] == 3'b100; // FMADD FMSUB FNMSUB FNMADD
wire op_add = !r4 && (f5 == 5'h00 || f5 == 5'h01);
wire op_mul = !r4 && f5 == 5'h02;
wire op_div = !r4 && f5 == 5'h03;
wire op_sqrt = !r4 && f5 == 5'h0B;
wire op_cvtw = !r4 && f5 == 5'h18; // float -> int
wire op_cvts = !r4 && f5 == 5'h1A; // int -> float
wire op_fma = r4 || op_add || op_mul;
wire uns = ri[20];
// a (for FADD/FSUB the multiplier is 1.0), b, c: picked, with their
// exponents and leading zeros, as the operands arrive (see S_IDLE)
reg [31:0] rxb, rxc;
wire [31:0] xa = ra;
wire [31:0] xb = rxb;
wire [31:0] xc = rxc;
wire negp = r4 && opc[3];
wire negc = (r4 && opc[2]) || (op_add && f5[0]);
wire use_c = !op_mul;
function [7:0] ex8(input [31:0] x); ex8 = x[30:23]; endfunction
`define FZ(x) (x[30:0] == 31'd0)
`define FINF(x) (x[30:23] == 8'hFF && x[22:0] == 23'd0)
`define FNAN(x) (x[30:23] == 8'hFF && x[22:0] != 23'd0)
`define FSNAN(x) (`FNAN(x) && !x[22])
wire az = `FZ(xa), bz = `FZ(xb), cz = `FZ(xc);
wire ai = `FINF(xa), bi = `FINF(xb), ci = `FINF(xc);
wire an = `FNAN(xa), bn = `FNAN(xb), cn = `FNAN(xc);
wire as_ = `FSNAN(xa), bs = `FSNAN(xb), cs = `FSNAN(xc);
wire [23:0] ma = {ex8(xa) != 8'd0, xa[22:0]};
wire [23:0] mb = {ex8(xb) != 8'd0, xb[22:0]};
wire [23:0] mc = {ex8(xc) != 8'd0, xc[22:0]};
reg signed [11:0] ea, eb, ec; // exponents (1 for a subnormal)
reg signed [11:0] eab; // ea + eb - 127, the product's
wire sp = xa[31] ^ xb[31] ^ negp;
wire sc = xc[31] ^ negc;
// ------------------------------------------------- simple operations
// a < b and a == b for numbers (not NaN)
wire a_lt_b = (az && bz) ? 1'b0 :
(ra[31] != rb[31]) ? ra[31] :
ra[31] ? ra[30:0] > rb[30:0] : ra[30:0] < rb[30:0];
wire b_lt_a = (az && `FZ(rb)) ? 1'b0 :
(ra[31] != rb[31]) ? rb[31] :
ra[31] ? rb[30:0] > ra[30:0] : rb[30:0] < ra[30:0];
wire a_eq_b = ra == rb || (`FZ(ra) && `FZ(rb));
wire rbn = `FNAN(rb), rbs = `FSNAN(rb), rbz = `FZ(rb);
reg [31:0] simple_r;
reg [4:0] simple_f;
always @* begin
simple_r = 32'd0; simple_f = 5'd0;
case (f5)
5'h04: simple_r = {f3 == 3'd0 ? rb[31] : f3 == 3'd1 ? ~rb[31] : ra[31] ^ rb[31], ra[30:0]};
5'h05: begin // FMIN / FMAX
simple_f = (as_ || rbs) ? NV : 5'd0;
if (an && rbn) simple_r = QNAN;
else if (an) simple_r = rb;
else if (rbn) simple_r = ra;
else if (az && rbz) simple_r = (f3[0] ? !ra[31] : ra[31]) ? ra : rb;
else if (f3[0]) simple_r = b_lt_a ? ra : (a_lt_b ? rb : ra);
else simple_r = a_lt_b ? ra : rb;
end
5'h14: begin // FLE FLT FEQ
if (an || rbn) begin
simple_r = 32'd0;
simple_f = (f3 == 3'd2) ? ((as_ || rbs) ? NV : 5'd0) : NV;
end else
simple_r = {31'd0, f3 == 3'd2 ? a_eq_b : f3 == 3'd1 ? a_lt_b : (a_lt_b || a_eq_b)};
end
5'h1C: begin
if (f3 == 3'd1) begin // FCLASS
simple_r[0] = ra[31] && ai;
simple_r[1] = ra[31] && ex8(ra) != 8'd0 && ex8(ra) != 8'hFF;
simple_r[2] = ra[31] && ex8(ra) == 8'd0 && !az;
simple_r[3] = ra[31] && az;
simple_r[4] = !ra[31] && az;
simple_r[5] = !ra[31] && ex8(ra) == 8'd0 && !az;
simple_r[6] = !ra[31] && ex8(ra) != 8'd0 && ex8(ra) != 8'hFF;
simple_r[7] = !ra[31] && ai;
simple_r[8] = as_;
simple_r[9] = an && !as_;
end else
simple_r = ra; // FMV.X.W
end
default: simple_r = ra; // FMV.W.X
endcase
end
// ---------------------------------------------------- the multiply-add
reg [23:0] pa, pb;
reg [47:0] p1, p2; // the product, two pipeline stages
always @(posedge clk) begin
p1 <= pa * pb;
p2 <= p1;
end
reg signed [11:0] ep; // biased exponent of the product
reg [23:0] c_m;
reg signed [11:0] c_e;
reg c_zero, s_p, s_c, noadd;
reg [76:0] c_al; // c aligned with the product (<< 3)
reg [77:0] sum;
reg signed [11:0] fx; // the back end's ex for the sum
// c's place: its lowest bit is at bit s+3 of the 77-bit window, with the
// product's at bit 3. s > 50 would leave a gap above the product; then c
// sits at the top and the exponent comes from c (the product only adds
// stickiness, which rounds the same at any distance that far down).
// (worked out from the operands in S_U, used in S_M1)
wire signed [12:0] s_u = {ec[11], ec} - {eab[11], eab} + 13'sd23;
reg signed [12:0] s_amt;
reg s_big;
reg [76:0] c_sh;
reg c_lost;
always @* begin
if (s_amt >= 0) begin
c_sh = {53'd0, c_m} << (s_amt + 3);
c_lost = 1'b0;
end else begin
// right by -s-3 (when negative), the lost bits make a sticky bit
c_sh = ({53'd0, c_m} << 3) >> (-s_amt);
c_lost = (-s_amt >= 13'sd27) ? c_m != 24'd0 :
((({53'd0, c_m} << 3) & ~({77{1'b1}} << (-s_amt))) != 77'd0);
end
end
// ------------------------------------------------------- the back end
reg n_sign;
reg [76:0] n_x;
reg signed [11:0] n_ex;
// leading one of n_x
reg [6:0] lz;
integer q;
always @* begin
lz = 7'd77;
for (q = 0; q <= 76; q = q + 1) if (n_x[q]) lz = 7'd76 - q[6:0];
end
reg signed [11:0] n_sh; // left shift (negative: right)
reg n_tiny; // below the normal range before rounding
reg n_zero;
reg [76:0] y;
reg y_st; // sticky from a right shift
reg [6:0] n_lz; // lz, registered in S_NZ
reg signed [11:0] e_norm; // n_ex - lz
reg signed [11:0] r_e; // the result's exponent (1 if subnormal)
// rounding
wire [23:0] y_m = y[76:53];
wire y_g = y[52];
wire y_s = y[51:0] != 52'd0 || y_st;
function rnd_up(input [2:0] m, input s, input lsb, input g, input st);
case (m)
3'd0: rnd_up = g && (st || lsb);
3'd1: rnd_up = 1'b0;
3'd2: rnd_up = s && (g || st);
3'd3: rnd_up = !s && (g || st);
default: rnd_up = g;
endcase
endfunction
reg r_inc, r_inexact, r_fine;
reg [23:0] r_m;
wire [24:0] r_mi = {1'b0, r_m} + {24'd0, r_inc};
// ------------------------------------------------- divide, square root
reg [26:0] dq;
reg [25:0] drem; // divide: remainder (< 2 * divisor)
reg [23:0] dden;
reg [4:0] dcnt;
wire [26:0] dtry = {1'b0, drem} - {3'd0, dden};
reg [53:0] srad; // square root: radicand, two bits a clock
reg [28:0] srem;
wire [30:0] stry_r = {srem, srad[53:52]};
wire [30:0] stry = stry_r - {2'd0, dq, 2'b01};
// leading zeros of a 24-bit significand (to normalise subnormals)
function [4:0] lz24(input [23:0] m);
integer i;
begin
lz24 = 5'd24;
for (i = 0; i < 24; i = i + 1) if (m[i]) lz24 = 5'd23 - i[4:0];
end
endfunction
reg [4:0] lza, lzb;
wire [23:0] na = ma << lza, nb = mb << lzb;
reg signed [11:0] nea, neb; // exponents of na, nb
// the same from the operands as they arrive
function signed [11:0] exb(input [31:0] x);
exb = x[30:23] == 8'd0 ? 12'sd1 : {4'd0, x[30:23]};
endfunction
function [23:0] mant(input [31:0] x); mant = {x[30:23] != 8'd0, x[22:0]}; endfunction
wire i_add = ins[6:4] != 3'b100 && ins[31:28] == 4'h0; // FADD, FSUB
wire [31:0] i_b = i_add ? 32'h3F80_0000 : b;
wire [31:0] i_c = i_add ? b : c;
wire [4:0] i_lza = lz24(mant(a)), i_lzb = lz24(mant(i_b));
// ------------------------------------------------------- float -> int
reg [32:0] cw_int;
reg cw_g, cw_s, cw_neg;
wire [47:0] cw_sh = {ma, 24'd0} >> (8'd150 - ex8(ra));
wire cw_inc = rnd_up(rrm, cw_neg, cw_int[0], cw_g, cw_s);
wire [32:0] cw_mag = cw_int + {32'd0, cw_inc};
// --------------------------------------------------------------------
always @(posedge clk) begin
done <= 1'b0;
case (st)
S_IDLE: if (start) begin
ra <= a; rb <= b; rc <= c; ri <= ins; rrm <= rm;
rxb <= i_b; rxc <= i_c;
ea <= exb(a); eb <= exb(i_b); ec <= exb(i_c);
eab <= exb(a) + exb(i_b) - 12'sd127;
lza <= i_lza; lzb <= i_lzb;
nea <= exb(a) - {7'd0, i_lza};
neb <= exb(i_b) - {7'd0, i_lzb};
st <= S_U;
end
S_U: begin
// multiply-add specials (only used by the multiply-add family)
pa <= ma; pb <= mb;
ep <= eab;
c_m <= mc; c_e <= ec; c_zero <= cz || !use_c;
s_big <= !(cz || !use_c) && s_u > 13'sd50;
s_amt <= (!(cz || !use_c) && s_u > 13'sd50) ? 13'sd50 : s_u;
s_p <= sp; s_c <= sc; noadd <= !use_c;
if (op_fma) begin
if (an || bn || (use_c && cn) || (ai && bz) || (az && bi) ||
((ai || bi) && use_c && ci && sp != sc)) begin
result <= QNAN;
flags <= (as_ || bs || (use_c && cs) || (ai && bz) || (az && bi) ||
((ai || bi) && !an && !bn && use_c && ci && !cn && sp != sc)) ? NV : 5'd0;
done <= 1'b1; st <= S_IDLE;
end else if (ai || bi) begin
result <= {sp, 31'h7F80_0000}; flags <= 5'd0; done <= 1'b1; st <= S_IDLE;
end else if (use_c && ci) begin
result <= {sc, 31'h7F80_0000}; flags <= 5'd0; done <= 1'b1; st <= S_IDLE;
end else if (az || bz) begin
flags <= 5'd0; done <= 1'b1; st <= S_IDLE;
if (!use_c) result <= {sp, 31'd0};
else if (!cz) result <= {sc, xc[30:0]};
else if (sp == sc) result <= {sp, 31'd0};
else result <= {rrm == 3'd2, 31'd0};
end else
st <= S_M1;
end else if (op_div) begin
n_sign <= ra[31] ^ rb[31];
if (an || bn || (ai && bi) || (az && bz)) begin
result <= QNAN;
flags <= (as_ || bs || (ai && bi && !an && !bn) || (az && bz)) ? NV : 5'd0;
done <= 1'b1; st <= S_IDLE;
end else if (ai || bz) begin
result <= {ra[31] ^ rb[31], 31'h7F80_0000};
flags <= ai ? 5'd0 : DZ; done <= 1'b1; st <= S_IDLE;
end else if (bi || az) begin
result <= {ra[31] ^ rb[31], 31'd0}; flags <= 5'd0; done <= 1'b1; st <= S_IDLE;
end else begin
// quotient bits of na/nb from 2^0 down to 2^-26
drem <= {2'b00, na}; dden <= nb; dq <= 27'd0; dcnt <= 5'd0;
n_ex <= nea - neb + 12'sd127;
st <= S_DIV;
end
end else if (op_sqrt) begin
n_sign <= 1'b0;
if (an) begin
result <= QNAN; flags <= as_ ? NV : 5'd0; done <= 1'b1; st <= S_IDLE;
end else if (az) begin
result <= ra; flags <= 5'd0; done <= 1'b1; st <= S_IDLE;
end else if (ra[31]) begin
result <= QNAN; flags <= NV; done <= 1'b1; st <= S_IDLE;
end else if (ai) begin
result <= ra; flags <= 5'd0; done <= 1'b1; st <= S_IDLE;
end else begin
// value = na * 2^(nea-150); an even exponent for the root
srad <= nea[0] ? {1'b0, na, 29'd0} : {na, 30'd0};
srem <= 29'd0; dq <= 27'd0; dcnt <= 5'd0;
// the root of na*2^30 (nea even) or na*2^29 (odd) has 27 bits
n_ex <= ((nea - (nea[0] ? 12'sd127 : 12'sd128)) >>> 1) + 12'sd127;
st <= S_SQRT;
end
end else if (op_cvts) begin
n_sign <= !uns && ra[31];
n_x <= {(!uns && ra[31] ? -ra : ra), 45'd0};
n_ex <= 12'sd158;
st <= S_NZ;
end else if (op_cvtw) begin
cw_neg <= ra[31];
if (ex8(ra) >= 8'd150) begin
cw_int <= {9'd0, ma} << (ex8(ra) - 8'd150);
cw_g <= 1'b0; cw_s <= 1'b0;
end else if (ex8(ra) >= 8'd126) begin
cw_int <= {9'd0, cw_sh[47:24]};
cw_g <= cw_sh[23]; cw_s <= cw_sh[22:0] != 23'd0;
end else begin
cw_int <= 33'd0; cw_g <= 1'b0; cw_s <= !az;
end
st <= S_CW;
end else begin
result <= simple_r; flags <= simple_f; done <= 1'b1; st <= S_IDLE;
end
end
S_CW: begin
done <= 1'b1; st <= S_IDLE;
flags <= 5'd0;
if (an || ex8(ra) >= 8'd159 ||
(uns ? (cw_neg ? cw_mag != 33'd0 : cw_mag[32])
: (cw_neg ? cw_mag > 33'h0_8000_0000 : cw_mag > 33'h0_7FFF_FFFF))) begin
flags <= NV;
if (uns) result <= (cw_neg && !an) ? 32'd0 : 32'hFFFF_FFFF;
else result <= (cw_neg && !an) ? 32'h8000_0000 : 32'h7FFF_FFFF;
end else begin
result <= cw_neg ? -cw_mag[31:0] : cw_mag[31:0];
flags <= (cw_g || cw_s) ? NX : 5'd0;
end
end
S_M1: begin // the product's first stage; align c
c_al <= c_zero ? 77'd0 : (c_sh | {76'd0, c_lost});
fx <= s_big ? c_e : ep + 12'sd27;
st <= S_M2;
end
S_M2: st <= S_ADD; // the product's second stage
S_ADD: begin
if (noadd || s_p == s_c)
sum <= {1'b0, c_al} + {27'd0, p2, 3'b000};
else
sum <= {1'b0, c_al} - {27'd0, p2, 3'b000};
st <= S_ABS;
end
S_ABS: begin
// the sum's sign: c's unless the subtraction went negative
if (sum[77]) begin
n_x <= -sum[76:0];
n_sign <= s_p;
end else begin
n_x <= sum[76:0];
n_sign <= noadd ? s_p : s_c;
end
n_ex <= fx;
st <= S_NZ;
end
S_NZ: begin // find the top bit
n_zero <= n_x == 77'd0;
n_lz <= lz;
e_norm <= n_ex - {5'd0, lz};
st <= S_N1;
end
S_N1: begin // where to put it
if (e_norm < 12'sd1) begin
n_sh <= n_ex - 12'sd1; // subnormal: as far as exponent 1
r_e <= 12'sd1;
n_tiny <= 1'b1;
end else begin
n_sh <= {5'd0, n_lz};
r_e <= e_norm;
n_tiny <= 1'b0;
end
st <= S_N2;
end
S_N2: begin
if (n_sh >= 0) begin
y <= n_x << n_sh;
y_st <= 1'b0;
end else if (n_sh > -12'sd78) begin
y <= n_x >> (-n_sh);
y_st <= (n_x & ~({77{1'b1}} << (-n_sh))) != 77'd0;
end else begin
y <= 77'd0;
y_st <= n_x != 77'd0;
end
st <= S_R1;
end
S_R1: begin
r_m <= y_m;
r_inc <= rnd_up(rrm, n_sign, y[53], y_g, y_s);
r_inexact <= y_g || y_s;
// would rounding one bit further down (an unbounded exponent)
// also reach the smallest normal? (tininess after rounding)
r_fine <= y[75:52] == 24'hFF_FFFF &&
rnd_up(rrm, n_sign, 1'b1, y[51], y[50:0] != 51'd0 || y_st);
st <= S_R2;
end
S_R2: begin
done <= 1'b1; st <= S_IDLE;
if (n_zero) begin
// an exact zero: cancellation (or a zero integer)
result <= {(op_cvts ? 1'b0 : rrm == 3'd2), 31'd0};
flags <= 5'd0;
end else if (r_e + {11'd0, r_mi[24]} >= 12'sd255) begin
flags <= OF | NX;
if (rrm == 3'd1 || (rrm == 3'd2 && !n_sign) || (rrm == 3'd3 && n_sign))
result <= {n_sign, 31'h7F7F_FFFF};
else
result <= {n_sign, 31'h7F80_0000};
end else begin
if (r_mi[24])
result <= {n_sign, r_e[7:0] + 8'd1, 23'd0};
else
result <= {n_sign, r_mi[23] ? r_e[7:0] : 8'd0, r_mi[22:0]};
flags <= {2'b00, 1'b0,
n_tiny && r_inexact && !(r_mi[23] && r_fine),
r_inexact};
end
end
S_DIV: begin
if (!dtry[26]) begin drem <= {dtry[24:0], 1'b0}; dq <= {dq[25:0], 1'b1}; end
else begin drem <= {drem[24:0], 1'b0}; dq <= {dq[25:0], 1'b0}; end
dcnt <= dcnt + 5'd1;
if (dcnt == 5'd26) st <= S_DIVF;
end
S_SQRT: begin
srad <= {srad[51:0], 2'b00};
if (!stry[30]) begin srem <= stry[28:0]; dq <= {dq[25:0], 1'b1}; end
else begin srem <= stry_r[28:0]; dq <= {dq[25:0], 1'b0}; end
dcnt <= dcnt + 5'd1;
if (dcnt == 5'd26) st <= S_SQRTF;
end
S_DIVF: begin
n_x <= {dq, drem != 26'd0, 49'd0};
st <= S_NZ;
end
S_SQRTF: begin
n_x <= {dq, srem != 29'd0, 49'd0};
st <= S_NZ;
end
default: st <= S_IDLE;
endcase
if (rst) begin
st <= S_IDLE;
done <= 1'b0;
end
end
endmodule
+55 -19
View File
@@ -24,15 +24,21 @@
// 01 in key (clears bit 0) out byte to the terminal
// 10 in millisecond counter bits 7:0; reading it latches bits 31:8 for 11-13
// 20 out 7-segment display, right two digits 21 out left two digits
// 30 out graphics X bits 7:0 31 out X bit 8 32 out Y
// 30 out graphics X bits 7:0 31 out X bits 9:8, Y bit 8 (bit 2)
// 32 out Y bits 7:0
// 33 out plot colour at (X,Y), then X+1 in colour at (X,Y)
// (in 640x480 mode a pixel is 0 or 1: any non-zero colour sets it)
// 34 out fill the whole graphics screen in bit 0 = fill busy
// (also turns the sprites off and the scroll back to 0, unless
// bit 7 is set)
// (also turns the sprites off, the scroll back to 0 and the
// 320x240 mode back on, unless bit 7 is set)
// 35 out scroll: buffer X shown at the left, bits 7:0
// 36 out bit 0 = scroll X bit 8; bit 1 = hide the graphics in a border (4
// columns each side, 2 rows top and bottom) to draw in unseen
// 37 out scroll: buffer Y shown at the top (0-239)
// 38 i/o bit 0 = 640x480 in two colours (the same memory, a bit a pixel;
// no scrolling or border) instead of 320x240 in 16
// 39 out 640x480 colours: bits 3:0 for a set pixel, 7:4 for a clear one
// (0 = transparent, the text's background showing through)
// 40 SPI flash control, 41 SPI flash data (see flash_spi.v)
// 60 out bit 1 = stop again (NMI) after one instruction of the program
// in why the last NMI came: 1 Pause key, 2 port 61, 3 step,
@@ -65,7 +71,7 @@ module rv32_system #(
parameter MEM_FILE = "basic.mem", // RAM 0000-FFFF
parameter MEM_HI_FILE = "basic-hi.mem", // RAM 10000-13FFF
parameter MON_FILE = "monitor.mem",
parameter CPU_HZ = 90_000_000,
parameter CPU_HZ = 100_000_000,
parameter ROM_TOP = 32'h0000_A000
) (
input clk, // CPU clock
@@ -78,6 +84,7 @@ module rv32_system #(
output reg tx_req,
output reg [7:0] tx_data,
input tx_ack,
input wide, // the screen is 132x64 (terminal clock: synchronised here)
output reg [15:0] seg_val,
output halted,
input brk_key, // pulse: the Pause key, enter the monitor
@@ -88,6 +95,8 @@ module rv32_system #(
output reg [8:0] scroll_x,
output reg [7:0] scroll_y,
output reg g_border,
output reg g_hires, // 640x480, 1 bit a pixel
output reg [7:0] g_cols, // its colours: {clear, set}
// sprites, on the video clock (see sprites.v)
input sp_go,
input [7:0] sp_line,
@@ -253,7 +262,10 @@ module rv32_system #(
// ------------------------------------------------------------ graphics
// 76800 pixels: a 64K array and an 11264 one, so they take about 9.5 block
// RAMs (one array would be built as 96K deep, 12 of them).
// RAMs (one array would be built as 96K deep, 12 of them). In 640x480 mode
// each 4-bit entry holds four pixels side by side (bit 0 the leftmost):
// entry y*160 + x/4. A plot there reads the entry and writes it back the
// next clock with one bit changed.
localparam GFX_PIXELS = 320 * 240;
(* ram_style = "block" *) reg [3:0] gfx_lo [0:65535];
(* ram_style = "block" *) reg [3:0] gfx_hi [0:GFX_PIXELS - 65536 - 1];
@@ -263,18 +275,31 @@ module rv32_system #(
for (gi = 0; gi < GFX_PIXELS - 65536; gi = gi + 1) gfx_hi[gi] = 4'd0;
end
reg [8:0] gx;
reg [7:0] gy;
reg [9:0] gx;
reg [8:0] gy;
reg [3:0] gfx_q_lo, gfx_q_hi, fill_c;
reg gfx_q_sel;
reg [16:0] fill_a;
reg fill_busy;
wire [16:0] gxy = {gy, 8'd0} + {2'd0, gy, 6'd0} + {8'd0, gx};
wire plot = io_wr && io_addr == 8'h33 && gx < 9'd320 && gy < 8'd240;
wire [16:0] g_addr = fill_busy ? fill_a : gxy;
wire g_we = fill_busy || plot;
wire [3:0] g_wd = fill_busy ? fill_c : io_wd[3:0];
wire [16:0] lxy = {gy[7:0], 8'd0} + {2'd0, gy[7:0], 6'd0} + {7'd0, gx}; // y*320 + x
wire [16:0] hxy = {gy, 7'd0} + {2'd0, gy, 5'd0} + {9'd0, gx[9:2]}; // y*160 + x/4
wire plot = io_wr && io_addr == 8'h33 &&
(g_hires ? gx < 10'd640 && gy < 9'd480 : gx < 10'd320 && gy < 9'd240);
reg rmw; // 640x480 plot: write the entry read last clock
reg [16:0] rmw_a;
reg [1:0] rmw_bit;
reg rmw_v;
wire [3:0] gfx_q = gfx_q_sel ? gfx_q_hi : gfx_q_lo;
wire [3:0] rmw_wd = (gfx_q & ~(4'd1 << rmw_bit)) | ({3'd0, rmw_v} << rmw_bit);
wire [16:0] g_addr = fill_busy ? fill_a : rmw ? rmw_a : g_hires ? hxy : lxy;
wire g_we = fill_busy || (plot && !g_hires) || rmw;
wire [3:0] g_wd = fill_busy ? fill_c : rmw ? rmw_wd : io_wd[3:0];
always @(posedge clk) begin
rmw <= plot && g_hires && !fill_busy;
rmw_a <= hxy;
rmw_bit <= gx[1:0];
rmw_v <= io_wd != 8'd0;
end
always @(posedge clk) begin
if (g_we && !g_addr[16]) gfx_lo[g_addr[15:0]] <= g_wd;
@@ -302,21 +327,28 @@ module rv32_system #(
always @(posedge clk)
if (rst) begin
fill_busy <= 1'b0;
gx <= 9'd0; gy <= 8'd0;
gx <= 10'd0; gy <= 9'd0;
scroll_x <= 9'd0; scroll_y <= 8'd0; g_border <= 1'b0;
g_hires <= 1'b0; g_cols <= 8'h0F;
end else begin
if (io_wr) case (io_addr)
8'h30: gx[7:0] <= io_wd;
8'h31: gx[8] <= io_wd[0];
8'h32: gy <= io_wd;
8'h31: begin gx[9:8] <= io_wd[1:0]; gy[8] <= io_wd[2]; end
8'h32: gy[7:0] <= io_wd;
8'h33: gx <= gx + 1'b1;
8'h34: begin
fill_busy <= 1'b1; fill_a <= 17'd0; fill_c <= io_wd[3:0];
if (!io_wd[7]) begin scroll_x <= 9'd0; scroll_y <= 8'd0; g_border <= 1'b0; end
fill_busy <= 1'b1; fill_a <= 17'd0;
// in 640x480 mode a colour fills all four pixels of each entry
fill_c <= g_hires && io_wd[7] ? {4{io_wd[3:0] != 4'd0}} : io_wd[3:0];
if (!io_wd[7]) begin
scroll_x <= 9'd0; scroll_y <= 8'd0; g_border <= 1'b0; g_hires <= 1'b0;
end
end
8'h35: scroll_x[7:0] <= io_wd;
8'h36: begin scroll_x[8] <= io_wd[0]; g_border <= io_wd[1]; end
8'h37: scroll_y <= io_wd >= 8'd240 ? io_wd - 8'd240 : io_wd;
8'h38: g_hires <= io_wd[0];
8'h39: g_cols <= io_wd;
default: ;
endcase
if (fill_busy) begin
@@ -427,16 +459,20 @@ module rv32_system #(
end
end
(* ASYNC_REG = "TRUE" *) reg [1:0] wide_s = 2'b00;
always @(posedge clk) wide_s <= {wide_s[0], wide};
// -------------------------------------------------------- port reads
always @* case (io_addr)
8'h00: io_din = {6'd0, tx_ready, rx_avail};
8'h00: io_din = {5'd0, wide_s[1], tx_ready, rx_avail};
8'h01: io_din = rx_data;
8'h10: io_din = ms[7:0]; // sampled on the same edge that fills ms_latch
8'h11: io_din = ms_latch[15:8];
8'h12: io_din = ms_latch[23:16];
8'h13: io_din = ms_latch[31:24];
8'h33: io_din = {4'd0, gfx_q};
8'h33: io_din = g_hires ? {7'd0, gfx_q[gx[1:0]]} : {4'd0, gfx_q};
8'h34: io_din = {7'd0, fill_busy};
8'h38: io_din = {7'd0, g_hires};
8'h40: io_din = fl_ctl_q;
8'h41: io_din = fl_dat_q;
8'h60: io_din = {5'd0, why};
+1 -1
View File
@@ -25,7 +25,7 @@
// sigma-delta modulator at the full clock rate; the PmodAMP2 filters it and
// drives headphones or a speaker.
module sound #(
parameter CPU_HZ = 90_000_000
parameter CPU_HZ = 100_000_000
) (
input clk,
input rst,
+8 -4
View File
@@ -1,7 +1,8 @@
`timescale 1ns / 1ps
// VT220 terminal engine with ANSI colour. Consumes received bytes and keeps
// the character buffer up to date: 80x32, or 132x64 after DECCOLM (CSI ?3h).
// the character buffer up to date: 132x64 (DECCOLM, CSI ?3h; the start-up
// mode unless WIDE_BOOT = 0) or 80x32 (CSI ?3l).
// The buffer is row-major with a 132-cell stride in both (address = row*132 +
// col), so scrolling copies whole 132-cell rows either way.
//
@@ -21,7 +22,9 @@
// Scrolling copies rows in memory. With smooth scroll on, a line feed at the
// bottom margin first slides the region up a few pixels per frame.
module term_ctrl (
module term_ctrl #(
parameter WIDE_BOOT = 1 // start (and ESC c) in 132x64; 0 for 80x32
) (
input clk,
input rst,
input [7:0] in_byte,
@@ -343,8 +346,9 @@ module term_ctrl (
begin
soft_reset;
{row, col} <= 0;
{sclm, lnm, wide, colm_clr} <= 4'b0;
sbot <= 6'd31;
{sclm, lnm, colm_clr} <= 3'b0;
wide <= WIDE_BOOT != 0;
sbot <= WIDE_BOOT != 0 ? 6'd63 : 6'd31;
dec_leds <= 4'd0;
sm_on <= 1'b0;
sm_off <= 5'd0;
+18 -5
View File
@@ -12,6 +12,9 @@
// at (scroll_x, scroll_y) of the buffer and wraps round at 320 and 240. With
// g_border the graphics are hidden in a border (4 columns each side, 2 rows
// top and bottom), where a scrolling program can draw what comes next unseen.
// With g_hires the same memory is 640x480 at a bit a pixel (each pixel 2x2,
// four pixels to an entry, bit 0 the leftmost), in two colours from g_cols
// ({clear, set}; 0 is transparent); it doesn't scroll or hide in a border.
// One pixel per clock, pipelined:
// clock 0 position -> row, column, glyph line (registered)
// clock 1 character RAM and graphics reads
@@ -38,6 +41,9 @@ module text_display #(
input [8:0] scroll_x, // graphics pixel shown at the top left
input [7:0] scroll_y,
input g_border, // hide 4 graphics columns each side, 2 rows top and bottom
input g_hires, // 640x480, 1 bit a pixel
input [7:0] g_cols, // its colours: {clear, set}
input g_show, // show the graphics layer at all
// sprites: the line to prepare next, and the pixel on screen
output reg sp_go,
output reg [7:0] sp_line,
@@ -114,6 +120,8 @@ module text_display #(
wire [8:0] gcol_s = h[10:2]; // graphics pixel on the screen, unscrolled
wire [7:0] grow_s = v[9:2];
reg [16:0] a_gfx;
reg [1:0] a_gbit;
wire [8:0] hrow = v[9:1]; // 640x480 pixel row
reg [8:0] a_spx;
reg a_spbuf;
always @(posedge clk) begin
@@ -128,8 +136,10 @@ module text_display #(
a_hs <= h >= H_VIS + H_FP && h < H_VIS + H_FP + H_SYNC; // positive sync
a_vs <= v >= V_VIS + V_FP && v < V_VIS + V_FP + V_SYNC;
a_gon <= v < 960;
a_ghide <= g_border && (gcol_s < 9'd4 || gcol_s >= 9'd316 || grow_s < 8'd2 || grow_s >= 8'd238);
a_gfx <= {1'b0, g_row, 8'd0} + {3'd0, g_row, 6'd0} + {8'd0, g_col};
a_ghide <= !g_hires && g_border && (gcol_s < 9'd4 || gcol_s >= 9'd316 || grow_s < 8'd2 || grow_s >= 8'd238);
a_gfx <= g_hires ? {hrow, 7'd0} + {2'd0, hrow, 5'd0} + {9'd0, h[10:3]}
: {1'b0, g_row, 8'd0} + {3'd0, g_row, 6'd0} + {8'd0, g_col};
a_gbit <= h[2:1];
a_spx <= h[10:2];
a_spbuf <= v[2];
end
@@ -141,6 +151,8 @@ module text_display #(
assign sp_buf = a_spbuf;
assign sp_on = a_gon;
reg [3:0] b_line;
reg [1:0] b_gbit;
always @(posedge clk) b_gbit <= a_gbit;
reg [2:0] b_bit;
reg b_blank, b_text, b_vis, b_cur, b_hs, b_vs, b_gon, b_ghide;
always @(posedge clk)
@@ -158,7 +170,8 @@ module text_display #(
always @(posedge clk) begin
glyph <= font[{ram_data[7:0], b_line}];
c_cell <= ram_data;
c_gfx <= b_gon && !b_ghide ? gfx_pix : 4'd0;
c_gfx <= !g_show || !b_gon || b_ghide ? 4'd0 :
!g_hires ? gfx_pix : gfx_pix[b_gbit] ? g_cols[3:0] : g_cols[7:4];
c_spr <= sp_pix;
{c_line, c_bit, c_blank, c_text, c_vis, c_cur, c_hs, c_vs} <=
{b_line, b_bit, b_blank, b_text, b_vis, b_cur, b_hs, b_vs};
@@ -212,8 +225,8 @@ module char_ram (
(* ram_style = "block" *) reg [17:0] hi [0:2 * PAGE - 16384 - 1];
integer i;
initial begin
for (i = 0; i < 16384; i = i + 1) lo[i] = {10'h00A, 8'h20};
for (i = 0; i < 2 * PAGE - 16384; i = i + 1) hi[i] = {10'h00A, 8'h20};
for (i = 0; i < 16384; i = i + 1) lo[i] = {10'h00F, 8'h20};
for (i = 0; i < 2 * PAGE - 16384; i = i + 1) hi[i] = {10'h00F, 8'h20};
end
wire [14:0] aa = {1'b0, a_addr} + (a_alt ? PAGE : 0);
+1 -1
View File
@@ -4,7 +4,7 @@ set root [file normalize [file dirname [info script]]/..]
set out $root/build
file mkdir $out
set mult [expr {[info exists ::env(CPU_MULT)] ? $::env(CPU_MULT) : 9.0}]
set mult [expr {[info exists ::env(CPU_MULT)] ? $::env(CPU_MULT) : 10.0}]
set div [expr {[info exists ::env(CPU_DIV)] ? $::env(CPU_DIV) : 10.0}]
set hz [expr {int(round(100e6 * $mult / $div))}]
puts "CPU clock: [expr {$hz / 1e6}] MHz"
+4 -3
View File
@@ -1,11 +1,12 @@
#!/bin/bash
# Build riscv-tests (rv32ui, rv32um, rv32mi) and our own tests in tests/, run
# Build riscv-tests (rv32ui, rv32um, rv32uf, rv32mi) and our own tests in tests/, run
# them all on rtl/rv32_cpu.v in xsim. Fetches riscv-tests into third_party/.
# scripts/cputest.sh [name-filter]
set -e
cd "$(dirname "$0")/.."
ROOT=$(pwd)
source scripts/rv_env.sh
RV_ARCH="-march=rv32imf_zicsr_zifencei -mabi=ilp32"
RT=$ROOT/third_party/riscv-tests
if [ ! -d "$RT/isa" ]; then
git clone --recursive https://github.com/riscv-software-src/riscv-tests.git "$RT"
@@ -33,7 +34,7 @@ build() { # name source
echo "$OUT/$name.mem $th $name" >> "$LIST"
}
FILTER=$1
for suite in rv32ui rv32um rv32mi; do
for suite in rv32ui rv32um rv32uf rv32mi; do
for t in $(sed -n "/^${suite}_sc_tests/,/^\$/p" "$RT/isa/$suite/Makefrag" | grep -v = | tr -d '\\'); do
build "$suite-$t" "$RT/isa/$suite/$t.S"
done
@@ -45,7 +46,7 @@ source scripts/vivado_env.sh
mkdir -p sim/cpu
cd sim/cpu
rm -f xsim.log
xvlog "$ROOT/rtl/rv32_cpu.v" "$ROOT/sim/tb_cpu.v" | grep -E "^(ERROR|WARNING)" || true
xvlog "$ROOT/rtl/rv32_cpu.v" "$ROOT/rtl/rv32_fpu.v" "$ROOT/sim/tb_cpu.v" | grep -E "^(ERROR|WARNING)" || true
[ -d xsim.dir/work ] && ! grep -q ERROR xvlog.log || { echo "compile failed"; exit 1; }
xelab -debug off tb_cpu -s tb_cpu >/dev/null
xsim tb_cpu -R -testplusarg list="$LIST" | grep -E '^(PASS|FAIL|[0-9]+ passed)'
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
# Test rtl/rv32_fpu.v against tools/f32.py on random vectors in xsim.
# scripts/fputest.sh [COUNT] [SEED]
set -e
cd "$(dirname "$0")/.."
ROOT=$(pwd)
source scripts/vivado_env.sh
mkdir -p sim/fpu
cd sim/fpu
python3 "$ROOT/tools/fpu-vectors.py" "${1:-20000}" "${2:-1}" > vectors.txt
xvlog "$ROOT/rtl/rv32_fpu.v" "$ROOT/sim/tb_fpu.v" | grep -E "^(ERROR|WARNING)" || true
xelab -debug off tb_fpu -s tb_fpu | grep -E "^(ERROR|WARNING)" || true
xsim tb_fpu -R -testplusarg vec=vectors.txt | grep -E '^(FAIL|[0-9]+ vectors)'
grep -q " vectors, 0 failed" xsim.log
+3
View File
@@ -11,3 +11,6 @@ if [ -z "$RV_PREFIX" ]; then
fi
[ -x "${RV_PREFIX}gcc" ] || command -v "${RV_PREFIX}gcc" >/dev/null || { echo "no RISC-V gcc found; set RV_PREFIX" >&2; exit 1; }
RV_ARCH="-march=rv32im_zicsr_zifencei -mabi=ilp32"
# BASIC and the games use the FPU (the monitor keeps to RV32IM, leaving the
# float registers alone)
RV_ARCH_F="-march=rv32imf_zicsr_zifencei -mabi=ilp32f"
+3 -1
View File
@@ -1,12 +1,14 @@
#!/bin/bash
# Run the whole-design testbench in Vivado's simulator; output lands in sim/work.
# scripts/sim.sh [quick] quick: only the computer, up to the monitor
# scripts/sim.sh [quick|wide] quick: only the computer, up to the monitor
# wide: the 132x64 start-up (the checks otherwise start at 80x32)
set -e
cd "$(dirname "$0")/.."
ROOT=$(pwd)
source scripts/vivado_env.sh
DEFS=""
[ "$1" = quick ] && DEFS="-d SKIP_TERMINAL -d STOP_BEFORE_MONITOR"
[ "$1" = wide ] && DEFS="-d SKIP_TERMINAL -d WIDE_BOOT"
MON=$ROOT/monitor/monitor.mem
[ -e "$MON" ] || { mkdir -p sim/work; MON=$ROOT/sim/work/empty.mem; : > "$MON"; }
mkdir -p sim/work
+41
View File
@@ -0,0 +1,41 @@
`timescale 1ns / 1ps
// rtl/rv32_fpu.v against vectors from tools/fpu-vectors.py (+vec=FILE).
module tb_fpu;
reg clk = 0;
always #5 clk = ~clk;
reg rst = 1, start = 0;
reg [31:0] ins, a, b, c;
reg [2:0] rm;
wire done;
wire [31:0] result;
wire [4:0] flags;
rv32_fpu fpu (.clk(clk), .rst(rst), .start(start), .ins(ins), .rm(rm),
.a(a), .b(b), .c(c), .done(done), .result(result), .flags(flags));
integer fd, n, bad, cyc, maxc;
reg [31:0] v_ins, v_rm, v_a, v_b, v_c, v_r, v_f;
reg [8*256-1:0] fname;
initial begin
if (!$value$plusargs("vec=%s", fname)) fname = "vectors.txt";
fd = $fopen(fname, "r");
n = 0; bad = 0; maxc = 0;
@(posedge clk); @(posedge clk); rst <= 0;
while ($fscanf(fd, "%h %h %h %h %h %h %h\n", v_ins, v_rm, v_a, v_b, v_c, v_r, v_f) == 7) begin
@(posedge clk);
ins <= v_ins; rm <= v_rm[2:0]; a <= v_a; b <= v_b; c <= v_c; start <= 1;
@(posedge clk); start <= 0;
cyc = 1;
while (!done) begin @(posedge clk); cyc = cyc + 1; end
if (cyc > maxc) maxc = cyc;
n = n + 1;
if (result !== v_r || flags !== v_f[4:0]) begin
bad = bad + 1;
if (bad <= 25)
$display("FAIL ins %h rm %0d a %h b %h c %h: got %h %b want %h %b",
v_ins, v_rm, v_a, v_b, v_c, result, flags, v_r, v_f[4:0]);
end
end
$display("%0d vectors, %0d failed, at most %0d clocks", n, bad, maxc);
$finish;
end
endmodule
+87 -11
View File
@@ -17,7 +17,12 @@ module tb_terminal;
wire qcs;
wire [3:0] qdb;
basys3_terminal #(.FONT_FILE(`FONT_FILE), .MEM_FILE(`MEM_FILE), .MEM_HI_FILE(`MEM_HI_FILE), .MON_FILE(`MON_FILE)) dut (
`ifdef WIDE_BOOT
localparam WIDE = 1; // scripts/sim.sh wide: the board as built, 132x64
`else
localparam WIDE = 0; // the other checks were written for an 80x32 start
`endif
basys3_terminal #(.WIDE_BOOT(WIDE), .FONT_FILE(`FONT_FILE), .MEM_FILE(`MEM_FILE), .MEM_HI_FILE(`MEM_HI_FILE), .MON_FILE(`MON_FILE)) dut (
.clk(clk), .btnC(btnC), .btnU(btnU), .btnD(btnD), .sw(sw), .led(led), .seg(), .dp(), .an(),
.vgaRed(r), .vgaGreen(g), .vgaBlue(b), .Hsync(hs), .Vsync(vs),
.RsRx(rsrx), .RsTx(rstx), .PS2Clk(ps2c), .PS2Data(ps2d),
@@ -28,6 +33,7 @@ module tb_terminal;
real BIT_NS = 1_000_000_000.0 / 115200; // changed for the 3 Mbaud test
integer errors = 0;
integer wk;
task uart_send(input [7:0] d);
integer i;
@@ -202,6 +208,7 @@ module tb_terminal;
ch = cellraw(rr, cc);
if (go && ch >= "0" && ch <= "9") hex_at = hex_at * 16 + (ch - "0");
else if (go && ch >= "A" && ch <= "F") hex_at = hex_at * 16 + (ch - "A" + 10);
else if (go && ch >= "a" && ch <= "f") hex_at = hex_at * 16 + (ch - "a" + 10);
else go = 0;
end
end
@@ -258,6 +265,8 @@ module tb_terminal;
initial begin
#2_000_000; // reset, clear, banner
if (WIDE) expect_row(0, "Basys 3 VT220 Terminal 132x64");
else expect_row(0, "Basys 3 VT220 Terminal 80x32");
`ifndef SKIP_TERMINAL
// ---- keyboard: a, shift+b, Enter, up, ctrl+c, F5
@@ -346,6 +355,35 @@ module tb_terminal;
if (hs_bad == 0 && vs_bad == 0) $display("PASS 1280x1024 sync timing");
else begin $display("FAIL sync timing: %0d hsync, %0d vsync periods off", hs_bad, vs_bad); errors = errors + 1; end
`endif
`ifdef WIDE_BOOT
// ---- start-up in 132x64: the screen, port 0 bit 2, BASIC's line editor
uart_str("\033[2J\033[H");
#100_000;
sw[15] = 1; sw[14] = 1;
#3_000_000;
if (dut.wide) $display("PASS the screen starts at 132x64");
else begin $display("FAIL the screen starts at 80x32"); errors = errors + 1; end
uart_str("PRINT INP(0) AND 4\015");
#2_000_000;
expect_row(1, "DARTMOUTH-STYLE BASIC");
expect_row(5, " 4");
// a 107-character line stays on one row; three Lefts and a Y land
// in that row only if the editor knows the screen is 132 wide
uart_str("10 REM ");
for (wk = 0; wk < 100; wk = wk + 1) uart_send("X");
uart_str("\033[D\033[D\033[DY");
#2_000_000;
if (cellraw(8, 106) == "X" && cellraw(8, 104) == "Y" && cellraw(9, 0) == " ")
$display("PASS the line editor works 132 wide");
else begin
$display("FAIL the line editor at 132 wide: row 8 col 104 '%c' col 106 '%c', row 9 col 0 '%c'",
cellraw(8, 104), cellraw(8, 106), cellraw(9, 0));
errors = errors + 1;
end
if (errors == 0) $display("ALL TESTS PASSED");
else $display("%0d TESTS FAILED", errors);
$finish;
`endif
// ---- BASIC as the console, input pasted over the UART
uart_str("\033[2J\033[H");
@@ -461,6 +499,35 @@ module tb_terminal;
errors = errors + 1;
end
// ---- 640x480 in two colours: four pixels an entry, a plot changes one
// bit (500, 501 and 503 set, then 500 cleared), pixel (x, y) is screen
// pixel (2x, 2y), set pixels colour 14 and clear ones colour 1
uart_str({"CLS:SCREEN 1,14,1:LINE 0,0,639,479:PLOT 500,333:PLOT 501,333:",
"PLOT 503,333:PLOT 500,333,0:PRINT POINT(639,479);POINT(501,333);POINT(502,333)\015"});
wait_row(0, " 1 1 0");
#5_000_000;
capture_frame("frame_8.ppm");
if (dut.sys.g_hires && dut.sys.gfx(333 * 160 + 125) == 4'b1010 &&
dut.sys.gfx(0) == 4'b0001 && dut.sys.gfx(479 * 160 + 159) == 4'b1000 &&
fb[666*1280 + 1002] == 12'h5FF && fb[667*1280 + 1003] == 12'h5FF &&
fb[666*1280 + 1000] == 12'hA00 && fb[666*1280 + 1004] == 12'hA00 &&
fb[958*1280 + 1278] == 12'h5FF && fb[1000*1280 + 600] == 12'h000)
$display("PASS 640x480 graphics");
else begin
$display("FAIL 640x480 graphics: %b %b %b %h %h %h %h %h %h", dut.sys.gfx(333 * 160 + 125),
dut.sys.gfx(0), dut.sys.gfx(479 * 160 + 159), fb[666*1280 + 1002],
fb[667*1280 + 1003], fb[666*1280 + 1000], fb[666*1280 + 1004],
fb[958*1280 + 1278], fb[1000*1280 + 600]);
errors = errors + 1;
end
uart_str("SCREEN 0\015");
#5_000_000;
if (!dut.sys.g_hires) $display("PASS SCREEN 0");
else begin
$display("FAIL SCREEN 0 left 640x480 on");
errors = errors + 1;
end
// ---- files in the flash, and the bitstream protection
uart_str({"CLS:DATE \"2026-11-28 09:30\":NEW\01510 PRINT \"SAVED\";6*7\015SAVE \"TEST1\"\015NEW\015",
"LOAD \"TEST1\"\015RUN\015DIR\015"});
@@ -493,15 +560,23 @@ module tb_terminal;
pc_a = screen_pc(0);
wait_at(9, 0, ">");
jp_txt = {cellraw(9, 19), cellraw(9, 20)};
jp_to = hex_at(9, 21);
jp_to = hex_at(9, 23); // "j 0x54a4"
dump_screen;
// the float registers, in place of the memory window, and setting one
uart_str("F\015");
wait_at(21, 0, " FLOAT REGISTERS");
wait_at(22, 0, " F0 ");
uart_str("R F1=3FC00000\015");
wait_at(22, 13, " F1 3FC00000");
uart_str("M\015");
wait_at(21, 0, " MEMORY");
uart_str("\015"); // Enter: one step
wait_at(0, 50, "STOPPED BY STEP");
wait_at(29, 0, "> ");
pc_b = screen_pc(0);
// MONITOR stops on a J (to the end of BASIC's statement routine): one
// MONITOR stops on a j (to the end of BASIC's statement routine): one
// step must land exactly on its target
if (jp_txt == "J " && pc_b == jp_to) $display("PASS step: PC %h -> %h", pc_a, pc_b);
if (jp_txt == "j " && pc_b == jp_to) $display("PASS step: PC %h -> %h", pc_a, pc_b);
else begin $display("FAIL step: PC %h -> %h, wanted %h (%0s)", pc_a, pc_b, jp_to, jp_txt); errors = errors + 1; end
// a breakpoint where the step stopped (the end of BASIC's statement
// routine), hit again by OUT; leaving from it steps off it first
@@ -558,16 +633,17 @@ module tb_terminal;
wait_row(0, " 72 73");
// ---- the assembler: source typed into BASIC, saved, assembled by the monitor
uart_str({"NEW\01510 ORG 12000H\01520 START: LA A1,MSG\01530 LOOP: LBU A0,0(A1)\015",
"40 BEQZ A0,DONE\01550 WAIT: LBU T0,-256(ZERO)\01560 ANDI T0,T0,2\015"});
uart_str({"70 BEQZ T0,WAIT\01580 SB A0,-255(ZERO)\01590 ADDI A1,A1,1\015100 J LOOP\015",
"110 DONE: RET\015"});
uart_str({"120 MSG: DB \"ASM OK\",0 ; THE MESSAGE\015SAVE \"HELLO\"\015MONITOR\015"});
// GNU as syntax, typed in lower case (BASIC stores it in capitals)
uart_str({"NEW\01510 .org 0x12000\01520 start: la a1, msg\01530 loop: lbu a0, 0(a1)\015",
"40 beqz a0, done\01550 wait: lbu t0, -256(zero)\01560 andi t0, t0, 2\015"});
uart_str({"70 beqz t0, wait\01580 sb a0, -255(zero)\01590 addi a1, a1, 1\015100 j loop\015",
"110 done: ret\015"});
uart_str({"120 msg: .string \"ASM OK\" # the message\015SAVE \"HELLO\"\015MONITOR\015"});
wait_at(29, 0, "> ");
uart_str("ASM \"HELLO\"\015");
wait_at(29, 40, "ASSEMBLED 12000-12032");
uart_str("A 12100\015LI A0,66\015\015");
wait_at(9, 2, "12100 04200513 LI A0,66");
uart_str("A 12100\015LI A0,'B'\015\015"); // the line assembler, in capitals
wait_at(9, 2, "12100 04200513 li a0,66");
// an Intel HEX record above 64K (an extended address first) and the end record
uart_str(":020000040001F9\015:03210000AABBCCAB\015:00000001FF\015");
wait_at(29, 40, "HEX LOADED 12100-12102");
+3 -2
View File
@@ -1,6 +1,7 @@
# terminfo for the Basys 3 FPGA terminal: a VT220 with 16 ANSI colours,
# underline, blink, 80x32 (basys3) or 132x64 after ESC[?3h (basys3-w).
# tic -x -o ~/.terminfo terminfo/basys3.ti then export TERM=basys3
# underline, blink. The RISC-V board starts at 132x64 (basys3-w); after
# ESC[?3l it is 80x32 (basys3).
# tic -x -o ~/.terminfo terminfo/basys3.ti then export TERM=basys3-w
basys3|Basys 3 FPGA VT220 terminal with ANSI colour,
lines#32, cols#80,
colors#16, pairs#256,
+22 -6
View File
@@ -47,6 +47,8 @@ class Board(RV32):
self.frame_at = -1000
self.joy = 0
self.gfx = bytearray(320 * 240)
self.hgfx = bytearray(640 * 480) # 640x480 mode (port 38): 0 or 1 a pixel
self.g_cols = 0x0F
self.gxv = self.gyv = 0
self.spr = [[0, 0, 0, 0] for _ in range(32)] # x, y, shape, ctl
self.sel = 0
@@ -70,24 +72,37 @@ class Board(RV32):
if p == 0x88:
return self.joy
if p == 0x33:
if self.g_hires:
return self.hgfx[self.gyv * 640 + self.gxv] if self.gxv < 640 and self.gyv < 480 else 0
return self.gfx[self.gyv * 320 + self.gxv] if self.gxv < 320 and self.gyv < 240 else 0
if p == 0x34:
return 0
if p == 0x38:
return self.g_hires
return 0xFF
def io_out(self, port, v):
p = port & 0xFF
if p == 1:
self.text.append(v)
elif p == 0x30: self.gxv = (self.gxv & 0x100) | v
elif p == 0x31: self.gxv = (self.gxv & 0xFF) | (v & 1) << 8
elif p == 0x32: self.gyv = v
elif p == 0x30: self.gxv = (self.gxv & 0x300) | v
elif p == 0x31:
self.gxv = (self.gxv & 0xFF) | (v & 3) << 8
self.gyv = (self.gyv & 0xFF) | (v & 4) << 6
elif p == 0x32: self.gyv = (self.gyv & 0x100) | v
elif p == 0x33:
if self.gxv < 320 and self.gyv < 240:
if self.g_hires:
if self.gxv < 640 and self.gyv < 480:
self.hgfx[self.gyv * 640 + self.gxv] = int(v != 0)
elif self.gxv < 320 and self.gyv < 240:
self.gfx[self.gyv * 320 + self.gxv] = v & 15
self.gxv = (self.gxv + 1) & 0x1FF
self.gxv = (self.gxv + 1) & 0x3FF
elif p == 0x34:
self.gfx[:] = bytes([v & 15]) * (320 * 240)
if self.g_hires and v & 0x80:
self.hgfx[:] = bytes([int(v & 15 != 0)]) * (640 * 480)
else:
self.gfx[:] = bytes([v & 15]) * (320 * 240)
self.hgfx[:] = bytes(640 * 480)
if not v & 0x80:
for s in self.spr: s[3] &= ~1
self.scroll_x = self.scroll_y = 0
@@ -97,6 +112,7 @@ class Board(RV32):
self.scroll_x = (self.scroll_x & 0xFF) | (v & 1) << 8
self.border = bool(v & 2)
elif p == 0x37: self.scroll_y = v - 240 if v >= 240 else v
elif p == 0x39: self.g_cols = v
elif p == 0x70: self.sel = v & 31
elif p == 0x71: self.xst = (self.xst & 0x100) | v
elif p == 0x72: self.xst = (self.xst & 0xFF) | (v & 1) << 8
+293
View File
@@ -0,0 +1,293 @@
"""Bit-exact IEEE 754 single precision, the way RISC-V's F extension does it.
The reference for rtl/rv32_fpu.v and the arithmetic of tools/rv32emu.py.
Values are 32-bit patterns (ints); every operation returns (bits, flags),
flags being fflags: NV 16, DZ 8, OF 4, UF 2, NX 1. Rounding modes are
RISC-V's: 0 RNE, 1 RTZ, 2 RDN, 3 RUP, 4 RMM. Tininess is detected after
rounding; NaN results are the canonical 7FC00000.
Arithmetic is exact (Fraction), then rounded once.
"""
from fractions import Fraction
NV, DZ, OF, UF, NX = 16, 8, 4, 2, 1
RNE, RTZ, RDN, RUP, RMM = 0, 1, 2, 3, 4
QNAN = 0x7FC00000
M32 = 0xFFFFFFFF
def sign(x): return x >> 31
def expo(x): return (x >> 23) & 0xFF
def frac(x): return x & 0x7FFFFF
def is_nan(x): return expo(x) == 255 and frac(x) != 0
def is_snan(x): return is_nan(x) and not (x >> 22) & 1
def is_inf(x): return (x & 0x7FFFFFFF) == 0x7F800000
def is_zero(x): return (x & 0x7FFFFFFF) == 0
def value(x):
"""The exact value of a finite pattern, without its sign."""
e, f = expo(x), frac(x)
if e == 0:
return Fraction(f, 1 << 149)
m = f | 0x800000
k = e - 150
return Fraction(m << k) if k >= 0 else Fraction(m, 1 << -k)
def _round_int(q, s, rm, neg):
"""Round q (a non-negative Fraction) to an integer; s marks a value a hair
above q (an inexact square root). Returns (n, inexact)."""
n = q.numerator // q.denominator
rem = q - n
if rem == 0 and not s:
return n, False
half = Fraction(1, 2)
if rm == RNE:
up = rem > half or (rem == half and (s or n & 1))
elif rm == RTZ:
up = False
elif rm == RDN:
up = neg
elif rm == RUP:
up = not neg
else: # RMM
up = rem >= half
return n + up, True
def round_f32(neg, x, rm, s=False):
"""Round the exact value (-1)^neg * x (x a non-negative Fraction; s: the
true value is a hair above x) to single precision. Returns (bits, flags)."""
sb = int(neg) << 31
if x == 0 and not s:
return sb, 0
# exponent e with 2^e <= x < 2^(e+1)
e = x.numerator.bit_length() - x.denominator.bit_length()
if Fraction(2) ** e > x:
e -= 1
# rounding with an unbounded exponent (for tininess after rounding)
n_u, _ = _round_int(x * Fraction(2) ** (23 - e), s, rm, neg)
tiny = n_u * Fraction(2) ** (e - 23) < Fraction(1, 1 << 126)
if e < -126:
n, inex = _round_int(x * Fraction(1 << 149), s, rm, neg)
flags = (NX | (UF if tiny else 0)) if inex else 0
if n >= 1 << 23: # rounded up to the smallest normal
return sb | (1 << 23) | (n - (1 << 23)), flags
return sb | n, flags
n, inex = _round_int(x * Fraction(2) ** (23 - e), s, rm, neg)
if n == 1 << 24:
n >>= 1
e += 1
if e > 127:
big = rm in (RNE, RMM) or (rm == RDN and neg) or (rm == RUP and not neg)
return sb | (0x7F800000 if big else 0x7F7FFFFF), OF | NX
return sb | ((e + 127) << 23) | (n - (1 << 23)), NX if inex else 0
def fma(a, b, c, rm, negp=False, negc=False, use_c=True):
"""(-1)^negp * a*b + (-1)^negc * c; use_c False is a plain multiply."""
sp = sign(a) ^ sign(b) ^ negp
sc = sign(c) ^ negc
nans = is_nan(a) or is_nan(b) or (use_c and is_nan(c))
inv = is_snan(a) or is_snan(b) or (use_c and is_snan(c))
inv |= (is_inf(a) and is_zero(b)) or (is_zero(a) and is_inf(b))
pinf = (is_inf(a) or is_inf(b)) and not nans
if pinf and use_c and is_inf(c) and sp != sc:
inv = True
if inv or nans:
return QNAN, NV if inv else 0
if pinf:
return (sp << 31) | 0x7F800000, 0
if use_c and is_inf(c):
return (sc << 31) | 0x7F800000, 0
p = value(a) * value(b) * (-1 if sp else 1)
if not use_c:
if p == 0:
return sp << 31, 0
return round_f32(p < 0, abs(p), rm)
q = value(c) * (-1 if sc else 1)
r = p + q
if r == 0:
if p == 0 and q == 0 and sp == sc:
return sp << 31, 0
return (1 << 31 if rm == RDN else 0), 0
return round_f32(r < 0, abs(r), rm)
ONE = 0x3F800000
def add(a, b, rm): return fma(a, ONE, b, rm)
def sub(a, b, rm): return fma(a, ONE, b, rm, negc=True)
def mul(a, b, rm): return fma(a, b, 0, rm, use_c=False)
def div(a, b, rm):
s = sign(a) ^ sign(b)
if is_nan(a) or is_nan(b):
return QNAN, NV if is_snan(a) or is_snan(b) else 0
if (is_inf(a) and is_inf(b)) or (is_zero(a) and is_zero(b)):
return QNAN, NV
if is_inf(a):
return (s << 31) | 0x7F800000, 0
if is_inf(b):
return s << 31, 0
if is_zero(b):
return (s << 31) | 0x7F800000, DZ
if is_zero(a):
return s << 31, 0
return round_f32(s, value(a) / value(b), rm)
def isqrt(n):
if n == 0:
return 0
x = 1 << ((n.bit_length() + 1) // 2)
while True:
y = (x + n // x) // 2
if y >= x:
return x
x = y
def sqrt(a, rm):
if is_nan(a):
return QNAN, NV if is_snan(a) else 0
if is_zero(a):
return a, 0
if sign(a):
return QNAN, NV
if is_inf(a):
return a, 0
n = value(a) * Fraction(4) ** 150 # an integer
n = n.numerator
r = isqrt(n)
return round_f32(0, Fraction(r, 1 << 150), rm, s=r * r != n)
def sgnj(a, b, f3):
s = [sign(b), sign(b) ^ 1, sign(a) ^ sign(b)][f3]
return (s << 31) | (a & 0x7FFFFFFF), 0
def _lt(a, b):
if is_zero(a) and is_zero(b):
return False
if sign(a) != sign(b):
return sign(a) == 1
if sign(a):
return (a & 0x7FFFFFFF) > (b & 0x7FFFFFFF)
return (a & 0x7FFFFFFF) < (b & 0x7FFFFFFF)
def _eq(a, b):
return a == b or (is_zero(a) and is_zero(b))
def minmax(a, b, is_max):
fl = NV if is_snan(a) or is_snan(b) else 0
if is_nan(a) and is_nan(b):
return QNAN, fl
if is_nan(a):
return b, fl
if is_nan(b):
return a, fl
if is_zero(a) and is_zero(b):
if is_max:
return (a if not sign(a) else b), fl
return (a if sign(a) else b), fl
if is_max:
return (b if _lt(a, b) else a), fl
return (a if _lt(a, b) else b), fl
def cmp(a, b, f3):
"""f3: 0 FLE, 1 FLT, 2 FEQ. Returns (0 or 1, flags)."""
if is_nan(a) or is_nan(b):
if f3 == 2:
return 0, NV if is_snan(a) or is_snan(b) else 0
return 0, NV
if f3 == 2:
return int(_eq(a, b)), 0
if f3 == 1:
return int(_lt(a, b)), 0
return int(_lt(a, b) or _eq(a, b)), 0
def fclass(a):
s, e, f = sign(a), expo(a), frac(a)
if e == 255:
if f == 0:
return 1 << 0 if s else 1 << 7
return 1 << 9 if f >> 22 else 1 << 8
if e == 0:
if f == 0:
return 1 << 3 if s else 1 << 4
return 1 << 2 if s else 1 << 5
return 1 << 1 if s else 1 << 6
def cvt_w(a, rm, unsigned):
"""float -> int32 / uint32: (bits, flags)."""
if is_nan(a):
return (M32 if unsigned else 0x7FFFFFFF), NV
if is_inf(a):
if unsigned:
return (0 if sign(a) else M32), NV
return (0x80000000 if sign(a) else 0x7FFFFFFF), NV
neg = sign(a)
n, inex = _round_int(value(a), False, rm, neg)
v = -n if neg else n
lo, hi = (0, M32) if unsigned else (-(1 << 31), (1 << 31) - 1)
if v < lo or v > hi:
if unsigned:
return (0 if neg else M32), NV
return (0x80000000 if neg else 0x7FFFFFFF), NV
return v & M32, NX if inex else 0
def cvt_s(x, rm, unsigned):
"""int32 / uint32 (as a 32-bit pattern) -> float."""
v = x if unsigned or not x >> 31 else x - (1 << 32)
if v == 0:
return 0, 0
return round_f32(v < 0, Fraction(abs(v)), rm)
def execute(ins, rm, a, b, c):
"""Run one F instruction (the 32-bit encoding) on operand patterns a, b, c
(a is the integer register for FMV.W.X and FCVT.S.W[U]); rm is the
resolved rounding mode. Returns (result, flags, to_int)."""
opc = ins & 0x7F
f3 = (ins >> 12) & 7
f5 = ins >> 27
r2 = (ins >> 20) & 31
if opc in (0x43, 0x47, 0x4B, 0x4F):
r, fl = fma(a, b, c, rm, negp=bool(opc & 8), negc=bool(opc & 4))
return r, fl, False
if f5 == 0:
return (*add(a, b, rm), False)
if f5 == 1:
return (*sub(a, b, rm), False)
if f5 == 2:
return (*mul(a, b, rm), False)
if f5 == 3:
return (*div(a, b, rm), False)
if f5 == 0x0B:
return (*sqrt(a, rm), False)
if f5 == 0x04:
return (*sgnj(a, b, f3), False)
if f5 == 0x05:
return (*minmax(a, b, f3 == 1), False)
if f5 == 0x18:
return (*cvt_w(a, rm, r2 & 1), True)
if f5 == 0x1C:
return (fclass(a) if f3 == 1 else a, 0, True)
if f5 == 0x14:
return (*cmp(a, b, f3), True)
if f5 == 0x1A:
return (*cvt_s(a, rm, r2 & 1), False)
if f5 == 0x1E:
return a, 0, False
raise ValueError("not an F instruction: %08x" % ins)
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Test vectors for rtl/rv32_fpu.v from tools/f32.py: every F instruction,
every rounding mode, special values, subnormals, boundaries and near-
cancellations. One line per case, hex: ins rm a b c result flags.
tools/fpu-vectors.py COUNT [SEED] > vectors.txt
"""
import os
import random
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import f32
SPECIAL = [0, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7F800001,
0x7FBFFFFF, 0x00000001, 0x80000001, 0x007FFFFF, 0x807FFFFF, 0x00800000,
0x80800000, 0x7F7FFFFF, 0xFF7FFFFF, 0x3F800000, 0xBF800000, 0x3F000000,
0x4B000000, 0x4F000000, 0xCF000000, 0x4F800000, 0x3EFFFFFF, 0x3FC00000]
def rnd():
k = random.random()
if k < 0.12:
return random.choice(SPECIAL)
if k < 0.32:
e = random.choice([0, 1, 2, 23, 24, 25, 100, 125, 126, 127, 128, 150, 157, 158, 159, 253, 254])
return (random.getrandbits(1) << 31) | (e << 23) | random.choice(
[random.getrandbits(23), 0, 0x7FFFFF, 1, 0x400000, random.getrandbits(4)])
if k < 0.55:
e = random.randint(110, 145)
return (random.getrandbits(1) << 31) | (e << 23) | random.getrandbits(23)
return random.getrandbits(32)
def enc_op(f5, f3, rs2=0):
return (f5 << 27) | (rs2 << 20) | (f3 << 12) | 0x53
def main():
n = int(sys.argv[1])
random.seed(int(sys.argv[2]) if len(sys.argv) > 2 else 1)
kinds = (['fma'] * 6 + ['add'] * 4 + ['sub'] * 3 + ['mul'] * 3 + ['div'] * 3 + ['sqrt'] * 2 +
['sgnj', 'minmax', 'cmp', 'class', 'mvxw', 'mvwx', 'cvtw', 'cvtw', 'cvts', 'cvts'])
for _ in range(n):
k = random.choice(kinds)
rm = random.randint(0, 4)
f3 = rm
a, b, c = rnd(), rnd(), rnd()
if k == 'fma':
opc = random.choice([0x43, 0x47, 0x4B, 0x4F])
ins = (opc | (f3 << 12))
if random.random() < 0.4: # near cancellation
p, _ = f32.mul(a, b, rm)
if not f32.is_nan(p):
want_neg = bool(opc & 8) == bool(opc & 4) # makes c cancel the product
c = (p ^ (0x80000000 if want_neg else 0)) + random.choice([0, 0, 1, -1, 2, 0x80, -0x1000])
c &= 0xFFFFFFFF
elif k in ('add', 'sub', 'mul', 'div', 'sqrt'):
f5 = {'add': 0, 'sub': 1, 'mul': 2, 'div': 3, 'sqrt': 0x0B}[k]
ins = enc_op(f5, f3)
if k in ('add', 'sub') and random.random() < 0.35:
b = (a ^ (0x80000000 if k == 'add' else 0)) + random.choice([0, 1, -1, 3, 0x40, 0x800000, -0x800000])
b &= 0xFFFFFFFF
elif k == 'sgnj':
f3 = random.randint(0, 2); ins = enc_op(0x04, f3)
elif k == 'minmax':
f3 = random.randint(0, 1); ins = enc_op(0x05, f3)
if random.random() < 0.3: b = a ^ random.choice([0, 0x80000000, 1])
elif k == 'cmp':
f3 = random.randint(0, 2); ins = enc_op(0x14, f3)
if random.random() < 0.3: b = a ^ random.choice([0, 0x80000000, 1])
elif k == 'class':
f3 = 1; ins = enc_op(0x1C, 1)
elif k == 'mvxw':
f3 = 0; ins = enc_op(0x1C, 0)
elif k == 'mvwx':
f3 = 0; ins = enc_op(0x1E, 0)
elif k == 'cvtw':
u = random.randint(0, 1); ins = enc_op(0x18, f3, u)
if random.random() < 0.5:
e = random.randint(120, 160)
a = (random.getrandbits(1) << 31) | (e << 23) | random.getrandbits(23)
else:
u = random.randint(0, 1); ins = enc_op(0x1A, f3, u)
if random.random() < 0.5:
a = random.getrandbits(random.randint(1, 32))
if random.random() < 0.3: a = (-a) & 0xFFFFFFFF
r, fl, _ = f32.execute(ins, rm, a, b, c)
print('%08x %x %08x %08x %08x %08x %02x' % (ins, rm, a, b, c, r, fl))
if __name__ == '__main__':
main()
+113 -5
View File
@@ -1,8 +1,9 @@
#!/usr/bin/env python3
"""RV32IM emulator of the Basys 3 RISC-V computer, for testing programs on the
"""RV32IMF emulator of the Basys 3 RISC-V computer, for testing programs on the
PC and as a reference for rtl/rv32_cpu.v.
The same machine as rtl/rv32_cpu.v and rtl/rv32_system.v: RV32IM, machine
The same machine as rtl/rv32_cpu.v and rtl/rv32_system.v: RV32IMF (floating
point from tools/f32.py, bit for bit as rtl/rv32_fpu.v), machine
mode, the CSRs the core has (no triggers), the resumable NMI, 80 KB of RAM
(writes below rom_top ignored), the monitor's 32 KB ROM at 20000h and 8 KB of
RAM at 28000h, the I/O ports at FFFFFF00h + N (io_in / io_out, to be
@@ -15,7 +16,10 @@ runs a raw image from address 0 with the console on ports 0/1: text from
each instruction run. The emulator also counts the clocks rv32_cpu would take
(cycles; see cost()).
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import f32 # noqa: E402
M32 = 0xFFFFFFFF
RAM_END = 0x14000
@@ -43,6 +47,10 @@ class RV32:
self.m[:len(mem)] = mem
self.rom_top = rom_top # writes below are ignored
self.x = [0] * 32
self.f = [0] * 32 # float registers (bit patterns)
self.fs = 1 # mstatus.FS: Initial
self.fflags = 0
self.frm = 0
self.pc = 0
self.cache = {}
self.csr = {0x300: 0, 0x304: 0, 0x305: 0, 0x340: 0, 0x341: 0, 0x342: 0, 0x343: 0,
@@ -58,6 +66,7 @@ class RV32:
self.why = 0
self.bp = [0, 0]
self.bp_on = 0
self.g_hires = 0 # port 38: 640x480 graphics mode
@property
def sp(self):
@@ -129,6 +138,8 @@ class RV32:
return self.why
if port == 0x34:
return 0 # graphics fill: done at once
if port == 0x38:
return self.g_hires
return 0xFF
def io_out(self, port, v):
@@ -144,6 +155,10 @@ class RV32:
self.nmi_pending, self.why_r = True, 2
elif port == 0x67:
self.bp_on = v & 3
elif port == 0x38:
self.g_hires = v & 1
elif port == 0x34 and not v & 0x80:
self.g_hires = 0
self.io_out(port, v)
def millis(self):
@@ -172,9 +187,13 @@ class RV32:
# ------------------------------------------------------------------ CSRs
def csr_read(self, n):
if n == 0x300:
return self.csr[0x300] | 0x1800
return self.csr[0x300] | 0x1800 | self.fs << 13 | (0x80000000 if self.fs == 3 else 0)
if n == 0x301:
return 0x40001100
return 0x40001120
if n in (1, 2, 3):
if not self.fs:
raise Trap(2)
return [0, self.fflags, self.frm, self.frm << 5 | self.fflags][n]
if n == 0x344:
return 0
if n == 0x744:
@@ -194,6 +213,17 @@ class RV32:
raise Trap(2)
if n == 0x300:
self.csr[0x300] = v & 0x88
self.fs = v >> 13 & 3
elif n in (1, 2, 3):
if not self.fs:
raise Trap(2)
if n == 1:
self.fflags = v & 31
elif n == 2:
self.frm = v & 7
else:
self.fflags, self.frm = v & 31, v >> 5 & 7
self.fs = 3
elif n == 0x304:
self.csr[0x304] = v & 0xFFFF0888
elif n in (0x305, 0x341, 0x741):
@@ -367,6 +397,8 @@ class RV32:
x[rd] = op(x[rs1], x[rs2])
return nxt
return f
if opc in (0x07, 0x27, 0x43, 0x47, 0x4B, 0x4F, 0x53):
return self.decode_f(ins, pc)
if opc == 0x0F and f3 in (0, 1): # fence, fence.i
return lambda: nxt
if opc == 0x73:
@@ -408,6 +440,74 @@ class RV32:
return f
return illegal
def decode_f(self, ins, pc):
"""The F extension: as rv32_cpu decodes it (illegal while mstatus.FS
is Off, or with a reserved rounding mode)."""
opc, rd, f3 = ins & 0x7F, ins >> 7 & 31, ins >> 12 & 7
rs1, rs2, rs3 = ins >> 15 & 31, ins >> 20 & 31, ins >> 27
x, fr = self.x, self.f
nxt = (pc + 4) & M32
ill = Trap(2, ins)
def illegal():
raise ill
if opc == 0x07 and f3 == 2: # flw
immi = sx(ins >> 20, 12)
def f():
if not self.fs:
raise ill
a = (x[rs1] + immi) & M32
if a & 3:
raise Trap(4, a)
fr[rd] = self.rd32(a)
self.fs = 3
return nxt
return f
if opc == 0x27 and f3 == 2: # fsw
imms = sx((ins >> 25) << 5 | (ins >> 7 & 31), 12)
def f():
if not self.fs:
raise ill
a = (x[rs1] + imms) & M32
if a & 3:
raise Trap(6, a)
self.wr32(a, fr[rs2])
return nxt
return f
if opc in (0x07, 0x27) or (ins >> 25) & 3:
return illegal
f5 = ins >> 27
uses_rm = opc != 0x53 or f5 in (0, 1, 2, 3, 0x0B, 0x18, 0x1A)
if opc == 0x53:
ok = (f5 <= 3 or (f5 == 0x0B and rs2 == 0) or (f5 == 4 and f3 <= 2) or
(f5 == 5 and f3 <= 1) or (f5 == 0x14 and f3 <= 2) or
(f5 in (0x18, 0x1A) and rs2 <= 1) or (f5 == 0x1C and rs2 == 0 and f3 <= 1) or
(f5 == 0x1E and rs2 == 0 and f3 == 0))
if not ok:
return illegal
to_int = opc == 0x53 and f5 in (0x18, 0x1C, 0x14)
from_int = opc == 0x53 and f5 in (0x1A, 0x1E)
def f():
if not self.fs:
raise ill
rm = self.frm if f3 == 7 else f3
if uses_rm and rm > 4:
raise ill
a = x[rs1] if from_int else fr[rs1]
r, fl, _ = f32.execute(ins, rm, a, fr[rs2], fr[rs3])
self.fflags |= fl
self.fs = 3
if to_int:
if rd:
x[rd] = r
else:
fr[rd] = r
return nxt
return f
# ------------------------------------------------------------------ run
def trap(self, cause, tval):
self.csr[0x341] = self.pc
@@ -452,9 +552,17 @@ class RV32:
def cost(self, pc):
"""Clocks rv32_cpu takes for the instruction at pc, just run: 2, or 3
for a load, store, jump or taken branch (4 for I/O), 4 for a multiply,
35 for a divide."""
35 for a divide; floating point as listed in rv32_cpu.v (the shortcut
for infinite, NaN and zero operands isn't counted)."""
ins = self.rd32(pc)
op = ins & 0x7F
if op in (0x07, 0x27):
return 3
if op in (0x43, 0x47, 0x4B, 0x4F):
return 13
if op == 0x53:
f5 = ins >> 27
return {0: 13, 1: 13, 2: 13, 3: 37, 0x0B: 37, 0x18: 5, 0x1A: 9}.get(f5, 4)
if op in (0x03, 0x23):
a = (self.x[ins >> 15 & 31] + sx(ins >> 20 if op == 3 else (ins >> 25) << 5 | (ins >> 7 & 31), 12)) & M32
return 4 if a >= 0xFFFFFE00 or MON_RAM <= a < MON_END else 3
Regular → Executable
View File
File mode changed.