raullalves
raullalves

Reputation: 856

How to preserve the global variables in the stack in MIPS when calling a function?

I'm developing a compiler from a language that mixes C++ and Javascript to MIPS Assembly

What's the best approach to preserve the global variables in the stack when calling one or more functions, including recursion?

At the main function, global and local variables are at the stack, starting from $fp, and that part works well. However, when calling another function, the methodology I'm using saves the return address $ra and sets new $fp and $sp. That means I have no more access to old $fp addresses where my global variables were saved. How to proceed?

The image below describes the process that I'm using. Image obtained from Prof. Sen lectures, from Berkley Prof. Koushik Sen - Berkley

Upvotes: 2

Views: 7417

Answers (1)

raullalves
raullalves

Reputation: 856

I put the globals at the .data segment

Here is how I access and modify their content

data
   globalVariable:  .word  10

.text

   #access
   lw $a0, globalVariable 

   #modify
   la $a0, globalVariable #get address
   li $a1, 11 #new value
   sw $a1 0($a0) #save new value

   lw $a2, globalVariable  #get new value

Upvotes: 4

Related Questions