---
description: What are the Phases of Compiler Design? Compiler operates in various phases each phase transforms the source program from one representation to another. Every phase takes inputs from its previous stag
title: Phases of Compiler with Example, Process &#038; Steps
image: https://www.guru99.com/images/phases-of-a-compiler.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Phases of Compiler describe how a compiler transforms source code into machine code through six stages: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation, supported by symbol table management and error handling throughout.

* 🔤 **Lexical Analysis:** The first phase scans source code and groups characters into tokens, filling the symbol table.
* 🌳 **Syntax Analysis:** Tokens are checked against grammar rules and arranged into a parse tree.
* ✅ **Semantic Analysis:** The compiler verifies type compatibility and meaning using the syntax tree and symbol table.
* 🔁 **Intermediate Code:** A machine-independent representation, such as three-address code, is generated for easy translation.
* ⚡ **Optimization:** Redundant and unreachable code is removed to make the program faster and smaller.
* 🖥️ **Code Generation:** The final phase converts optimized code into target machine code, allocating registers and memory.

[ Read More ](javascript:void%280%29;) 

![](https://www.guru99.com/images/phases-of-a-compiler.png)

## What are the Phases of Compiler Design?

**Compiler** operates in various phases each phase transforms the source program from one representation to another. Every phase takes inputs from its previous stage and feeds its output to the next phase of the compiler.  
There are 6 phases in a compiler. Each of this phase help in converting the high-level langue the machine code. The phases of a compiler are:

1. Lexical analysis
2. Syntax analysis
3. Semantic analysis
4. Intermediate code generator
5. Code optimizer
6. Code generator

[](https://www.guru99.com/images/1/020819%5F1119%5FPhasesofCom1.png)

Phases of Compiler

All these phases convert the source code by dividing into tokens, creating parse trees, and optimizing the source code by different phases.

## Phase 1: Lexical Analysis

Lexical Analysis is the first phase when compiler scans the source code. This process can be left to right, character by character, and group these characters into tokens.  
Here, the character stream from the source program is grouped in meaningful sequences by identifying the tokens. It makes the entry of the corresponding tickets into the symbol table and passes that token to next phase.  
The primary functions of this phase are:

* Identify the lexical units in a source code
* Classify lexical units into classes like constants, reserved words, and enter them in different tables. It will Ignore comments in the source program
* Identify token which is not a part of the language

**Example**:  
x = y + 10

Tokens

| X  | identifier          |
| -- | ------------------- |
| \= | Assignment operator |
| Y  | identifier          |
| +  | Addition operator   |
| 10 | Number              |

## Phase 2: Syntax Analysis

Syntax analysis is all about discovering structure in code. It determines whether or not a text follows the expected format. The main aim of this phase is to make sure that the source code was written by the programmer is correct or not.  
Syntax analysis is based on the rules based on the specific programing language by constructing the parse tree with the help of tokens. It also determines the structure of source language and grammar or syntax of the language.  
Here, is a list of tasks performed in this phase:

* Obtain tokens from the lexical analyzer
* Checks if the expression is syntactically correct or not
* Report all syntax errors
* Construct a hierarchical structure which is known as a parse tree

### Example

Any identifier/number is an expression  
If x is an identifier and y+10 is an expression, then x= y+10 is a statement.  
Consider parse tree for the following example

(a+b)*c

[](https://www.guru99.com/images/1/020819%5F1119%5FPhasesofCom2.png)

In Parse Tree

* Interior node: record with an operator filed and two files for children
* Leaf: records with 2/more fields; one for token and other information about the token
* Ensure that the components of the program fit together meaningfully
* Gathers type information and checks for type compatibility
* Checks operands are permitted by the source language

### RELATED ARTICLES

* [What is a Compiler Design? Types, Construction Tools, Example ](https://www.guru99.com/compiler-design-tutorial.html "What is a Compiler Design? Types, Construction Tools, Example")
* [Compiler vs Interpreter – Difference Between Them ](https://www.guru99.com/difference-compiler-vs-interpreter.html "Compiler vs Interpreter – Difference Between Them")
* [Lexical Analysis (Analyzer) in Compiler Design with Example ](https://www.guru99.com/compiler-design-lexical-analysis.html "Lexical Analysis (Analyzer) in Compiler Design with Example")
* [Compiler Design Tutorial for Beginners ](https://www.guru99.com/compiler-tutorial.html "Compiler Design Tutorial for Beginners")

## Phase 3: Semantic Analysis

Semantic analysis checks the semantic consistency of the code. It uses the syntax tree of the previous phase along with the symbol table to verify that the given source code is semantically consistent. It also checks whether the code is conveying an appropriate meaning.  
Semantic Analyzer will check for Type mismatches, incompatible operands, a function called with improper arguments, an undeclared variable, etc.  
Functions of Semantic analyses phase are:

* Helps you to store type information gathered and save it in symbol table or syntax tree
* Allows you to perform type checking
* In the case of type mismatch, where there are no exact type correction rules which satisfy the desired operation a semantic error is shown
* Collects type information and checks for type compatibility
* Checks if the source language permits the operands or not

### Example

float x = 20.2;
float y = x*30;

In the above code, the semantic analyzer will typecast the integer 30 to float 30.0 before multiplication

## Phase 4: Intermediate Code Generation

Once the semantic analysis phase is over the compiler, generates intermediate code for the target machine. It represents a program for some abstract machine.  
Intermediate code is between the high-level and machine level language. This intermediate code needs to be generated in such a manner that makes it easy to translate it into the target machine code.  
**Functions on Intermediate Code generation:**

* It should be generated from the semantic representation of the source program
* Holds the values computed during the process of translation
* Helps you to translate the intermediate code into target language
* Allows you to maintain precedence ordering of the source language
* It holds the correct number of operands of the instruction

### Example

For example,

total = count + rate * 5

Intermediate code with the help of address code method is:

t1 := int_to_float(5)
t2 := rate * t1
t3 := count + t2
total := t3

## Phase 5: Code Optimization

The next phase of is code optimization or Intermediate code. This phase removes unnecessary code line and arranges the sequence of statements to speed up the execution of the program without wasting resources. The main goal of this phase is to improve on the intermediate code to generate a code that runs faster and occupies less space.  
**The primary functions of this phase are:**

* It helps you to establish a trade-off between execution and compilation speed
* Improves the running time of the target program
* Generates streamlined code still in intermediate representation
* Removing unreachable code and getting rid of unused variables
* Removing statements which are not altered from the loop

**Example:**  
Consider the following code

a = intofloat(10)
b = c * a
d = e + b
f = d

Can become

b =c * 10.0
f = e+b

## Phase 6: Code Generation

Code generation is the last and final phase of a compiler. It gets inputs from code optimization phases and produces the page code or object code as a result. The objective of this phase is to allocate storage and generate relocatable machine code.  
It also allocates memory locations for the variable. The instructions in the intermediate code are converted into machine instructions. This phase coverts the optimize or intermediate code into the target language.  
The target language is the machine code. Therefore, all the memory locations and registers are also selected and allotted during this phase. The code generated by this phase is executed to take inputs and generate expected outputs.

### Example

a = b + 60.0  
Would be possibly translated to registers.

MOVF a, R1
MULF #60.0, R2
ADDF R1, R2

## Symbol Table Management

A symbol table contains a record for each identifier with fields for the attributes of the identifier. This component makes it easier for the compiler to search the identifier record and retrieve it quickly. The symbol table also helps you for the scope management. The symbol table and error handler interact with all the phases and symbol table update correspondingly.

## Error Handling Routine

In the compiler design process error may occur in all the below-given phases:

* Lexical analyzer: Wrongly spelled tokens
* Syntax analyzer: Missing parenthesis
* Intermediate code generator: Mismatched operands for an operator
* Code Optimizer: When the statement is not reachable
* Code Generator: When the memory is full or proper registers are not allocated
* Symbol tables: Error of multiple declared identifiers

Most common errors are invalid character sequence in scanning, invalid token sequences in type, scope error, and parsing in semantic analysis.  
The error may be encountered in any of the above phases. After finding errors, the phase needs to deal with the errors to continue with the compilation process. These errors need to be reported to the error handler which handles the error to perform the compilation process. Generally, the errors are reported in the form of message.

## FAQs

🔀 What is the difference between the analysis and synthesis phases of a compiler?

The analysis phase (front end) breaks source code apart through lexical, syntax, and semantic analysis. The synthesis phase (back end) builds the target program through intermediate code generation, optimization, and code generation.

⚖️ What is the difference between a compiler and an interpreter?

A compiler translates the whole source program into machine code before running it. An interpreter translates and executes code line by line, which is easier to debug but usually slower at runtime.

🔢 What is three-address code in a compiler?

Three-address code is an intermediate representation where each instruction has at most three operands, such as t1 = a + b. It is simple to optimize and easy to translate into target machine code.

🤖 How is AI used in modern compilers?

AI and machine learning help modern compilers with smarter optimization decisions, such as choosing loop transformations, inlining, and register allocation. They predict which optimizations improve performance for a given program and target.

🤖 Can AI help you understand compiler phases?

Yes. AI can explain each phase with examples, trace how a sample statement moves from tokens to machine code, and answer follow-up questions. This makes compiler design easier for students to learn.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/phases-of-a-compiler.png","url":"https://www.guru99.com/images/phases-of-a-compiler.png","width":"700","height":"250","caption":"Phases of a Compiler","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/compiler-design","name":"Compiler Design"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html","name":"Phases of Compiler with Example, Process &#038; Steps"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html#webpage","url":"https://www.guru99.com/compiler-design-phases-of-compiler.html","name":"Phases of Compiler with Example, Process &#038; Steps","dateModified":"2026-07-02T16:49:13+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/phases-of-a-compiler.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/kaia","name":"Kaia Cerulean","description":"I am Kaia Cerulean, a Compiler Engineer, offering expert guidance on mastering compiler design and optimization through clear, practical tutorials.","url":"https://www.guru99.com/author/kaia","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/kaia-cerulean-author.png","url":"https://www.guru99.com/images/kaia-cerulean-author.png","caption":"Kaia Cerulean","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Compiler Design","headline":"Phases of Compiler with Example, Process &#038; Steps","description":"What are the Phases of Compiler Design? Compiler operates in various phases each phase transforms the source program from one representation to another. Every phase takes inputs from its previous stag","keywords":"bigdata, programming, database, server","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/kaia","name":"Kaia Cerulean"},"dateModified":"2026-07-02T16:49:13+05:30","image":{"@id":"https://www.guru99.com/images/phases-of-a-compiler.png"},"copyrightYear":"2026","name":"Phases of Compiler with Example, Process &#038; Steps","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between the front end and back end of a compiler?","acceptedAnswer":{"@type":"Answer","text":"The front end handles the source-dependent phases: lexical, syntax, and semantic analysis, plus intermediate code generation and symbol-table creation. The back end handles the target-dependent work, namely code optimization and code generation."}},{"@type":"Question","name":"What is the difference between the analysis and synthesis phases of a compiler?","acceptedAnswer":{"@type":"Answer","text":"The analysis (front-end) part breaks the source program into pieces and builds an intermediate representation, covering the first phases. The synthesis (back-end) part constructs the target program from that representation through optimization and code generation."}},{"@type":"Question","name":"What is the difference between a phase and a pass in a compiler?","acceptedAnswer":{"@type":"Answer","text":"A phase is a single logical step, such as lexical analysis. A pass is one complete scan of the source or intermediate code, and a single pass may group several phases together for efficiency."}},{"@type":"Question","name":"What is the difference between a compiler and an interpreter?","acceptedAnswer":{"@type":"Answer","text":"A compiler translates an entire program into machine code before it runs, while an interpreter executes code line by line. Compilers report all errors together, whereas interpreters stop at the first error they meet."}},{"@type":"Question","name":"Do all compilers use all six phases?","acceptedAnswer":{"@type":"Answer","text":"Not always. The six phases are a logical model. Simple compilers may merge phases, and some skip separate optimization. Production compilers often add more sub-phases, but the same core analysis and synthesis tasks still occur."}},{"@type":"Question","name":"How is AI or machine learning used in compiler design and optimization?","acceptedAnswer":{"@type":"Answer","text":"Machine learning helps compilers pick better optimization strategies, predict performance, and tune settings that once needed manual expert effort. AI models trained on large codebases can choose which optimizations improve speed on a given processor."}},{"@type":"Question","name":"Can AI assistants like GitHub Copilot or GPT explain compiler phases?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI assistants such as GitHub Copilot and GPT can explain each phase, generate example parsers, and summarize grammar rules. They speed up learning, though you should verify their output, since compiler logic must be exact."}},{"@type":"Question","name":"Will AI replace traditional compilers?","acceptedAnswer":{"@type":"Answer","text":"No. AI accelerates parts of compilation, such as optimization and code suggestions, but compilers still need precise, deterministic rules to guarantee correct machine code. AI augments compiler design rather than replacing the underlying phases."}}]}],"@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html#schema-1129719","isPartOf":{"@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/compiler-design-phases-of-compiler.html#webpage"}}]}
```
