aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Functions/bitSwapLastTwo.cpp
blob: d8957598c6241ad86b98d3bdb5b824f3a0354a02 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionUnaryArithmetic.h>
#include <DataTypes/NumberTraits.h>

namespace DB
{
namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
    extern const int BAD_ARGUMENTS;
}

namespace
{

/// Working with UInt8: last bit = can be true, previous = can be false (Like src/Storages/MergeTree/BoolMask.h).
/// This function provides "NOT" operation for BoolMasks by swapping last two bits ("can be true" <-> "can be false").
template <typename A>
struct BitSwapLastTwoImpl
{
    using ResultType = UInt8;
    static constexpr const bool allow_string_or_fixed_string = false;

    static inline ResultType NO_SANITIZE_UNDEFINED apply([[maybe_unused]] A a)
    {
        if constexpr (!std::is_same_v<A, ResultType>)
            // Should be a logical error, but this function is callable from SQL.
            // Need to investigate this.
            throw DB::Exception(ErrorCodes::BAD_ARGUMENTS, "It's a bug! Only UInt8 type is supported by __bitSwapLastTwo.");

        auto little_bits = littleBits<A>(a);
        return static_cast<ResultType>(((little_bits & 1) << 1) | ((little_bits >> 1) & 1));
    }

#if USE_EMBEDDED_COMPILER
static constexpr bool compilable = true;

static inline llvm::Value * compile(llvm::IRBuilder<> & b, llvm::Value * arg, bool)
{
    if (!arg->getType()->isIntegerTy())
        throw Exception(ErrorCodes::LOGICAL_ERROR, "__bitSwapLastTwo expected an integral type");
    return b.CreateOr(
            b.CreateShl(b.CreateAnd(arg, 1), 1),
            b.CreateAnd(b.CreateLShr(arg, 1), 1)
            );
}
#endif
};

struct NameBitSwapLastTwo { static constexpr auto name = "__bitSwapLastTwo"; };
using FunctionBitSwapLastTwo = FunctionUnaryArithmetic<BitSwapLastTwoImpl, NameBitSwapLastTwo, true>;

}

template <> struct FunctionUnaryArithmeticMonotonicity<NameBitSwapLastTwo>
{
    static bool has() { return false; }
    static IFunction::Monotonicity get(const Field &, const Field &)
    {
        return {};
    }
};

REGISTER_FUNCTION(BitSwapLastTwo)
{
    factory.registerFunction<FunctionBitSwapLastTwo>();
}

}