Branch Table - Typical Implementation

Typical Implementation

A branch table consists of a serial list of unconditional branch instructions that is branched into using an offset created by multiplying a sequential index by the instruction length (the number of bytes in memory occupied by each branch instruction). It relies on the fact that machine code instructions for branching have a fixed length and can be executed extremely efficiently by most hardware, and is most useful when dealing with raw data values that may be easily converted to sequential index values. Given such data, a branch table can be extremely efficient. It usually consists of the following 3 steps:

  1. optionally validating the input data to ensure it is acceptable (this may occur without cost as part of the next step, if the input is a single byte and a 256 byte translate table is used to directly obtain the offset below). Also, if there is no doubt about the values of the input, this step can be omitted.
  2. transform the data into an offset into the branch table. This usually involves multiplying or shifting (effectively multiplying by a power of 2) it to take into account the instruction length. If a static translate table is used, this multiplying can be performed manually or by the compiler, without any run time cost.
  3. branching to an address made up of the base address of the branch table plus the just generated offset. This sometimes involves an addition of the offset onto the program counter register (unless, in some instruction sets, the branch instruction allows an extra index register). This final address usually points to one of a sequence of unconditional branch instructions, or the instruction immediately beyond them (saving one entry in the table).

The following pseudocode illustrates the concept

... validate x /* transform x to 0 (invalid) or 1,2,3, according to value..) */ y = x*4; /* multiply by branch instruction length (e.g. 4 ) */ goto next(y); /* branch into 'table' of branch instructions */ /* start of branch table */ next: goto codebad; /* x= 0 (invalid) */ goto codeone; /* x= 1 */ goto codetwo; /* x= 2 */ ... rest of branch table codebad: /* deal with invalid input */

Read more about this topic:  Branch Table

Famous quotes containing the word typical:

    A building is akin to dogma; it is insolent, like dogma. Whether or no it is permanent, it claims permanence, like a dogma. People ask why we have no typical architecture of the modern world, like impressionism in painting. Surely it is obviously because we have not enough dogmas; we cannot bear to see anything in the sky that is solid and enduring, anything in the sky that does not change like the clouds of the sky.
    Gilbert Keith Chesterton (1874–1936)