Branch tables are usually described as an efficient way a compiler can implement a switch statement, and that actually seems how GCC and Clang do it (and LLVM even has an opcode just for that).

If a sequence of if statements is used (instead of a switch), GCC doesn't seem to generate a table, but Clang still does.

Given a compiler that turns the code into basic blocks inside a control flow graph in static single assignment form, how would it decide where to generate tables? Is there any research on that? I'm particularly interested in finding an algorithm for lowering consecutive branchings (found on the CFG/SSA form) into a branch table (as Clang seems to do).

(I actually tried looking for any papers about that but didn't find anything.)

Edit: I do understand that the obvious way to do this is to expand the definition of the SSA to include multiple branchings as a primitive (i.e., blocks may branch to an arbitrary number of blocks); I'm wondering if (and how) the tables could be done in a simpler definition, where each basic block may move to at most two other blocks (i.e., only unconditional moves and an if branching).


The book "A Retargetable C Compiler: Design and Implementation" by Christopher Fraser and David Hanson gives some detail on how they lower switch statements to a combination of conditional branches and jump tables. They cite prior work that their technique builds on, so it would be a good start for a literature survey.

There should be nothing particular to SSA that makes generating jump tables harder or easier. An SSA IR like LLVM can include an explicit instruction for an N-way branch, so that generation of jump tables is really about how to lower such an instruction.

(Update: you've edited the question in a way that makes it clear this isn't really about generating jump tables, but rather about re-discovering switch-style control flow from cascading if statements in an IR. This is again probably not specific to SSA. You might look at the "Relooper" algorithm as implemented for Emscripten which deals with more general control-flow restructuring. I'm not aware of a reference specific to recovering N-way branches, but it seems like simple ad hoc approaches should work well.)

| cite | improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.