15.1. Peephole Optimizers
Dragon Book, Section 8.7

A peephole optimizer sweeps through the code array, looking at a small window of instructions, looking for ways to improve the code.

For example, sequence

  goto 15
  label 15

can be replaced by

  label 15

Some preprocessing allows the peephole optimizer to expand its view beyond just a few contiguous instructions.

For example, a pass over the code array can locate all labels. Then, when a branch instruction is encountered, the optimizer can look at the code that follows the given label. Upon seeing

  if x = y goto 5
  …
  label 5
  goto 6

the optimizer can replace the conditional branch instruction by

  if x = y goto 6

and can look at the same instruction again, possibly leading to more changes.

A peephole optimizer can also eliminate tests with constant conditions. For example,

  if 0 = 1 goto 10

can be removed. You might expect such tests rarely to occur, but in fact they can be common.

Tracing instructions are typically protected by tests, which can check defined constants. For example, if 'tracing' is a constant that is defined to be 0, then source code

   if(tracing > 0) {
     print(…);
   }

leads to a test with a constant condition. A bit more sophisticated optimizer can also eliminate the unreachable code for the print line.