Backport of #3888