Partial backport of core PR11817 (commit 6f7f5bc)
Depends on D3561
Very few changes remain from this commit due to previous refactoring and
Because a lot of changes are erased by later commits, I backported it
last (it is the first commit in core PR) so that it is easier to review.