Lecture 012

Code Generation

For our specific implementation:

Operation to Implement

Operation to Implement

A language with integer operation. P stands for program. D stands for declearation. E stands for expression.

A language with integer operation. P stands for program. D stands for declearation. E stands for expression.

We define code generation cgen(): For expression e, cgen(e) produce code for e such that the code will evaluate e and preserve the stack after evaluation.

For constant i, cgen(i) = li $a0 i

cgen(e1 + e2) =
  cgen(e1)
  sw $a0 0($sp)
  addiu $sp $sp -4
  cgen(e2)
  lw $t1 4($sp)
  add $a0 $t1 $a0
  addiu $sp $sp 4

Good for stack machine:

Calling Sequence: instructions to set up a function activation

Caller Side of Function Activation

Caller Side of Function Activation

Callee Side of Function Activation (Note that the image forgot to include label) 8 = 4 + 4 = old frame pointer + return value

Callee Side of Function Activation (Note that the image forgot to include label) 8 = 4 + 4 = old frame pointer + return value

The stack of before, after function call

The stack of before, after function call

Code for variable reference is generated using relative position to the frame pointer: cgen(x_i) = lw $a0 z($fp) where z = 4 \times i (z is computed at compile time) for ith variable.

For production compiler:

Temporary in AR

Example: how many temporary location to reserve in AR

Example: how many temporary location to reserve in AR

In general, let NT(e) be a function that calculate the number of temporary location we need to reserve in AR, then, NT(e1 + e2) = max(NT(e1), NT(e2) + 1)

Other Formulas for NT(e) function.

Other Formulas for NT(e) function.

Now activation record stores: - return address - frame pointer - n arguments - NT(e) many temporaries

New scheme for code generation with temporary in AR

New scheme for code generation with temporary in AR

Object Layout in Inherited Class

Field: object's attribute

Our goal:

Example Object Layout

Example Object Layout

Layout: in contiguous memory

Attribute Inheritage

Attribute Inheritage

In this structure, if a child object want to add attribute, it can just change object size and then append additional attributes to attributes (and change class tag)

Object Table: here B and C is inheritaged from A. B has overwritten function fA to fB and added a new method g.

Object Table: here B and C is inheritaged from A. B has overwritten function fA to fB and added a new method g.

Object Table: a global table to map each object type to their the method address that object can invoke. It is global because the number of method for a class does not change.

Table of Content