Add a single-precision FPU (the F extension)
rtl/rv32_fpu.v: IEEE 754 single precision with all five rounding modes, subnormals, the exception flags and the canonical NaN. Multiply-add (DSPs, exact product, 77-bit sum) with add, subtract and multiply as its special cases; divide and square root a bit a clock; one normalise-and- round back end. 12 clocks for add/mul/fma, 36 for div/sqrt. About 3000 LUTs and 2 DSPs; the system still meets 90 MHz. rv32_cpu.v: float registers, FLW/FSW, OP-FP and the R4 instructions, fflags/frm/fcsr, mstatus.FS (Initial at reset), misa F. tools/f32.py is an exact model (checked against x86 hardware) used by scripts/fputest.sh (random vectors, every instruction and rounding mode) and by tools/rv32emu.py, which now runs RV32IMF. cputest.sh adds rv32uf. BASIC and the games are built for rv32imf/ilp32f (BASIC 36.4 -> 28.7 KB, SIN about twice as fast); setjmp saves fs0-fs11; sqrtf is FSQRT.S. The monitor saves and restores f0-f31 and fcsr, shows them (F), sets them (R F1=...), and its disassembler and assembler know every F instruction (checked against objdump and GNU as). Docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
19278d1d74
commit
71fd403294
31 files changed
+9143
-7638
No files matched your search
@@ -10,3 +10,4 @@ third_party/
|
|||||||
*_out.txt
|
*_out.txt
|
||||||
sim_time.txt
|
sim_time.txt
|
||||||
out/
|
out/
|
||||||
|
sim/fpu/
|
||||||
@@ -20,7 +20,9 @@ covers it.
|
|||||||
|
|
||||||
## The processor (`rtl/rv32_cpu.v`)
|
## 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
|
(`cycle`, `time`, `instret`), `fence.i`, `ecall`/`ebreak`/`mret`/`wfi`, traps
|
||||||
and interrupts (`mtvec`, `mepc`, `mcause`, `mtval`; software, timer, external
|
and interrupts (`mtvec`, `mepc`, `mcause`, `mtval`; software, timer, external
|
||||||
and 16 local interrupt lines), two hardware triggers for execute, load and
|
and 16 local interrupt lines), two hardware triggers for execute, load and
|
||||||
@@ -29,9 +31,11 @@ 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
|
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
|
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
|
and stores, 4 for multiplies, 35 for divides; BASIC averages about 2.5.
|
||||||
runs at 90 MHz (the Z-80's clock) and takes about 2,100 LUTs, 900 flip-flops
|
Floating-point add, subtract, multiply and the fused multiply-adds take 12
|
||||||
and 4 DSP slices.
|
clocks, divide and square root 36. It runs at 90 MHz (the Z-80's clock) 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`)
|
## The machine (`rtl/rv32_system.v`)
|
||||||
|
|
||||||
@@ -61,9 +65,10 @@ All in C (plus a little assembly), compiled with GCC for `rv32im`:
|
|||||||
- `basic/` — BASIC, ported from the Z-80 version: the same language, the same
|
- `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
|
manual. `lib/` has the few C library functions it needs (small string
|
||||||
functions, `setjmp`, and single-precision `sinf` … `sqrtf`), since newlib's
|
functions, `setjmp`, and single-precision `sinf` … `sqrtf`), since newlib's
|
||||||
bring in its stdio and malloc. Floating point is IEEE single precision from
|
bring in its stdio and malloc. BASIC and the games are compiled for the FPU
|
||||||
libgcc, correctly rounded (the Z-80's SDCC library wasn't, so the last digit
|
(`rv32imf`, `ilp32f`); its arithmetic is IEEE single precision, correctly
|
||||||
of a result can differ).
|
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
|
- `monitor/` — the machine-code monitor, with a RISC-V disassembler and a
|
||||||
two-pass assembler in place of the Z-80 ones.
|
two-pass assembler in place of the Z-80 ones.
|
||||||
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
|
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
|
||||||
@@ -94,10 +99,11 @@ games/keep/keep.bas` and `SAVE "KEEP"` in BASIC.
|
|||||||
|
|
||||||
| | |
|
| | |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `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/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, 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/sim.sh` | the whole design in xsim: the terminal, BASIC, graphics, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor. |
|
||||||
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as |
|
| `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 and string arrays, 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 |
|
| `bench/` | the processor alone with 64 KB of RAM, for timing |
|
||||||
|
|
||||||
## Toolchain
|
## Toolchain
|
||||||
|
|||||||
Binary file not shown.
+4154
-4154
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -5,13 +5,13 @@ set -e
|
|||||||
cd "$(dirname "$0")"
|
cd "$(dirname "$0")"
|
||||||
source ../scripts/rv_env.sh
|
source ../scripts/rv_env.sh
|
||||||
mkdir -p out
|
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/crt0.o crt0.S
|
||||||
${RV_PREFIX}gcc $CFLAGS -c -o out/basic.o basic.c
|
${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/string.o ../lib/string.c
|
||||||
${RV_PREFIX}gcc $CFLAGS -c -o out/mathf.o ../lib/mathf.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 $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
|
-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}objcopy -O binary -j .text -j .data out/basic.elf basic.bin
|
||||||
${RV_PREFIX}nm -n out/basic.elf > out/basic.sym
|
${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.
|
# 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
|
# 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"
|
#include "basys3.h"
|
||||||
.section .text.start, "ax"
|
.section .text.start, "ax"
|
||||||
.globl _start
|
.globl _start
|
||||||
@@ -12,6 +12,9 @@ _start:
|
|||||||
la sp, __stack_top
|
la sp, __stack_top
|
||||||
li t0, MON_TRAP # illegal instructions etc. stop in the monitor
|
li t0, MON_TRAP # illegal instructions etc. stop in the monitor
|
||||||
csrw mtvec, t0
|
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 a0, __data_start # copy initialised data
|
||||||
la a1, __data_load
|
la a1, __data_load
|
||||||
la a2, __data_end
|
la a2, __data_end
|
||||||
|
|||||||
+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}]
|
set div [expr {[info exists ::env(DIV)] ? $::env(DIV) : 10.0}]
|
||||||
puts "CPU clock: [expr {100.0 * $mult / $div}] MHz"
|
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_mem $root/bench/bench.mem
|
||||||
read_xdc $root/bench/bench.xdc
|
read_xdc $root/bench/bench.xdc
|
||||||
synth_design -top cpu_bench -part xc7a35tcpg236-1 -generic MULT=$mult -generic DIV=$div
|
synth_design -top cpu_bench -part xc7a35tcpg236-1 -generic MULT=$mult -generic DIV=$div
|
||||||
|
|||||||
+27
-13
@@ -360,8 +360,9 @@ MONITOR
|
|||||||
```
|
```
|
||||||
|
|
||||||
`CALL` runs machine code at *address* as a subroutine, called the standard
|
`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
|
RISC-V way: it must end with `RET` and leave `SP`, `GP`, `TP`, `S0`–`S11` and
|
||||||
it found them (`A0`–`A7` and `T0`–`T6` are free to use). `MONITOR` stops BASIC in the
|
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.
|
machine-code monitor (section 10). See section 9 for memory and ports.
|
||||||
|
|
||||||
### Graphics and text placement
|
### Graphics and text placement
|
||||||
@@ -763,18 +764,19 @@ each voice, so a note or a bang fades away by itself.
|
|||||||
|
|
||||||
### Speed
|
### Speed
|
||||||
|
|
||||||
The processor is a 32-bit RISC-V (RV32IM: the base instructions plus
|
The processor is a 32-bit RISC-V (RV32IMF: the base instructions, multiply
|
||||||
multiply and divide) running at 90 MHz. Most instructions take 2 clocks; loads,
|
and divide, and single-precision floating point) running at 90 MHz. Most
|
||||||
stores, jumps and taken branches 3, a multiply 4 and a divide 35, which comes to
|
instructions take 2 clocks; loads, stores, jumps and taken branches 3, a
|
||||||
about 2.5 clocks per instruction in BASIC, some 36 million instructions a
|
multiply 4 and a divide 35, which comes to about 2.5 clocks per instruction in
|
||||||
second. BASIC does its floating-point arithmetic in software, so in round
|
BASIC, some 36 million instructions a second. Its floating-point unit adds,
|
||||||
numbers:
|
subtracts and multiplies in 12 clocks and divides or takes a square root in 36,
|
||||||
|
correctly rounded. In round numbers:
|
||||||
|
|
||||||
| Operation | Time |
|
| Operation | Time |
|
||||||
|---|---|
|
|---|---|
|
||||||
| One pass of an empty `FOR … NEXT` loop | 9 µs (about 100,000 a second) |
|
| One pass of an empty `FOR … NEXT` loop | 8 µs (about 120,000 a second) |
|
||||||
| `X = I * 1.5` | 43 µs |
|
| `X = I * 1.5` | 26 µs |
|
||||||
| `Y = SIN(X)` | 85 µs |
|
| `Y = SIN(X)` | 37 µs |
|
||||||
| `LINE` right across the screen | 0.2 ms |
|
| `LINE` right across the screen | 0.2 ms |
|
||||||
|
|
||||||
Constants in a program are converted from text every time they are used, so a
|
Constants in a program are converted from text every time they are used, so a
|
||||||
@@ -837,7 +839,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) |
|
| `D addr` | Show the disassembly from *addr* (`D` alone: from PC) |
|
||||||
| `M addr` | Show memory from *addr* |
|
| `M addr` | Show memory from *addr* |
|
||||||
| `E addr bytes…` | Write bytes into memory: `E 12000 13 05 10 04` |
|
| `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 |
|
| `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"` | Load a memory file back to where it was saved from |
|
||||||
| `LOAD "NAME" addr` | Load it at *addr* instead (0A000h or above) |
|
| `LOAD "NAME" addr` | Load it at *addr* instead (0A000h or above) |
|
||||||
@@ -856,7 +859,9 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
|
|||||||
itself, the monitor first steps past it.
|
itself, the monitor first steps past it.
|
||||||
- **Memory below 0A000h** is BASIC's ROM and can be viewed but not changed. `E`
|
- **Memory below 0A000h** is BASIC's ROM and can be viewed but not changed. `E`
|
||||||
says so if you try.
|
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`,
|
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`;
|
`RET`, `BEQZ`, `CSRR` and so on), with hex numbers like `1F0H` and `0A200H`;
|
||||||
anything else is shown as `DW` and its value.
|
anything else is shown as `DW` and its value.
|
||||||
@@ -939,6 +944,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`,
|
*target* (saving RA), `JALR` *register*, `RET`, `CALL`, `BEQZ`, `BNEZ`,
|
||||||
`BLEZ`, `BGEZ`, `BLTZ`, `BGTZ`, `BGT`, `BLE`, `BGTU`, `BLEU`, `CSRR`, `CSRW`,
|
`BLEZ`, `BGEZ`, `BLTZ`, `BGTZ`, `BGT`, `BLE`, `BGTU`, `BLEU`, `CSRR`, `CSRW`,
|
||||||
`CSRS`, `CSRC`, `CSRWI`, `CSRSI`, `CSRCI`.
|
`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
|
- **`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
|
known by then, otherwise two (`LUI`, `ADDI`); **`LA`** is always two
|
||||||
(`AUIPC`, `ADDI`); **`CALL`** is `JAL RA`, which reaches 1 MB either way.
|
(`AUIPC`, `ADDI`); **`CALL`** is `JAL RA`, which reaches 1 MB either way.
|
||||||
|
|||||||
Binary file not shown.
+2
-2
@@ -8,11 +8,11 @@ source ../scripts/rv_env.sh
|
|||||||
G=$1
|
G=$1
|
||||||
mkdir -p $G/out
|
mkdir -p $G/out
|
||||||
python3 $G/gen.py $G/out/data.h
|
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/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/$G.o $G/$G.c
|
||||||
${RV_PREFIX}gcc $CFLAGS -c -o $G/out/string.o ../lib/string.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
|
-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}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
|
${RV_PREFIX}nm -n $G/out/$G.elf > $G/out/$G.sym
|
||||||
|
|||||||
+7
-1
@@ -1,7 +1,8 @@
|
|||||||
/* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf
|
/* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf
|
||||||
floorf. Range reduction by Cody and Waite, minimax polynomials as in the
|
floorf. 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
|
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.) */
|
bring in errno, stdio and malloc.) */
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
@@ -141,6 +142,10 @@ float logf(float x)
|
|||||||
/* exact: one bit at a time (after fdlibm) */
|
/* exact: one bit at a time (after fdlibm) */
|
||||||
float sqrtf(float x)
|
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 };
|
fbits u = { x };
|
||||||
int32_t ix = (int32_t)u.i, m, i;
|
int32_t ix = (int32_t)u.i, m, i;
|
||||||
uint32_t q, s, r, t;
|
uint32_t q, s, r, t;
|
||||||
@@ -167,6 +172,7 @@ float sqrtf(float x)
|
|||||||
if (ix) q += q & 1;
|
if (ix) q += q & 1;
|
||||||
u.i = (q >> 1) + 0x3F000000 + ((uint32_t)m << 23);
|
u.i = (q >> 1) + 0x3F000000 + ((uint32_t)m << 23);
|
||||||
return u.f;
|
return u.f;
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
float floorf(float x)
|
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
|
.text
|
||||||
.globl setjmp, longjmp
|
.globl setjmp, longjmp
|
||||||
setjmp:
|
setjmp:
|
||||||
@@ -16,6 +17,20 @@ setjmp:
|
|||||||
sw s9, 44(a0)
|
sw s9, 44(a0)
|
||||||
sw s10, 48(a0)
|
sw s10, 48(a0)
|
||||||
sw s11, 52(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
|
li a0, 0
|
||||||
ret
|
ret
|
||||||
longjmp:
|
longjmp:
|
||||||
@@ -33,6 +48,20 @@ longjmp:
|
|||||||
lw s9, 44(a0)
|
lw s9, 44(a0)
|
||||||
lw s10, 48(a0)
|
lw s10, 48(a0)
|
||||||
lw s11, 52(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
|
seqz a0, a1
|
||||||
add a0, a0, a1 # 0 becomes 1
|
add a0, a0, a1 # 0 becomes 1
|
||||||
ret
|
ret
|
||||||
+111
-3
@@ -11,7 +11,12 @@
|
|||||||
* Instructions: RV32I and M, CSRRW..CSRRCI, ECALL EBREAK MRET MNRET WFI FENCE
|
* 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
|
* 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
|
* 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.
|
* -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"),
|
* 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
|
* 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 */
|
/* ------------------------------------------------------------- operands */
|
||||||
#define MAXOP 3
|
#define MAXOP 5
|
||||||
static char a_ops[MAXOP][40];
|
static char a_ops[MAXOP][40];
|
||||||
static u8 a_nops;
|
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 u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
|
||||||
static i32 lo12(u32 v) { return sx(v, 12); }
|
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 */
|
/* --------------------------------------------------------- instructions */
|
||||||
enum {
|
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,
|
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). */
|
/* Assemble one source line (uppercase except in quotes). */
|
||||||
static void a_line(char *s)
|
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;
|
u8 has_lab = 0, q = 0;
|
||||||
u16 m;
|
u16 m;
|
||||||
char *c;
|
char *c;
|
||||||
@@ -485,6 +581,7 @@ static void a_line(char *s)
|
|||||||
a_sp();
|
a_sp();
|
||||||
if (!*ap) return;
|
if (!*ap) return;
|
||||||
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
|
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
|
||||||
|
mn = ap;
|
||||||
a_name(w);
|
a_name(w);
|
||||||
a_sp();
|
a_sp();
|
||||||
if (*ap == ':') { /* LABEL: */
|
if (*ap == ':') { /* LABEL: */
|
||||||
@@ -493,6 +590,7 @@ static void a_line(char *s)
|
|||||||
a_sp();
|
a_sp();
|
||||||
if (!*ap) { sym_def(lab, a_pc); return; }
|
if (!*ap) { sym_def(lab, a_pc); return; }
|
||||||
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
|
if (!a_alpha(*ap)) { a_fail("SYNTAX ERROR"); return; }
|
||||||
|
mn = ap;
|
||||||
a_name(w);
|
a_name(w);
|
||||||
a_sp();
|
a_sp();
|
||||||
} else if (!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) {
|
} 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);
|
else while (a_pc & (n - 1)) a_emit(0);
|
||||||
return;
|
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++)
|
for (m = 0; m < NINS; m++)
|
||||||
if (!strncmp(w, itab[m].name, 8)) break;
|
if (!strncmp(w, itab[m].name, 8)) break;
|
||||||
if (m == NINS) { a_fail("UNKNOWN INSTRUCTION"); return; }
|
if (m == NINS) { a_fail("UNKNOWN INSTRUCTION"); return; }
|
||||||
|
|||||||
+2
-2
@@ -5,12 +5,12 @@ set -e
|
|||||||
cd "$(dirname "$0")"
|
cd "$(dirname "$0")"
|
||||||
source ../scripts/rv_env.sh
|
source ../scripts/rv_env.sh
|
||||||
mkdir -p out
|
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/crt0.o crt0.S
|
||||||
${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c
|
${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/string.o ../lib/string.c
|
||||||
${RV_PREFIX}gcc $CFLAGS -c -o out/setjmp.o ../lib/setjmp.S
|
${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 \
|
-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
|
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
|
${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).
|
# instruction, a misaligned access, ebreak, ecall, an unhandled interrupt).
|
||||||
# The program's registers go to u (struct regs in monitor.c), the monitor runs,
|
# 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.
|
# 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 INITED, 0x29FFC # C data is set up once, then kept
|
||||||
.equ U_PC, 128
|
.equ U_PC, 128
|
||||||
.equ U_HOW, 132 # 0 NMI, 1 trap
|
.equ U_HOW, 132 # 0 NMI, 1 trap
|
||||||
.equ U_CAUSE, 136
|
.equ U_CAUSE, 136
|
||||||
.equ U_TVAL, 140
|
.equ U_TVAL, 140
|
||||||
.equ U_STATUS, 144
|
.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"
|
.section .text.start, "ax"
|
||||||
.globl _start, u
|
.globl _start, u
|
||||||
@@ -56,6 +63,21 @@ trap_entry:
|
|||||||
|
|
||||||
common:
|
common:
|
||||||
li sp, U # the monitor's stack, below u
|
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
|
li t0, INITED
|
||||||
lw t1, 0(t0)
|
lw t1, 0(t0)
|
||||||
li t2, 0xA5A5
|
li t2, 0xA5A5
|
||||||
@@ -79,7 +101,18 @@ common:
|
|||||||
3: call mon_main
|
3: call mon_main
|
||||||
|
|
||||||
li sp, U
|
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
|
csrw 0x741, t0 # mnepc
|
||||||
lw t0, U_HOW(sp)
|
lw t0, U_HOW(sp)
|
||||||
beqz t0, 4f
|
beqz t0, 4f
|
||||||
|
|||||||
Binary file not shown.
+132
-5
@@ -27,12 +27,15 @@ typedef int32_t i32;
|
|||||||
#define fl_ctl IO8(0x40)
|
#define fl_ctl IO8(0x40)
|
||||||
#define fl_dat IO8(0x41)
|
#define fl_dat IO8(0x41)
|
||||||
|
|
||||||
/* saved by crt0.S at 29F00h */
|
/* saved by crt0.S at 29E80h */
|
||||||
struct regs {
|
struct regs {
|
||||||
u32 x[32]; /* x[0] is 0 */
|
u32 x[32]; /* x[0] is 0 */
|
||||||
u32 pc;
|
u32 pc;
|
||||||
u32 how; /* 0 NMI, 1 trap */
|
u32 how; /* 0 NMI, 1 trap */
|
||||||
u32 cause, tval, status; /* for a 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;
|
extern struct regs u;
|
||||||
|
|
||||||
@@ -101,6 +104,7 @@ static const struct csrn csrs[] = {
|
|||||||
{ 0x7A5, "TCONTROL" }, { 0xB00, "MCYCLE" }, { 0xB02, "MINSTRET" }, { 0xB80, "MCYCLEH" },
|
{ 0x7A5, "TCONTROL" }, { 0xB00, "MCYCLE" }, { 0xB02, "MINSTRET" }, { 0xB80, "MCYCLEH" },
|
||||||
{ 0xB82, "MINSTRETH" }, { 0xC00, "CYCLE" }, { 0xC01, "TIME" }, { 0xC02, "INSTRET" },
|
{ 0xB82, "MINSTRETH" }, { 0xC00, "CYCLE" }, { 0xC01, "TIME" }, { 0xC02, "INSTRET" },
|
||||||
{ 0xC80, "CYCLEH" }, { 0xC81, "TIMEH" }, { 0xC82, "INSTRETH" }, { 0xF14, "MHARTID" },
|
{ 0xC80, "CYCLEH" }, { 0xC81, "TIMEH" }, { 0xC82, "INSTRETH" }, { 0xF14, "MHARTID" },
|
||||||
|
{ 0x001, "FFLAGS" }, { 0x002, "FRM" }, { 0x003, "FCSR" },
|
||||||
{ 0, 0 }
|
{ 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 muln[8] = { "MUL", "MULH", "MULHSU", "MULHU", "DIV", "DIVU", "REM", "REMU" };
|
||||||
static const char *const csrin[8] = { 0, "CSRRW", "CSRRS", "CSRRC", 0, "CSRRWI", "CSRRSI", "CSRRCI" };
|
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. */
|
/* One instruction at a into line (at lp); returns its length, 4. */
|
||||||
static u8 disasm(u32 a)
|
static u8 disasm(u32 a)
|
||||||
{
|
{
|
||||||
@@ -199,6 +270,18 @@ static u8 disasm(u32 a)
|
|||||||
else break;
|
else break;
|
||||||
s_reg(rd); s_c(); s_reg(rs1); s_c(); s_reg(rs2);
|
s_reg(rd); s_c(); s_reg(rs1); s_c(); s_reg(rs2);
|
||||||
return 4;
|
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:
|
case 0x0F:
|
||||||
if (f3 == 0) { s_str("FENCE"); return 4; }
|
if (f3 == 0) { s_str("FENCE"); return 4; }
|
||||||
if (f3 == 1) { s_str("FENCE.I"); return 4; }
|
if (f3 == 1) { s_str("FENCE.I"); return 4; }
|
||||||
@@ -340,6 +423,7 @@ static char cmd[80];
|
|||||||
static u8 msg_err;
|
static u8 msg_err;
|
||||||
static const char *msg;
|
static const char *msg;
|
||||||
static u8 why_in; /* why the monitor was entered */
|
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];
|
static char load_msg[32];
|
||||||
|
|
||||||
/* ------------------------------------------------------------- drawing */
|
/* ------------------------------------------------------------- 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)
|
static void draw_mem(void)
|
||||||
{
|
{
|
||||||
u32 a = mem_a;
|
u32 a = mem_a;
|
||||||
u8 r, j, c;
|
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++) {
|
for (r = 0; r < MEM_ROWS; r++) {
|
||||||
lp = line;
|
lp = line;
|
||||||
s_ch(' '); s_hex(a, 5); s_str(" ");
|
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");
|
at(DIS_TOP - 1, 0); sgr("36"); puts_(" ADDR WORD INSTRUCTION"); sgr("0");
|
||||||
draw_dis();
|
draw_dis();
|
||||||
draw_stack();
|
draw_stack();
|
||||||
at(MEM_TOP - 1, 0); sgr("36"); puts_(" MEMORY"); sgr("0");
|
|
||||||
draw_mem();
|
draw_mem();
|
||||||
at(28, 0); sgr("36");
|
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");
|
sgr("0");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -927,6 +1033,21 @@ static u8 set_reg(void)
|
|||||||
u8 r;
|
u8 r;
|
||||||
u32 v;
|
u32 v;
|
||||||
skip_sp();
|
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; }
|
if (cp[0] == 'P' && cp[1] == 'C') { cp += 2; r = 32; }
|
||||||
else if ((r = reg_num()) == 0xFF || r == 0) return 0;
|
else if ((r = reg_num()) == 0xFF || r == 0) return 0;
|
||||||
skip_sp();
|
skip_sp();
|
||||||
@@ -1052,6 +1173,7 @@ static u8 command(void)
|
|||||||
return 0;
|
return 0;
|
||||||
case 'M':
|
case 'M':
|
||||||
if (get_hex(&v)) mem_a = v;
|
if (get_hex(&v)) mem_a = v;
|
||||||
|
show_f = 0;
|
||||||
draw_mem();
|
draw_mem();
|
||||||
return 0;
|
return 0;
|
||||||
case 'E': /* E addr bytes... */
|
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; }
|
if (!wr(a++, v)) { msg = "ROM: NOT CHANGED"; msg_err = 1; break; }
|
||||||
draw_all();
|
draw_all();
|
||||||
return 0;
|
return 0;
|
||||||
|
case 'F':
|
||||||
|
show_f = 1;
|
||||||
|
draw_mem();
|
||||||
|
msg = "M TO SHOW MEMORY AGAIN";
|
||||||
|
return 0;
|
||||||
case 'R':
|
case 'R':
|
||||||
if (!set_reg()) { msg = "R PC|X1-X31|RA|SP|A0... = VALUE"; msg_err = 1; return 0; }
|
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_regs(); draw_dis(); draw_stack(); draw_mem();
|
||||||
return 0;
|
return 0;
|
||||||
case '?':
|
case '?':
|
||||||
case 'H':
|
case 'H':
|
||||||
|
|||||||
+4
-1
@@ -1,5 +1,5 @@
|
|||||||
/* The monitor: ROM 20000-27FFF (writes ignored), RAM 28000-29FFF (data only)
|
/* 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")
|
OUTPUT_ARCH("riscv")
|
||||||
ENTRY(_start)
|
ENTRY(_start)
|
||||||
MEMORY
|
MEMORY
|
||||||
@@ -22,6 +22,9 @@ SECTIONS
|
|||||||
__data_end = .;
|
__data_end = .;
|
||||||
} > RAM AT > ROM
|
} > RAM AT > ROM
|
||||||
__data_load = LOADADDR(.data);
|
__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 (NOLOAD) : ALIGN(4) {
|
||||||
__bss_start = .;
|
__bss_start = .;
|
||||||
*(.sbss .sbss.* .bss .bss.* COMMON)
|
*(.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
|
||||||
FENCE.I
|
FENCE.I
|
||||||
NOP
|
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
|
RET
|
||||||
MSG: DB "HI",13,10,0
|
MSG: DB "HI",13,10,0
|
||||||
ALIGN 4
|
ALIGN 4
|
||||||
@@ -114,7 +141,7 @@ def main():
|
|||||||
start, ours = ours.split()
|
start, ours = ours.split()
|
||||||
tmp = tempfile.mkdtemp()
|
tmp = tempfile.mkdtemp()
|
||||||
open(os.path.join(tmp, "t.s"), "w").write(to_gnu(SRC))
|
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)
|
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"),
|
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)
|
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 | 0 << 15 | imm << 20) # li
|
||||||
ws.append(0x13 | r() << 7 | r() << 15) # mv
|
ws.append(0x13 | r() << 7 | r() << 15) # mv
|
||||||
ws.append(0x00008067) # ret
|
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]
|
ws += [0x13, 0x73, 0x00100073, 0x30200073, 0x70200073, 0x10500073, 0x0FF0000F, 0x100F]
|
||||||
return ws
|
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,
|
"MNEPC": 0x741, "MNCAUSE": 0x742, "MNSTATUS": 0x744, "TSELECT": 0x7A0, "TDATA1": 0x7A1,
|
||||||
"TDATA2": 0x7A2, "TCONTROL": 0x7A5, "MCYCLE": 0xB00, "MINSTRET": 0xB02, "MCYCLEH": 0xB80,
|
"TDATA2": 0x7A2, "TCONTROL": 0x7A5, "MCYCLE": 0xB00, "MINSTRET": 0xB02, "MCYCLEH": 0xB80,
|
||||||
"MINSTRETH": 0xB82, "CYCLE": 0xC00, "TIME": 0xC01, "INSTRET": 0xC02, "CYCLEH": 0xC80,
|
"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):
|
def same(gnu_mn, gnu_ops, our):
|
||||||
@@ -109,6 +135,14 @@ def same(gnu_mn, gnu_ops, our):
|
|||||||
gnu_ops = ["RA"] + gnu_ops
|
gnu_ops = ["RA"] + gnu_ops
|
||||||
elif gnu_mn.startswith("RD") and gnu_mn[2:] in CSRN:
|
elif gnu_mn.startswith("RD") and gnu_mn[2:] in CSRN:
|
||||||
gnu_mn, gnu_ops = "CSRR", gnu_ops + [gnu_mn[2:]]
|
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]
|
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]
|
ops = [str(CSRN[o]) if o in CSRN else o for o in ops]
|
||||||
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"}
|
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"}
|
||||||
|
|||||||
+106
-18
@@ -1,12 +1,16 @@
|
|||||||
`timescale 1ns / 1ps
|
`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
|
// 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
|
// 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
|
// 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
|
// 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
|
// 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.
|
// 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
|
// Speed: 90 MHz with 1.5 ns to spare on the XC7A35T-1 (bench/), about 2100
|
||||||
// LUTs, 900 flip-flops and 4 DSP slices.
|
// 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),
|
// 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,
|
// misa, mie, mip, mtvec (direct mode), mscratch, mepc, mcause, mtval, mcycle,
|
||||||
// minstret, mhartid etc. (read 0), and two Sdtrig match triggers (tselect,
|
// 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 dbg_decode, // high in an instruction's first cycle
|
||||||
output reg retire // pulse: an instruction completed
|
output reg retire // pulse: an instruction completed
|
||||||
);
|
);
|
||||||
localparam S_IF = 3'd0, S_D = 3'd1, S_E = 3'd2, S_MEM = 3'd3,
|
localparam S_IF = 4'd0, S_D = 4'd1, S_E = 4'd2, S_MEM = 4'd3,
|
||||||
S_MUL = 3'd4, S_DIV = 3'd5, S_DIVF = 3'd6, S_XT = 3'd7;
|
S_MUL = 4'd4, S_DIV = 4'd5, S_DIVF = 4'd6, S_XT = 4'd7, S_FP = 4'd8;
|
||||||
reg [2:0] state;
|
reg [3:0] state;
|
||||||
reg [31:0] pc;
|
reg [31:0] pc;
|
||||||
|
|
||||||
assign i_en = state == S_IF || state == S_D;
|
assign i_en = state == S_IF || state == S_D;
|
||||||
@@ -94,6 +100,15 @@ module rv32_cpu #(
|
|||||||
reg [31:0] rf_wd;
|
reg [31:0] rf_wd;
|
||||||
always @(posedge clk) if (rf_we && rf_wa != 5'd0) rf[rf_wa] <= 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.
|
// Decode (state D): inst is the fetched word.
|
||||||
wire [31:0] inst = i_rdata;
|
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 [4:0] rs1 = inst[19:15], rs2 = inst[24:20];
|
||||||
wire [31:0] rv1 = rs1 == 5'd0 ? 32'd0 : rf[rs1];
|
wire [31:0] rv1 = rs1 == 5'd0 ? 32'd0 : rf[rs1];
|
||||||
wire [31:0] rv2 = rs2 == 5'd0 ? 32'd0 : rf[rs2];
|
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_i = {{20{inst[31]}}, inst[31:20]};
|
||||||
wire [31:0] imm_s = {{20{inst[31]}}, inst[31:25], inst[11:7]};
|
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_mret = inst == 32'h3020_0073;
|
||||||
wire is_wfi = inst == 32'h1050_0073;
|
wire is_wfi = inst == 32'h1050_0073;
|
||||||
wire is_mnret = inst == 32'h7020_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 |
|
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_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.
|
// Execute-stage registers, loaded at the end of D.
|
||||||
@@ -148,7 +187,10 @@ module rv32_cpu #(
|
|||||||
reg x_trap; // the deferred trap, below
|
reg x_trap; // the deferred trap, below
|
||||||
reg [31:0] x_cause, x_val;
|
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,
|
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 [2:0] e_f3 = ir[14:12];
|
||||||
wire [4:0] e_rd = ir[11:7];
|
wire [4:0] e_rd = ir[11:7];
|
||||||
reg [2:0] alu_fn;
|
reg [2:0] alu_fn;
|
||||||
@@ -221,8 +263,11 @@ module rv32_cpu #(
|
|||||||
always @* begin
|
always @* begin
|
||||||
csr_ok = 1'b1;
|
csr_ok = 1'b1;
|
||||||
case (csr_a)
|
case (csr_a)
|
||||||
12'h300: csr_rd = {19'd0, 2'b11, 3'd0, mpie_b, 3'd0, mie_b, 3'd0};
|
12'h001: begin csr_rd = {27'd0, fflags}; csr_ok = fp_on; end
|
||||||
12'h301: csr_rd = 32'h4000_1100; // RV32 I M
|
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'h304: csr_rd = mie_r;
|
||||||
12'h305: csr_rd = mtvec;
|
12'h305: csr_rd = mtvec;
|
||||||
12'h310: csr_rd = 32'd0; // mstatush
|
12'h310: csr_rd = 32'd0; // mstatush
|
||||||
@@ -346,16 +391,34 @@ module rv32_cpu #(
|
|||||||
end
|
end
|
||||||
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
|
// Register write-back
|
||||||
always @* begin
|
always @* begin
|
||||||
rf_we = 1'b0; rf_wa = e_rd; rf_wd = alu_out;
|
rf_we = 1'b0; rf_wa = e_rd; rf_wd = alu_out;
|
||||||
|
frf_we = 1'b0; frf_wd = fpu_res;
|
||||||
case (state)
|
case (state)
|
||||||
S_E: begin
|
S_E: begin
|
||||||
rf_we = !trap && (e_alu || e_jal || e_jalr || e_csr);
|
rf_we = !trap && (e_alu || e_jal || e_jalr || e_csr);
|
||||||
rf_wd = e_csr ? csr_rd : (e_jal || e_jalr) ? pc4 : alu_out;
|
rf_wd = e_csr ? csr_rd : (e_jal || e_jalr) ? pc4 : alu_out;
|
||||||
end
|
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_MUL: begin rf_we = m_cnt; rf_wd = m_hi ? m_p2[63:32] : m_p2[31:0]; end
|
||||||
S_DIVF: begin
|
S_DIVF: begin
|
||||||
rf_we = 1'b1;
|
rf_we = 1'b1;
|
||||||
@@ -368,9 +431,12 @@ module rv32_cpu #(
|
|||||||
endcase
|
endcase
|
||||||
end
|
end
|
||||||
|
|
||||||
|
always @(posedge clk) if (frf_we) frf[e_rd] <= frf_wd;
|
||||||
|
|
||||||
// an instruction completes (counted by instret unless it writes instret)
|
// an instruction completes (counted by instret unless it writes instret)
|
||||||
reg count_i;
|
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_MEM && d_ack) || (state == S_MUL && m_cnt) ||
|
||||||
state == S_DIVF || (state == S_XT && !x_trap);
|
state == S_DIVF || (state == S_XT && !x_trap);
|
||||||
|
|
||||||
@@ -387,7 +453,10 @@ module rv32_cpu #(
|
|||||||
|
|
||||||
if (csr_go) begin
|
if (csr_go) begin
|
||||||
case (csr_a)
|
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'h304: mie_r <= csr_wv & MIE_MASK;
|
||||||
12'h305: mtvec <= {csr_wv[31:2], 2'b00};
|
12'h305: mtvec <= {csr_wv[31:2], 2'b00};
|
||||||
12'h340: mscratch <= csr_wv;
|
12'h340: mscratch <= csr_wv;
|
||||||
@@ -421,9 +490,16 @@ module rv32_cpu #(
|
|||||||
pc4 <= pc + 32'd4;
|
pc4 <= pc + 32'd4;
|
||||||
tgt <= pc + (is_jal ? imm_j : imm_b);
|
tgt <= pc + (is_jal ? imm_j : imm_b);
|
||||||
a <= is_lui ? 32'd0 : (is_auipc || is_jal) ? pc : rv1;
|
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;
|
(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_fn <= (is_lui || is_auipc) ? 3'd0 : f3;
|
||||||
alu_alt <= inst[30];
|
alu_alt <= inst[30];
|
||||||
e_alu <= is_lui | is_auipc | is_opi | is_op;
|
e_alu <= is_lui | is_auipc | is_opi | is_op;
|
||||||
@@ -432,8 +508,8 @@ module rv32_cpu #(
|
|||||||
e_jalr <= is_jalr;
|
e_jalr <= is_jalr;
|
||||||
e_br <= is_br;
|
e_br <= is_br;
|
||||||
e_tmis <= is_jal ? inst[21] : inst[8];
|
e_tmis <= is_jal ? inst[21] : inst[8];
|
||||||
e_ld <= is_ld;
|
e_ld <= is_ld || (is_flw && fp_on);
|
||||||
e_st <= is_st;
|
e_st <= is_st || (is_fsw && fp_on);
|
||||||
e_mul <= is_mdv & !f3[2];
|
e_mul <= is_mdv & !f3[2];
|
||||||
e_div <= is_mdv & f3[2];
|
e_div <= is_mdv & f3[2];
|
||||||
e_csr <= is_csr;
|
e_csr <= is_csr;
|
||||||
@@ -471,6 +547,8 @@ module rv32_cpu #(
|
|||||||
state <= S_MUL;
|
state <= S_MUL;
|
||||||
else if (e_div)
|
else if (e_div)
|
||||||
state <= S_DIV;
|
state <= S_DIV;
|
||||||
|
else if (e_fp)
|
||||||
|
state <= S_FP;
|
||||||
else if (e_br && e_tmis)
|
else if (e_br && e_tmis)
|
||||||
state <= S_XT;
|
state <= S_XT;
|
||||||
else if (e_mret) begin
|
else if (e_mret) begin
|
||||||
@@ -492,7 +570,16 @@ module rv32_cpu #(
|
|||||||
end
|
end
|
||||||
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
|
S_MUL: begin
|
||||||
m_cnt <= 1'b1;
|
m_cnt <= 1'b1;
|
||||||
@@ -546,6 +633,7 @@ module rv32_cpu #(
|
|||||||
mcycle <= 64'd0; minstret <= 64'd0;
|
mcycle <= 64'd0; minstret <= 64'd0;
|
||||||
retire <= 1'b0; count_i <= 1'b0;
|
retire <= 1'b0; count_i <= 1'b0;
|
||||||
nmie <= 1'b1; stepped <= 1'b0; nmi_taken <= 1'b0;
|
nmie <= 1'b1; stepped <= 1'b0; nmi_taken <= 1'b0;
|
||||||
|
fs <= 2'b01; fflags <= 5'd0; frm <= 3'd0;
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
endmodule
|
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
|
||||||
+4
-3
@@ -1,11 +1,12 @@
|
|||||||
#!/bin/bash
|
#!/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/.
|
# them all on rtl/rv32_cpu.v in xsim. Fetches riscv-tests into third_party/.
|
||||||
# scripts/cputest.sh [name-filter]
|
# scripts/cputest.sh [name-filter]
|
||||||
set -e
|
set -e
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
ROOT=$(pwd)
|
ROOT=$(pwd)
|
||||||
source scripts/rv_env.sh
|
source scripts/rv_env.sh
|
||||||
|
RV_ARCH="-march=rv32imf_zicsr_zifencei -mabi=ilp32"
|
||||||
RT=$ROOT/third_party/riscv-tests
|
RT=$ROOT/third_party/riscv-tests
|
||||||
if [ ! -d "$RT/isa" ]; then
|
if [ ! -d "$RT/isa" ]; then
|
||||||
git clone --recursive https://github.com/riscv-software-src/riscv-tests.git "$RT"
|
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"
|
echo "$OUT/$name.mem $th $name" >> "$LIST"
|
||||||
}
|
}
|
||||||
FILTER=$1
|
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
|
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"
|
build "$suite-$t" "$RT/isa/$suite/$t.S"
|
||||||
done
|
done
|
||||||
@@ -45,7 +46,7 @@ source scripts/vivado_env.sh
|
|||||||
mkdir -p sim/cpu
|
mkdir -p sim/cpu
|
||||||
cd sim/cpu
|
cd sim/cpu
|
||||||
rm -f xsim.log
|
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; }
|
[ -d xsim.dir/work ] && ! grep -q ERROR xvlog.log || { echo "compile failed"; exit 1; }
|
||||||
xelab -debug off tb_cpu -s tb_cpu >/dev/null
|
xelab -debug off tb_cpu -s tb_cpu >/dev/null
|
||||||
xsim tb_cpu -R -testplusarg list="$LIST" | grep -E '^(PASS|FAIL|[0-9]+ passed)'
|
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
|
fi
|
||||||
[ -x "${RV_PREFIX}gcc" ] || command -v "${RV_PREFIX}gcc" >/dev/null || { echo "no RISC-V gcc found; set RV_PREFIX" >&2; exit 1; }
|
[ -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"
|
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"
|
||||||
@@ -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
|
||||||
@@ -530,6 +530,14 @@ module tb_terminal;
|
|||||||
jp_txt = {cellraw(9, 19), cellraw(9, 20)};
|
jp_txt = {cellraw(9, 19), cellraw(9, 20)};
|
||||||
jp_to = hex_at(9, 21);
|
jp_to = hex_at(9, 21);
|
||||||
dump_screen;
|
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
|
uart_str("\015"); // Enter: one step
|
||||||
wait_at(0, 50, "STOPPED BY STEP");
|
wait_at(0, 50, "STOPPED BY STEP");
|
||||||
wait_at(29, 0, "> ");
|
wait_at(29, 0, "> ");
|
||||||
|
|||||||
+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()
|
||||||
+106
-5
@@ -1,8 +1,9 @@
|
|||||||
#!/usr/bin/env python3
|
#!/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.
|
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
|
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
|
(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
|
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
|
each instruction run. The emulator also counts the clocks rv32_cpu would take
|
||||||
(cycles; see cost()).
|
(cycles; see cost()).
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
import f32 # noqa: E402
|
||||||
|
|
||||||
M32 = 0xFFFFFFFF
|
M32 = 0xFFFFFFFF
|
||||||
RAM_END = 0x14000
|
RAM_END = 0x14000
|
||||||
@@ -43,6 +47,10 @@ class RV32:
|
|||||||
self.m[:len(mem)] = mem
|
self.m[:len(mem)] = mem
|
||||||
self.rom_top = rom_top # writes below are ignored
|
self.rom_top = rom_top # writes below are ignored
|
||||||
self.x = [0] * 32
|
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.pc = 0
|
||||||
self.cache = {}
|
self.cache = {}
|
||||||
self.csr = {0x300: 0, 0x304: 0, 0x305: 0, 0x340: 0, 0x341: 0, 0x342: 0, 0x343: 0,
|
self.csr = {0x300: 0, 0x304: 0, 0x305: 0, 0x340: 0, 0x341: 0, 0x342: 0, 0x343: 0,
|
||||||
@@ -172,9 +180,13 @@ class RV32:
|
|||||||
# ------------------------------------------------------------------ CSRs
|
# ------------------------------------------------------------------ CSRs
|
||||||
def csr_read(self, n):
|
def csr_read(self, n):
|
||||||
if n == 0x300:
|
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:
|
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:
|
if n == 0x344:
|
||||||
return 0
|
return 0
|
||||||
if n == 0x744:
|
if n == 0x744:
|
||||||
@@ -194,6 +206,17 @@ class RV32:
|
|||||||
raise Trap(2)
|
raise Trap(2)
|
||||||
if n == 0x300:
|
if n == 0x300:
|
||||||
self.csr[0x300] = v & 0x88
|
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:
|
elif n == 0x304:
|
||||||
self.csr[0x304] = v & 0xFFFF0888
|
self.csr[0x304] = v & 0xFFFF0888
|
||||||
elif n in (0x305, 0x341, 0x741):
|
elif n in (0x305, 0x341, 0x741):
|
||||||
@@ -367,6 +390,8 @@ class RV32:
|
|||||||
x[rd] = op(x[rs1], x[rs2])
|
x[rd] = op(x[rs1], x[rs2])
|
||||||
return nxt
|
return nxt
|
||||||
return f
|
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
|
if opc == 0x0F and f3 in (0, 1): # fence, fence.i
|
||||||
return lambda: nxt
|
return lambda: nxt
|
||||||
if opc == 0x73:
|
if opc == 0x73:
|
||||||
@@ -408,6 +433,74 @@ class RV32:
|
|||||||
return f
|
return f
|
||||||
return illegal
|
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
|
# ------------------------------------------------------------------ run
|
||||||
def trap(self, cause, tval):
|
def trap(self, cause, tval):
|
||||||
self.csr[0x341] = self.pc
|
self.csr[0x341] = self.pc
|
||||||
@@ -452,9 +545,17 @@ class RV32:
|
|||||||
def cost(self, pc):
|
def cost(self, pc):
|
||||||
"""Clocks rv32_cpu takes for the instruction at pc, just run: 2, or 3
|
"""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,
|
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)
|
ins = self.rd32(pc)
|
||||||
op = ins & 0x7F
|
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):
|
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
|
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
|
return 4 if a >= 0xFFFFFE00 or MON_RAM <= a < MON_END else 3
|
||||||
|
|||||||
Reference in new issue
Block a user