Chapter2 2
Chapter2 2
Stack
Text (instructions)
2
Recap – Numeric Representations
• Binary 001000112 = 1 x 25 + 1 x 21 + 1 x 20
Dec Binary Hex Dec Binary Hex Dec Binary Hex Dec Binary Hex
0 0000 00 4 0100 04 8 1000 08 12 1100 0c
1 0001 01 5 0101 05 9 1001 09 13 1101 0d
2 0010 02 6 0110 06 10 1010 0a 14 1110 0e
3 0011 03 7 0111 07 11 1011 0b 15 1111 0f
3
Instruction Formats
5
Control Instructions
• Unconditional branch:
j L1
jr $s0 (useful for big jumps and procedure returns)
Convert to assembly:
if (i == j)
f = g+h;
else
f = g-h;
6
Control Instructions
• Unconditional branch:
j L1
jr $s0 (useful for big jumps and procedure returns)
Convert to assembly:
if (i == j) bne $s3, $s4, Else
f = g+h; add $s0, $s1, $s2
else j End
f = g-h; Else: sub $s0, $s1, $s2
7
End:
Example
Convert to assembly:
while (save[i] == k)
i += 1;
8
Example
Loop: sll $t1, $s3, 2
Convert to assembly: add $t1, $t1, $s6
lw $t0, 0($t1)
while (save[i] == k) bne $t0, $s5, Exit
i += 1; addi $s3, $s3, 1
j Loop
Exit:
Values of i and k are in $s3 sll $t1, $s3, 2
and $s5 and base of array add $t1, $t1, $s6
save[] is in $s6 Loop: lw $t0, 0($t1)
bne $t0, $s5, Exit
addi $s3, $s3, 1
addi $t1, $t1, 4
j Loop
Exit: 9
Registers
parameters (arguments) are placed where the callee can see them
control is transferred to the callee
acquire storage resources for callee
execute the procedure
place result value where caller can access it
return control to caller
3
Jump-and-Link
• A special register (storage not part of the register file) maintains the
address of the instruction currently being executed – this is the
program counter (PC)
call Proc B
Proc B’s values …
call Proc C
Proc C’s values …
… return
Stack grows return
this way return
Low address 5
Saves and Restores
6
Storage Management on a Call/Return
• A new procedure must create space for all its variables on the stack
• After the callee creates stack space, it updates the value of $sp
• Once the callee finishes, it copies the return value into $v0, frees
up stack space, and $sp is incremented
• On return, the caller/callee brings in stack values, ra, temps into registers
• The responsibility for copies between stack and registers may fall
upon either the caller or the callee
7
Example 1 (pg. 98)
9
Example 2 (pg. 101)
11
Example 3 (pg. 108)
12
Large Constants
4
Starting a Program
C Program x.c
Compiler
Linker
Loader
Memory 5
Role of Assembler
6
Role of Linker
7
Full Example – Sort in C (pg. 133)