> For the complete documentation index, see [llms.txt](https://isubasinghe.gitbook.io/isithas-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://isubasinghe.gitbook.io/isithas-wiki/computer_science/programming_language_theory/optimisations/peephole_optimisation.md).

# Peephole optimisation

## Basic idea

Slide a small window over the instruction stream and replace short patterns with cheaper equivalents (e.g. `mul x, 2` → `shl x, 1`; `mov a, b; mov b, a` → `mov a, b`). Cheap, local, and surprisingly effective at the end of the pipeline.

## Key facts

* Window typically 2-5 instructions.
* Rules are target-specific (instruction selection's afterburn).
* Modern compilers often implement these as e-graph rewrites or table-driven patterns.
