How does GCC decide what order to output assembly functions in?

c, gcc

Solution

The later parts of the inter-procedural optimisation phase use a bottom-up traversal of the call graph; that's the ordering that you see. There's a paper about the original design of this part of GCC here (from a while ago; this stuff first appeared in GCC 3.4).

You can prevent the reordering using `-fno-toplevel-reorder` (or `-fno-unit-at-a-time` for less recent versions of GCC), but that disables some of the related optimisations.

Problem

Reading through the assembly GCC generates for C files in my project, I notice functions are not outputted in assembly in the same order they appear in the source file. What is the goal of this reordering and what heuristics does GCC use to decide the order? (Is it just an artifact of the data structure holding functions?) This is not `-freorder-functions`, since I'm not using `-fprofile-arcs`.

Original source