Constexpr Trick for Instruction Decoding in C++
Created on 2025-01-29T12:15:07-06:00
Thesis: write a single large function which handles every edge case. assign bit masks where each bit is "in this operation does this edge case apply?" use `constexpr` to read the operation number from a parameter but compute the offset at compile time. create an array of calls to this function such that each call has the ID number of the operator. the hope is the compiler optimizes the parameter (used only in a constexpr) away, thus all mask tests are against constants, thus are removed, thus all if/else statements can be optimized out also, resulting in an array of functions with minor context changes while only maintaining a single large function.
templatevoid ins(uint16_t instr) { uint16_t r0, r1, r2, imm5, imm_flag; uint16_t pc_plus_off, base_plus_off; constexpr uint16_t opbit = (1 << op); if (0x4EEE & opbit) { r0 = (instr >> 9) & 0x7; } if (0x12F3 & opbit) { r1 = (instr >> 6) & 0x7; } ... } ... static void (*op_table[16])(uint16_t) = { ins<0>, ins<1>, ins<2>, ins<3>, ins<4>, ins<5>, ins<6>, ins<7>, NULL, ins<9>, ins<10>, ins<11>, ins<12>, NULL, ins<14>, ins<15> };