metadata: Encode attributes for const items

Fix #19773

Together with #19774 (which this is rebased on):

Fix #18156, fix #19722, fix #19185
Merge pull request #19793 from tomjakubowski/metadata-const-attrs

metadata: Encode attributes for const items

Reviewed-by: alexcrichton