This proposed patch adds some code to SimplifySwitch in SimplifyCFG in order to convert some switch constructs to selects when that is possible.
The idea here is to avoid unnecessary control-flow when the switch is simple enough to be converted into a simple one or two-way select with only a comparison. In order for that to be feasible the switch must be a the kind of "producing a value" like for example
switch (a) {
case 5: return 10; case 9: return 11; default: return 12;
}
The method uses three methods to try and transform the switch into a select.
First it checks if the number of cases is just 2 and in that case it just generates a simple comparison to check if the value is the one from the first case or from the second.
If this approach fails it then tries to see if case label values are dividable in two ordered groups and tries to emit a select that checks on a pivot value to see from which group we should select the value from.
If this is not possible it tries a third approach which is trying to identify some bits that are always one in one of the groups to select from and that are always zero in the other and use a bit mask to determine in which category the value falls into.
Reducing control flow in this way for these cases should be profitable for all hardware.
Please, comment on what you think about this.
range loop?