Expression caching

improved version of #9006 (which was an improved version of #8942)
This test got moved down after the merge/cherry-pick, although I think it should be simplified like I mentioned above.