Backport of #3718