Switch Lowering in GCC(xoranth.net)
208 points by signa11 1 day ago | 47 comments
tl;dr: GCC lowers switch statements using three main strategies: bitset tests (packing case values into a register and using the `bt` instruction), jump tables, and binary decision trees. The compiler uses dynamic programming to find optimal groupings for bitsets and jump tables, with heuristics based on case density—jump tables require roughly one case per 8 entries when optimizing for speed (one per 2 for size), while bitsets need ≤64-value ranges and ≤3 unique destinations. Anything not profitable for these optimizations falls back to a probability-balanced binary comparison tree.
HN Discussion:
  • ~Compilers should implement perfect hashing for large sparse switch tables but don't
  • ~Large switch statements cause severe compile-time issues in LLVM, pushing users to alternatives
  • ↑Decision trees can outperform jump tables in practice, supporting the article's nuance
  • •Clarifying or correcting technical details in the article (e.g., why a simplification isn't valid, possible typos)
  • ↑Switch lowering is a useful lens for understanding hardware branch prediction behavior