BlueAngel45
BlueAngel45

Reputation: 31

Converting C code snippet to MIPS Assembly

as part of a homework assignment we're required to convert the following code snippet from C to MIPS Assembly:

for (i=0; i<A; i++) { 
    for (j=0; j<B; j++) {  
        C[4 * j] = i + j;  
        }  
} 

I believe I have the logic down and most of the code is correct. I'm just stuck at the line: D[4 * j] = i + j;. I know how to get the sum of i and j, but I'm not sure how to actually put it into a multiple of its j address. Could someone please tell me what I'm missing in loop2? Thanks

.data
A: .word 2
B: .word 5
D: .word 0 : 100
size: .word 100

.text
    .globl  main
main:

    lw, $s0, A      #$s0 = A
    addi $s0, $s0, -1   #Allows for loop to properly run
    lw $s1, B       #$s1 = B
    addi $s1, $s1, -1   #Allows for loop to properly run
        la $s5, C           # load address of array
        li $t0, 0       #i = 0
        li $t1, 0       #j = 0
        
loop1:
    
    blt $s0, $t0, Exit  #for(i = 0; i < A; i++)
    addi $t0, $t0, 1    #i++
    li $t1, 0       #Sets j to 0 before calling loop2
    j loop2         #Calls loop2

loop2:

    blt $s0, $t0, loop1 #for(j = 0; j < B; j++)
    addi $t2, $t0, -1   #Allows to properly perform loop
    {Where I'm confused what to do}

    
    
    {Last two steps of loop2}
    addi $t1, $t1, 1    #j++
    j loop2
    
Exit:
      # The program is finished. Exit.
      li   $v0, 10          # system call for exit
      syscall               # Exit!

Upvotes: 0

Views: 166

Answers (1)

Erik Eidt
Erik Eidt

Reputation: 26786

Your assembly code barely resembles the C equivalent you're showing.  For example, there is no -1 in the C code, yet used multiple times in the assembly code!

Thus, you have gone down the classic error-prone approach of hyper-optimizing your code during translation from C to assembly.  This is a very error prone process, and also unnecessary!!

The best way to do this pointer and loop optimization is to do it all in C first!  We can express many, many optimizations such as these and others in C directly!  Then test it in C to make sure it works, only then take to assembly knowing that at least the algorithm works!

Upvotes: 2

Related Questions