Switch Lowering in GCC
Switch lowering is the phase where GCC transforms a high‑level `switch` statement into a series of lower‑level control‑flow constructs that the backend can more easily optimise. The compiler first analyses the case values to decide whether a jump table, a binary search, or a cascade of compares will yield the best performance and smallest code size for the target architecture. This decision is driven by heuristics such as the density of case values, the range between the smallest and largest label, and the expected execution frequency of each case.
When a jump table is chosen, GCC emits a contiguous array of target addresses indexed by the switch expression, often after applying a bias to handle non‑zero lower bounds. The generated code then performs a bounds check, computes the offset, and does an indirect jump. On architectures lacking efficient indirect jumps, GCC may fall back to a series of conditional branches or a binary search tree, each branch comparing the switch value against a pivot and jumping to the appropriate subtree.
If the case values are sparse or the range is huge, GCC prefers a balanced binary search tree or a series of if‑else chains. In this mode, the compiler builds a decision tree that minimises the number of comparisons on average, sometimes using profile‑guided information to place the most likely cases near the root. The tree is emitted as a cascade of compare‑and‑branch instructions, which can be further optimised by later passes such as branch prediction hints or block layout rearrangement.
Finally, GCC’s switch‑lowering pass interacts with other optimisation stages like constant propagation, dead‑code elimination, and instruction scheduling. After the initial lowering, subsequent passes may prune unreachable case blocks, fold constant indices into direct jumps, or even replace a jump table with a simple arithmetic computation if the case values follow a predictable pattern. Understanding how GCC chooses and emits these structures can help you write switch statements that compile to efficient machine code, especially on performance‑critical embedded or low‑level systems.
Source: Switch Lowering in GCC