wabt icon indicating copy to clipboard operation
wabt copied to clipboard

[wasm2c] MSVC miscompiles for certain fp constants

Open InflexCZE opened this issue 2 years ago • 6 comments

Given WASM

0000024: 44                                        ; f64.const
0000025: 0000 0000 0000 e0c1                       ; f64 literal

(module
  (func (export "addTwo") (result f64)
    f64.const -0x1p+31
  )
)

and wasm2c conversion output

//wasm2c test.wasm
f64 w2c__addTwo_0(w2c_* instance) {
  FUNC_PROLOGUE;
  f64 var_d0;
  var_d0 = -2147483648;
  FUNC_EPILOGUE;
  return var_d0;
}

there is slight discrepancy in output of different compilers. Clang & GCC correctly output -2147483648.000000 MSVC throws warning (error with /sdl) and outputs 2147483648.000000 (notice absence of negative mark) https://godbolt.org/z/MrjMzdeKE image

While the conversion output is likely correct according to C spec (at least Clang and GCC are not screaming with -Wall), it's very inconvenient for Windows users to do these fixups manually.

Proposal is to use alternative notation

  var_d0 = -2147483648.0; //Notice additional decimal

which makes all tested compilers happy and correct. https://godbolt.org/z/5sE4adbYd image

InflexCZE avatar Feb 10 '24 21:02 InflexCZE

Thanks for reporting this! Can you please test https://github.com/WebAssembly/wabt/pull/2389 and see if it fixes the issue for you?

There should probably be a test for this situation, ideally eventually upstream in the spec tests.

I'm also nervous about MSVC's handling of wasm2c output for conversion instructions given https://github.com/WebAssembly/wabt/blob/main/src/c-writer.cc#L4851 and https://github.com/WebAssembly/wabt/blob/main/src/config.cc#L76 -- we should make sure this is also tested.

keithw avatar Feb 10 '24 22:02 keithw

There should probably be a test for this situation, ideally eventually upstream in the spec tests.

@keithw, PTAL at this spec PR.

rossberg avatar Feb 11 '24 07:02 rossberg

#2389 looks good, no unexpected overhead either https://godbolt.org/z/xf4Wfa4Ev

  1. Might be good to export with //decimal value comment at the end of the line, for users' convenience
  2. Will prolly need byte re-order for little-endian

InflexCZE avatar Feb 11 '24 15:02 InflexCZE

it works fine on both endian

SoniEx2 avatar Feb 11 '24 16:02 SoniEx2

#2389 looks good, no unexpected overhead either https://godbolt.org/z/xf4Wfa4Ev

1. Might be good to export with `//decimal value` comment at the end of the line, for users' convenience

Thanks, good idea. Done in #2389.

keithw avatar Feb 11 '24 20:02 keithw