User Tools

Site Tools


Tutorial on code generation

Step 1: Preparation
Step 2: Extend the symbol table
  • Create a function in the Parser class that is able to return a fresh label (for example label0, label1, label2 …) each time it is called. (Use an int attribute to store the label index and use the stringstream type build the label.)
  • Add a string label; field to the data type stored in the symbol table.
  • Change the constructor of that data type to get the label as parameter.
  • Change the C++ code at the declaration rules so that a new label is generated for each declaration and passed to the constructor.
Step 3: Change the semantic type of expressions
  • Create a struct or class in semantics.h that is able to store both the type of an expression and also its generated code. Create a two-parameter constructor for this type.
  • Make the new struct/class the semantic value of expressions. (See the %type and the %union in while.y.)
  • Make the C++ code fragments in the expression-related rules consistent with the above change.
Step 4: Generate code for expressions
  • Implement the code generation templates for expressions.
Step 5: Generate code for instructions
  • Add semantic type of string to instructions.
  • Implement the code generation templates for instructions.
Step 6: Generate code for variable declarations
  • In the start rule, iterate through the symbol table and generate a label: resd 1 or label: resb 1 line for each variable.
  • Concatenate these lines to form the section .bss together.
Step 7: Completion
  • In the start rule, put together the code of the instructions (in the .text section) and the code of the declarations (in the .bss section), and add the necessary extern and global declarations at the beginning to form a complete assembly file.
  • Test the generated code using nasm and running the executable.
compilers/codgen_tutorial.txt · Last modified: 2016/12/15 11:06 by deva