Search code examples
assemblyprogramming-languagesmips

What happens to registers when there are more than 32 variables?


One major difference between the variables of a programming language and registers is the limited number of registers, typically 32 on current computers, like MIPS.

This is what I read while studying MIPS language. Assume that there is a program which has more than 32 variables and each variable stored in a register. What will happen the rest of variables while there is no empty register?


Solution

  • Not all MIPS 32 registers are used to store variables, some has special uses like $k0, $k1, $gp, $sp, so the available registers for storing variables are less.

    Usually variables are not stored in registers, they are stored in memory by creating a stack frame for the function like here:

    # make space of 30 vars, 4 bytes each
    addi    $sp, $sp, -4 * 30
    
    # $t0 = 1
    addi    $t0, $0, 1
    
    # store vars into the stack
    sw      $t0, 0($sp)  # 1
    addi    $t0, $t0, 1  # $t0++
    sw      $t0, 4($sp)  # 2
    addi    $t0, $t0, 1  # $t0++
    sw      $t0, 8($sp)  # 3
    addi    $t0, $t0, 1  # $t0++
    sw      $t0, 12($sp) # 4
    #...
    
    # now to access the 4th var, 12($sp), into $t1
    lw      $t1, 12($sp)
    
    # do stuff
    
    # deallocate the space and destroy those vars when you done
    addi    $sp, $sp, 4 * 30
    

    when you want to update the variable or use it heavily like in counters, you load it from the memory into a register, do what you want to do and then update the memory stored variable.