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:

  1. Loop Invariant Code Motion (LICM)

  2. Common Subexpression Elimination (CSE)

  3. Strength Reduction

  4. 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 odd

  • Inner 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*j appears 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.

  • x and y are 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

5*i, 7 are loop invariant

CSE

Yes

4*j repeated

Strength Reduction

Yes

4*j → incremental addition

Dead Code Elimination

No

All computations are used

Answer:

Dead Code Elimination is NOT applicable (False statement)

Explore the full course: Compiler Design

Loading lesson…