I have allocated a certain amount of memory and would like to assign the location of this memory to variable I have declared in the .data section of the program. I know how to assign the memory location to the variable, but once I do that how can I use that variable to access the allocated memory?
MIPS uses the jump-and-link instruction jal to call functions. — The jal saves the return address (the address of the next instruction) in the dedicated register $ra, before jumping to the function.
In a computer, the memory address register (Oct) is the CPU register that either stores the memory address from which data will be fetched to the CPU registers, or the address to which data will be sent and stored via system bus.
A MIPS memory address is 32 bits (always). How can a load or store instruction specify an address that is the same size as itself? An instruction that refers to memory uses a base register and an offset. The base register is a general purpose register that contains a 32-bit address.
If I understand your problem correctly, you will want to use the la
(load address) instruction to get the address into a register. You will then use the lw
(load word) and sw
(store word) instructions to manipulate the data. For instance, consider the following piece of code
.data
tmpval: .word 5
__start:
sub $sp, $sp, 12
sw $ra, 0($sp) # Return addy
sw $t0, 4($sp)
sw $t1, 8($sp)
la $t0, tmpval
lw $t1, 0($t0) # $t1 == tmpval == 5
li $t1, $2 # $t1 == 2
sw $t1, 0($t0) # tmpval == 2
lw $ra, 0($sp)
lw $t0, 4($sp)
lw $t1, 8($sp)
add $sp, $sp, 12
jr $ra
So in the inner-block of code you can see that you treat $t0
(or any other register for that matter) as a memory location and work with it appropriately.
MIPS has many instructions for loading and storing to memory: load word (lw), load halfword (lh), load byte(lb), store word (sw), store half word (sh), and store byte (sb) just to name a few. They all use the same sort of syntax so here is an example from loading from a memory location:
lw $t, C($s)
which will load the word from the memory location held in register $s plus C to register $t. ie $t = [$s + C]
Similarly for storing:
sw $t, C($s)
which will store the word in register $t to the memory location in $s plus C. ie [$s + C] = $t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With