Valhalla Legends Forums Archive | Assembly Language (any cpu) | Does this make any sense?

AuthorMessageTime
iago
This is MIPS, a toy assembly language.
beq = branch-if-equal
lw = load word
Most instructions are: op dest, src, src
Registers are anything beginnning with $ (usually there are specific ones, but this isn't real code).

The question is, optimize this code to use the delayed branch slot.. What that means is, because of pipelining, the instruction after the instruction immediately after the branch will be executed before it, but can be dangerous if the instruction changes the data used in the branch, so you have to be careful (most people will put a nop there for safety). Anyway, here's the code:
[code]Loop:
lw $2, 100($3)
addi $3, $3, 4
beq $3, $4, Loop[/code]

What I did was:
[code]Loop:
addi $3, $3, 4
beq $3, $4, Loop
lw $2, 96($3) <-- delay slot, executed before the loop
[/code]

Does this seem silly to anybody else? It seems like the lw doesn't even have to be PART of the loop, right?
November 6, 2003, 2:01 AM
Yoni
Wrong.

In the first snippet, $2 receives the value of $3 before 4 is added to it for the last time, meaning it gets the value ($3 - 4).
In the second snippet, $2 gets the value of $3 after 4 is added to it, meaning it gets the value ($3).

Dunno anything about MIPS so I can't give optimization tips. But, I observe that this (first) code is equivalent to (pseudo):

$2 = $4 - 4
$3 = $4

So, why is a loop required at all?

I might be misreading the lw instruction though...
November 6, 2003, 4:17 PM
iago
The first is actually closer to thie:
Loop:
lw $2, 100($3)
addi $3, $3, 4
beq $3, $4, Loop
=
do
*$2 = $3[100];
$3 += 4
while $3 != $4

Hopefully, I guess, $4 is a multiple of $3.
Your code will work, *except* it won't cause an infinite loop 3/4 of the time :P
November 6, 2003, 5:51 PM
Adron
It could be a "ProbeForRead"-like function?
November 7, 2003, 10:26 AM

Search