Wednesday, December 23, 2009

Selection sort, 64-bit

Having haphazardly embarked on Agner Fog's informative C++ optimization guide [pdf], I decided it was time to write some x86-64 assembly to gain familiarity with the x86-64 instruction set.

Selection sort is an easy hello-world type application for assembly programming. On a Windows platform, getting Visual Studio and NASM to build a project together demanded a moment's tinkering, so I didn't want to be too ambitious.

The code listing follows. The best part is there is no stack frame to prepare or registers to spill. This doesn't do anything sophisticated like prefetch data, and of course isn't the best algorithm for sorting. It is pretty easy to spot the nested loops.

Posted for your amusement.


section .text code align=16

global selsort

; void selsort(int *A, int N)
;
; A: rcx
; N: rdx
;
selsort:
xor rax, rax

L1:
mov r8, rax
inc r8
mov r10, rax

L2:
cmp r8, rdx
jz L3

mov r11d, dword[rcx+r8*4]
mov r9d, dword[rcx+r10*4]

cmp r9d, r11d
cmova r10, r8

inc r8
jmp L2

L3:
mov r11d, dword[rcx+rax*4]
mov r9d, dword[rcx+r10*4]

cmp r9d, r11d
jge L4

mov dword[rcx+r10*4], r11d
mov dword[rcx+rax*4], r9d

L4:
inc rax
cmp rax, rdx
jnz L1

ret

No comments: