system-callscalling-conventionriscvrars-simulator

Should temporary registers be saved before issuing an environment call?


In the following RISC-V assembly code:

...
#Using some temporary (t) registers
...

addi a7,zero,1 #Printint system call code
addi a0,zero,100
ecall

...

Should any temporary (t) registers be saved to the stack before using ecall? When ecall is used, an exception occurs, kernel mode is on and code is executed from an exception handler. Some information is saved when exceptions occur, such as EPC and CAUSE , but what about the temporary registers? Environment calls are considered not to be like procedures for safety reasons, but they look like it. Do the procedure calling conventions still apply in this case?


Solution

  • You are correct that the hardware captures some information, such as the epc (if it didn't the interrupted pc would be lost during transfer of control to the exception handler).

    However that's all the hardware does — the rest is up to software.  Here, RARS is providing the exception handler for ecall.

    RARS documentation states (from the help section on syscalls, which is what these are called on MIPS (and RARS came from MARS)):

    Register contents are not affected by a system call, except for result registers as specified in the table below.

    And below this quote in the help is ecall function code table labeled "Table of Available Services", in which 1 is PrintInt.

    Should any temporary (t) registers be saved to the stack before using ecall?

    No, it is not necessary, the $t registers will be unaffected by an ecall.

    This also means that we can add ecalls to do printf-style debugging without concern for preserving the $t registers, which is nice.  However, keeping that in mind, we might generally avoid $a0 and $a7 for our own variables, since putting in an ecall for debugging will need those registers.


    In addition, you can write your own exception handler, and it would not have to follow any particular conventions for parameter passing or even register preservation.