Hi RISC-V folks,
We are using a RISC-V-based microcontroller as an embedded controller,
and found out that RISC-V behaves differently from most of our other
architectures when performing an integer division: the core just
returns 0xffffffff, and does not raise any kind of exception.
The ISA manual [1] clearly states that's expected:
"""
We considered raising exceptions on integer divide by zero, with these
exceptions causing a trap in most execution environments. However,
this would be the only arithmetic trap in the standard ISA
(floating-point exceptions set flags and write default values, but do
not cause traps) and would require language implementors to interact
with the execution environment’s trap handlers for this case. Further,
where language standards mandate that a divide-by-zero exception must
cause an immediate control flow change, only a single branch
instruction needs to be added to each divide operation, and this
branch instruction can be inserted after the divide and should
normally be very predictably not taken, adding little runtime
overhead.
"""
For safety, we'd actually like to catch those divisions by zero in our
codebase, so we'd like the compiler to emit those check instructions.
GCC does have a `-mcheck-zero-division` option, but that's only
available for MIPS. We ended up using UBSAN's
`-fsanitize=integer-divide-by-zero` to instrument these divisions [3].
Combined with LTO, the additional code is actually quite reasonable,
and performance impact is negligible, but this still feels like a
hack...
Are we the first ones to hit this issue? Has somebody already started
working on adding compiler (GCC or LLVM) support for these checks? I
feel that Linux userspace applications would expect SIGFPE to be
emitted in those cases... Or is the common thinking that it's ok to
ignore those divisions by zero? (and that the code itself should
perform the checks where required)
Thanks!
Best,
Nicolas
[1]
http://www.five-embeddev.com/riscv-isa-manual/latest/m.html
[2]
https://gcc.gnu.org/onlinedocs/gcc-10.2.0/gcc/MIPS-Options.html#MIPS-Options
[3]
https://crrev.com/c/2605039