How do we modularize programs?
int my_sub(int p){
return p + p;
}
int main(void){
int x,z;
x = my_sub(3);
z = my_sub(4);
}
r31
is called the “return address” register ra
and it is used to hold the address to go back to the program counter when a subroutine is calledmain: movi r4, 3 ; the parameter 3 that we put into the my_sub function
call my_sub ; ra <- pc
; pcc <- my_sub
nextins: movi r4, 4 ; parameter 3
call my_sub ; ra <- pc
; pcc <- my_sub
done: br done
my_sub: add r2, r4, r4 ; r2 gets r4 + r4 (return value)
ret ; pc<-ra
main:
- This is a label indicating the main entry point of the program.movi r4, 3
- This instruction moves the immediate value 3 into register r4
. This sets up a parameter for the subroutine my_sub
.call my_sub
- This instruction calls the subroutine (or function) labeled my_sub
. The call
typically does two things: it stores the address of the next instruction (which would be nextins:
in this case) into the return address register (ra
), and then sets the program counter (pc
) to the address of my_sub
to start executing from there.
ra <- pc
means the return address register (ra
) is set to the address of the current program counter (pc
), which would be the address of the instruction following the call
.pcc <- my_sub
is not a standard assembly language operation; it might be a comment or pseudocode indicating that the program counter will continue from my_sub
.nextins: movi r4, 4
- This is another label followed by an instruction that would be executed after my_sub
returns. It moves the immediate value 4 into register r4
, setting up another parameter for my_sub
.call my_sub
- This calls the my_sub
subroutine again with the new parameter in r4
.done: br done
- This is a label followed by a branch instruction that creates an infinite loop, effectively stopping the program from proceeding. The br done
instruction causes the program to jump to the done
label indefinitely.my_sub:
- This is the label for the subroutine.add r2, r4, r4
- This instruction adds the value in register r4
to itself and stores the result in register r2
. Since r4
was previously set to 3, then 4, this would effectively double the parameter passed to my_sub
.ret
- This is the return instruction, which sets the program counter (pc
) back to the value stored in the return address register (ra
), which would be the address of the instruction following the call
instruction that invoked my_sub
.