### Stack Machines

- Code generation model.
- It only contains a stack. It takes an instruction I=F(a
_{1},a_{2}…a_{n}) pushes and pops from the stack according to the instruction. For example, 7+5 would be implemented as:

LET S be a stack when 7 is input then S → S.7 when 5 is input then S → S.7.5 for add operation 5 and 7 are popped out and 12 is pushed, S → S.12 instructions for the above: push 7 push 5 add

In the above method, **S is untouched.**

- The other kind of machine is register machine, the above addition in this kind of machine can be done using one line instruction:

add r1, r2, r3;

*Stack machine vs. Register machine:*In a register based machine the average instructions are larger than the stack machine’s instructions, so the code is simpler in stack machines. Register machines are faster, optimization can also be easily implemented here as the common code can be processed and used number of times. For more, refer this article.- Something intermediate or mixture of these machines is called
*n-register stack machine.*In this machine n-top locations of stack is stored in registers. - 1-register stack machine is a special type, where the register that has the top value of the stack is called
*accumulator.*- In the case of stack machine, when an add operation is performed, it reads out 2 data and writes one, but when the same operation is performed by this machine, it would be implemented as:

acc ← acc + top_of_stack

- Taking the machine as 1-register stack machine, the operation op(e
_{1},e_{2}…e_{n}) would be done as:

for i ← 1 to n: if i is not 1: push e_{i-1}in stack e_{i}is evaluated and stored in accumulator; what op will do is thet it will pop all n-1 elements in stack and apply it with accumulator which stores e_{n}

**If the above is done for any expression then the stack is unchanged. Expression evaluation preserves the stack.**

Advertisements