design icon indicating copy to clipboard operation
design copied to clipboard

Non-trapping instruction for signed division on overflow

Open gkdn opened this issue 5 years ago • 4 comments

Existing signed division traps on overflow: https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#integer-divide-signed

This results in costlier division emulation in languages like Java that doesn't trap on division by -1.

(Also see https://github.com/WebAssembly/design/issues/986 for prior art)

gkdn avatar Nov 11 '20 03:11 gkdn

Looking into this a bit, it seems that idiv on x86 produces a division error on overflow that engines would have to recover from or guard against and sdiv on ARM results in the desired INT_MIN on overflow.

(How do engines handle recovering from or detecting division by zero and division overflow today?)

I wonder if it would make sense to provide non-trapping division variants that don't trap on division by zero, too. Would any languages use those? @gkdn, are you doing anything to protect against division by zero or are you just letting that trap?

tlively avatar Nov 11 '20 04:11 tlively

We are letting division by zero to trap.

Looking at C# language, it has also similar semantics (by default); traps on div-by-zero and doesn't trap on overflow.

gkdn avatar Nov 11 '20 04:11 gkdn

(How do engines handle recovering from or detecting division by zero and division overflow today?)

Not sure if you're asking about JS, wasm, or even Java here, but fwiw SpiderMonkey emits explicit checks for both cases (on x64). If we thought it was a performance issue we could probably switch to trap handling, though this is probably easiest when those cases error out, not when they generate a value for continued execution.

lars-t-hansen avatar Nov 11 '20 07:11 lars-t-hansen

On x86 division is already a >24 cycle instruction. It doesn't seem to me that a few bounds checks will noticeably impact performance.

taralx avatar Nov 12 '20 02:11 taralx