A rewrite rule is a pair of circuits on the same qubits with (up to phase) and . A peephole optimizer repeatedly finds an occurrence of some in the circuit, where an occurrence may be spread out in time provided the gates between its parts commute past them, and replaces it with . Typical rules: cancel (for example two adjacent CNOTs or Hadamards on the same qubits); merge , moving through CNOT controls; and resynthesise a maximal two-qubit block with the three-CNOT construction when that is cheaper.
A template is a circuit implementing the identity. Any occurrence of (with more than half of 's gates) can be replaced by , which is shorter (Maslov et al.). Finding all maximal matches of a pattern in a circuit modulo commutation is itself an algorithmic problem; Iten et al. give an exact algorithm that is polynomial in the circuit size for a fixed pattern size. Rule-based optimizers with continuous rotation angles, phase-polynomial resynthesis and floating rotations are described by Nam et al..
Local rewriting always terminates when each step strictly lowers an integer cost, but it finds only local optima: the final circuit depends on the order in which rules are applied.