Lecture8-Code Optimization
Lecture8-Code Optimization
� 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:
goto L1 goto L2
… …
L1: goto L1:
L2 goto L2
if a < b goto if
L1 a<b 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 * 4 L19:
R2 = R2+M[R0+_a] R0 = R1 * 4
R1 = R1+1 R2 = R2+M[R0+_
L18: R1 = R1+1
R4 = M[_n] L18:
NZ = R1 – R4 NZ = R1 – R4
if NZ < 0 goto L19 if NZ < 0 goto
� 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 * 4 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
� 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
NZ = R1 – R4
if NZ < 0 goto L19
� Common sub-expression elimination : an
expression was previously calculated
and the variables in the expression
have not changed. Can avoid recomputing
the expression.
�R1 = M[R13+I] << 2
Example:
R1 = M[R1+_b] R1=M[R13+I] << 2
R2 = M[R13+I] << 2; R1 = M[R1+_b]
R2 = M[R2+_b] R2 = R1