title: LIFO stack algorithm design
body: <p>I'm implementing a stack-based VM and I've been trying to read up on literature that explains or outlines algorithms for dealing with stacks no no avail. Here's an example:</p>
  
  <pre><code>int i = 3
  int j = 4
  int k = 5
  </code></pre>
  
  <p>Lets assume <code>i</code>, <code>j</code>, and <code>k</code> are local variables so they would be traditionally stored on the stack. The assembly/bytecode translation would look something like:</p>
  
  <pre><code>pushi 3
  pushi 4
  pushi 5
  </code></pre>
  
  <p>And the stack would be: <code>5 4 3</code></p>
  
  <p>I have an integer stack and a string stack, hence the <code>pushi</code>, however my question is without storing these on the heap (with some <code>ptr*</code> or literal identifier), how would a compiler or interpreter know that if I want to do something like <code>int x = i + j</code> after the definition, I have to pop <strong>two</strong> and <strong>three</strong> times, respectively, <strong>as well as</strong> do my best not to lose <code>k</code> (save it in a register or something, then push it back)?</p>
  
  <p>I hope my question made some sense and there's probably a much smarter approach :P Thank you for any insight!</p>