metadata: Encode attributes for const items

Fix #19773

Together with #19774 (which this is rebased on):

Fix #18156, fix #19722, fix #19185