This is based on:
D.A. Patterson and J.L. Hennessy (1994) Computer Organisation and Design: The Hardware Software Interface, Morgan Kauffmann Publishers Inc., San Francisco.
In C++ we would write:
if(x==y) {
//executed if x==y
}
In MIPS this type of conditional expression is broken down into simpler elements.
beq R1,R2,Label#branch if equal
means that if the value in regester R1 == the value in register R2, then control jumps to the address specified by Label.
Similarly,
bne R1,R2,Label #branch if not equal
means
if(R1 != R2) goto Label
Consider the following example:
if(x==y) x++; else y++;
Assume that x is in $20 and y is in $21.
bne $20,$21,ELSE #if (x!=y) goto ELSE label addi $21,$21,1 #x = x+1 - addi (immediate) j CONTINUE #jump to CONTINUE label ELSE: addi $21,$21,1 #y = y+1 CONTINUE: ??? #...whatever is required here...
Note that the "labels" here are arbitrary symbolic names representing addresses in memory.
Here's another example. Suppose that X[100] is an array of ints, and it is required to add them all. In C++ we might write:
sum = 0; for(i=0;i<100;++i) sum += x[i];
In MIPS, this would be expressed as:
Assume that x is at Xstart, sum is at register $20. i is at $10, and n = 100 is in $21
move $10,$0 #i = 0 move $20,$0 #sum = 0 addi $21,$0,100 #n= 400, not 100, because of byte addressing LOOP: beq $10,$21,CONTINUE #if(i==n) goto CONTINUE lw $22,Xstart($10) #$22 = x[i] add $20,$20,$22 #sum += x[i] addi $10,$10,1 #i += 4, because of byte addressing j LOOP #goto LOOP CONTINUE:
Note the use of addi (add immediate) which is called immediate addressing.
The actual number 1 is added to the register,
rather than a reference through another register.
Note the byte addressing - so that to get at the words we have to increment
through memory in steps of 4 (not 1). Hence the test is whether 400 has been
reached, not 100.
Note also the use of move, which is not actually a MIPS instruction, but a
symbolic name for programmer convenience. It copies the contents of the
second register to the first. In the example, recall that $0 always
contains zero. For example,
move $10,$0
addi $10,$0,0