Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bda9bb67b6 | ||
|
|
71fd403294 | ||
|
|
19278d1d74 |
No files matched your search
@@ -10,3 +10,4 @@ third_party/
|
||||
*_out.txt
|
||||
sim_time.txt
|
||||
out/
|
||||
sim/fpu/
|
||||
@@ -1,21 +1,115 @@
|
||||
# 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 90 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, 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 +118,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 12
|
||||
clocks, divide and square root 36. It runs at 90 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 +131,42 @@ 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. `lib/` has the few C library functions it
|
||||
needs (small string functions, `setjmp`, and `sinf` … `sqrtf`), 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, 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)` | 37 µs |
|
||||
| `Y = EXP(X)` | 45 µs |
|
||||
| `X = I * 1.5` | 26 µs |
|
||||
| An empty `FOR` loop, each time round | 8.3 µs |
|
||||
|
||||
## Building
|
||||
|
||||
@@ -81,18 +185,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. |
|
||||
| `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 |
|
||||
| `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. |
|
||||
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays and graphics modes, 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 +202,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).
|
||||
Binary file not shown.
+54
-28
@@ -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,12 +180,17 @@ static struct chan ch[NCHAN];
|
||||
static struct chan *chan_arg(u8 mode);
|
||||
static u8 chan_line(struct chan *c);
|
||||
|
||||
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
|
||||
@@ -187,7 +200,7 @@ 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"
|
||||
@@ -761,7 +774,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();
|
||||
}
|
||||
@@ -1037,10 +1051,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 +1069,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 +1087,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 +1147,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 (;;) {
|
||||
@@ -1567,16 +1582,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 +1635,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 +1681,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;
|
||||
}
|
||||
@@ -2308,7 +2334,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:
|
||||
|
||||
+5698
-5698
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -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
@@ -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
|
||||
|
||||
Executable
+57
@@ -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()
|
||||
+1
-1
@@ -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
|
||||
|
||||
+74
-27
@@ -360,14 +360,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
|
||||
|
||||
@@ -408,7 +409,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 +422,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 +479,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 +626,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 +686,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,18 +795,19 @@ 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 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. Its floating-point unit adds,
|
||||
subtracts and multiplies in 12 clocks and divides or takes a square root in 36,
|
||||
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 |
|
||||
| One pass of an empty `FOR … NEXT` loop | 8 µs (about 120,000 a second) |
|
||||
| `X = I * 1.5` | 26 µs |
|
||||
| `Y = SIN(X)` | 37 µs |
|
||||
| `LINE` right across the screen | 0.2 ms |
|
||||
|
||||
Constants in a program are converted from text every time they are used, so a
|
||||
@@ -835,7 +870,8 @@ 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) |
|
||||
@@ -854,7 +890,9 @@ 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
|
||||
- **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, 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.
|
||||
@@ -937,6 +975,15 @@ address is offered. An empty line ends. Labels from the last `ASM` can be used.
|
||||
*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`.
|
||||
- **`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.
|
||||
@@ -1391,7 +1438,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
@@ -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
|
||||
|
||||
@@ -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
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -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
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -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
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -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
File diff suppressed because it is too large.
Load diff
+7
-1
@@ -1,7 +1,8 @@
|
||||
/* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf
|
||||
floorf. 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 +142,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 +172,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)
|
||||
|
||||
+30
-1
@@ -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
|
||||
+111
-3
@@ -11,7 +11,12 @@
|
||||
* 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
|
||||
* 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 (NAME EQU value), DB/DEFB/DEFM (numbers and "strings"),
|
||||
* DH (16 bits), DW/DEFW (32 bits), DS/DEFS n, ALIGN n, END. Instructions must
|
||||
@@ -174,7 +179,7 @@ static u32 a_expr(void)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- operands */
|
||||
#define MAXOP 3
|
||||
#define MAXOP 5
|
||||
static char a_ops[MAXOP][40];
|
||||
static u8 a_nops;
|
||||
|
||||
@@ -314,6 +319,96 @@ static u32 enc_u(u32 base, u8 rd, u32 imm)
|
||||
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 4"); 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,
|
||||
@@ -464,7 +559,8 @@ static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); }
|
||||
/* Assemble one source line (uppercase except in quotes). */
|
||||
static void a_line(char *s)
|
||||
{
|
||||
char w[8], lab[8];
|
||||
char w[8], lab[8], fm[12];
|
||||
const char *mn;
|
||||
u8 has_lab = 0, q = 0;
|
||||
u16 m;
|
||||
char *c;
|
||||
@@ -485,6 +581,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,6 +590,7 @@ 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])) {
|
||||
@@ -520,6 +618,16 @@ static void a_line(char *s)
|
||||
else while (a_pc & (n - 1)) a_emit(0);
|
||||
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; }
|
||||
|
||||
+2
-2
@@ -5,12 +5,12 @@ 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"
|
||||
CFLAGS="$RV_ARCH -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/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
@@ -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.
+132
-5
@@ -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;
|
||||
|
||||
@@ -101,6 +104,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,6 +127,73 @@ 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" };
|
||||
|
||||
/* 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" };
|
||||
static void s_freg(u8 r) { s_ch('F'); s_udec(r); }
|
||||
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); returns its length, 4. */
|
||||
static u8 disasm(u32 a)
|
||||
{
|
||||
@@ -199,6 +270,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; }
|
||||
@@ -340,6 +423,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 +482,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 +563,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");
|
||||
}
|
||||
|
||||
@@ -927,6 +1033,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 +1173,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 +1182,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':
|
||||
|
||||
+4
-1
@@ -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
|
||||
@@ -22,6 +22,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)
|
||||
|
||||
+3413
-3413
File diff suppressed because it is too large.
Load diff
+28
-1
@@ -68,6 +68,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
|
||||
@@ -114,7 +141,7 @@ def main():
|
||||
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"),
|
||||
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)
|
||||
|
||||
+35
-1
@@ -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,7 +116,12 @@ 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")}
|
||||
|
||||
|
||||
def same(gnu_mn, gnu_ops, our):
|
||||
@@ -109,6 +135,14 @@ 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"}
|
||||
|
||||
+13
-8
@@ -8,7 +8,7 @@
|
||||
// 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,6 +30,7 @@ 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_DIV = 10.0,
|
||||
@@ -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
|
||||
|
||||
@@ -331,7 +332,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 +345,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 +429,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 +447,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 +475,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),
|
||||
|
||||
+106
-18
@@ -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, 8 for int -> float, 12 for add, subtract,
|
||||
// multiply and the multiply-adds (4 if an operand is infinite, NaN or zero),
|
||||
// 36 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.
|
||||
@@ -28,7 +32,9 @@
|
||||
// Speed: 90 MHz with 1.5 ns to spare on the XC7A35T-1 (bench/), 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
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
`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 10 (2 when an operand is
|
||||
// infinite, NaN or zero), divide and square root 34, int -> float 6,
|
||||
// float -> int 3, the rest 2.
|
||||
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;
|
||||
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
|
||||
wire [31:0] xa = ra;
|
||||
wire [31:0] xb = op_add ? 32'h3F80_0000 : rb;
|
||||
wire [31:0] xc = op_add ? rb : rc;
|
||||
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]};
|
||||
wire signed [11:0] ea = ex8(xa) == 8'd0 ? 12'sd1 : {4'd0, ex8(xa)};
|
||||
wire signed [11:0] eb = ex8(xb) == 8'd0 ? 12'sd1 : {4'd0, ex8(xb)};
|
||||
wire signed [11:0] ec = ex8(xc) == 8'd0 ? 12'sd1 : {4'd0, ex8(xc)};
|
||||
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} - ({ea[11], ea} + {eb[11], eb} - 13'sd127) + 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
|
||||
wire signed [11:0] e_norm = n_ex - {5'd0, 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
|
||||
wire [4:0] lza = lz24(ma), lzb = lz24(mb);
|
||||
wire [23:0] na = ma << lza, nb = mb << lzb;
|
||||
wire signed [11:0] nea = ea - {7'd0, lza}, neb = eb - {7'd0, lzb};
|
||||
|
||||
// ------------------------------------------------------- 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;
|
||||
st <= S_U;
|
||||
end
|
||||
|
||||
S_U: begin
|
||||
// multiply-add specials (only used by the multiply-add family)
|
||||
pa <= ma; pb <= mb;
|
||||
ep <= ea + eb - 12'sd127;
|
||||
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_N1;
|
||||
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_N1;
|
||||
end
|
||||
|
||||
S_N1: begin // where to put the top bit
|
||||
n_zero <= n_x == 77'd0;
|
||||
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, 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_N1;
|
||||
end
|
||||
|
||||
S_SQRTF: begin
|
||||
n_x <= {dq, srem != 29'd0, 49'd0};
|
||||
st <= S_N1;
|
||||
end
|
||||
|
||||
default: st <= S_IDLE;
|
||||
endcase
|
||||
if (rst) begin
|
||||
st <= S_IDLE;
|
||||
done <= 1'b0;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
+54
-18
@@ -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,
|
||||
@@ -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};
|
||||
|
||||
+8
-4
@@ -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
@@ -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);
|
||||
|
||||
+4
-3
@@ -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)'
|
||||
|
||||
Executable
+14
@@ -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
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
+73
-1
@@ -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;
|
||||
@@ -346,6 +352,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 +496,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"});
|
||||
@@ -495,6 +559,14 @@ module tb_terminal;
|
||||
jp_txt = {cellraw(9, 19), cellraw(9, 20)};
|
||||
jp_to = hex_at(9, 21);
|
||||
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, "> ");
|
||||
|
||||
+3
-2
@@ -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,
|
||||
|
||||
+21
-5
@@ -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:
|
||||
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
@@ -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)
|
||||
Executable
+92
@@ -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
@@ -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 12
|
||||
if op == 0x53:
|
||||
f5 = ins >> 27
|
||||
return {0: 12, 1: 12, 2: 12, 3: 36, 0x0B: 36, 0x18: 5, 0x1A: 8}.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
File mode changed.
Reference in new issue
Block a user