Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing addresses in a register for MIPS

Tags:

assembly

mips

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?

like image 427
Kyle Bauer Avatar asked Apr 25 '12 22:04

Kyle Bauer


People also ask

Which register is used to store the return address for MIPS functions?

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.

Do registers hold memory addresses?

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.

What is an address in MIPS?

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.


2 Answers

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.

like image 188
RageD Avatar answered Sep 18 '22 12:09

RageD


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

like image 20
seanwatson Avatar answered Sep 20 '22 12:09

seanwatson