Based on https://github.com/solson/miri/pull/493 but there were more conflicts than code so I opted not to cherry-pick.