Search code examples
assemblycompiler-errorsnasmx86-64code-translation

Why does this compiler output by GCC error when translated into NASM?


I was toying around with GCC assembly output a little, trying it with a fast integer average. Here's the C code I used initially:

unsigned int average (unsigned int x, unsigned int y) {
    return (x&y)+((x^y)>>1);
}

Here's the assembly it emitted (using Intel syntax):

average:
  mov edx, edi
  and edi, esi
  xor edx, esi
  shr edx
  lea eax, [rdx+rdi]
  ret

When I translated it for NASM:

average:
    mov edx, edi
    and edi, esi
    xor edx, esi
    shr edx, 1
    lea eax, [rdx+rdi]
    ret

It complains with this error, on the line with lea:

<source>:6: error: impossible combination of address sizes
<source>:6: error: invalid effective address

I'm not super familiar with assembly, but this seems super odd. Could someone explain to me what the heck is going on here?


Solution

  • The error message is misleading. The cause of this error is that nasm tries to assemble your code as 16 or 32 bit code, both of which do not support 64 bit registers. To fix this problem, invoke nasm with options that cause it to assemble 64 bit code, e.g. on Linux:

    nasm -f elf64 source.asm
    

    or on Windows:

    nasm -f win64 source.asm