#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.