Switch codegen.

claptrap clap at trap.com
Mon Aug 7 20:22:06 UTC 2023


Given code like this...

```d
const int x;
while(...)
{
     switch (x)
     {
         case 0: whatever; break;
         case 1: whatever; break;
         case 2: whatever; break;
         case 3: whatever; break;
         case 4: whatever; break;
     }
}
```

It generates a jump table if there's at least 4 or 5 cases, but 
at the start of the switch it generates 6 instructions (x64), 
check the bounds, lookup / calc the destination, and the actual 
jump. Like this...

```d
         lea     r13, [rip + .LJTI0_0]
         cmp     r14d, 7
         ja      .LBB0_11
         movsxd  rax, dword ptr [r13 + 4*r12]
         add     rax, r13
         jmp     rax
```

So the point is if the switch is in a loop and x is constant, 
most of that could be done ahead, outside the loop. It could 
actually be reduced to a single indirect jump inside the loop. It 
seems there is a LLVM IR instruction that may be useful for this, 
"indirectbr", it's a sort of computed goto.

https://llvm.org/docs/LangRef.html#indirectbr-instruction

Is this at all feasible? If so how would this be done? In the 
actual IR codegen or as an optimization pass? I willing to do the 
work if it's possible.



More information about the digitalmars-d-ldc mailing list