0
#include <stdio.h>

int main(void)
{
    int var1 = 12;
    int var2 = 5;

    asm volatile("mov %3, %0 \n"
                 "add %2, %1" : "=r"(var1), "=r"(var2) : "r"(var1), "r"(var2));

    /*
    asm volatile("mov %1, %0 \n"
                 "add %0, %1" : "+r"(var1), "+r"(var2));*/
    /*
    asm volatile("mov %1, %0" : "=r"(var1) : "r"(var2));
    asm volatile("add %1, %0" : "=r"(var2) : "r"(var1));*/


    printf("var1 = %d, var2 = %d\n", var1, var2);

    return 0;
}

The first and second pieces of commented asm both result in

var1 = 5, var2 = 10

which is as I expect -- var1 assigned using var2, then both added together to obtain new var2.

I use

gcc test.c

within centos7 on x86_64 machine to compile, so I think I'm using GAS (which means both add and mov have their src/dst reg as 1st/2nd operand).

So, My problem here is, why would the first asm generate the following result:

var1 = 5, var2 = 24

I must admit the first asm looks quite nasty (at least to me, which is why I tried the other two versions to verify my thought), but is it "wrong" ? Or, does it totally make no sense to write so?

If, for example, it's actually acceptable to write such asm code, then I could not figure out why its output looks like that. Is it machine/abi dependent or what? Why doesn't it also give var1 = 5, var2 = 10 ?

I'm really a newbie for x86 assembly, so plz forgive me for this question if it looks dumb, and THANK YOU in advance for taking time to read my question.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
J.C.
  • 51
  • 1
  • 3
  • 9
  • 2
    The code is unsafe: `"=r"(var1)` is missing an early clobber but you write it before reading both inputs. So either output was possible, depending on the compiler's choices. This isn't an assembly problem, it's a GNU C *inline* asm problem in describing your asm snippet to the compiler. Don't use inline asm until you already understand asm, and how GCC thinks about constraints and optimization. – Peter Cordes Apr 21 '20 at 08:26
  • 1
    examine the disassembly of this function to see what you have created and why it isnt working. start with real assembly language first then figure out there is almost no reason to use inline. But if you do the only way to be successful is to constantly disassemble and examine the output. – old_timer Apr 21 '20 at 11:01

0 Answers0