| 1 | #include <Functions/FunctionFactory.h> | 
|---|
| 2 | #include <Functions/FunctionBinaryArithmetic.h> | 
|---|
| 3 | #include <Core/AccurateComparison.h> | 
|---|
| 4 |  | 
|---|
| 5 | namespace DB | 
|---|
| 6 | { | 
|---|
| 7 |  | 
|---|
| 8 | template <typename A, typename B> | 
|---|
| 9 | struct LeastBaseImpl | 
|---|
| 10 | { | 
|---|
| 11 | using ResultType = NumberTraits::ResultOfLeast<A, B>; | 
|---|
| 12 |  | 
|---|
| 13 | template <typename Result = ResultType> | 
|---|
| 14 | static inline Result apply(A a, B b) | 
|---|
| 15 | { | 
|---|
| 16 | /** gcc 4.9.2 successfully vectorizes a loop from this function. */ | 
|---|
| 17 | return static_cast<Result>(a) < static_cast<Result>(b) ? static_cast<Result>(a) : static_cast<Result>(b); | 
|---|
| 18 | } | 
|---|
| 19 |  | 
|---|
| 20 | #if USE_EMBEDDED_COMPILER | 
|---|
| 21 | static constexpr bool compilable = true; | 
|---|
| 22 |  | 
|---|
| 23 | static inline llvm::Value * compile(llvm::IRBuilder<> & b, llvm::Value * left, llvm::Value * right, bool is_signed) | 
|---|
| 24 | { | 
|---|
| 25 | if (!left->getType()->isIntegerTy()) | 
|---|
| 26 | /// XXX minnum is basically fmin(), it may or may not match whatever apply() does | 
|---|
| 27 | return b.CreateMinNum(left, right); | 
|---|
| 28 | return b.CreateSelect(is_signed ? b.CreateICmpSLT(left, right) : b.CreateICmpULT(left, right), left, right); | 
|---|
| 29 | } | 
|---|
| 30 | #endif | 
|---|
| 31 | }; | 
|---|
| 32 |  | 
|---|
| 33 | template <typename A, typename B> | 
|---|
| 34 | struct LeastSpecialImpl | 
|---|
| 35 | { | 
|---|
| 36 | using ResultType = std::make_signed_t<A>; | 
|---|
| 37 |  | 
|---|
| 38 | template <typename Result = ResultType> | 
|---|
| 39 | static inline Result apply(A a, B b) | 
|---|
| 40 | { | 
|---|
| 41 | static_assert(std::is_same_v<Result, ResultType>, "ResultType != Result"); | 
|---|
| 42 | return accurate::lessOp(a, b) ? static_cast<Result>(a) : static_cast<Result>(b); | 
|---|
| 43 | } | 
|---|
| 44 |  | 
|---|
| 45 | #if USE_EMBEDDED_COMPILER | 
|---|
| 46 | static constexpr bool compilable = false; /// ??? | 
|---|
| 47 | #endif | 
|---|
| 48 | }; | 
|---|
| 49 |  | 
|---|
| 50 | template <typename A, typename B> | 
|---|
| 51 | using LeastImpl = std::conditional_t<!NumberTraits::LeastGreatestSpecialCase<A, B>, LeastBaseImpl<A, B>, LeastSpecialImpl<A, B>>; | 
|---|
| 52 |  | 
|---|
| 53 | struct NameLeast { static constexpr auto name = "least"; }; | 
|---|
| 54 | using FunctionLeast = FunctionBinaryArithmetic<LeastImpl, NameLeast>; | 
|---|
| 55 |  | 
|---|
| 56 | void registerFunctionLeast(FunctionFactory & factory) | 
|---|
| 57 | { | 
|---|
| 58 | factory.registerFunction<FunctionLeast>(); | 
|---|
| 59 | } | 
|---|
| 60 |  | 
|---|
| 61 | } | 
|---|
| 62 |  | 
|---|