ClickHouse
56 строк · 1.9 Кб
1#include <Functions/FunctionFactory.h>
2#include <Functions/FunctionBinaryArithmetic.h>
3#include <base/arithmeticOverflow.h>
4
5namespace DB
6{
7
8template <typename A, typename B>
9struct PlusImpl
10{
11using ResultType = typename NumberTraits::ResultOfAdditionMultiplication<A, B>::Type;
12static const constexpr bool allow_fixed_string = false;
13static const constexpr bool allow_string_integer = false;
14static const constexpr bool is_commutative = true;
15
16template <typename Result = ResultType>
17static inline NO_SANITIZE_UNDEFINED Result apply(A a, B b)
18{
19/// Next everywhere, static_cast - so that there is no wrong result in expressions of the form Int64 c = UInt32(a) * Int32(-1).
20if constexpr (is_big_int_v<A> || is_big_int_v<B>)
21{
22using CastA = std::conditional_t<std::is_floating_point_v<B>, B, A>;
23using CastB = std::conditional_t<std::is_floating_point_v<A>, A, B>;
24
25return static_cast<Result>(static_cast<CastA>(a)) + static_cast<Result>(static_cast<CastB>(b));
26}
27else
28return static_cast<Result>(a) + static_cast<Result>(b);
29}
30
31/// Apply operation and check overflow. It's used for Deciamal operations. @returns true if overflowed, false otherwise.
32template <typename Result = ResultType>
33static inline bool apply(A a, B b, Result & c)
34{
35return common::addOverflow(static_cast<Result>(a), b, c);
36}
37
38#if USE_EMBEDDED_COMPILER
39static constexpr bool compilable = true;
40
41static inline llvm::Value * compile(llvm::IRBuilder<> & b, llvm::Value * left, llvm::Value * right, bool)
42{
43return left->getType()->isIntegerTy() ? b.CreateAdd(left, right) : b.CreateFAdd(left, right);
44}
45#endif
46};
47
48struct NamePlus { static constexpr auto name = "plus"; };
49using FunctionPlus = BinaryArithmeticOverloadResolver<PlusImpl, NamePlus>;
50
51REGISTER_FUNCTION(Plus)
52{
53factory.registerFunction<FunctionPlus>();
54}
55
56}
57