Assembly Language for Beginners

(nextflipdebug2) #1

1.14. CONDITIONAL JUMPS


int64_t my_max(int64_t a, int64_t b)
{
if (a>b)
return a;
else
return b;
};


int64_t my_min(int64_t a, int64_t b)
{
if (a<b)
return a;
else
return b;
};


There is some unneeded value shuffling, but the code is comprehensible:


Listing 1.135: Non-optimizing GCC 4.9.1 ARM64

my_max:
sub sp, sp, #16
str x0, [sp,8]
str x1, [sp]
ldr x1, [sp,8]
ldr x0, [sp]
cmp x1, x0
ble .L2
ldr x0, [sp,8]
b .L3
.L2:
ldr x0, [sp]
.L3:
add sp, sp, 16
ret


my_min:
sub sp, sp, #16
str x0, [sp,8]
str x1, [sp]
ldr x1, [sp,8]
ldr x0, [sp]
cmp x1, x0
bge .L5
ldr x0, [sp,8]
b .L6
.L5:
ldr x0, [sp]
.L6:
add sp, sp, 16
ret


Branchless


No need to load function arguments from the stack, as they are already in the registers:


Listing 1.136: Optimizing GCC 4.9.1 x64

my_max:
; RDI=A
; RSI=B
; compare A and B:
cmp rdi, rsi
; prepare B in RAX for return:
mov rax, rsi
; if A>=B, put A (RDI) in RAX for return.
; this instruction is idle if otherwise (if A<B)

Free download pdf