Reputation: 37
How do i implement a Java function in Hack Assembly? I know that instructions to change variables is easily made, but how does HACK call a function? For Example:
function(int a, int b) {
if (a-b > 0)
return a;
else
return b;
}
My (i think wrong) result is :
@a
D=M
@b
D=D-M
@JUMPMARK1
D;JGT
@Jumpmark2
0;JMP
(JUMPMARK1)
@a
D=M
@function
M=D
(Jumpmark2)
@b
D=M
@function
M=D
So the issue is that i dont know where to store the result(return)..should i create a variable like i did in this example for the function and store it there?
Upvotes: 2
Views: 699
Reputation: 1289
In order to implement true function calls in Hack, you need to first implement a push-down stack. Once that is done it is relatively straightforward.
Then, to make function calls, you load D with the return address and push it. For single-parameter function calls you can pass the function parameter in D; for multiple-parameter calls you will also need to push these values onto the stack.
You then make an unconditional jump to the function. In the function, you do whatever you need to do (including popping any parameters from the stack). Finally, you pop the return address from the stack into A and unconditionally jump.
The return operation can be done in 4 instructions. The call operation requires 9 instructions.
If functions are guaranteed to be non-recursive, you can dispense with the stack and put the function parameters, including the return address, in a fixed block of memory associated with each function.
Upvotes: 1