Search code examples
c++cassemblyinline-assemblyx87

Converting an inline-asm x87 fsqrt function from C++ to C for x86-64


I was looking at different methods to compute the square root, and one in particular (sqrt14 from here) caught my attention, unfortunately it was written in C++ (it only uses assembly), it's difficult for me to translate it back to C - if that's possible.

double inline __declspec (naked) __fastcall sqrt14(double n)
{
    _asm fld qword ptr [esp+4]
    _asm fsqrt
    _asm ret 8
} 

As can be seen here, inserting assembly in C++ is different from C.

I wanted to ask you if it was possible to have a C equivalent, and if so, can I ask you to write it? If it's useful, my architecture is 64bits.

I suspect that the function declaration will be like this one:

double inline __attribute__((fastcall, naked)) sqrt14(double n);

... but I don't know enough about assembly to do the rest...


Solution

  • The example you cite is very specific to one compiler...

    • __declspec (naked) is an implementation specific feature (non-Standard)
    • __fastcall is an implementation specific feature (non-Standard)

    Even in your revised example:

    • __attribute__((fastcall, naked)) is an implementation specific feature (non-Standard)

    Even the inclusion of assembler is an implementation specific feature (non-Standard) - ie each compiler may do it a slightly different way.

    So the long and short of it, the example code is fine for the compiler and target processor, but is completely non-portable to another toolchain or processor.