Victor Brunell
Victor Brunell

Reputation: 6448

Passing Arguments: MIPS

I'd like to pass a character as an argument to a function in MIPS. Do I do this by storing the character into register $a0, use jal to move to the function, then extract what's in $a0 into a separate register using lw?

If someone could give me an example of passing an argument or two in MIPS, I'd really appreciate it. I've found a lot of info on the MIPS calling conventions, but not any simple and succinct examples.

Upvotes: 7

Views: 26002

Answers (2)

Kash'
Kash'

Reputation: 1

a very easy way to go about it would be to load the argument in a temp register and then just use:

move $a0,$t0

this way the argument stored in the temp register will be given as an argument

Upvotes: 0

Konrad Lindenbach
Konrad Lindenbach

Reputation: 4961

No need to use lw which is for extracting words from memory. You can simply use $a0 in the sub-routine.

Take a look at this example of a "print-char" function:

.text

main:

    #save $ra on stack
    addi $sp $sp -4
    sw   $fp 0($sp)
    move $fp $sp
    addi $sp $sp -4
    sw   $ra  -4($fp)

    #call sub-routine
    addi $a0 $zero 'A'
    jal printchar

    #restore and shrink stack
    lw $ra  -4($fp)
    lw $fp   0($fp)
    addi $sp $sp 8

    jr $ra

#prints a char and then a new line
printchar:

    #call print-char syscall
    addi $v0 $zero 11
    syscall

    addi $a0 $zero 10
    syscall

    jr $ra

As demonstrated, you the value of the $a0 register is just used in the sub-routine as it returns the value that it was given before the jal.

Also demonstrated is proper expansion and shrinking of the stack as is necessary for calling a sub-routing. As you will notice, the sub-routine does not perform this operation as it does not call a sub-routine and there-fore does not need to save the $ra. Stack manipulations would also be required in the sub-routine if it were to use an $s register as the MIPS calling convention specifies these as callee saved.

Upvotes: 4

Related Questions