Lec09-Code Generation
Lec09-Code Generation
Absolute-Machine code
Relocatable Machine code
Assembly language code
Basic Block
7. b := d+f
5. f := a-d
6. goto 10 B2 B3 8. e := a - c
9. if b>c goto 15
10. b := d+c
B4
11. if a>b goto 1
1. a := b+c
2. d := d-b
3. e := a+f B1
4. if a>b goto 7
7. b := d+f
5. f := a-d
6. goto 10 B2 B3 8. e := a - c
9. if b>c goto 15
10. b := d+c
B4
11. if a>b goto 1
Computing Next uses of variables in a
basic block
i: x:= …+…;
…
(no intervening assignments to x) …
…
j: y:=…+x*…;
3. In the symbol table set y and z to “live” and the next uses
of y and z to i.
The following shows the next use information for the
basic blocks considered earlier.
a d,0;b 1,1;c 1,1;d 1,2;e d,0;f 1,3
1. a1,3 := b1,2+c 1,0 a 1,3;b 1,2;c 1,0;d 1,2;e d,0;f 1,3
2. d 1,0:=d 1,0-b d,0 a 1,3;b d,0;c 1,0;d 1,0;e d,0;f 1,3
3. e 1,0:= a 1,0+f 1,0 a 1,0;b d,0;c 1,0;d 1,0;e 1,0;f 1,0
MOV R0,R1 1
MOV R5,M 2
ADD #1,R3 2
SUB 4(R0),*5(R1) 3
A Code-Generation Algorithm
For each quadruple A := B op C we perform the following
R M
4) If the current values of B and/or C have no next uses, are not live
on exit from the block, and are in registers, alter the register
descriptor to indicate that, after execution of A :=B OP C, those
registers no longer will contain B and/or C, respectively.
GETREG( ):
• Examples:
– Redundant loads and stores
MOV R0, a
MOV a, R0
– Unreachable code
If debug = 1 goto L1
Goto L2
L1: print debugging info
L2:
– Examples:
• Flow of control optimization:
goto L1 goto L2
… …
L1: goto L2 L1: goto L2
R2 = 0 R2 = 0
R1 = 0 R1 = 0
GOTO L18 R4 = M[_n]
L19: GOTO L18
R0 = R1 << 2 L19:
R2 = R2+M[R0+_a] R0 = R1 << 2
R1 = R1+1 R2 = R2+M[R0+_a]
L18: R1 = R1+1
NZ = R1 - M[_n] L18:
if NZ < 0 goto L19 NZ = R1 – R4
if NZ < 0 goto L19
• Strength reduction: replace expensive operation by
equivalent cheaper operations
• Example:
R2 = 0 R2 = 0
R1 = 0 R1 = 0
R4 = M[_n] R4 = M[_n]
GOTO L18 R3 = _a
L19: GOTO L18
R0 = R1 << 2 L19:
R2 = R2+M[R0+_a] R2 = R2+M[R3]
R1 = R1+1 R3 = R3 + 4
L18: R1 = R1+1
NZ = R1 – R4 L18:
if NZ < 0 goto L19 NZ = R1 – R4
if NZ < 0 goto L19
• Induction variable elimination: can induce value from
another variable.
• Example:
R2 = 0 R2 = 0
R1 = 0 R4 = M[_n] << 2
R4 = M[_n] R3 = _a
R3 = _a GOTO L18
GOTO L18 L19:
L19: R2 = R2+M[R3]
R2 = R2+M[R3] R3 = R3 + 4
R3 = R3 + 4 L18:
R1 = R1+1 NZ = R3 – R4
L18: if NZ < 0 goto L19
NZ = R1 – R4
if NZ < 0 goto L19
• Common subexpression elimination:an expression
was previously calculated and the variables in the
expression have not changed. Can avoid
recomputing the expression.
• Example:
R1 = M[R13+I] << 2 R1=M[R13+I] << 2
R1 = M[R1+_b] R1 = M[R1+_b]
R2 = M[R13+I] << 2; R2 = R1
R2 = M[R2+_b]
The End