I\'m trying to learn x86-64 inline assembly and decided to implement this very simple swap method that simply orders a
and b
in ascending order:
You cannot just put a bunch of asm
statements inline like that. The optimizer is free to re-order, duplicate, and drop them based on what constraints it knows. (In your case, it knows none.)
So firstly, you should consolidate the asm together, with proper read/write/clobber constraints. Secondly, there is a special asm goto
form that gives assembly to C-level labels.
void swap(int *a, int *b) {
int tmp1, tmp2;
asm(
"mov (%2), %0\n"
"mov (%3), %1\n"
: "=r" (tmp1), "=r" (tmp2)
: "r" (a), "r" (b)
: "memory" // pointer in register doesn't imply that the pointed-to memory has to be "in sync"
// or use "m" memory source operands to let the compiler pick the addressing mode
);
asm goto(
"cmp %1, %0\n"
"jle %l4\n"
"mov %1, (%2)\n"
"mov %0, (%3)\n"
:
: "r" (tmp1), "r" (tmp2), "r" (a), "r" (b)
: "cc", "memory"
: L1
);
L1:
return;
}