Answers to Self-Study Questions

Test Yourself #1

Question 1

  1. Evaluate the condition, leaving the value on the stack
  2. Pop the top-of-stack value into register T0
  3. Jump to ElseLabel if T0 == FALSE
  4. Code for the statement list in If
  5. Jump to DoneLabel
  6. ElseLabel:
  7. Code for the statement list in Else
  8. DoneLabel:

Question 2

public void codeGen() {
  String falseLabel = Codegen.nextLabel();
  myExp.codeGen();
  Codegen.genPop(Codegen.T0);
  Codegen.generate("beq", Codegen.T0, Codegen.FALSE, falseLabel);
  myStmtList.codeGen();
  Codegen.genLabel(falseLabel);
}

Question 3

  1. LoopLabel:
  2. Evaluate the condition, leaving the value on the stack.
  3. Pop the top-of-stack value and see if it's zero; if zero, jump to DoneLab
  4. Code for the statements in the body of the loop.
  5. Jump to LoopLabel
  6. DoneLabel:

Test Yourself #2

AndNode

  1. code to evaluate the left operand, jumping to FalseLab if 0
  2. code to evaluate the right operand
  3. FalseLab:

OrNode

  1. code to evaluate the left operand, jumping to TrueLab if 1
  2. code to evaluate the right operand
  3. TrueLab:

Test Yourself #3

OrNode

  1. code to evaluate left operand with jumps to TrueLab and L1
  2. L1:
  3. code to evaluate right operand with jumps to TrueLab and FalseLab
NotNode
  1. code to evaluate the operand with jumps to TrueLab and FalseLab

Test Yourself #4

OrNode

   Numeric Code                           Control-Flow Code
   ------------                           -----------------
   -- code to evaluate left operand,      -- code to evaluate left operand,
   -- leaving the value on the stack      -- with jumps to TrueLab and L1

   pop; if zero goto FalseLab             L1:
   push 1
   goto DoneLab
FalseLab:

   -- code to evaluate right operand,     -- code to evaluate right operand,
   -- leaving the value on the stack      -- with jumps to TrueLab and FalseLab
DoneLab:                                  
NotNode
   Numeric Code                           Control-Flow Code
   ------------                           -----------------
   -- code to evaluate the operand,       -- code to evaluate the operand,
   -- leaving the value on the stack      -- with jumps to TrueLab and FalseLab

   pop; if zero push 1 else push 0