Consider the following C code segment: for (i = 0; i < n; i++) { for (j = 0; j…
Consider the following C code segment:
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i % 2)
{
x += (4*j + 5*i);
y += (7 + 4*j);
}
}
}Analyze the code and discuss the applicability of the following compiler optimizations:
Loop Invariant Code Motion (LICM)
Common Subexpression Elimination (CSE)
Strength Reduction
Dead Code Elimination
Clearly identify which optimization is not applicable (false) and justify your answer.
Attempted by 13 students.
Show answer & explanation
Overview of the Code
Two nested loops: each runs n times → total iterations = n²
Condition:
if (i % 2)
→ executes only when i is oddInner computations:
x += (4*j + 5*i)y += (7 + 4*j)
Analysis of Compiler Optimizations
(A) Loop Invariant Code Motion (LICM)
An expression is loop-invariant if it does not change within a loop.
5*i→ invariant w.r.t inner loop (j loop)7→ constant (fully invariant)
These can be moved outside the inner loop
LICM is applicable
(B) Common Subexpression Elimination (CSE)
Common subexpressions:
4*jappears in both:x += (4*j + 5*i)y += (7 + 4*j)
Can be computed once:
t = 4*j;
x += (t + 5*i);
y += (7 + t);CSE is applicable
(C) Strength Reduction
Strength reduction replaces expensive operations with cheaper ones.
4*j→ can be replaced using incremental addition:Instead of multiplication, use:
t = t + 4
Strength reduction is applicable
(D) Dead Code Elimination
Dead code refers to computations whose results are never used.
xandyare being updated (accumulated)Their values are assumed to be used later in the program
No statement is redundant or unused
Dead Code Elimination is NOT applicable
Summary Table
Optimization Technique | Applicable? | Reason |
|---|---|---|
LICM | Yes |
|
CSE | Yes |
|
Strength Reduction | Yes |
|
Dead Code Elimination | No | All computations are used |
Answer:
Dead Code Elimination is NOT applicable (False statement)