Implementing new primitive comparisons to allow branchless algorithms

This page presents motivation and technical details behind implementing new primitive comparison operators (this was originaly reported as Trac ticket #6135). See ​this page for instructions how to adjust your already existing code to work with new primops.

The problem

This kind of code is common in image processing (and array programming in general) where one needs to check whether the (x,y) coordinates are within the image. Primitive comparison operators <# and >=# have type Int# -> Int# -> Bool. Logical OR operator (||) is defined as:

(||) :: Bool -> Bool -> Bool
True || _ = True
False || x = x

in GHC.Classes (ghc-prim library) which is equivalent of:

(||) x y = case x of
True -> True
False -> y

During the compilation process (assuming the optimizations are turned on) the definition of (||) gets inlined and then case-of-case transform is performed successively. This results in following Core (cleaned up for clarity):

There are five possible branches to take, although four of them have the same result. This is caused by code duplication introduced by case-of-case transform (see ​this blog post for a step by step derivation). According to Ben Lippmeier, who submitted the original bug report, mis-predicted branches are bad in object code because they stall the pipeline.

Note: this example was produced with GHC 7.6.3. At the moment of merging new primops into HEAD, there was no code duplication at the assembly level when using old primops. However, avoiding code duplication is not the main problem new primops are meant to solve. That problem are conditional branches.

Solution

This problem was solved by modifying comparison primops to return unboxed unlifted Int# instead of Bool (which is lifted and thus is returned as a thunk that needs to be evaluated). Having Int# returned as a result of logical comparison will allow to use branchless bitwise logical operators instead of branching logical operators defined by Haskell.

Implementation details

Below is a summary of implementation details and decisions:

The new comparison primops return a value of type Int#: 1# represents True and 0# represents False. The Int# type was chosen because on Haskell it is more common to use signed Int type insetad of unsigned Word. By using Int# the users can easily convert unboxed result into a boxed value, without need to use word2Int# and int2word# primops.

Unlike C, 2# or -3# don't represent a Boolean value. More concretely, you can use tagToEnum# to convert one of these Int# values to a Bool, but tagToEnum# does no error checking, so it would be Very Very Bad to call it on 2#.

As a small side-task, four new logical bitwise primops have been implemented: andI#, orI#, xorI# and negI# (#7689). These operate on values of type Int#. Earlier we had only bitwise logical primops operating on values of type Word#.

Names of the existing comparison primops were changed. Operators had $ added before #, others had I added before the # (this is a mnemonic denoting that this primop returns and Int#). Examples:

Thanks to these wrappers the change is almost backwards compatible. The only thing primop users need to change in their existing code to make it work again is adding import of GHC.PrimWrappers module.

Functions for comparing Integer type, implemented in integer-gmp and integer-simple libraries, received a similar treatment. Technically they are not primops, because they are implemented in Haskell (in case of integer-gmp also with FFI), but they pretend to be ones. There are six primops for comparing Integer values:

Each of these functions has a wrapper that calls tagToEnum# and returns a Bool. These wrappers are: eqInteger, neqInteger, leInteger, ltInteger, gtInteger and geInteger.

Six primops are an exception to the rules above: sameMutableArray#, sameMutableByteArray#, sameMutableArrayArray#, sameMutVar#, sameMVar# and sameTVar#. Their names have remained the same as before and new wrappers created for them lack # at the end of their name. We made that decission because this naming feels more consistent and these primops are rarely used so we expect that they won't break a lot of existing code.

Other libraries that were modified to work with the new primops are: base, ghc-prim and primitive. The only required modifications were imports of the GHC.PrimWrappers module in modules that use the primops.

Eliminating branches using new primops

With the new primops we can rewrite the original expression that motivated the problem:

Let's analyze line by line the part responsible for evaluating the scrutinee:

movq %rsi, %rax # load y (stored in %rsi) into %rax register
orq %r14, %rax # perform bitwise OR between y (now in %rax) and x (in %r14)
# and store result in %rax
shrq $63, %rax # shift %rax 63 bits to the right. If both x and y were
# positive numbers, then their sign bits (MSB) were set to
# 0 and so %rax is now 0. If at least one of them was
# negative then its sign bit must have been 1 and so %rax
# is now 1
cmpq %rdi, %r14 # compare width (in %rdi) with x (in %r14) and set the flags
# in the flag register according to the result.
setge %cl # if, based on flags set by cmpq, x was greater or equal to
# width then we set %cl to 1. Otherwise it is set to 0.
movzbl %cl, %ecx # zero the bits of %ecx register except the lowest 8 bits
# containg the result of previous operation
orq %rax, %rcx # perform logical OR on results of the previous test and
# store the result in %rcx. At this point if %rcx is 1
# then either x was negative, or y was negative or
# x was greater or equal to width
cmpq %r8, %rsi # now we are checking whether y is greter or equal to
# height. This is the same as previosly for x and width.
setge %al # This time we set LSB of %al to 1 if y >= height
movzbl %al, %eax # as previously, clear bits of %eax except lowest 8 bits
orq %rcx, %rax # perform logical OR which combines result of previous
# three comparisons with the last one
jne .LBB2_1 # if ZF is not set it this means that either %rcx or %rax
# was not zero, which means that at least one condition
# in the scrutinee was true

The assembly does not contain comparisons and branches in the scrutinee of the case expression, but still uses jumps to select an appropriate branch of the case expression.

Benchmarks

Below is a benchmark for the proof-of-concept branchless filter function that demonstrates performance gains possible with the new primops:

Benchmarking shows that filterN function is about 55-65% faster than the filter function based on stream fusion (tested for unboxed vectors containing 10 thousand and 10 million elements). Below is an example benchmarking report from criterion: