Use byte addresses, so adjacent 32-bit array elements are four bytes apart. The following MIPS instructions include harmless
sll $zero,$zero,0 instructions in every branch delay slot; the second load is followed by another independent instruction before its value is consumed, also accommodating an early MIPS architecture with a load-use delay. All mnemonics here denote individual machine instructions. beq $t3,$zero,done # n=0: do not access any array
sll $zero,$zero,0
loop:
lw $t4,0($t0) # current a element
lw $t5,0($t1) # current b element
addiu $t0,$t0,4 # advance a; also separates lw from its use
subu $t6,$t4,$t5 # current difference, modulo 2^32
sw $t6,0($t2) # store current c element
addiu $t1,$t1,4
addiu $t2,$t2,4
addiu $t3,$t3,-1 # one fewer element remains
bne $t3,$zero,loop
sll $zero,$zero,0
done:A loop invariant at the head of the loop, after completed iterations, is that the three addresses point to elements , the count is , and every output element before equals the corresponding difference. One iteration reads element , stores its difference and advances to , preserving the loop invariant. The remaining count is a nonnegative loop variant decreasing by one, so the loop ends with .
The code uses
subu to avoid signed-overflow traps: the suffix does not restrict the operands to unsigned values. Its precise result isFor representable signed differences this is exactly . If trapping signed arithmetic is required instead, use sub and assume all differences are representable. The arrays must occupy valid word-aligned storage with no address wrap; the usual separate output array avoids overwriting unread inputs. Articles by others on the same topic
There are currently no matching articles.