Code optimization is the compiler phase that transforms intermediate code into an equivalent form that executes faster, uses less memory or consumes fewer resources without changing the program's meaning.
Basic Principle
An optimization must preserve the observable behavior of the source program. The optimized program should produce the same result for every valid input.
Position in Compiler
Intermediate Code
|
v
+------------------+
| Code Optimizer |
+------------------+
|
Optimized Intermediate Code
|
v
Target Code Generator
Main Objectives
Reduce execution time.
Reduce code size.
Reduce memory accesses.
Improve register utilization.
Remove unnecessary computations.
Reduce power and processor-resource usage.
Characteristics of a Good Optimizer
Preserves program meaning.
Produces measurable improvement.
Does not excessively increase compilation time.
Works for a broad class of programs.
Uses safe and predictable transformations.
Example
Before:
t1 = 2 * 3
t2 = a + 0
t3 = t1 + t2
After:
t3 = 6 + a
Constant folding and algebraic simplification remove unnecessary instructions.
Types of Optimization
Machine-independent optimization
Machine-dependent optimization
Local optimization
Global optimization
Loop optimization
Peephole optimization
Conclusion: Code optimization improves program efficiency while preserving correctness and is a major responsibility of the compiler back end.
2. Organization of Code Optimizer 14 Marks
The organization of a code optimizer describes how optimization analyses and transformations are arranged between intermediate-code generation and target-code generation.
General Organization
Source Program
|
Front End
|
Intermediate Code
|
+-------------------------------+
| Machine-Independent Optimizer |
+-------------------------------+
|
Optimized Intermediate Code
|
Code Generator
|
+-----------------------------+
| Machine-Dependent Optimizer |
+-----------------------------+
|
Target Program
Machine-Independent Optimization
These transformations do not depend on target-machine instructions.
Constant folding
Common subexpression elimination
Dead-code elimination
Copy propagation
Loop-invariant code motion
Strength reduction
Machine-Dependent Optimization
These transformations use details of the target architecture.
Register allocation
Instruction selection
Instruction scheduling
Use of special machine instructions
Peephole improvement of target code
Optimizer Components
Control-flow analyzer: constructs basic blocks and flow graphs.
Data-flow analyzer: computes reaching definitions, liveness and available expressions.
Cost estimator: estimates whether transformation is beneficial.
Optimization Levels
Level
Area
Example
Local
One basic block
Constant folding
Global
Multiple blocks in one procedure
Global common subexpression elimination
Loop
Loop body and control
Loop-invariant code motion
Interprocedural
Multiple procedures
Inlining
3. Optimization Criteria and Safety 14 Marks
Correctness Requirement
The optimizer must not change program semantics. It must preserve values, control flow, side effects and exception behavior where required by the language.
Profitability
A valid transformation is not always profitable. The compiler estimates whether it reduces execution cost or code size.
Cost Measures
Number of instructions
Number of memory accesses
Loop execution frequency
Branch cost
Register pressure
Code-size increase
Conservative Optimization
If the compiler cannot prove that a transformation is safe, it should normally avoid that transformation.
Important: Optimization should improve efficiency without changing the output, input behavior or required side effects of the program.
4. Principal Sources of Optimization 14 Marks
1. Common Subexpression Elimination
Before:
t1 = a * b
t2 = a * b + c
After:
t1 = a * b
t2 = t1 + c
2. Constant Folding
Before: x = 4 * 5
After: x = 20
3. Constant Propagation
Before:
a = 10
b = a + 5
After:
a = 10
b = 15
4. Copy Propagation
Before:
x = y
z = x + 1
After:
x = y
z = y + 1
5. Dead-Code Elimination
x = 5
x = 8
The first assignment is dead if x is not used between them.
6. Algebraic Simplification
x + 0 → x
x * 1 → x
x * 0 → 0
x - x → 0
7. Strength Reduction
x * 2 → x + x
i * 4 inside loop → incremental address update
8. Code Motion
A computation whose result does not change within a loop can be moved outside the loop.
5. Basic Blocks 14 Marks
A basic block is a maximal sequence of consecutive instructions with one entry point and one exit point.
Properties
Control enters only at the first instruction.
Control leaves only at the last instruction.
There is no branch into the middle.
There is no branch out except at the end.
All instructions execute sequentially once the block is entered.
Example
1. t1 = a + b
2. t2 = t1 * c
3. if t2 > d goto 6
4. x = t2 - d
5. goto 7
6. x = d - t2
7. y = x + 1
Exchange nested-loop order to improve memory locality.
Safety Conditions
Preserve data dependencies.
Preserve side effects.
Do not move computations that may cause exceptions incorrectly.
13. Peephole Optimization 14 Marks
Peephole optimization examines a small sliding window of consecutive target or intermediate instructions and replaces inefficient patterns with better ones.
Instructions after an unconditional jump and before the next reachable label may be removed.
Advantages
Simple implementation.
Low analysis cost.
Improves target code.
Can use machine-specific instruction patterns.
Limitations
Limited to a small instruction window.
Cannot perform broad global transformations.
Repeated passes may be needed.
14. Basic Block Optimization 14 Marks
Basic block optimization improves straight-line code within a basic block using local analysis and transformation.
Steps
Construct the basic block.
Build a DAG or value representation.
Identify common subexpressions.
Propagate constants and copies.
Remove dead assignments.
Apply algebraic simplification.
Generate an efficient instruction order.
Example
Original:
a = b + c
d = b + c
e = d * 2
f = e + 0
a = 10
Optimized:
d = b + c
e = d + d
f = e
a = 10
Transformations
Common subexpression elimination
Dead-code elimination
Reordering independent statements
Use of cheaper operators
Temporary-variable reduction
Benefits
Fewer instructions.
Reduced temporary storage.
Better register use.
Faster execution.
15. Basic Data-Flow Concepts 14 Marks
Data-flow analysis collects information about how values and definitions move through a control-flow graph.
Reaching Definitions
A definition reaches a point if there is a path from the definition to that point without another definition of the same variable.
Live Variable
A variable is live at a point if its current value may be used along some path before being redefined.
Available Expression
An expression is available at a point if it has already been computed on every path and none of its operands have changed.
Uses
Analysis
Main Use
Reaching definitions
Constant propagation and use-definition chains
Live variables
Register allocation and dead-code elimination
Available expressions
Common subexpression elimination
Very busy expressions
Code motion
IN and OUT Sets
Data-flow equations commonly compute information entering and leaving each basic block.
IN[B] = information entering block B
OUT[B] = information leaving block B
16. Basics of Code Generation 14 Marks
Code generation is the compiler phase that converts intermediate code into target assembly or machine instructions.
Inputs
Intermediate representation
Symbol-table information
Target-machine description
Main Issues
Instruction selection
Register allocation and assignment
Order of evaluation
Use of addressing modes
Storage management
Instruction scheduling
Simple Example
Three-address code:
t1 = a + b
x = t1
Possible target code:
MOV R0, a
ADD R0, b
MOV x, R0
Register Allocation
Register allocation decides which values should remain in limited processor registers. Register assignment chooses the actual register.
Desirable Properties
Correct target code
Efficient instruction sequence
Good register use
Fast code-generation process
17. Important Comparisons 14 Marks
Local vs Global Optimization
Feature
Local
Global
Scope
One basic block
Multiple basic blocks
Analysis cost
Low
Higher
Information required
Local statements
Control and data flow
Example
Constant folding
Global dead-code elimination
Machine-Independent vs Machine-Dependent Optimization
Feature
Machine Independent
Machine Dependent
Target details
Not required
Required
Applied to
Intermediate code
Target code or low-level IR
Examples
Common subexpression elimination
Register allocation, instruction scheduling
Basic Block vs Flow Graph
Basic Block
Flow Graph
Straight-line instruction sequence
Graph of basic blocks
One entry and one exit
Represents possible control transfers
Used for local optimization
Used for global optimization
Unit 5 Quick Revision
Optimization improves code without changing meaning.
Machine-independent optimization works on intermediate code.
A basic block has one entry and one exit.
Leaders identify starting instructions of basic blocks.
A flow graph represents control flow among blocks.
A DAG shares common expressions inside a block.
Back edges help identify natural loops.
Loop optimization gives major performance benefits.
Peephole optimization examines a small instruction window.
Data-flow analysis supports global optimization.
Code generation performs instruction selection and register allocation.
Important RGPV Exam Questions
Long Answer Questions
Define code optimization and explain its objectives and classifications.
Explain the organization of a code optimizer with a neat diagram.
Discuss principal sources of code optimization with examples.
Define a basic block and explain the algorithm for constructing basic blocks.
Explain flow graphs with a suitable example.
Explain DAG representation of a basic block.
Construct a DAG for a given basic block and explain its uses.
Explain local optimization techniques.
Define dominators, back edges and natural loops.
Explain loop optimization techniques with examples.
Explain peephole optimization and its transformations.
Explain basic block optimization using DAG.
Explain reaching definitions, live variables and available expressions.
Explain the basic issues in code generation.
Compare machine-independent and machine-dependent optimization.
Short Answer Questions
What is code optimization?
Define basic block.
What is a leader?
Define control-flow graph.
What is a DAG?
Define common subexpression.
What is dead code?
Define loop-invariant computation.
What is peephole optimization?
Define live variable.
Exam Strategy: For basic-block questions, first mark leaders, form blocks and then draw the flow graph. For optimization questions, always show before-and-after code.
Download Study Resources
Unit 5 PDF
Printable detailed notes will be uploaded soon.
Coming Soon
Optimization Problems
Basic block and DAG practice will be available soon.
Coming Soon
PYQ Analysis
Repeated Unit 5 questions will be added soon.
Coming Soon
Frequently Asked Questions
Its purpose is to improve execution speed, memory usage or code size without changing program behavior.
It is a maximal straight-line sequence of instructions having one entry and one exit.
A DAG identifies common subexpressions, dependencies and dead computations and supports efficient local optimization.
An edge n to d is a back edge when d dominates n. Back edges are used to identify natural loops.
It is a local method that examines a small sequence of instructions and replaces inefficient patterns with equivalent better ones.