我无法弄清楚如何在此函数中正确使用 printf 。因此该函数称为 multInts,应该将第一个数组的第一个元素与第二个数组的第一个元素相乘,然后继续遍历整个数组。但是,实验说明指定我不能在主函数中调用 printf 。因此,我需要打印出“Products:\n”一词,然后在之后的每个新行中打印出产品。但是,我不知道如何在循环中使用 printf 。讲师说我们应该“在计算乘积后在循环中调用 printf”,并且“在调用 printf 之前保存和恢复调用者保存寄存器”,但我不确定这意味着什么。
到目前为止,我的代码如下所示:
.file "lab4.s"
.section .rodata
.LC0:
.string "Products: \n"
.LC1:
.string "%i \n"
.data
sizeIntArrays:
.long 5
sizeShortArrays:
.word 4
intArray1:
.long 10
.long 25
.long 33
.long 48
.long 52
intArray2:
.long 20
.long -37
.long 42
.long -61
.long -10
##### MAIN FUNCTION
.text
.globl main
.type main,@function
main:
pushq %rbp
movq %rsp, %rbp
#pass parameters and call other functions
movl sizeIntArrays, %edi #move size to registers for 1st parameter
leaq intArray1, %rsi #load effective address of intArray1 to register rsi
leaq intArray2, %rdx #load effective address of intArray2 to register rdx
call multInts #call multInts function
movq $0, %rax #return 0 to caller
movq %rbp, %rsp
popq %rbp
ret
.size main,.-main
##### MULTINTS
.globl multInts
.type multInts,@function
multInts:
pushq %rbp
movq %rsp, %rbp
#add code here for what the functions should do
movq $0, %r8 #initialize index for array access in caller save reg
movq $0, %rcx #initialize 8 byte caller save result reg
loop0:
cmpl %r8d, %edi #compare index to size
je exit0 #exit if equal
movslq (%rsi,%r8,4),%rax # Load a long into RAX
movslq (%rdx,%r8,4),%r11 # Load a long into R11
imulq %r11, %rax # RAX *= R11
addq %rax, %rcx # RCX += RAX
incq %r8 #increment index
jmp loop0
exit0:
movq $.LC0, %rdi
movq %rcx, %rsi
movq $0, %rax
call printf
movq %rbp, %rsp
popq %rbp
ret
.size multInts,.-multInts
我尝试做的只是将 printf 指令移到循环之前,但是在尝试运行循环时它给了我一个分段错误,因为 %rdi 和 %rsi 包含需要在循环中使用的数组的地址环形。我该如何解决这个问题以及我应该使用哪些寄存器?另外,如何在循环内调用 printf ?
输出应如下所示:
Products:
200
-925
1386
-2928
-520