GCC doesn't produce the correct assembler code when I use optimizations.
[code]
#include
#define mulscale(a,d,c) \
({ int __a=(a), __d=(d), __c=(c); \
__asm__ __volatile__ ("imull %%edx; shrdl %%cl, %%edx, %%eax" \
: "=a" (__a), "=d" (__d) \
: "a" (__a), "d" (__d), "c" (__c) : "cc"); \
__a; })
#define divscale(a,b,c) \
({ int __a=(a), __b=(b), __c=(c); \
__asm__ __volatile__ ("movl %%eax, %%edx; shll %%cl, %%eax; negb %%cl;
sarl %%cl, %%edx; idivl %%ebx" \
: "=a" (__a) : "a" (__a), "c" (__c), "b" (__b) : "edx", "cc"); \
__a; })
void badcode(int scale,int i,int vx,int vy,int vz)
{
int x1,y1;
i = divscale(i,vz,scale);
printf(" ");
x1 = mulscale(vx,i,scale);
y1 = mulscale(vy,i,scale);
printf("%d %d\n",x1,y1);
}
int main()
{
badcode(29,1856,-2048,-59,768);
return 0;
}
[/code]
Scenario 1:
Compile options "-O0"
Program output "-4950 -143"
CORRECT
Scenario 2:
Compile options "-O1"
Uncomment the printf(" ")
Program output "-4950 -143"
CORRECT but it's an ugly workaround
Scenario 3:
Compile options "-O1"
Comment out the printf(" ")
Program output "-1431655680 -978670931"
INCORRECT
The
screenshot(http://www.mediafire.com/?sharekey=bf284efa985bb0620dec85adfe0a530ae04e75f6e8ebb871)
shows comparison between Scenario 2 and Scenario 3.
As you can see, GCC stores the "scale" variable in ECX which is modified later
and GCC fails to restore it.
In the meantime I fixed my code by saving ECX in the stack.
I understand it might be difficult to detect all the cases when registers are
modified(especially when it happens implicitly) but
if GCC actually tries to do so and fails, this ticket can be considered as a
bugreport rather a feature request.
By the way, I'm quite impressed that GCC is smart enough to replace printf(" ")
with putch(' ').
--
Summary: GCC doesn't take into account ECX being modified inside
inline assembler
Product: gcc
Version: 4.4.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: inline-asm
AssignedTo: unassigned at gcc dot gnu dot org
ReportedBy: hunterggl at gmail dot com
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40621