A.
Change into pointer version
/*
* bubble-sort-pointer.c
*/
void bubble_p(long* data, long count) {
long *i, *last;
for (last = data+count-1; last > data; last--) {
for (i = data; i < last; i++) {
if (*(i+1) < *i) {
/* swap adjacent elements */
long t = *(i+1);
*(i+1) = *i;
*i = t;
}
}
}
}
B.
Compile bubble-sort-pointer.c
gcc -S -Og bubble-sort-pointer.c
get gas file
.file "bubble-sort-pointer.c"
.text
.globl bubble_p
.type bubble_p, @function
bubble_p:
.LFB0:
.cfi_startproc
leaq -8(%rdi,%rsi,8), %rsi
jmp .L2
.L4:
movq 8(%rax), %rdx
movq (%rax), %rcx
cmpq %rcx, %rdx
jge .L3
movq %rcx, 8(%rax)
movq %rdx, (%rax)
.L3:
addq $8, %rax
jmp .L5
.L6:
movq %rdi, %rax
.L5:
cmpq %rsi, %rax
jb .L4
subq $8, %rsi
.L2:
cmpq %rdi, %rsi
ja .L6
rep ret
.cfi_endproc
.LFE0:
.size bubble_p, .-bubble_p
.ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609"
.section .note.GNU-stack,"",@progbits
Change it into ys version
/* bubble-sort-pointer.ys */
.pos 0
irmovq stack, %rsp
call main
halt
# Array of 4 elements
.align 8
data:
.quad 0x0000000000000004
.quad 0x0000000000000003
.quad 0x0000000000000002
data_end:
.quad 0x0000000000000001
main:
irmovq data,%rdi
irmovq data_end,%rsi
call ysBubbleP
ret
# long ys_bubble_p(long *data, long *end)
# data in %rdi, end in %rsi
ysBubbleP:
jmp L2
L4:
mrmovq 8(%rax), %r9
mrmovq (%rax), %r10
rrmovq %r9, %r8
subq %r10, %r8
jge L3
rmmovq %r10, 8(%rax)
rmmovq %r9, (%rax)
L3:
irmovq $8, %r8
addq %r8, %rax
jmp L5
L6:
rrmovq %rdi, %rax
L5:
rrmovq %rsi, %r8
subq %rax, %r8
jg L4
irmovq $8, %r8
subq %r8, %rsi
L2:
rrmovq %rsi, %r8
subq %rdi, %r8
jg L6
ret
.pos 0x200
stack:
main difference is second param of function is long* end
instead of
long count
for convinient, long* end
marks the position of last element.
using yas
assemble it and yis
run it, see output
../sim/misc/yas bubble-sort-pointer.ys
../sim/misc/yis bubble-sort-pointer.yo
Stopped in 117 steps at PC = 0x13. Status 'HLT', CC Z=1 S=0 O=0
Changes to registers:
%rax: 0x0000000000000000 0x0000000000000020
%rsp: 0x0000000000000000 0x0000000000000200
%rsi: 0x0000000000000000 0x0000000000000018
%rdi: 0x0000000000000000 0x0000000000000018
%r9: 0x0000000000000000 0x0000000000000001
%r10: 0x0000000000000000 0x0000000000000002
Changes to memory:
0x0018: 0x0000000000000004 0x0000000000000001
0x0020: 0x0000000000000003 0x0000000000000002
0x0028: 0x0000000000000002 0x0000000000000003
0x0030: 0x0000000000000001 0x0000000000000004
0x01f0: 0x0000000000000000 0x0000000000000055
0x01f8: 0x0000000000000000 0x0000000000000013
initial array order is 4,3,2,1, now 1,2,3,4