Array Loop Preview


Consider the following C code segment:

        /* Double every value in A */
        int i;
        for ( i = 0; i < numVals; i++ )
        {
            A[i] *= 2;      /* which means A[i] = A[i] * 2 */
        }


How would we start to translate this to MIPS?

Break it into smaller steps

OriginalBroken down into smaller steps
/* Double every value in A */
int i;
for ( i = 0; i < numVals; i++ )
{


    A[i] *= 2;



} 
       
/* Double every value in A */
int i = 0;
while ( i < numVals )
{
    /* A[i] = A[i] * 2 */
    int x = A[i];
    x *= 2;
    A[i] = x;

    i++;  /* Increment i for loop */
} 

Translate to MIPS

CMIPS Equivalent
/* Double every value in A */
int i = 0;
while ( i < numVals )
{



    /* A[i] = A[i] * 2 */
    int x = A[i];
    x *= 2;
    A[i] = x;

    i++;  /* Increment i for loop */

}
        # $s7 = A, $t0 = i, $t5 = x
        addi $t0, $zero, 0
LOOP:   ⋮
        ⋮
        # Calculate address of A[i]
        sll $t1, $t0, 2
        add $t1, $s7, $t1
        # Read value at A[i] into x; etc
        lw  $t5, 0($t1)
        sll $t5, $t5, 1
        sw  $t5, 0($t1)

        addi $t0, $t0, 1
        ⋮
ENDLOOP:
        ⋮
# $t0 = i = 0
⋮
⋮

# $t1 = 4 * i (shift left 2)
# t1 = A + 4i, i.e., &A[i]

# read A[i] into $t5 (x)
# x *= 2 (shift left 1)
# store $t5 out to A[i]

# increment i
  Array access is highlighted; loop components are not.


Alyce Brady, Kalamazoo College