CodeGeneration Lec10
CodeGeneration Lec10
CodeGeneration Lec10
Code Generation
Pop Quiz/Review
What options do we have for generating code?
t3 = A OR t2 B NOT
0 t1 = A < B if
1 t1 goto 3 <
2 goto 11 < = =
3 t2 = c < d A B
4 t2 goto 8 C D x - x +
5 t3 = y-2
6 x = t3 y
7 goto 10 2 y 2
8 t4 = y + 2
9 x = t4
10 goto 0
lw $t0, B,
lw $t1, C,
add $t2, $t0, $t1
sw $t2, A
lw $t0, A
lw $t1, C
mul $t2, $t0, $t1
sw $t2, D
t1=B+C lw $t0, B,
lw $t1, C
add $t2, $t0, $t1
sw $t2, t1
t2=t1*C lw $t0, t1
lw $t1, C
mul $t2, $t0, $t1
sw $t2, t2
d = t2 lw $t0, t2
sw $t0, d
8 Code Generation April, 2011
Generating Code via Macro Expansion
Macroexpansion gives poor quality code if each tuple
expanded separately
Ignoring state (values already loaded)
lw $t0, A
lw $t1, B
bge $t0, $t1, _else24
lw $t2, C
li $t3, 10
mul $t4, $t2, $t3
sw $t4, A
_else24:
lw $t0, A
lw $t1, B
bge $t0, $t1, _else24
lw $t2, C
li $t3, 10
mul $t4, $t2, $t3
sw $t4, A
j _endif24
_else24: lw $t5, C
li $t6, 9
mul $t7, $t6, $t6
sw $t7, A
_endif24:
r0 0
r1
°
°
°
r31
PC
lo
hi
Example:
C code: A[8] = h + A[8];
assume h in $s2 and base address of the array A in $s3
.text
.globl main # exports symbol “main”
main:
la $a0,str # put string address into a0
li $v0,4 # system call to print
Text Segment
syscall # out a string (Code)
li $v0,10
syscall # exit with no result
Labels Directives
.text
.globl main # exports symbol “main”
main:
la $a0,str # put string address into a0
li $v0,4 # system call to print
syscall # out a string
li $v0,10
syscall # exit with no result
Directives
Reminder
Registers variable in C code $s0 ... $s7 $16 ... 23
Registers temporary variable $t0 ... $t7 $8 ... 15
Register $zero always 0
# $t4[0]=&L0, $t4[1]=&L1, …,
L0 : add $s0, $s3, $s4 # f = i + j
j Exit
L1 : add $s0, $s1, $s2 # f = g + h
j Exit
L2 : sub $s0, $s1, $s2 # f = g – h
j Exit
L3 : sub $s0, $s1, $s2 # f = i – j
Exit :
CSCE 212 46
If-Statement
if ((a>b)&&(c==d)) e=0; else e=f;
lw $s0,a
lw $s1,b
bgt $s0,$s1,next0
b nope
next0: lw $s0,c
lw $s1,d
beq $s0,$s1,yup
nope: lw $s0,f
sw $s0,e
b out
yup: xor $s0,$s0,$s0
sw $s0,e
out: …
CSCE 212 47
For Loop
for (i=0;i<a;i++) b[i]=i;
lw $s0,a
li $s1,0
loop0: blt $s1,$s0,loop1
b out
loop1: sll $s2,S1,2
sw $s1,b($s2)
addi $s1,$s1,1
b loop0
out: …
CSCE 212 48
Pre-Test While Loop
while (a<b) {
a++;
}
lw $s0,a
lw $s1,b
loop0: blt $s0,$s1,loop1
b out
loop1: addi $s0,Ss0,1
sw $s0,a
b loop0
out: …
CSCE 212 49
Post-Test While Loop
do {
a++;
} while (a<b);
lw $s0,a
lw $s1,b
loop0: addi $s0,$s0,1
sw $s0,a
blt $s0,$s1,loop0
…
CSCE 212 50
Complex Loop
for (i=0;i<n;i++) a[i]=b[i]+10;
CSCE 212 51