Load and Store
 
How Do Variables Get from Memory to the Registers?
- 
Load:  Assume that the address of variable
ais
    in register$t0and we want to load the value inainto$s0
    lw $s0, 0($t0)       
    
- 
What's this 0($t0)stuff?
- 
General idea: load a word (4 bytes) of data that is a certain distance
(offset) from a base address
- 
$t0is the address of the beginning of a segment
in memory (the base address)
- 
The constant 0(...)specifies the offset
from the beginning of the memory segment (in bytes)
Example: Assume that obj is a
variable of type struct with several data members and that
$t0 holds the address of the beginning of obj.
How do we load obj.a into $s0,
obj.b into $s1, and
obj.e into $s2?
| C |  | Load data members into registers | 
| struct s_tag {
    int a;
    int b;
    int c;
    int d;
    int e;
} obj; |  | 
lw $s0, 0($t0)   
lw $s1, 4($t0)   
lw $s2, 16($t0)   | 
    
         | Addresses | Memory: Addressable Bytes | 
         | ( obj.a) | 00000000 | 00000000 | 00000000 | 00000000 | ==> $s0 | 
         | ( obj.b) | 00000000 | 00000001 | 00000011 | 00000111 | ==> $s1 | 
         | ( obj.c) | -------- | -------- | -------- | -------- | 
         | ( obj.d) | -------- | -------- | -------- | -------- | 
         | ( obj.e) | 00110010 | 00001010 | 01100001 | 01010101 | ==> $s2 | 
        
- 
Local variables can also be represented as a constant offset from the
beginning of the memory segment for local data.
From Registers Back to Memory
- 
Store:  How do we compute
obj.e += k?  (Assumekis in$s4.)
    lw  $t8, 16($t0)    
    add $t8, $t8, $s4   
    sw  $t8, 16($t0)    
    
What about loading and storing elements from arrays?
- 
    Problem: The lw/swoffset
    has to be a constant.
- 
So, how do we represent a variable array index, e.g.,
A[i]?
- 
Can't use a constant offset.  So,
compute the address of the individual array element, put it in a register,
and use 0 as the offset.
| Register | Value | 
|---|
| $t0 | ? | 
| $t1 | ? | 
| $s6 | 2 | 
| $s7 | 2012 | 
 
    add $t0, $s6, $s6   
    add $t0, $t0, $t0   
    add $t0, $s7, $t0   
    lw $t1, 0($t0)      
    
         | Addresses | Memory: Addressable Bytes | 
         | ( A[0]) | -------- | -------- | -------- | -------- | 
         | ( A[1]) | -------- | -------- | -------- | -------- | 
         | ( A[2]) | 00110010 | 00001010 | 01100001 | 01010101 | ==> $t1 | 
         | ( A[3]) | -------- | -------- | -------- | -------- | 
         | ( A[4]) | -------- | -------- | -------- | -------- | 
        
Handy Trick ...
What's an efficient way to multiply binary numbers by 2?
by 4?
    add $t0, $s6, $zero   
    sll $t0, $t0, 2       
    add $t0, $s7, $t0     
    lw $t1, 0($t0)        
Alyce Brady, Kalamazoo College