Home > Software engineering >  How to write inline assembly to bit rotate
How to write inline assembly to bit rotate

Time:07-02

I was reading gcc's guide on extended ASM and I'm running into a problem where the compiler isn't interpreting the assembly the way I thought it would. I thought I'd try it with a bit rotate instruction since those aren't readily available in C.

Here's my C function:

int rotate_right(int num,int count) {
    asm (
        "rcr %[value],%[count]"
        : [value] "=r" (num)
        : [count] "r" (count)
        );

    return num;
}

And the compiled output using x86-64 gcc (trunk) -O0:

        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     DWORD PTR [rbp-8], esi
        mov     eax, DWORD PTR [rbp-8]
        rcr eax,eax
        mov     DWORD PTR [rbp-4], eax
        mov     eax, DWORD PTR [rbp-4]
        pop     rbp
        ret

The problem I'm having is that GCC is taking my inline assembly to mean "rotate EAX by EAX rather than by the count parameter I intended. This is what I expected to get:

        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     DWORD PTR [rbp-8], esi
        mov     eax, DWORD PTR [rbp-8]
        mov     ecx, DWORD PTR [rbp-4]
        rcr     eax,ecx
        pop     rbp
        ret

CodePudding user response:

First, let me solve your problem as stated in the title.

static inline int ror(int num, int count) {
  __asm__ ("ror\t%0,            
  • Related