MIPS Code Examples and Register Optimization
Classified in Computers
Written on in
English with a size of 3.4 KB
Code in MIPS to add the 4 integer variables: a, b, c, d.
Add e,a,b # a gets b+c or a,b,c # a gets b+c
Add e,e,c # a gets a+dor a,a,c, # a gets a+d
Add e,e,d # a gets a+ eor a,a,e # a gets a+e
Code in MIPS for: f = (g + h) ‐ (i + j);
or #f,.., j are mapped to $s0, ., $s4
add t0,g,h #temp t0=g+hadd $t0,$s1,$s2
add t1,i,j #temp t1=i+jadd $t1,$s3,$s4
sub f,t0,t1 #f=t0-t1sub $s0,$t0,$t1
Why the size of a register is 32 bit?
32 bit occurs frequently and thus in MIPS, it has a special name ‘word’. Size 32 aligns well with the MIPS instruction format.
‘MIPS is Big Endian’ – what does it mean?
Most significant byte at least address of a word.
What are lw and sw instructions used for?
MIPS data transfer instructions with an address to access particular memory locations:
- lw (load word): transfer data from memory to register
- sw (store word): transfer data from register to memory.
C code: g = h + A[8]; assume, g in $s1, h in $s2, base address
of A in $s3. Write down MIPS code.
offset→32($s3)←base register
lw $t0, 32($s3) #load word where 32 is A[8]*4
add $s1, $s2, $t0
C code: A[12] = h + A[8]; assume h in $s2, base address of A in $s3.
lw $t0, 32($s3) #load word
add $t0, $s2, $t0
sw $t0, 48($s3) #store word where 48 = A[12]*4
Why does the usage of register is better than memory?
Registers are faster to access than memory. Operating on memory data requires loads and stores, more instructions to be executed. Compiler must use registers for variables as much as possible. Register optimization is important!
C code: k=k‐5; assume k in $s1. Write down MIPS
addi $s2, $s1, -5
We are using the pseudo‐instruction: move $t2, $s1; to transfer
the content of $s1 in $t2. Write down MIPS code using $zero
register and instruction add.
add $t2, $s1, $zero
What is the binary bit pattern for most negative and most positive
numbers in 2’s complement?
Most-negative: 1000 0000 ... 0000
Most-positive: 0111 1111 ... 1111
Assume, x is an 8 bit binary number. Explain, why x + x= -1.
x is complement of x.
So, x+x=1111…1111₂=-1
x+1=-x
What is a sign extension? Explain in the context of transferring two
8‐bit signed numbers: +2 and ‐2, to two 16‐bit numbers.
8-bit to 16-bit:
+2: 0000 0010 => 0000 0000 0000 0010
-2: 1111 1110 => 1111 1111 1111 1110
MIPS has 32 32‐bit registers. What are the names of arguments
and result‐returning registers?
$v0, $v1 - Result-Returning
$a0, $a1, $a2, $a3 - Argument 1-4
$t0-$t9 - Temp
$s0-$s7 - Saved Temp
C code:A[300]=h+A[300];assume,$t1 has the base of A and $s2
maps to h. MIPS
lw $t0, 1200($t1)
add $t0, $s2, $t0
sw $t0, 1200($t1)
Register $t1 is holding a bit pattern. Out of 0th to 31st bit, we are
interested to see whether the 10th bit is 1 or not in $t1. MIPS
addi $s1, $zero, 1024; Since, 2^10 = 1024
and $t2, $t1, $s1;
bne $t2, $zero, YES