Clean up redundant expressions, pull out loop invariants