NewsCrawler.org

How GCC Lowers Switch Statements: Jump Tables, Comparison Trees, and Bitsets

The post examines how GCC translates switch statements into machine code, compiled with the -O3 optimization flag; of the strategies shown, all but bitset lowering also apply to clang. For dense case values GCC builds a jump table[1] indexed by the input, and it detects when the values are offset by a constant, adjusting the index accordingly. Experimentation puts GCC's threshold at around eight jump table entries per case label: a function with seven entries per label compiles to a jump table, while a sparser function with eight entries per label is expanded into a tree of comparisons. The author notes that one example could be simplified by dividing x by eight before the jump, a simplification GCC does not find.

GCC also recognizes dense subsets of cases: in an example with the outlier case 100, it emits a separate branch for that case but a jump table for cases 1 through 5. When case labels share the same target, the heuristic changes: a switch with 20 case labels between 0 and 87 would require an 88-entry jump table, but GCC counts comparisons instead of case labels, and since 10 * 8 < 88 the conversion is deemed unprofitable, so a sequence of comparisons is emitted. For a set of character codes GCC emits the x86 instruction bt[2] with the constant 2753205, whose binary form is a bitset whose set bits correspond to the ASCII values of the case labels, each reduced by 48.

In GCC's source, switch lowering is handled by the pass_lower_switch pass, which calls analyze_switch_statement; the underlying representation is gimple[3]. Each case label becomes a simple_cluster that records the value range, the outgoing edge, and the probability of being chosen, which is uniform by default or comes from profile-guided optimization[4]. Labels not converted into bitsets (the bit_test_cluster strategy) are collected in a scratch vector, and an attempt is then made to turn them into jump tables.

Read the original xoranth.netDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page