Open In App

Peephole Optimization in Compiler Design

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Peephole optimization is a type of code Optimization performed on a small part of the code. It is performed on a very small set of instructions in a segment of code.

The small set of instructions or small part of code on which peephole optimization is performed is known as peephole or window.

It basically works on the theory of replacement in which a part of code is replaced by shorter and faster code without a change in output. The peephole is machine-dependent optimization. 

Objectives of Peephole Optimization: 

The objective of peephole optimization is as follows:

  1. To improve performance
  2. To reduce memory footprint
  3. To reduce code size

Peephole Optimization Techniques

A. Redundant load and store elimination: In this technique, redundancy is eliminated.

Initial code:
y = x + 5;
i = y;
z = i;
w = z * 3;

Optimized code:
y = x + 5;
w = y * 3; //* there is no i now

//* We've removed two redundant variables i & z whose value were just being copied from one another.

B. Constant folding: The code that can be simplified by the user itself, is simplified. Here simplification to be done at runtime are replaced with simplified code to avoid additional computation.

Initial code:
x = 2 * 3;

Optimized code:
x = 6;

C. Strength Reduction: The operators that consume higher execution time are replaced by the operators consuming less execution time.

Initial code:
y = x * 2;

Optimized code:
y = x + x; or y = x << 1;

Initial code:
y = x / 2;

Optimized code:
y = x >> 1;

D. Null sequences/ Simplify Algebraic Expressions : Useless operations are deleted.

a := a + 0;
a := a * 1;
a := a/1;
a := a - 0;

E. Combine operations: Several operations are replaced by a single equivalent operation.

F. Deadcode Elimination:- Dead code refers to portions of the program that are never executed or do not affect the program’s observable behavior. Eliminating dead code helps improve the efficiency and performance of the compiled program by reducing unnecessary computations and memory usage.

Initial Code:-
int Dead(void)
{
int a=10;
int z=50;
int c;
c=z*5;
printf(c);
a=20;
a=a*10; //No need of These Two Lines
return 0;
}
Optimized Code:-
int Dead(void)
{
int a=10;
int z=50;
int c;
c=z*5;
printf(c);
return 0;
}

Last Updated : 09 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads