Peephole optimization is an optimization technique performed on a small set of compiler-generated instructions, known as a peephole or window,[1][2] that involves replacing the instructions with a logically equivalent set that has better performance.
For example:
Instead of pushing a register onto the stack and then immediately popping the value back into the register, remove both instructions
Instead of multiplying x by 2, do x + x
Instead of multiplying a floating point register by 8, add 3 to the floating point register's exponent
The term peephole optimization was introduced by William Marshall McKeeman in 1965.[3]
Replacements
Peephole optimization replacements include but are not limited to:[4]
Null sequences – Delete useless operations
Combine operations – Replace several operations with one equivalent
Algebraic laws – Use algebraic laws to simplify or reorder instructions
Special case instructions – Use instructions designed for special operand cases
Address mode operations – Use address modes to simplify code
can be replaced with the following which executes faster:
aload 1
dup
mul
As for most peephole optimizations, this is based on the relative efficiency of different instructions. In this case, dup (which duplicates and pushes the top of the stack) is known/assumed to be more efficient than aload (which loads a local variable and pushes it onto the stack).
MOVb,R0; Copy b to the registerADDc,R0; Add c to the register, the register is now b+cMOVR0,a; Copy the register to aMOVa,R0; Copy a to the registerADDe,R0; Add e to the register, the register is now a+e [(b+c)+e]MOVR0,d; Copy the register to d
but can be optimized to:
MOVb,R0; Copy b to the registerADDc,R0; Add c to the register, which is now b+c (a)MOVR0,a; Copy the register to aADDe,R0; Add e to the register, which is now b+c+e [(a)+e]MOVR0,d; Copy the register to d
Removing redundant stack instructions
If the compiler saves registers on the stack before calling a subroutine and restores them when returning, consecutive calls to subroutines may have redundant stack instructions.
Suppose the compiler generates the following Z80 instructions for each procedure call:
The sequence POP regs followed by PUSH for the same registers is generally redundant. In cases where it is redundant, a peephole optimization would remove these instructions. In the example, this would cause another redundant POP/PUSH pair to appear in the peephole, and these would be removed in turn. Assuming that subroutine _ADDR2 does not depend on previous register values, removing all of the redundant code in the example above would eventually leave the following code: