ocaml / ocaml

The core OCaml system: compilers, runtime system, base libraries
https://ocaml.org
Other
5.19k stars 1.06k forks source link

Fix undefined behavior of left-shifting a negative number #13094

Closed MisterDA closed 1 month ago

MisterDA commented 1 month ago

Compilers likely behave and cast (15-127) to unsigned, but strictly speaking this is UB and needs to be explicit, otherwise the compiler may warn or wrongly optimize.

test.c:71:26: warning: shifting a negative signed value is undefined [-Wshift-negative-value]
      f.i += ((15 - 127) << 23) + 0xfff;
              ~~~~~~~~~~ ^
1 warning generated.

The warning is raised by clang. I've checked that the assembly code generated stays the same.

nojb commented 1 month ago

@MisterDA Feel free to add a Changes entry if you wish.

MisterDA commented 1 month ago

@MisterDA Feel free to add a Changes entry if you wish.

Done, thanks.

The original code is at https://gist.github.com/rygorous/2156668. I've reported this issue.

Octachron commented 1 month ago

Cherry-picked to 5.2 as a safe bug fix in 9e54469 .