CD Unit4
CD Unit4
VI SEMESTER
ETCS-302
Code Optimization
Type of code optimization
Loop optimization
Basic Blocks
Live variables
c = a * b
x = a
till
d = a * b + 4
Here, after variable propagation a*b and x*b identified as common sub expression.
Department of Computer Science
9 and Engineering, BVCOE, New Delhi
Dead code elimination:
Before elimination the code is:
c = a * b
c = a * b
x = b
x = b
till
till
d = a * b + 4
d = a * b + 4
After elimination the code is:
c = a * b
c = a * b
till
till
d = a * b + 4
d = a * b + 4
Here, x= b is a dead state because it will never subsequently
used in the program. So, we can eliminate this state.
Department of Computer Science
10 and Engineering, BVCOE, New Delhi
Code Motion
It reduces the evaluation frequency of expression.
It brings loop invariant statements out of the loop.
do
do
{
{
item = 10;
item = 10;
valuevalue = value + item;
valuevalue = value + item;
} while(value<100)
} while(value<100);
This code can be further optimized as
item = 10;
item = 10;
do
do
{ {
valuevalue = value + item;
valuevalue = value + item;
} while(value<100);
} while(value<100);
Department of Computer Science
11 and Engineering, BVCOE, New Delhi
Strength Reduction:
Strength reduction is used to replace the high strength
operator by the low strength.
Before Strength reduction After Strength Reduction
int j = 0; int j = 0;
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
{ {
j = 2*i; j = j + 2;
} }
return j; return j;
Optimized code:
t = Sin(x)/Cos(x);
while(i<100) { a = t + i;
i++; }
v=r+u q=s*u
q=v+r