Intermediate Language
COP-3402
SimpleIR
Our intermediate representation.
Example: C program
int main(int argc, char **argv) { int x; int retval; x = read_int(); retval = print_int(x); return 0; }
Example: SimpleIR
function main localvars argc argv x retval params argc argv x := call read_int x := x * 2 retval := call print_int x return 0
Compilation units
- One file is one compilation
- One compilation unit defines one function
Minimum SimpleIR
function main return 0
function
andreturn
must appear in each SimpleIR program- Function takes a single name
- Return takes an integer literal or a variable name
Defines a new function called main.
With parameters
function main localvars argc argv x y params argc argv # instructions go here return 0
- localvars declares all variable, including parameters
- params are a subset of localvars
For instance, in C, parameters to the function are local variables. In SimpleIR you need to declare all local variables first, include all parameters. Then specify separately which local variables are the parameters.
Statements
Assignment
x := 2 y := x
- Sets the value of a variable to
- Use the
:=
symbol - Assignment to either
- an to integer literal or
- another variable name
Arithmetic
x := x + 2
- A single operation, no arithmetic expressions
- Always assigns the result to a variable name
Function calls
x := call print_int x
- Works like a C function call
- No parentheses
- List arguments after the function name
Branching
ifgoto x > 0 goto end x = x * -1 end:
- No structured code, more like assembly
- goto for unconditional branches, ifgoto for conditional
- Define labels as targets of branching
Pointers
t1 := &x t2 := *t1 *t1 := 11
- Ampersand gets address
- t2 := *t1 dereferences t1 and gets its value
- *t1 dereferences t1 and assigns its value
Example program: exponents
function exponent localvars base exp result params base exp result = 1 top: if exp <= 0 goto end result = result * base exp = exp - 1 goto top end: return result
SimpleIR Grammar
grammar SimpleIR; unit: function; function: 'function' NAME localvars? params? statement* return; localvars: 'localvars' NAME+; params: 'params' NAME+; return: 'return' operand=(NAME | NUM); statement: assign | deref | ref | assignderef | operation | call | label | goto | ifgoto; operation: NAME ':=' operand1=(NAME | NUM) operator=('+' | '-' | '*' | '/' | '%') operand2=(NAME | NUM); assign: NAME ':=' operand=(NAME | NUM); deref: NAME ':=' '*' NAME; ref: NAME ':=' '&' NAME; assignderef: '*' NAME ':=' operand=(NAME | NUM); call: NAME ':=' 'call' NAME NAME*; label: NAME ':'; goto: 'goto' NAME; ifgoto: 'if' operand1=(NAME | NUM) operator=('=' | '!=' | '<' | '<=' | '>' | '>=') operand2=(NAME | NUM) 'goto' labelname=NAME; NAME: [a-zA-Z_] ([a-zA-Z_] | [0-9])* ; NUM: [0-9]+ ; PLUS: '+' ; MINUS: '-' ; STAR: '*' ; SLASH: '/' ; PERCENT: '%' ; EQ: '=' ; NEQ: '!=' ; LT: '<' ; LTE: '<=' ; GT: '>' ; GTE: '>=' ; WS: [ \t\r\n]+ -> skip ;