Find the correct code optimization technique that can be applied to the…
Find the correct code optimization technique that can be applied to the following given code.
X=1
Z = 3
y = x*3 +a
b = z + a
c = y*c+ b
Answer: A. Copy Propagation; B. Constant Folding; C. Common subexpression Elimination; D. Dead Code elimination — Explanation: all four listed optimizations can be applied if performed in the right order. Below are the stepwise transformations and why each optimization…
- A.
Copy Propagation
- B.
Constant Folding
- C.
Common subexpression Elimination
- D.
Dead Code elimination
Attempted by 25 students.
Show answer & explanation
Correct answer: A, B, C, D
Explanation: all four listed optimizations can be applied if performed in the right order. Below are the stepwise transformations and why each optimization applies.
Constant folding — evaluate expressions involving known constants.
Original (normalized):
x = 1
z = 3
y = x * 3 + a
b = z + a
c = y * c + b
After constant folding (x = 1 makes x*3 = 3; z is 3):
y = 3 + a
b = 3 + a
c = y * c + b
Common subexpression elimination — detect that y and b compute the same expression.
Since both y and b are 3 + a, compute it once and reuse the result (introduce a single definition or make one variable copy the other).
Example transform:
y = 3 + a
b = y // reuse the computed value
Copy propagation — substitute the copy where it is used.
Replace uses of b with y in later code to eliminate the extra variable:
c = y * c + y
Dead code elimination — remove assignments that are no longer needed.
After propagation the assignments to x and z are unused and can be removed. The temporary b is also eliminated.
Final optimized code (after these passes):
y = 3 + a
c = y * c + y
Notes:
The optimizations interact: constant folding exposes the common subexpression; eliminating the common subexpression creates a copy that can be propagated; propagation enables dead-code elimination.
Further algebraic simplification (e.g., factoring c = y*c + y into c = y * (c + 1)) is possible but is a different transformation (algebraic simplification/strength reduction).