Issue 157797
Summary Float to int16_t conversion error.
Labels new issue
Assignees
Reporter tomaso-cerebras
    **Short summary:** It seems that converting 32768.0f to int16_t yields 32768, and not he expected -32768 with -O1 and -O2.

**Compiler version:**
mac-laptop>  g++ --version
Apple clang version 17.0.0 (clang-1700.0.13.5)
Target: arm64-apple-darwin24.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

**Reproducer code and commands**
Assuming the C++ code below is stored in the file intdivbug.cc, incorrect (with -O1 and -O2) and correct behavior (-O0) is shown below. If the flag enable_big is changed and set to false, int16_t result to memory before use (through volatile variable), and results in correct results at all three optimization levels (-O0, -O1, and -O2).

_Correct behavior:_
mac-laptop> g++ -Wall -O0 -o intdivbug intdivbug.cc
mac-laptop> ./intdivbug                            
Finished.

_Incorrect behavior (with -O1):_
mac-laptop> g++ -Wall -O0 -o intdivbug intdivbug.cc
mac-laptop> ./intdivbug                            
a = -32768, b = -1, ce = -32768, c = 32768
Finished.

_Incorrect behavior (with -O1):_
mac-laptop> g++ -Wall -O2 -o intdivbug intdivbug.cc
max-laptop> ./intdivbug 
a = -32768, b = -1, ce = -32768, c = 32768
Finished.


**Reproducer code**
// Test driver for integer division.
#include <cstdio>
#include <cstdint>

typedef float sp;
//typedef short xp;
typedef int16_t xp;

xp intdiv(xp a,xp b) {
 sp
    af = a,
    bf = b,
    cf = (af/bf)*(1+1e-6);
  xp c = cf;
 return c;
}

const bool enable_bug = true;

volatile xp cv[1];
int main(void) {
  xp lim = 32767;
  for(int ai = -lim-1; ai <= -lim; ai++)
 for(int bi = -lim-1; bi <= lim; bi++)
      if(bi != 0) {
	xp a = ai,b = bi;
	xp ce = a/b,c;
	if(enable_bug) {
	  c = intdiv(a,b);	  
	 if(ce != c)
	    printf("a = %d, b = %d, ce = %d, c = %d\n",a,b,ce,(int) c);
	} else {
	  cv[0] = intdiv(a,b);
	  if(ce != cv[0])
	 printf("a = %d, b = %d, ce = %d, c = %d\n",a,b,ce,(int) cv[0]);
	}
 }
  printf("Finished.\n");
  return 0;
}

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to