Currently implemented algorithm doesn't work well for me, because my linker scripts put RW or RWX sections first. For example
SECTIONS { .rwx : { *(.rwx) } /* RWX sections go here */ .ro : { *(.ro) } /* RO sections go after RWX */ }
If there is any RO orphan section in linked image it will be placed before RWX sections and produce extra PT_LOAD. This doesn't match nor gold nor ld behavior.
The approach I'm currently using (and one this patch implements) is to first find sections which can share same PT_LOAD with some orphan section. If such sections have been found they are compared with orphan section using compareSectionsNonScript<ELFT>() and best insertion position is chosen. If no section has equal access attributes then insertion position is found using current algorithm (insert before first section which is greater in sort order).
I don't know if this is right way to go, but this works much better for me (I don't have to edit scripts and results match ld/gold)
This needs to be updated.