In an attempt to implement arrays in my programming language that compiles to assembly, I am struggling with expressions like array[0]
. I have tested other indices like 1, 2, etc. and they work, but array[0]
always returns 0, no matter what value is actually stored there in the array.
Assuming an array has these elements: [85, 15, 76, 58, 17]
, then element 0
should be 85
.Here is the code my compiler generates, can you see what is wrong with this?
.text.globl main.type main, @functionmain: .cfi_startproc pushq %rbp movq %rsp, %rbp call usr_main mov %rax, %rdi movq $60, %rax syscall movq %rbp, %rsp pop %rbp ret .cfi_endproc.size main, .-main.type usr_main, @functionusr_main: .cfi_startproc push %rbp movq %rsp, %rbp # define array movq $85, -8(%rbp) movq $15, -16(%rbp) movq $76, -24(%rbp) movq $58, -32(%rbp) movq $17, -40(%rbp) push $0 # an "offset", based on the size of other defined arrays (there are none) # Evaluate computed array expr (index expr) # IndexExpr Step 1: Evaluate offset of array # find "offset" movq (%rsp), %rdx # IndexExpr Step 2: Evaluate computed expr (the index) movq $0, %rbx # index of 0 # IndexExpr Step 3: Do some nerd stuff for %rbp offset add %rdx, %rbx neg %rbx # IndexExpr Step 4: Evaluate offset from %rbp and return the expr movq -8(%rbp, %rbx, 8), %rax movq %rbp, %rsp pop %rbp ret .cfi_endproc .size usr_main, .-usr_main
I have tried changing the offset in the effective address -8
to other values, however each time array[0]
always returns 0
.I have also tried incrementing %rbx
before the effective address and setting the offset to 0
, with no luck.