lecture4

advertisement
MIPS Instruction Set
Conditional Expressions and Branching
Outline
• Motivation for conditional expressions
and loops
• How to add a sequence of numbers
• Conditional expressions (branching)
• Jumping
• Switching
Last time ...adding 3
numbers...
• What a mess this is...
– lw $10,A($0)
# $10 = a0
($0 always contains 0)
– li $4, 4
# $4 = 4
– lw $3,A($4)
# $3 = a1
– add $10,$10,$3
# $10 = a0 + a1
– li $4, 8
# $4 = 8
– lw $3,A($4)
# $3 = a2
– add $10,$10,$3
# $10 = a0 + a1+ a2
– li $4, 12
# $4 = 12
– sw $10,A($4)
# a3 gets $10
• Suppose 100 numbers to be added?
• Doesn’t generalise!
Adding a sequence of n
numbers
• x[0], x[1], ..., x[n-1] sequence of n
numbers.(n=100, say).
• Consider (abstract representation)
sum = 0
n = 100
# initialise sum
# initialise boundary condition
i=0
# initialise counter
LOOP:
# label
sum = sum + x[i] #overwrite sum
i = i+1
#increment counter
if (i != n) then go to LOOP
Adding the Sequence in MIPS
LOOP:
move $5,$0
# puts 0 into $5 (sum)
addi $4,$0,100
# puts 100 into $4 (n)
move $11,$0
li
$12,4
mult $14,$11,$12
lw $6,Xstart($14)
add $5,$5,$6
addi $11,$11,1
bne $11,$4, LOOP
sw $5,Sum($0)
# puts 0 into $11 (i)
# puts 4 into $12
# $14 = i*4 (why?!)
# retrieves x[i]
# sum = sum + x[i]
# i = i+1
# if i < n go to LOOP
#result put in memory
Conditional Expressions
• bne $a,$b,LABEL
– branch if not equal
» if $a != $b then jump to LABEL
• beq $a,$b,LABEL
– branch if equal
» if $a == $b jumpt to LABEL
• slt $a,$b,$c
– set if less than
» if ($b < $c) then $a = 1 else $a = 0
Example (introduces jump)
• Consider the following abstract code
if (a < b) then c = 100
else c = 500
• In MIPS (suppose a,b,c are $5,$6,$7)
slt $10,$5,$6
beq $10,$0,ELSE
addi $7,$0,100
j CONTINUE
ELSE :
addi $7,$0,500
CONTINUE: whatever here...
# $10 = 1 if $5<$6
# if $10==0 goto else
# $7 =100
# jump to continue
# $7 = 500
Choosing from several alternatives
• Abstract code
if k=0 then a=20
else if k=1 then a=10
else if k=2 then a=11;
• C/C++ representation (uses ‘switch’)
switch(k){
0 : a = 20; break;
1 : a = 10; break;
2 : a = 11;
}
Using jump register (jr $a)
• jumps to instruction referenced in $a
• suppose Label is memory location
containing addresses L0, L1, L2. ($4=k*4)
lw $10,Label($4)
# $10 = Label[k]
jr $10
# jump $10
L0:
addi $20,$0,20
# $20 gets 20
j BREAK
L1:
addi $20,$0,10
# $20 gets 10
j BREAK
L2:
addi $20,$0,11
# $20 gets 11
BREAK: continue whatever here
Summary
• bne $a,$b,LABEL
• beq $a,$b,LABEL
• slt $a,$b,$c
• j LABEL
• jr $a
#branch if not equal
#branch if equal
# select if less than
#jump to the instruction
referenced by LABEL
#jump to instruction
referenced in register $a
Still potential for a mess!...
• Adding 100 numbers x[] is fine.
• Suppose later we want to add 1011
numbers using sequence y[]?
– Do we have to repeat the same set of
instructions all over again, with small
modifications?
– No way!
• Use procedures!!!
Download