The stacks value

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

The stacks value

Nick
What exactly is the purpose of using the stack architecture?  It seems like the code could
just be translated from the high-level language to the target assembly language without using
the stack.
The stack would definitely make that translation simpler. For instance, some problems like
the following can be translated much quicker after the result is gotten from the stack:

sum = (8+4)*(5-3)

holding the constants on a stack and then putting that result in sum can then be done in
two assembly instruction:

@24 //the stack result gotten from (8+4)*(5-3)
D = A
@sum
M = D

It is clearly much simpler to do that using stack architecture as opposed to translating it all to
assembly which would take multiple instructions and even require calling a multiplication function.

Is that the reason for having a stack as opposed to translating everything directly to the target assembler language?  Thanks for the answer, and I hope the question is clear.
Reply | Threaded
Open this post in threaded view
|

Re: The stacks value

cadet1620
Administrator
The main reason to have the abstract machine layer between the compiler and the assembler is to make it easier to retarget a compiler for different processors. For instance, the Gnu C compiler has been retargetted to 100s of different microprocessors over the years. When somebody wants to retarget it to a new processor, all they need to do is rewrite the "VM translator" part of the compiler.

Modern compilers do a lot of optimization at many different levels in the compilation processor. The constant expression detection that you mention is one of them. In the Hack world, that optimization would be part of the Jack compiler.

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: The stacks value

Dano
In reply to this post by Nick
What is more, with the stack architecture you don't have to allocate registers (typically a graph coloring operation), generate register spill code and you don't have to explicitly push/pop register values when calling/returning from the subroutine.

Sure, you can use another intermediate representation (for example, search for a SSA-form). However I can not imagine how you would understand/implement it in a semester-long course.
Reply | Threaded
Open this post in threaded view
|

Re: The stacks value

Nick
Thanks for the responses.  From your answer I see that optimization at high levels will result in tighter code at the low level and I assume the effort put in to do the optimization results in faster code in the long run at the low level.  Thanks for the information on the different types of compiler architectures too.