[1/2] sim: riscv: fix a divw division by -1 bug

Message ID AS8P193MB1285190D16ECDFD0DD14DBE6E4092@AS8P193MB1285.EURP193.PROD.OUTLOOK.COM
State New
Headers
Series [1/2] sim: riscv: fix a divw division by -1 bug |

Checks

Context Check Description
linaro-tcwg-bot/tcwg_gdb_build--master-aarch64 success Testing passed
linaro-tcwg-bot/tcwg_gdb_build--master-arm success Testing passed
linaro-tcwg-bot/tcwg_gdb_check--master-arm success Testing passed
linaro-tcwg-bot/tcwg_gdb_check--master-aarch64 success Testing passed

Commit Message

Bernd Edlinger April 15, 2024, 2:46 p.m. UTC
  There is a bug in divw for riscv64 target
with dividing by -1, the result was always 0,
when it should in fact be sign-extended -dividend.
It did not affect the rv32 target, because
these instructions are rv64 only.
Since 1 << 31 is an integer overflow this avoids
an undefined behaviour bug at the same time.

This caused test failures in the gcc testsuite like:

FAIL: gcc.c-torture/execute/arith-rand-ll.c   -O0  execution test
FAIL: gcc.c-torture/execute/arith-rand-ll.c   -O1  execution test
FAIL: gcc.c-torture/execute/arith-rand-ll.c   -O2  execution test
FAIL: gcc.c-torture/execute/arith-rand-ll.c   -O3  execution test
FAIL: gcc.c-torture/execute/arith-rand.c   -O0  execution test
FAIL: gcc.c-torture/execute/arith-rand.c   -O1  execution test
FAIL: gcc.c-torture/execute/arith-rand.c   -O2  execution test
FAIL: gcc.c-torture/execute/arith-rand.c   -O3  execution test
...
---
 sim/riscv/sim-main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
  

Patch

diff --git a/sim/riscv/sim-main.c b/sim/riscv/sim-main.c
index c8adb65139b..515ff835223 100644
--- a/sim/riscv/sim-main.c
+++ b/sim/riscv/sim-main.c
@@ -724,7 +724,7 @@  execute_m (SIM_CPU *cpu, unsigned_word iw, const struct riscv_opcode *op)
 		  rd_name, rs1_name, rs2_name, rd_name, rs1_name, rs2_name);
       RISCV_ASSERT_RV64 (cpu, "insn: %s", op->name);
       if (EXTEND32 (riscv_cpu->regs[rs2]) == -1)
-	tmp = 1 << 31;
+	tmp = EXTEND32 (-(uint32_t) riscv_cpu->regs[rs1]);
       else if (EXTEND32 (riscv_cpu->regs[rs2]))
 	tmp = EXTEND32 (riscv_cpu->regs[rs1]) / EXTEND32 (riscv_cpu->regs[rs2]);
       else