This is an archive of the discontinued LLVM Phabricator instance.

Optimize std::midpoint for signed integers
Needs ReviewPublic

Authored by Aj0SK on Nov 23 2019, 6:55 PM.

Details

Reviewers
mclow.lists
Summary

Idea of algorithm is based on finding floored "average" of numbers using bit hack.
Then we want to add -1/+1 only if the numbers have different parity.
We can make this decisions only using bit operators.

You can find benchmark of this algorithm against two older here ->
http://quick-bench.com/hqhZWR7IB4IoUj3aLTN28dOUuPY . In this benchmark
you can see that algorithm works faster for signed types and equally
fast for unsigned types. Even if this algorithm uses more instructions it has higher
Block RThroughput as ilustrated here -> https://godbolt.org/z/5TDmr4 .

Diff Detail

Event Timeline

Aj0SK created this revision.Nov 23 2019, 6:55 PM
Herald added a project: Restricted Project. · View Herald TranscriptNov 23 2019, 6:55 PM
Aj0SK added a comment.Nov 24 2019, 4:16 AM

Maybe I would add explanation why the term

(__a & __b) + ((__a ^ __b) >> 1)

calculates the floored average. Adding a and b can be rewritten as a + b = (a ^ b) + ((a & b) << 1) . After this we have to divide a+b by 2. This can be done also using shifting to right by 1. After this we get (a + b)/2 = ((a ^ b) >>1) + (a & b).