Intermediate Code Generation
Intermediate Code Generation
Compiler Phases:
source program lexical analyzer syntax analyzer
semantic analyzer
Symbol table intermediate code generator
error handler
code optimizer
code generator target program
SPIM
Spim is a self-contained simulator that runs MIPS32 programs Spim implements almost the entire MIPS32 assembler-extended instruction set Spim files have the extension .s
SPIM - declarations
.data
Assembler directive that specifies data declarations is starting Declares variable names used in a program Example: .data # word (4 bytes) x: word 0 y: word 0 z: word 0
SPIM - code
.text
Assembler directive that specifies where the program code (instructions) are located Label main: marks the starting point for code execution Ending point is marked by the exit system call: li $v0, 10 syscall
SPIM - syscall
Service print_int print_float print_double Code in $v0 1 2 3 Arguments $a0 = integer to print $f12 = float to print $f12 = double to print Results
print_string
read_int read_float read_double read_string
4
5 6 7 8
sbrk exit
9 10
{ return ADD; } { return SUB; } { return MUL; } { return DIV; } { return OP; } { return CP; } { yylval = atoi(yytext); return NUMBER; } { return EOL; } { /* ignore white space */ } { yyerror("Mystery character %c\n", *yytext); }
9
Multiplications
factor: term | factor MUL term { fprintf(out,"\n\n### DO MULTIPLICATION ###\n"); fprintf(out, "lw\t$t0, ($sp)\t#pop 1st!\n"); fprintf(out, "addu\t$sp, $sp, 4\t#move the ptr\n"); fprintf(out, "lw\t$t1, ($sp)\t#pop 2nd!\n"); fprintf(out, "addu\t$sp, $sp, 4\t#move the ptr\n"); fprintf(out, "mul\t$t0, $t1, $t0\t#multiply\n"); fprintf(out, "subu\t$sp, $sp, 4\t#move the stack ptr\n"); fprintf(out, "sw\t$t0, ($sp)\t#push!\n"); }
12
Addition
exp: factor | exp ADD factor { fprintf(output,"\n\n### DO ADDITION ###\n"); fprintf(out, "lw\t$t0, ($sp)\t#pop 1st!\n"); fprintf(out, "addu\t$sp, $sp, 4\t#move the ptr\n"); fprintf(out, "lw\t$t0, ($sp)\t#pop 2nd!\n"); fprintf(out, "addu\t$sp, $sp, 4\t#move the ptr\n"); fprintf(out, "add\t$t0, $t1, $t0\t#add\n"); fprintf(out, "subu\t$sp, $sp, 4\t#move the stack ptr\n"); fprintf(out, "sw\t$t0, ($sp)\t#push!\n");
13