assemblymips

What does lw and bne in this situation mean?


I'm quite new to programming and I was wondering what lw (both times) and bne are exactly doing in this question? I'm sorry for any mistakes in the question because I had to translate it to english.

Here starts the question:

Part of the data memory contains the following values:

address-value

100-1

104-2

108-4

112-8

116-16

Given the code below, what will be the value of register r1 after executing this code?

addi    r2,r0,104
lw  r1,-4(r2)
addi    r3,r0,116
label:  addi    r2,r2,4
lw  r4,-4(r2)
add r4,r4,r4
add r1,r4,r1
bne r2,r3,label

Solution

  • As Michael said, reading what instructions do and placing comments after each line will help you understanding the code.

    addi    r2,r0,104       ;r2 = 0d104
    lw      r1,-4(r2)       ;r1 = (0d100)
    addi    r3,r0,116       ;r3 = 0d116
    label:addi    r2,r2,4   ;r2 += 4
    lw      r4,-4(r2)       ;r4 = (r2-4)
    add     r4,r4,r4        ;r4 *= 2
    add     r1,r4,r1        ;r1 += r4
    bne     r2,r3,label     ;if(r2 ≠ r3), branch to label
    nop
    

    LW means Load Word. It loads a word into a register from the specified address.

    BNE means Branch on Not Equal. It executes the instruction that follows it without delays (which is why I added a nop after your code), and branch to the specified address if the two registers submitted as parameters are not equal.

    So what happens is that r1 is initialized with the value at (0d100), that is 1. Then r3 is set to 0d116.

    r2 is incremented by 4, r4 is equal to the value at (0d104), is multiplied by 2, then is added to r1. It then loops until r2 = 0d116, which means the value at 0d116 will never be read.

    r1 = 1 + 2×2 + 4×2 + 8×2 = 29