a = 5-b*2
we see that produces:
$N1 = b * 2
$N2 = 5 - $N1
a = $N2
PIR allows memory instructions involving
three arguments like a = b + c.
This fact and the observation that $N2
is used only once
lead us to conclude that
the former translation can be changed to:
$N1 = b * 2
a = 5 - $N1
Perl regular expressions constitute a formidable
tool to implement peephole optimization. The
regexp below finds patterns
$N# = something
IDENT = $N#
and substitutes them by IDENT = something:
sub peephole_optimization {
$_[0] =~ s{
(\$N\d+)\s*=\s*(.*\n)\s* # $N#num = ... something ...
([a-zA-Z_]\w*)\s*=\s*\1 # IDENTIFIER = $N#num
}
{$3 = $2}gx; # IDENTIFIER = ... something ...
}