Move recipe optimizations logic to the python back-end.

This also provides a bit of a framework for writing optimizations so that
they will be easy to add in the future.