The Wayback Machine - https://web.archive.org/web/20240823065832/https://www.geeksforgeeks.org/code-optimization-in-compiler-design/
Open In App

Code Optimization in Compiler Design

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The code optimization is the synthesis phase is a program transformation technique, which tries to improve the intermediate code by making it consume fewer resources (i.e. CPU, Memory) so that faster-running machine code will result. Compiler optimizing process should meet the following objectives :

  • The optimization must be correct, it must not, in any way, change the meaning of the program.
  • Optimization should increase the speed and performance of the program.
  • The compilation time must be kept reasonable.
  • The optimization process should not delay the overall compiling process.

When to Optimize? 

Optimization of the code is often performed at the end of the development stage since it reduces readability and adds code that is used to increase the performance. 

Why Optimize? 

Optimizing an algorithm is beyond the scope of the code optimization phase. So the program is optimized. And it may involve reducing the size of the code. So, optimization helps to:

  • Reduce the space consumed and increases the speed of compilation.
  • Manually analyzing datasets involves a lot of time. Hence, we make use of software like Tableau for data analysis. Similarly, manually performing the optimization is also tedious and is better done using a code optimizer.
  • An optimized code often promotes re-usability.

Types of Code Optimization: The optimization process can be broadly classified into two types:

  1. Machine Independent Optimization: This code optimization phase attempts to improve the intermediate code to get a better target code as the output. The part of the intermediate code which is transformed here does not involve any CPU registers or absolute memory locations.
  2. Machine Dependent Optimization: Machine-dependent optimization is done after the target code has been generated and when the code is transformed according to the target machine architecture. It involves CPU registers and may have absolute memory references rather than relative references. Machine-dependent optimizers put efforts to take maximum advantage of the memory hierarchy.

Code Optimization is done in the following different ways:

1. Compile Time Evaluation:

C
(i)   A = 2*(22.0/7.0)*r  
      Perform 2*(22.0/7.0)*r at compile time. 
(ii)  x = 12.4 
      y = x/2.3  
      Evaluate x/2.3 as 12.4/2.3 at compile time.

2. Variable Propagation:

C
//Before Optimization  
c = a * b                                                
x = a                                                   
till                                                            
d = x * b + 4  
 
 
//After Optimization  
c = a * b   
x = a 
till 
d = a * b + 4

3. Constant Propagation:  

  • If the value of a variable is a constant, then replace the variable with the constant. The variable may not always be a constant.

Example: 

C
(i)  A = 2*(22.0/7.0)*r 
     Performs 2*(22.0/7.0)*r at compile time.
(ii)  x = 12.4
      y = x/2.3 
      Evaluates x/2.3 as 12.4/2.3 at compile time.
(iii) int k=2;
      if(k) go to L3;
      It is evaluated as : 
      go to L3 ( Because k = 2 which implies condition is always true)

4. Constant Folding: 

  • Consider an expression : a = b op c and the values b and c are constants, then the value of a can be computed at compile time.

Example: 

C
#define k 5
x = 2 * k  
y = k + 5
  
This can be computed at compile time and the values of x and y are : 
 x = 10
 y = 10

Note: Difference between Constant Propagation and Constant Folding: 

  • In Constant Propagation, the variable is substituted with its assigned constant where as in Constant Folding, the variables whose values can be computed at compile time are considered and computed. 

5. Copy Propagation: 

  • It is extension of constant propagation.
  • After a is assigned to x, use a to replace x till a is assigned again to another variable or value or expression.
  • It helps in reducing the compile time as it reduces copying.

Example : 

C
     //Before Optimization 
     c = a * b                                               
     x = a                                                  
     till                                                           
     d = x * b + 4 

    
     //After Optimization 
     d = a * b + 4

6. Common Sub Expression Elimination: 

  • In the above example, a*b and x*b is a common sub expression.

7. Dead Code Elimination: 

  •  Copy propagation often leads to making assignment statements into dead code.
  • A variable is said to be dead if it is never used after its last definition.
  • In order to find the dead variables, a data flow analysis should be done.

Example: 

8. Unreachable Code Elimination: 

  • First, Control Flow Graph should be constructed.
  • The block which does not have an incoming edge is an Unreachable code block.
  • After constant propagation and constant folding, the unreachable branches can be eliminated.
     
C++
#include <iostream>
using namespace std;

int main() {
  int num;
  num=10;
    cout << "GFG!";
    return 0;
  cout << num; //unreachable code
}
//after elimination of unreachable code
int main() {
  int num;
  num=10;
    cout << "GFG!";
    return 0;
 }

9. Function Inlining: 

  • Here, a function call is replaced by the body of the function itself.
  • This saves a lot of time in copying all the parameters, storing the return address, etc.

10. Function Cloning: 

  • Here, specialized codes for a function are created for different calling parameters.
  • Example: Function Overloading

11. Induction Variable and Strength Reduction: 

  • An induction variable is used in the loop for the following kind of assignment i = i + constant. It is a kind of Loop Optimization Technique. 
  • Strength reduction means replacing the high strength operator with a low strength.

Examples: 

C
Example 1 : 
Multiplication with powers of 2 can be replaced by shift left operator which is less 
expensive than multiplication
a=a*16 
// Can be modified as : 
a = a<<4

Example 2 : 
i = 1;                                                                      
while (i<10)                                                          
{                                                                             
   y = i * 4; 
}


//After Reduction
i = 1
t = 4
{ 
  while( t<40) 
  y = t; 
  t = t + 4;
}

Loop Optimization Techniques: 

1. Code Motion or Frequency Reduction: 

  • The evaluation frequency of expression is reduced.
  • The loop invariant statements are brought out of the loop. 

Example: 

C
      a = 200;
       while(a&gt;0)
       {
           b = x + y;
           if (a % b == 0)
           printf(“%d”, a);
         }


      //This code can be further optimized as
      a = 200;
      b = x + y;
      while(a&gt;0)
       {
           if (a % b == 0}
           printf(“%d”, a);
         }

2. Loop Jamming: 

  • Two or more loops are combined in a single loop. It helps in reducing the compile time.

Example: 

C
// Before loop jamming
for(int k=0;k<10;k++)
{
 x = k*2;
}

for(int k=0;k<10;k++)
{
 y = k+3;
}

//After loop jamming
for(int k=0;k<10;k++)
{
 x = k*2;
 y = k+3;
}

3. Loop Unrolling: 

  • It helps in optimizing the execution time of the program by reducing the iterations.
  • It increases the program’s speed by eliminating the loop control and test instructions.

Example: 

C
//Before Loop Unrolling 

for(int i=0;i<2;i++)
{
  printf("Hello");
}

//After Loop Unrolling

printf("Hello");
printf("Hello");

Where to apply Optimization? 

Now that we learned the need for optimization and its two types,now let’s see where to apply these optimization.

  • Source program: Optimizing the source program involves making changes to the algorithm or changing the loop structures. The user is the actor here.
  • Intermediate Code: Optimizing the intermediate code involves changing the address calculations and transforming the procedure calls involved. Here compiler is the actor.
  • Target Code: Optimizing the target code is done by the compiler. Usage of registers, and select and move instructions are part of the optimization involved in the target code.
  • Local Optimization: Transformations are applied to small basic blocks of statements. Techniques followed are  Local Value Numbering and Tree Height Balancing.
  • Regional Optimization: Transformations are applied to Extended Basic Blocks. Techniques followed are Super Local Value Numbering and Loop Unrolling.
  • Global Optimization: Transformations are applied to large program segments that include functions, procedures, and loops. Techniques followed are Live Variable Analysis and Global Code Replacement.
  • Interprocedural Optimization:  As the name indicates, the optimizations are applied inter procedurally. Techniques followed are Inline Substitution and Procedure Placement.

Advantages of Code Optimization:

Improved performance: Code optimization can result in code that executes faster and uses fewer resources, leading to improved performance.

Reduction in code size: Code optimization can help reduce the size of the generated code, making it easier to distribute and deploy.

Increased portability: Code optimization can result in code that is more portable across different platforms, making it easier to target a wider range of hardware and software.

Reduced power consumption: Code optimization can lead to code that consumes less power, making it more energy-efficient.

Improved maintainability: Code optimization can result in code that is easier to understand and maintain, reducing the cost of software maintenance.

Disadvantages of Code Optimization:

Increased compilation time: Code optimization can significantly increase the compilation time, which can be a significant drawback when developing large software systems.

Increased complexity: Code optimization can result in more complex code, making it harder to understand and debug.

Potential for introducing bugs: Code optimization can introduce bugs into the code if not done carefully, leading to unexpected behavior and errors.

Difficulty in assessing the effectiveness: It can be difficult to determine the effectiveness of code optimization, making it hard to justify the time and resources spent on the process.



Previous Article
Next Article

Similar Reads

Machine Independent Code optimization in Compiler Design
Machine Independent code optimization tries to make the intermediate code more efficient by transforming a section of code that doesn't involve hardware components like CPU registers or any absolute memory location. Generally, it optimizes code by eliminating redundancies, reducing the number of lines in code, eliminating useless code or reducing t
7 min read
Common Subexpression Elimination - Code optimization Technique in Compiler Design
Code Optimization Technique is an approach to enhance the performance of the code by either eliminating or rearranging the code lines. Code Optimization techniques are as follows: Compile-time evaluation Common Sub-expression elimination Dead code elimination Code movement Strength reductionCommon Sub-expression Elimination:The expression or sub-ex
2 min read
Incremental Compiler in Compiler Design
Incremental Compiler is a compiler that generates code for a statement, or group of statements, which is independent of the code generated for other statements. Examples : C/C++ GNU Compiler, Java eclipse platform, etc. The Incremental Compiler is such a compilation scheme in which only modified source text gets recompiled and merged with previousl
5 min read
Peephole Optimization in Compiler Design
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
2 min read
Loop Optimization in Compiler Design
Loop Optimization is the process of increasing execution speed and reducing the overheads associated with loops. It plays an important role in improving cache performance and making effective use of parallel processing capabilities. Most execution time of a scientific program is spent on loops. Loop Optimization is a machine independent optimizatio
4 min read
Need for Intermediate Code and Code Optimization
Intermediate Code : Intermediate Code are machine independent code, but they are close to machine instruction. Syntax tree, Postfix notation, 3-address code, DAG can be used as intermediate language. Need for Intermediate Code: Suppose we have x no of the source language and y no of the target language: Without ICG - we have to change each source l
3 min read
Advantages of Multipass Compiler Over Single Pass Compiler
Programmers, write computer programs that make certain tasks easier for users. This program code is written in High-Level Programming languages like C, C++, etc. Computer device doesn't understand this language or the program written by a programmer, so the translator that translates the High-Level Program code into Machine Readable Instructions is
6 min read
Difference between Native compiler and Cross compiler
1. Native Compiler : Native compiler are compilers that generates code for the same Platform on which it runs. It converts high language into computer's native language. For example, Turbo C or GCC compiler. if a compiler runs on a Windows machine and produces executable code for Windows, then it is a native compiler. Native compilers are widely us
6 min read
Compiler Design | Detection of a Loop in Three Address Code
Prerequisite - Three address code in Compiler Loop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent actually inside the loop for an iterative program. In the case of the recursive program a block will be ther
3 min read
Target Code Generation in Compiler Design
Target code generation is the final Phase of Compiler. Input : Optimized Intermediate Representation. Output : Target Code. Task Performed : Register allocation methods and optimization, assembly level code. Method : Three popular strategies for register allocation and optimization. Implementation : Algorithms. Target code generation deals with ass
2 min read
Global Code Scheduling in Compiler Design
In the fifth phase of compiler design, code optimization is performed. There are various code optimization techniques. But the order of execution of code in a computer program also matters in code optimization. Global Code Scheduling in compiler design is the process that is performed to rearrange the order of execution of code which improves perfo
7 min read
Introduction of Object Code in Compiler Design
Let assume that, you have a c program, then you give the C program to compiler and compiler will produce the output in assembly code. Now, that assembly language code will give to the assembler and assembler is going to produce you some code. That is known as Object Code. In the context of compiler design, object code is the intermediate code that
7 min read
Intermediate Code Generation in Compiler Design
In the analysis-synthesis model of a compiler, the front end of a compiler translates a source program into an independent intermediate code, then the back end of the compiler uses this intermediate code to generate the target code (which can be understood by the machine). The benefits of using machine-independent intermediate code are: Because of
5 min read
Three address code in Compiler
Prerequisite – Intermediate Code Generation  Three address code is a type of intermediate code which is easy to generate and can be easily converted to machine code. It makes use of at most three addresses and one operator to represent an expression and the value computed at each instruction is stored in temporary variable generated by compiler. Th
4 min read
Frequency Reduction in Code Optimization
Prerequisite - Compiler Design | Code Optimization Frequency reduction is a type in loop optimization process which is machine independent. In frequency reduction code inside a loop is optimized to improve the running time of program. Frequency reduction is used to decrease the amount of code in a loop. A statement or expression, which can be moved
2 min read
Machine Dependent and Machine Independent Code Optimization
What is Machine Dependent? In computing, machine dependent refers to features of a program or system that are specific to a particular hardware platform or operating system, and are not portable across different hardware or software environments. For example, a machine-dependent program may use instructions or features that are specific to a partic
8 min read
Compiler Design - GATE CSE Previous Year Questions
Solving GATE Previous Year's Questions (PYQs) not only clears the concepts but also helps to gain flexibility, speed, accuracy, and understanding of the level of questions generally asked in the GATE exam, and that eventually helps you to gain good marks in the examination. Previous Year Questions help a candidate practice and revise for GATE, whic
4 min read
Syntax Directed Translation in Compiler Design
Parser uses a CFG(Context-free-Grammar) to validate the input string and produce output for the next phase of the compiler. Output could be either a parse tree or an abstract syntax tree. Now to interleave semantic analysis with the syntax analysis phase of the compiler, we use Syntax Directed Translation. Conceptually, with both syntax-directed de
5 min read
Compiler Design | Syntax Directed Definition
Prerequisite - Introduction to Syntax Analysis, Syntax Directed Translation Syntax Directed Definition (SDD) is a kind of abstract specification. It is generalization of context free grammar in which each grammar production X --&gt; a is associated with it a set of production rules of the form s = f(b1, b2, ......bk) where s is the attribute obtain
4 min read
Error Handling in Compiler Design
The tasks of the Error Handling process are to detect each error, report it to the user, and then make some recovery strategy and implement them to handle the error. During this whole process processing time of the program should not be slow. Functions of Error Handler: Error DetectionError ReportError RecoveryError handler=Error Detection+Error Re
7 min read
Synthesis Phase in Compiler Design
Pre-requisites: Phases of a Compiler The synthesis phase, also known as the code generation or code optimization phase, is the final step of a compiler. It takes the intermediate code generated by the front end of the compiler and converts it into machine code or assembly code, which can be executed by a computer. The intermediate code can be in th
4 min read
Labeling Algorithm in Compiler Design
Labeling algorithm is used by compiler during code generation phase. Basically, this algorithm is used to find out how many registers will be required by a program to complete its execution. Labeling algorithm works in bottom-up fashion. We will start labeling firstly child nodes and then interior nodes. Rules of labeling algorithm are: Traverse th
3 min read
Transition diagram for Identifiers in Compiler Design
Transition diagram is a special kind of flowchart for language analysis. In transition diagram the boxes of flowchart are drawn as circle and called as states. States are connected by arrows called as edges. The label or weight on edge indicates the input character that can appear after that state. Transition diagram of identifier is given below: T
4 min read
Input Buffering in Compiler Design
The lexical analyzer scans the input from left to right one character at a time. It uses two pointers begin ptr(bp) and forward ptr(fp) to keep track of the pointer of the input scanned. Input buffering is an important concept in compiler design that refers to the way in which the compiler reads input from the source code. In many cases, the compil
5 min read
Bootstrapping in Compiler Design
Bootstrapping is a process in which simple language is used to translate more complicated program which in turn may handle for more complicated program. This complicated program can further handle even more complicated program and so on. Writing a compiler for any high level language is a complicated process. It takes lot of time to write a compile
4 min read
Types of Parsers in Compiler Design
The parser is that phase of the compiler which takes a token string as input and with the help of existing grammar, converts it into the corresponding Intermediate Representation(IR). The parser is also known as Syntax Analyzer. Types of Parser: The parser is mainly classified into two categories, i.e. Top-down Parser, and Bottom-up Parser. These a
2 min read
Semantic Analysis in Compiler Design
Semantic Analysis is the third phase of Compiler. Semantic Analysis makes sure that declarations and statements of program are semantically correct. It is a collection of procedures which is called by parser as and when required by grammar. Both syntax tree of previous phase and symbol table are used to check the consistency of the given code. Type
2 min read
Error Recovery Strategies in Compiler Design
The error may occur at various levels of compilation, so error handling is important for the correct execution of code. There are mainly five error recovery strategies, which are as follows: Panic modePhrase level recoveryError productionGlobal correctionSymbol tablePanic Mode:This strategy is used by most parsing methods. In this method of discove
4 min read
BNF Notation in Compiler Design
BNF stands for Backus Naur Form notation. It is a formal method for describing the syntax of programming language which is understood as Backus Naur Formas introduced by John Bakus and Peter Naur in 1960. BNF and CFG (Context Free Grammar) were nearly identical. BNF may be a meta-language (a language that cannot describe another language) for prima
3 min read
Parse Tree in Compiler Design
Here we will study the concept and uses of Parse Tree in Compiler Design. First, let us check out two terms : Parse : It means to resolve (a sentence) into its component parts and describe their syntactic roles or simply it is an act of parsing a string or a text.Tree: A tree may be a widely used abstract data type that simulates a hierarchical tre
2 min read
Article Tags :
three90RightbarBannerImg