Eroxl's Notes
Jump Table

A jump table is an array of addresses that enables efficient multi-way branching. Jump tables are commonly used to implement switch statements by indexing into the table based on the condition value and jumping to the corresponding address.

Structure

A jump table is simply an array where each element stores the address of a code label:

void *jt[4] = { &&L0, &&L1, &&L2, &&L3 };

In SM213 Assembly:

jmptable:
    .long case0    # Address of case 0
    .long case1    # Address of case 1
    .long case2    # Address of case 2
    .long default  # Address of default

Switch Statement Implementation

C Code

switch (i) {
    case 0: j = 10; break;
    case 1: j = 11; break;
    case 2: j = 12; break;
    default: j = 14; break;
}

With Goto and Jump Table

static const void* jt[3] = { &&L0, &&L1, &&L2 };
if (i < 0 || i > 2) goto DEFAULT;
goto *jt[i];

L0: j = 10; goto CONT;
L1: j = 11; goto CONT;
L2: j = 12; goto CONT;
DEFAULT: j = 14;
CONT:

In Assembly

    ld $i, r0           # r0 = &i
    ld (r0), r0         # r0 = i
    ld $-3, r1          # r1 = -3
    add r0, r1          # r1 = i - 3
    bgt r1, default     # if i > 2, goto default
    ld $i, r0           # r0 = i (reload)
    beq r0, default     # if i < 0, goto default
    ld $jmptable, r1    # r1 = &jmptable
    j *(r1, r0, 4)      # Jump to jmptable[i]

Handling Gaps and Offsets

Gaps in case Labels

If case labels have gaps, the jump table includes the default address for missing cases:

switch (i) {
    case 20: j = 10; break;
    case 21: j = 11; break;
    case 23: j = 13; break;  // Note: case 22 missing
    default: j = 14; break;
}

Jump table for cases 20-23:

void *jt[4] = { &&L20, &&L21, &&DEFAULT, &&L23 };
goto *jt[i - 20];  // Normalize to 0-based index

Normalization

Case labels are normalized by subtracting the minimum case value:

if (i < 20 || i > 23) goto DEFAULT;
goto *jt[i - 20];  // Maps 20→0, 21→1, 22→2, 23→3

Performance Tradeoffs

Jump Table Advantages

  • Constant time: O(1) lookup regardless of number of cases
  • Efficient for dense cases: When case values are close together

Jump Table Disadvantages

  • Space overhead: Requires memory for all values in range
  • Inefficient for sparse cases: Wastes space for missing values

When to Use

The compiler chooses between jump tables and if-else chains based on:

Scenario Best Approach
Dense cases (few gaps) Jump table
Sparse cases (many gaps) If-else chain
Few cases (< 4-5) If-else chain
Large range (e.g., 1000-9000) If-else chain
Moderate range with most values Jump table