Loops in MIPS

 


What about loops?

Use beq, bne, and j, just as for conditional statements.

Example:

Assume that $s0 = i, $s1 = n, $s2 = A, $s3 = sum, and that A is an array of int.
	C					FORTRAN
	-------					-------

  	sum = 0;				SUM = 0
	i = 0;					I = 0
	while ( i < n )			LOOP:	IF ( I .GE. N ) GOTO END
	{              				SUM = SUM + A[I]
	   sum += A[i]; 			I = I + 1
	   i++; 				GOTO LOOP
        }         			END:	...







                move $s3, $zero		# sum = 0
                move $s0, $zero		# i = 0
        LOOP:	slt $t0, $s0, $s1	# t0 is 1 if i < n; 0 if i >= n
                beq $t0, $zero, END	# goto END if i >= n
                sll $t0, $s0, 2  	# t0 = i * 4
                add $t0, $t0, $s2	# t0 is address of A[i]
                lw $t1, 0 ($t0)		# t1 = A[i]
                add $s3, $s3, $t1	# sum += A[i]
                addi $s0, $s0, 1	# i += 1 (or i++)
		j LOOP
	END:	...


Squeezing out every ounce of efficiency:



                move $s3, $zero		# sum = 0
                move $s0, $zero		# i = 0
                j TEST                  # go to loop test
        LOOP:	sll $t0, $s0, 2  	# t0 = i * 4
                add $t0, $t0, $s2	# t0 is address of A[i]
                lw $t1, 0 ($t0)		# t1 = A[i]
                add $s3, $s3, $t1	# sum += A[i]
                addi $s0, $s0, 1	# i += 1 (or i++)
        TEST:	slt $t0, $s0, $s1	# t0 is 1 if i < n; 0 if i >= n
                bne $t0, $zero, END	# goto LOOP if i < n
	END:	...


Alyce Brady, Kalamazoo College