GCC(/Clang): Merging functions with identical instructions (COMDAT folding)

Neither GCC nor Clang is a linker, and ICF needs to be done by the linker, or at least with cooperation with the linker. Edit: They don’t do ICF, so yes, distinct instantiations produce distinct code. The GNU gold linker supports ICF with the --icf option, which needs the GCC option -ffunction-sections to be used.

Distinct functions must have distinct addresses … I can’t remember if ICF is disabled for any function that has its address taken, but if not it should be possible to put a load of no-op instructions before the combined function and make each distinct instantiation start on a different instruction, so they have different addresses. Edit: gold’s --icf=safe option only enables ICF for functions that can be proven not to have their address taken, so code that relies on distinct addresses will still work.

ICF is a neat optimization, but not essential. With a bit of effort you can hoist out non-dependent code to a non-template, or a template with fewer parameters, to reduce the quantity of duplicated code in the executable. There’s more information on this in the slides for a Diet Templates talk I did a couple of years ago.

Leave a Comment