3

What is the simplest, most readable and straightforward way to raise an illegal instruction in RISC-V on purpose?

I know that per spec any "full zero" instruction (so 32/16 bits only zeros) is a "Defined Illegal Instruction" (section 12.5, user spec). But I have no idea if there exists an asm shorthand for that (at least I could not find any) that I could then use in inline asm in C code.

There must surely be a portable and reliable way to always cause an illegal instruction exception? I personally find writing to read-only registers or similar hacks quite offputting, as they are not very explicit. But maybe this is just how its done?

Thank you in advance

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Fabian
  • 312
  • 3
  • 13
  • Any inline-asm syntax compatible with GNU C / GAS would let you use `.word 0` to emit four bytes of zeros for a RISC-V target. There may also be a mnemonic for it, IDK. – Peter Cordes Nov 16 '21 at 13:18
  • 2
    https://reviews.llvm.org/D54316 <- try `c.unimp` –  Nov 16 '21 at 13:19
  • @peterCordes you are right! I can simply put "__asm__ volatile(".word 0");" into the C code. Never would have thought that the compiler/assembler would eat that! Thanks – Fabian Nov 16 '21 at 13:21
  • @dratenik Thanks, this is exactly what I was looking for!! Simple and explicit: __asm__ volatile ("unimp");. Its simply zeros again, but a lot more readable. – Fabian Nov 16 '21 at 13:25
  • Assemblers just assemble bytes into the output (in the current section). GNU C inline asm works by printing this text into the compiler's asm output that will eventually be fed to an assembler. (And clang mostly works as-if that happened, at least for things with purely local effects or `.pushsection`/`.popsection` to put some data somewhere.) So that's why it works. But yeah, good that there's an `unimp` mnemonic for it, that's always better than manually encoding, especially when you might compile for 16-bit compressed instructions. – Peter Cordes Nov 16 '21 at 13:26
  • ok, it works, so let's make that an answer. :) –  Nov 16 '21 at 13:38

1 Answers1

6

The mnemonic for it is unimp. It is documented in the RISC-V asm manual, so it should be portable.

  • thank you again! Link to this: https://github.com/riscv-non-isa/riscv-asm-manual/blob/master/riscv-asm.md#instruction-aliases. – Fabian Nov 16 '21 at 13:42