Search code examples
assemblyriscvmachine-code

Explain what this assembly language program does in plain English


    .data
array:  .word   1 2 3 4 5
mfact:  .word   100
dfact:  .word   20

    .text
main:   lui s0, 0x10010     # U format  4 cycles
    lw  t0, 20(s0)      # I format  5 cycles
    lw  t1, 24(s0)      # I format  5 cycles
    or  s1, zero, zero  # R format  4 cycles
    ori s2, zero, 5     # I format  4 cycles

loop:   slli    s3, s1, 2       # I format  4 cycles
    add s4, s3, s0      # R format  4 cycles
    lw  t2, 0(s4)       # I format  5 cycles
    mul t3, t2, t0      # R format  10 cycles
    div t4, t3, t1      # R format  40 cycles
    sw  t4, 0(s4)       # S format  4 cycles
    addi    s1, s1, 1       # I format  4 cycles
    blt s1, s2, loop    # B format  3 cycles

exit:   ori a7, zero, 10    # I format  4 cycles
    ecall           # I format  3 cycles
    

The question does not have any more information. I think the program divides and multiplies the numbers 1-5 until it reaches 0 then it stops. Am I correct about that?


Solution

  • This program is supposed to take each element of an array of 5 word and multiply it with the first word after the array, then divide the result with the second element after the array. However there is some problems:
    1- you need to add com between the words of the array.
    2- you need to declare main as a global function, so that the linker can find it. Otherwise you will have an undefined reference error.
    3- the lui s0, 0x10010 could be problematic. Are you sure the linker will put array at this address? Did you modified the linker script to force it? IF you are not sure of what the linker will do . It will be better to declare array as an object and use it directly with and lui + addi.

    The code will be:

        .data
        .type   array, @object
        .size   array, 20
    array:  .word   1, 2, 3, 4, 5
    mfact:  .word   100
    dfact:  .word   20
    
        .text
        .global main
        .type   main, @function
    main:
        lui s0, %hi(array)      # U format  4 cycles
        addi s0, s0, %lo(array) # I format  4 cycles
        lw  t0, 20(s0)          # I format  5 cycles
        lw  t1, 24(s0)          # I format  5 cycles
        or  s1, zero, zero      # R format  4 cycles
        ori s2, zero, 5         # I format  4 cycles
    
    loop:
        slli    s3, s1, 2       # I format  4 cycles
        add s4, s3, s0          # R format  4 cycles
        lw  t2, 0(s4)           # I format  5 cycles
        mul t3, t2, t0          # R format  10 cycles
        div t4, t3, t1          # R format  40 cycles
        sw  t4, 0(s4)           # S format  4 cycles
        addi    s1, s1, 1       # I format  4 cycles
        blt s1, s2, loop        # B format  3 cycles
    
    exit:
        ori a7, zero, 10        # I format  4 cycles
        ecall                   # I format  3 cycles
        .size   main, .-main