Modern two’s-complement integer representation makes the most-negative value asymmetric (e.g., -2^31 has no positive counterpart), so dividing that value by -1 cannot be represented and triggers signed overflow. C treats signed overflow as undefined behavior, but Futhark’s semantics define wrapping arithmetic, so simply emitting straightforward C for signed division can produce undefined behavior in rare inputs. To avoid this, generated C represents integers as unsigned types and performs arithmetic there, but division requires a special-case treatment: the compiler must detect the most-negative/−1 combination and handle it explicitly. That change eliminates undefined behavior but introduces extra checks and branches around divisions.
Benchmarks show the correctness fix is essentially free on CPU code (no measurable difference), but it can significantly slow GPU code: a CUDA test with many repeated divisions roughly doubled runtime because the added branches prevent the GPU from emitting long runs of consecutive div.s32 instructions and from unrolling efficiently; similar but smaller impact appears on AMD hardware. The author accepts the runtime cost as necessary, advises using unsigned division when negatives are impossible, and notes this is the last remembered instance of undefined behavior in generated C, though an implementation-defined bit-shift issue remains.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.