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

Intermediate Code Generation in Compiler Design

Last Updated : 19 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 the machine-independent intermediate code, portability will be enhanced. For ex, suppose, if a compiler translates the source language to its target machine language without having the option for generating intermediate code, then for each new machine, a full native compiler is required. Because, obviously, there were some modifications in the compiler itself according to the machine specifications.
  • Retargeting is facilitated.
  • It is easier to apply source code modification to improve the performance of source code by optimizing the intermediate code.

1 
If we generate machine code directly from source code then for n target machine we will have optimizers and n code generator but if we will have a machine-independent intermediate code, we will have only one optimizer. Intermediate code can be either language-specific (e.g., Bytecode for Java) or language. independent (three-address code). The following are commonly used intermediate code representations:

  1. Postfix Notation:
    • Also known as reverse Polish notation or suffix notation.
    • In the infix notation, the operator is placed between operands, e.g., a + b. Postfix notation positions the operator at the right end, as in ab +.
    • For any postfix expressions e1 and e2 with a binary operator (+) , applying the operator yields e1e2+.
    • Postfix notation eliminates the need for parentheses, as the operator’s position and arity allow unambiguous expression decoding.
    • In postfix notation, the operator consistently follows the operand.
      Example 1: The postfix representation of the expression (a + b) * c is : ab + c *
      Example 2: The postfix representation of the expression (a – b) * (c + d) + (a – b) is :   ab – cd + *ab -+
      Read more: Infix to Postfix
       
  2. Three-Address Code:
    • A three address statement involves a maximum of three references, consisting of two for operands and one for the result.
    • A sequence of three address statements collectively forms a three address code.
    • The typical form of a three address statement is expressed as x = y op z, where x, y, and z represent memory addresses.
    • Each variable (x, y, z) in a three address statement is associated with a specific memory location.
    • While a standard three address statement includes three references, there are instances where a statement may contain fewer than three references, yet it is still categorized as a three address statement.
      Example: The three address code for the expression a + b * c + d : T1 = b * c T2 = a + T1 T3 = T2 + d; T 1 , T2 , T3 are temporary variables.

      There are 3 ways to represent a Three-Address Code in compiler design: 
      i) Quadruples
      ii) Triples
      iii) Indirect  Triples
      Read more: Three-address code
       

  3. Syntax Tree:
    • A syntax tree serves as a condensed representation of a parse tree.
    • The operator and keyword nodes present in the parse tree undergo a relocation process to become part of their respective parent nodes in the syntax tree. the internal nodes are operators and child nodes are operands.
    • Creating a syntax tree involves strategically placing parentheses within the expression. This technique contributes to a more intuitive representation, making it easier to discern the sequence in which operands should be processed.
    • The syntax tree not only condenses the parse tree but also offers an improved visual representation of the program’s syntactic structure,
      Example: x = (a + b * c) / (a – b * c)
       2

       

Advantages of Intermediate Code Generation:

Easier to implement: Intermediate code generation can simplify the code generation process by reducing the complexity of the input code, making it easier to implement.

Facilitates code optimization: Intermediate code generation can enable the use of various code optimization techniques, leading to improved performance and efficiency of the generated code.

Platform independence: Intermediate code is platform-independent, meaning that it can be translated into machine code or bytecode for any platform.

Code reuse: Intermediate code can be reused in the future to generate code for other platforms or languages.

Easier debugging: Intermediate code can be easier to debug than machine code or bytecode, as it is closer to the original source code.

Disadvantages of Intermediate Code Generation:

Increased compilation time: Intermediate code generation can significantly increase the compilation time, making it less suitable for real-time or time-critical applications.

Additional memory usage: Intermediate code generation requires additional memory to store the intermediate representation, which can be a concern for memory-limited systems.

Increased complexity: Intermediate code generation can increase the complexity of the compiler design, making it harder to implement and maintain.

Reduced performance: The process of generating intermediate code can result in code that executes slower than code generated directly from the source code.

 


Previous Article
Next Article

Similar Reads

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
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
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
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
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
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
Code Optimization in Compiler Design
Code optimization is a crucial phase in compiler design aimed at enhancing the performance and efficiency of the executable code. By improving the quality of the generated machine code optimizations can reduce execution time, minimize resource usage, and improve overall system performance. This process involves the various techniques and strategies
9 min read
Flow Graph in Code Generation
A basic block is a simple combination of statements. Except for entry and exit, the basic blocks do not have any branches like in and out. It means that the flow of control enters at the beginning and it always leaves at the end without any halt. The execution of a set of instructions of a basic block always takes place in the form of a sequence. T
4 min read
Introduction to Intermediate Representation(IR)
Intermediate Representation(IR), as the name suggests, is any representation of a program between the source and target languages. The intermediate form of the program that is being compiled is the central data structure in a compiler. A compiler may have a single IR or a series of IRs. The decisions that are made during the design of IR affect the
3 min read
Three address code in Compiler
TAC is an intermediate representation of three-address code utilized by compilers to ease the process of code generation. Complex expressions are, therefore, decomposed into simple steps comprising, at most, three addresses: two operands and one result using this code. The results from TAC are always stored in the temporary variables that a compile
6 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
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
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
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
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
Register Allocation Algorithms in Compiler Design
Register allocation is an important method in the final phase of the compiler . Registers are faster to access than cache memory . Registers are available in small size up to few hundred Kb .Thus it is necessary to use minimum number of registers for variable allocation . There are three popular Register allocation algorithms . Naive Register Alloc
5 min read
Language Processing System in Compiler Design
The computer is an intelligent combination of software and hardware. Hardware is simply a piece of mechanical equipment and its functions are being compiled by the relevant software. The hardware considers instructions as electronic charge, which is equivalent to the binary language in software programming. The binary language has only 0s and 1s. T
4 min read
Constant Propagation in Compiler Design
Constant Propagation is one of the local code optimization technique in Compiler Design. It can be defined as the process of replacing the constant value of variables in the expression. In simpler words, we can say that if some value is assigned a known constant, than we can simply replace the that value by constant. Constants assigned to a variabl
3 min read
Article Tags :