Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't simple inline assembly function work correctly in GCC?

I have a simple inline assembly function, which works fine in MSVC, but for some reason refuses to work under Apple GCC 4.2.1 (i386 arch, forced 32-bit mode). Fortunately, much more complex assembly functions work fine, however I can't fathom why won't this one work... Unfortunately, I can't debug it - by the look of things there is no registers window in XCode 4.0.2 (it was in 3.2 versions).

I'm positive that the problem is not related with Intel style assembly.

int Convert(double value)
{
     _asm
     {
         fld value
         push eax
         fistp dword ptr [esp]
         pop eax
     }

// The returned value is insane
}
like image 767
Ryan Avatar asked Dec 22 '22 10:12

Ryan


1 Answers

Fortunately, much more complex assembly functions work fine[...]

Are these also inline assembly functions? Because GCC uses a completely different syntax for inline assembler. You can make the syntax look more familiar though, see wikipedia.

1     int Convert(double value) 
2     {   
3         int result; 
4         __asm__ __volatile__ ( 
5             "fist %0\n\t" 
6             : "=m" (result) 
7             : "t" (value) 
8             );          
9         return result; 
10     }   

Is how I would do it. =m specifies that we want a memory operand to store the result in (we don't want a register as fist doesn't work with those). t specifies that the value is passed on the stack top, that also ensures proper cleanup for us.

EDIT:

Another thing to try, assuming gcc with xcode allows the same kind of inline assembler as msvc, is:

 int Convert(double value)
 {
      int result;
      _asm
      {
          fld value
          push eax
          fistp dword ptr [esp]
          pop eax
          mov [result], eax
      }
      return result;
 } 

That should also shut up the warnings about missing return values you're probably getting. It might simply be that it is more strict about allowing you to return values from assembler blocks by writing eax than msvc.

like image 82
user786653 Avatar answered Dec 24 '22 02:12

user786653