by rowanG077 · 3y ago · 0 comments
Edit: Everybody in the comments is focusing on performance. For performance sensitive code the point is not that it's branchless, the point is that it is fast, that some branchless code is faster than branching code is an implementation detail. During encryption the point is that it certain codepaths MUST be branchless.
Erm, that likely depends on the industry you're in?
In HPC, branchless algorithms are often needed to use wide architectures (SIMD / GPUs) to their full capacity...
> And it doesn't really matter whether a branch can be well predicted.
I'm not so sure this is true. See https://lemire.me/blog/2019/10/15/mispredicted-branches-can-... as an example.
A properly predicted branch can be _faster_ than a cmov instruction, however the important point is avoiding the branch mispredict. The fact that we're using cmov is beside the point. We could achieve a similar effect by performing a subtraction and doing bitwise arithmetic to extract the sign bit (which, in effect, performs a comparison).
Specifically, subtraction, arithmetic shift right, and AND. `((A-B) ASR 31) AND C`. Your result is C if `A - B < 0`, and your result is 0 if `A - B >= 0`.
https://en.cppreference.com/w/cpp/language/operator_arithmet...
I guess we build branch predictors on our CPUs for fun?
That just isn’t true.
This is certainly true for at minimum DDoS attacks, and I would absolutely consider that a security risk.
This is more than just a theoretical issue. These channel attacks have been demonstrated in practice, even if the victim CPU is running across the internet.
In this context, branchless means something different: the performance of the CPU is maximized for the given hardware, by not flushing the speculative execution of the CPU.