1. Home
  2. Explore
  3. Computer Science
  4. Compiler Components Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Compiler Components Overview

Overview of Compilers

A compiler translates a program written in a high-level programming language into machine-executable code. Compilation is not usually performed in one direct step. Instead, the compiler passes the program through several phases, each of which transforms or analyzes the program in a different way.

A useful conceptual model divides an optimizing compiler into three major parts:

  1. Front end — analyzes the source program and produces an intermediate representation.

  2. Optimizer — transforms the intermediate representation to improve code quality.

  3. Back end — converts the intermediate representation into code for a specific target machine.

The front end determines what the program means, the optimizer improves how it can be implemented, and the back end produces code for a particular processor.

This three-part division is a conceptual model rather than a requirement for every compiler. Actual compilers may use different designs, combine phases, or divide them into separate programs. Some compilers have separate executables for the front end, optimizer, and back end, connected by a driver; others integrate several or all phases into one program.


The Role of Algorithms in Compilation

A compiler overview focuses on what each phase does. A detailed study of compiler construction focuses on how each phase performs its work.

In computer science, the answer to a “how” question is generally an algorithm:

  • Scanning asks how to divide a character sequence into tokens.

  • Parsing asks how to determine whether tokens form a valid program structure.

  • Semantic analysis asks how to check meaning and relationships between program components.

  • Optimization asks how to transform code without changing its meaning.

  • Code generation asks how to select and organize machine instructions.

Each phase therefore involves algorithms and data structures designed for a particular type of analysis or transformation.


The Compiler Pipeline

A high-level program is gradually converted into increasingly concrete forms.

For example, a statement such as:

X = A + B

may pass through representations such as:

  1. A sequence of source characters.

  2. A sequence of tokens.

  3. A syntax tree.

  4. An intermediate representation.

  5. Abstract assembly instructions using virtual registers.

  6. Target-specific machine instructions.

  7. Instructions using physical registers and actual memory addresses.

The compiler does not generally translate directly from source code to final machine code in a single step. Multiple intermediate stages make the translation manageable and allow the compiler to perform analysis and optimization.


Intermediate Representations

An intermediate representation, or IR, is a form used inside the compiler to represent the program between the source language and the target machine language.

The compiler may use several different intermediate representations during compilation. A representation that is convenient for syntax analysis may not be the best representation for optimization or code generation.

Abstract Syntax Tree

An abstract syntax tree, or AST, represents the logical structure of a program while omitting unnecessary surface details such as punctuation and formatting.

For the expression:

X = A + B

the AST represents:

  • An assignment operation.

  • An addition operation on the right-hand side.

  • Variables AAA and BBB as operands.

  • Variable XXX as the assignment destination.

Conceptually, the structure is:

Assignment
├── X
└── Addition
    ├── A
    └── B

The AST captures the operations and their relationships. It does not need to preserve the exact original arrangement of characters once the relevant structure has been identified.

An AST is only one possible intermediate representation. A compiler may later convert it into a linear intermediate representation, such as a sequence of intermediate instructions.


From an Expression to Assembly

A high-level statement such as:

X = A + B

can be represented conceptually by assembly-like operations:

  1. Load AAA into a register.

  2. Load BBB into another register.

  3. Add the two registers.

  4. Store the result into XXX.

A possible abstract sequence is:

LOAD A, R1
LOAD B, R2
ADD R1, R2, R3
STORE R3, X

The exact syntax and instruction set depend on the target processor. At this conceptual level, the important point is the sequence of required operations rather than the precise assembly-language notation.


The Front End

The front end converts source code into an intermediate representation, such as an AST. It determines whether the program is correctly formed and meaningful according to the rules of the programming language.

The main front-end phases are:

  1. Scanning, also called lexing or lexical analysis.

  2. Parsing, also called syntactic analysis.

  3. Semantic analysis.

The front end produces a valid intermediate representation only if the program successfully passes all three phases.


1. Scanning or Lexical Analysis

Purpose of Scanning

Scanning is the low-level analysis of the input program. The scanner views the entire program as one long sequence of characters—a single large string, regardless of whether the program contains a few lines or millions of lines.

Its task is to divide this character sequence into meaningful units called:

  • Tokens

  • Lexemes

A token is a recognized category of input, while a lexeme is the actual character sequence belonging to that category.

For example, given:

X12 = A3 + B45;

the scanner identifies units such as:

  • X12 — identifier

  • = — assignment operator

  • A3 — identifier

  • + — addition operator

  • B45 — identifier

  • ; — statement terminator

The scanner does not determine whether the entire sequence forms a valid statement. It only identifies the individual parts.

How Token Boundaries Are Determined

The scanner determines where one token ends and another begins using the rules of the programming language.

For example, an identifier might be defined as a sequence of letters and digits, possibly subject to additional restrictions. The equal sign is not allowed as part of an identifier, so the scanner recognizes that:

X12

ends when it encounters:

=

The scanner can usually recognize the boundary even when spaces are omitted:

X12=A3+B45;

Whitespace often makes source code easier for humans to read and may simplify scanning, but many programming languages do not require spaces around operators.

Token Categories

A programming language defines lexical rules for categories such as:

  • Identifiers

  • Keywords

  • Numeric literals

  • String literals

  • Operators

  • Punctuation

  • Comments

  • Delimiters

For instance, an identifier rule may allow letters and digits but exclude operators such as = and +.

The scanner also recognizes that a sequence such as:

= A3

does not form one valid token if the language has no lexical rule beginning with an equal sign and continuing with an identifier. Instead, it identifies = and A3 as separate tokens.

Formal Tools Used in Scanning

Lexical rules are commonly described using regular expressions. A regular expression specifies the character patterns that form valid tokens.

For example, a simplified identifier rule might allow:

  • A letter as the first character.

  • Letters and digits as later characters.

The implementation of these rules commonly uses finite automata, computational models that process an input string one character at a time and determine whether it matches a permitted pattern.

The relationship is:

  • Regular expressions describe token patterns.

  • Finite automata implement or recognize those patterns.

  • Scanners use these rules to convert characters into tokens.

Scanning answers: “What are the words in this program?”


2. Parsing or Syntactic Analysis

Purpose of Parsing

Parsing takes the token sequence produced by the scanner and determines whether the tokens form valid structures according to the programming language’s syntax.

The scanner produces words; the parser builds sentences out of those words.

The analogy is:

  • Human language word → Programming-language token or lexeme

  • Human language sentence → Programming-language statement

For example, scanning might produce the categories:

identifier = identifier + identifier ;

Parsing determines whether this sequence matches a valid statement structure.

Grammars

The syntax of a programming language is defined using a grammar. A grammar consists of rules describing how valid statements and expressions can be constructed.

A grammar might contain a rule conceptually equivalent to:

assignment_statement → identifier = expression ;

Other rules define what counts as a valid expression, such as:

expression → identifier
expression → expression + expression
expression → expression * expression

The actual grammar must also specify precedence, associativity, grouping, declarations, control structures, function calls, and other language constructs.

Syntax Errors

A sequence may consist entirely of valid tokens but still be syntactically invalid.

For example:

X = A + B * ;

contains recognizable identifiers and operators, but it does not form a valid expression because the multiplication operator lacks a proper operand.

The parser reports a syntax error when the token sequence does not match any valid grammar rule.

Constructing the Syntax Tree

Besides checking syntax, the parser generally builds a structural representation such as a parse tree or AST.

For:

X = A + B;

the parser identifies:

  • The statement as an assignment.

  • XXX as the destination identifier.

  • A+BA + BA+B as the expression being assigned.

  • AAA and BBB as operands of the addition operation.

The AST preserves the meaningful relationships between the operations and operands while omitting unnecessary grammatical details.

Formal Tools Used in Parsing

Parsing is based on grammars and parsing algorithms. Different grammar types and algorithms support different language features and implementation strategies.

The central relationship is:

  • Grammar — defines valid program structures.

  • Parser — checks whether tokens satisfy the grammar.

  • AST or parse tree — records the recognized structure.

Parsing answers: “Do these words form a valid sentence in the programming language, and what is its structure?”


3. Semantic Analysis

Purpose of Semantic Analysis

A program can be lexically correct and syntactically correct but still fail to make sense.

This distinction also exists in human language. A sentence such as:

“The room drives the car.”

may be grammatically valid but semantically unusual or meaningless because a room cannot normally drive a car.

Programming languages have analogous restrictions. A statement may match the grammar but still be invalid because its operations do not make sense for the involved data.

Type Consistency

A major responsibility of semantic analysis is checking type consistency.

Consider:

X = A + B;

This statement is meaningful if:

  • AAA, BBB, and XXX are all integers.

  • The language defines addition for the types of AAA and BBB.

  • The result of the addition can be assigned to XXX.

It may be invalid if:

  • AAA is an object of class Student.

  • BBB is an object of class Car.

  • XXX is an integer.

  • The language does not define addition between a student and a car or assignment of the result to an integer.

The syntax remains correct because the token sequence has the expected form. However, the statement is semantically invalid because the types do not support the requested operations.

Why Code Generation Requires Semantic Validity

The compiler can generate machine code only for operations that have a defined meaning.

For example, machine instructions may support integer addition and floating-point addition, but they do not inherently provide a meaningful operation for adding arbitrary unrelated objects. If the language does not define such an operation, the compiler cannot translate it into valid machine instructions.

Semantic analysis therefore determines whether a syntactically valid program has an interpretation that the compiler can implement.

Local and Global Analysis

Syntax checking is often relatively local. The parser can examine a statement and compare its structure with a grammar rule.

Semantic analysis is often more global. It may need to connect a use of a variable with a declaration that occurred much earlier in the program.

For example:

... many lines of code ...

integer A;
integer B;
integer X;

... more code ...

X = A + B;

When analyzing the assignment, the compiler must find the declarations of AAA, BBB, and XXX and determine their types. Those declarations may be far away from the statement being analyzed.

Semantic analysis may also need to check:

  • Whether a variable has been declared.

  • Whether a name is used within its scope.

  • Whether an expression’s type is compatible with an assignment destination.

  • Whether a function is called with the correct argument types.

  • Whether operators are defined for their operands.

  • Whether control-flow constructs are used legally.

  • Whether conversions are allowed.


The Symbol Table

The symbol table is a compiler data structure that stores information about identifiers declared in the program.

When the compiler processes a declaration, it creates an entry for the declared name. The entry may include:

  • The identifier’s name.

  • Its type.

  • Its scope.

  • Its storage location.

  • Whether it is a variable, function, class, or other entity.

  • Function parameter information.

  • Other attributes required by later phases.

When the compiler encounters a use of an identifier, it looks up that identifier in the symbol table. This allows the compiler to determine what the identifier refers to and whether the use is valid.

For example, when analyzing:

X = A + B;

the compiler can use the symbol table to determine:

  • What entities XXX, AAA, and BBB refer to.

  • Their declared types.

  • Whether they are visible in the current scope.

  • Where their values will eventually be stored.

The symbol table connects uses of names with the declarations and properties that give those names meaning.


Front-End Error Conditions

A program must pass each front-end phase before the compiler can produce a valid AST or equivalent IR.

Scanning Failure

A scanning error means that the character sequence contains an invalid token or an unrecognized character pattern.

Examples include:

  • An illegal character.

  • A malformed numeric literal.

  • An improperly terminated string.

  • An invalid identifier format.

Parsing Failure

A parsing error means that the tokens are valid individually but cannot be arranged into a valid language construct.

Examples include:

  • A missing operand.

  • An unmatched parenthesis.

  • An incorrectly ordered keyword.

  • An operator appearing where an expression is required.

Semantic Failure

A semantic error means that the program is structurally valid but violates meaning-related rules.

Examples include:

  • Using an undeclared variable.

  • Applying an operator to incompatible types.

  • Assigning a value to an incompatible destination.

  • Calling a function with invalid arguments.

  • Using a name outside its scope.

The compiler generally reports an error when a phase detects a violation. Only after scanning, parsing, and semantic analysis succeed can the compiler reliably continue to optimization and code generation.


Symbolic Information and Machine Code

High-level source programs contain symbolic information, including:

  • Variable names.

  • Function names.

  • Class names.

  • Labels.

  • Other programmer-defined identifiers.

For example, the names AAA, BBB, and XXX are symbolic references. They allow programmers to describe computations using meaningful names rather than physical storage locations.

Actual assembly language for a particular processor generally does not use source-level variable names as the locations of data. Instead, the compiler maps variables to:

  • Registers.

  • Memory addresses.

  • Stack-frame offsets.

  • Other target-specific storage locations.

Local Variables and Stack Frames

A common model assumes that local variables are stored in the stack frame of the current function.

Each local variable has an offset relative to a base address associated with that function’s activation record, also called its stack frame.

For example, if each variable occupies 323232 bits, the compiler might conceptually assign:

  • Variable AAA — offset 000.

  • Variable BBB — offset 444.

  • Variable CCC — offset 888.

The offsets are measured in bytes, since 323232 bits occupy 444 bytes.

The actual address of a variable is calculated relative to the base address of the current stack frame. The base is often accessed through a pointer to the current activation record.

Thus, an abstract reference to AAA may eventually become an address of the form:

base address of current stack frame+offset of A\text{base address of current stack frame} + \text{offset of } Abase address of current stack frame+offset of A

The precise representation depends on the target architecture and calling convention.

Preserving Symbolic Information for Debugging

For pure code generation, the compiler does not necessarily need to preserve source-level variable names after building an AST or another suitable IR. It could replace names with internal nodes, storage locations, or other representations.

In practice, compilers often preserve symbolic information throughout much of compilation because of debugging.

A debugger needs to display information in source-level terms, such as:

  • The current line of source code.

  • The value of variable XXX.

  • The location of a function.

  • The relationship between machine instructions and source statements.

The compiler therefore maintains mappings between source-level names and the generated code or storage locations. Without this information, debugging compiled programs would be substantially more difficult.


The Optimizer

The optimizer operates on an intermediate representation after the front end has established that the program is valid.

Its purpose is to apply transformations that may improve:

  • Execution speed.

  • Code size.

  • Energy efficiency.

  • Register usage.

  • Memory behavior.

  • Other aspects of generated code quality.

In principle, most optimizer transformations should be machine independent. This means that the transformation is expressed in terms of the program’s logical or intermediate representation rather than the details of a particular processor.

However, complete machine independence is difficult to achieve. The usefulness of an optimization can depend on target-machine properties such as:

  • The number of registers.

  • Cache size and organization.

  • Memory latency.

  • Instruction latency.

  • Available instruction forms.

  • Processor pipeline behavior.

Therefore, practical optimizers often include machine-specific parameters even when the transformations are conceptually general.


Common Subexpression Elimination

Common subexpression elimination is an optimization that identifies an expression computed more than once and attempts to reuse its result.

Consider:

X = A + B + C;
Y = D / (A + B);

The subexpression A+BA + BA+B appears in both statements. The compiler may transform the code into:

T = A + B;
X = T + C;
Y = D / T;

The intended benefit is that A+BA + BA+B is computed once rather than twice.

Why the Transformation May Help

If the value of TTT remains readily available in a register, reusing it may avoid a second addition. This can reduce the number of executed instructions.

Why the Transformation Is Not Always Better

An optimization is not automatically beneficial in every situation. The new temporary TTT must be stored somewhere, and retaining it may create costs.

Potential disadvantages include:

  • If TTT is stored in memory, later uses require memory loads.

  • A memory load may be much slower than recomputing a simple addition.

  • If TTT is in the cache, accessing it may still take longer than performing the addition.

  • If TTT occupies a register for a long time, another variable may be forced out of a register and into memory.

  • Register pressure may increase.

  • The additional lifetime of TTT may interfere with other optimizations.

A simple addition may execute in very few processor cycles, while retrieving a value from memory can be far more expensive. Consequently, common subexpression elimination is most helpful when the reused value can remain in a register or otherwise be accessed cheaply.

Compiler optimizations are heuristic improvements, not universal guarantees. A transformation that improves one aspect of performance can worsen another.

Machine Dependence in Optimization

Common subexpression elimination appears machine independent because it concerns the logical expression structure. However, its actual benefit depends on the target machine’s resources.

For example:

  • A processor with many registers may keep TTT in a register easily.

  • A processor with few registers may need to spill TTT to memory.

  • A machine with fast memory access may tolerate the additional load.

  • A machine with slow memory access may benefit more from recomputing the expression.

This is why real optimizers often use target-dependent information even when their transformations are designed to be generally applicable.


The Back End

The back end is the part of the compiler that is most directly dependent on the target machine. It converts an intermediate representation into actual instructions for a specific processor architecture.

Major back-end responsibilities include:

  1. Instruction selection

  2. Register allocation

  3. Instruction scheduling

The back end may also handle other target-specific tasks, such as instruction encoding, calling conventions, data layout, and address formation.

Many compilers support multiple target machines. For example, a single compiler may generate code for:

  • Intel x86 processors.

  • ARM processors.

  • GPUs.

  • Embedded processors.

  • Other architectures.

A multi-target compiler may organize its back end into:

  • General components shared across processors.

  • Target-specific components for each architecture.

This design allows a common front end and optimizer to support several machine-code targets while using different instruction-generation strategies for each one.


Instruction Selection

Purpose

Instruction selection chooses actual target-machine instructions that implement the operations in the intermediate representation.

Consider:

X = A * B + C * D;

Its AST contains:

  • A multiplication of AAA and BBB.

  • A multiplication of CCC and DDD.

  • An addition of the two products.

  • An assignment of the final result to XXX.

A simple abstract assembly sequence might be:

LOAD A, R1
LOAD B, R2
MUL R1, R2, R3

LOAD C, R4
LOAD D, R5
MUL R4, R5, R6

ADD R3, R6, R7
STORE R7, X

This sequence assumes that the compiler can use as many registers as necessary. At this stage, the registers are often virtual registers, not actual processor registers.

Generic and Target-Specific Instructions

A compiler may first generate a simple, generic form of assembly resembling a reduced instruction set. Such instructions commonly include:

  • Loads.

  • Stores.

  • Arithmetic operations.

  • Basic control-flow operations.

The compiler then selects actual target instructions.

Some processors provide complex instructions that operate directly on memory operands. On such a machine, the sequence:

  1. Load AAA.

  2. Load BBB.

  3. Multiply the loaded values.

might be replaced by a single instruction that multiplies values directly from memory and places the result in a register or another memory location.

The best choice depends on the target processor’s instruction set and performance characteristics.

Instruction selection chooses the most appropriate real instruction sequence for implementing each intermediate operation.


Virtual and Physical Registers

Before register allocation, the compiler often behaves as though it has an unlimited number of registers. This simplifies the generation of intermediate code.

For example, the compiler may use:

R1, R2, R3, R4, R5, R6, R7

even if the actual processor has far fewer registers.

These are virtual registers. They are temporary names used in an intermediate representation and do not necessarily correspond to physical hardware registers.

A real processor has a finite set of physical registers. The compiler must eventually map every virtual register to one of these physical registers or to a memory location.


Register Allocation

Register allocation assigns virtual registers to the limited physical registers available on the target processor.

For example, several virtual registers may need to be mapped onto a smaller set of physical registers. If too many values are needed at once, some values must be moved to memory. This process is called spilling.

Register allocation must consider:

  • Which values are simultaneously needed.

  • How long each value remains live.

  • Which values interfere with one another.

  • The number of physical registers.

  • The cost of moving values between registers and memory.

Keeping a frequently used value in a register is generally faster than repeatedly loading it from memory. However, assigning a register to one value may prevent another value from using that register.

The compiler therefore attempts to use registers for the values whose register residence is likely to provide the greatest benefit.

Register allocation maps unlimited-looking virtual registers in intermediate code onto a finite set of physical registers and memory locations.


Instruction Scheduling

Purpose

Instruction scheduling determines the order in which instructions should execute.

The order produced by an earlier compiler phase may be logically correct but inefficient for the target processor. Some instructions have latency: the result is not available immediately after the instruction begins or completes.

Load instructions are a common example. After loading a value from memory, the processor may need to wait several cycles before that value can be used by a dependent arithmetic instruction.

A naive sequence might be:

LOAD A, R1
MUL R1, R2, R3

If the multiplication must wait for the load to finish, processor cycles may be wasted.

The scheduler may instead place an independent instruction between them:

LOAD A, R1
LOAD C, R4
MUL R1, R2, R3

The second load uses time that would otherwise be spent waiting for the first load. This technique is called latency hiding.

Constraints on Reordering

Instructions cannot be rearranged arbitrarily. The scheduler must preserve:

  • Data dependencies.

  • Control-flow behavior.

  • Memory ordering requirements.

  • Program semantics.

For example, an instruction that uses the result of another instruction cannot be moved before its producer. Independent instructions, however, may often be reordered to improve processor utilization.

Instruction scheduling reorders safe, independent instructions to reduce waiting and improve execution performance.


Overall Relationships Between Compiler Phases

The phases form a progression from abstract source-level concepts to concrete machine-level instructions.

Front-End Progression

  1. Scanning converts characters into tokens.

  2. Parsing converts tokens into syntactic structures.

  3. Semantic analysis checks whether those structures are meaningful.

  4. The result is an AST or another valid intermediate representation.

Optimization Progression

  1. The optimizer transforms the intermediate representation.

  2. The transformations aim to improve performance or other code properties.

  3. Their success depends partly on target-machine resources and behavior.

Back-End Progression

  1. Instruction selection chooses target instructions.

  2. Register allocation maps virtual registers to physical registers.

  3. Instruction scheduling orders the instructions to make effective use of the processor.

The compiler gradually replaces:

  • Source characters with tokens.

  • Tokens with structured operations.

  • Structured operations with intermediate instructions.

  • Virtual resources with physical machine resources.

  • Symbolic names with registers and addresses.

The result is executable code whose behavior corresponds to the original high-level program.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent