Search code examples
assemblymipsmips32self-modifyingmips64

Is there any way to create a counter by self-modifying in MIPS?


I want to create a subroutine like this:

  • first time call: return 0
  • second time call: return 1
  • third time call: return 2
  • ...

but we should not use register and memory to save the current number. we have to solve this by changing the code (self-modifying). Is there any way?


Solution

  • This is the solution which I found:

    # subroutine
    nextInt:                    # return value is in $v0
    add     $v0,$zero,0
    la      $t0,nextInt         # load subroutine address
    lw      $t1,0($t0)          # load content of address
    addi    $t1,$t1,1           # change content (increment)
    sw      $t1,0($t0)          # save
    jr      $ra