Originally Posted by
matsp
It is MUCH easier for a compiler to realize that
Code:
temp = a;
a = b;
b = temp;
is a swap than it is to detect the xor pattern is a swap - but sure, the optimizer could be written to recognize both/either one.
--
Mats
source code
Code:
#include<stdio.h>
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void swap2(int x,int y)
{
x=x^y;
y=x^y;
x=x^y;
}
int main()
{
int x=3,y=4;
swap(x,y);
swap2(x,y);
printf("x=%d,y=%d",x,y);
}
assembly instruction by gcc inline assembler
Code:
swap:
pushl %ebp
movl %esp, %ebp
subl $16, %esp
movl 8(%ebp), %eax
movl %eax, -4(%ebp)
movl 12(%ebp), %eax
movl %eax, 8(%ebp)
movl -4(%ebp), %eax
movl %eax, 12(%ebp)
leave
ret
.size swap, .-swap
.globl swap2
.type swap2, @function
swap2:
pushl %ebp
movl %esp, %ebp
movl 12(%ebp), %eax
xorl %eax, 8(%ebp)
movl 8(%ebp), %eax
xorl %eax, 12(%ebp)
movl 12(%ebp), %eax
xorl %eax, 8(%ebp)
popl %ebp
ret
.size swap2, .-swap2
.section .rodata
optimised (O3)
Code:
swap:
pushl %ebp
movl %esp, %ebp
popl %ebp
ret
.size swap, .-swap
.globl swap2
.type swap2, @function
swap2:
pushl %ebp
movl %esp, %ebp
popl %ebp
ret
.size swap2, .-swap2
.section .rodata.str1.1,"aMS",@progbits,1
xchg is not called after all(making compiler call xchg/swp isnt easy after all)...and when optimised, both are exactly the same.