swapElements: pushl %ebp movl %esp, %ebp movl 8(%ebp), %edx ; address of array a in %edx movl 12(%ebp), %ecx ; i in %ecx movl 16(%ebp), %eax ; j in %eax pushl %ebx leal (%edx,%ecx,4), %ecx ; address of a[i] in %ecx leal (%edx,%eax,4), %eax ; address of a[j] in %eax movl (%ecx), %ebx ; value of a[i] in %ebx movl (%eax), %edx ; value of a[j] in %edx movl %edx, (%ecx) ; %edx stored in a[i] movl %ebx, (%eax) ; %ebx stored in a[j] popl %ebx popl %ebp ret ; return
-
The variable tmp is not allocated a memory location. Instead register %ebx and %edx are being used as 2 temporaries - ond for a[i] and a[j].
The compiler likes this better since registers as temporaries have faster access and at least one register is needed anyway in movl instructions.
-
That is, the assembly code actually uses a different algorithm. It uses two register temporaries instead of one memory temporary.
-
Since two register temporaries are used, there are 4 movl instructions to do the swap instead of 3. This is because the movl instruction can't have both operands be memory locations.
(But 4 is better than using 2 movl instructions for each of the 3 assignments.)
-
Register %ebx that is used as the temporary r4, is callee save register:
If the called function uses %ebx, it must save the current value before using the register and must restore the value before the function returns.
Caller save: %eax, %ecx, %edx
Callee save: %ebx, %esi, %edi