Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 14 additions & 32 deletions be/src/exec/common/arithmetic_overflow.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,42 +115,24 @@ inline bool mul_overflow(long long x, long long y, long long& res) {
return __builtin_smulll_overflow(x, y, &res);
}

// from __muloXi4 in llvm's compiler-rt
static inline __int128 int128_overflow_mul(__int128 a, __int128 b, int* overflow) {
const int N = (int)(sizeof(__int128) * CHAR_BIT);
const auto MIN = (__int128)((__uint128_t)1 << (N - 1));
const __int128 MAX = ~MIN;
*overflow = 0;
__int128 result = (__uint128_t)a * b;
if (a == MIN) {
if (b != 0 && b != 1) {
*overflow = 1;
}
return result;
}
if (b == MIN) {
if (a != 0 && a != 1) {
*overflow = 1;
}
return result;
}
__int128 sa = a >> (N - 1);
__int128 abs_a = (a ^ sa) - sa;
__int128 sb = b >> (N - 1);
__int128 abs_b = (b ^ sb) - sb;
const bool negative = (a < 0) != (b < 0);
// Unsigned multiplication avoids __muloti4 on ARM toolchains using libgcc.
// Taking the magnitudes in unsigned arithmetic also handles INT128_MIN safely.
const auto abs_a = a < 0 ? -static_cast<__uint128_t>(a) : static_cast<__uint128_t>(a);
const auto abs_b = b < 0 ? -static_cast<__uint128_t>(b) : static_cast<__uint128_t>(b);
__uint128_t magnitude;
bool unsigned_overflow = false;
// A zero/unit factor cannot overflow unsigned 128 bits; keep this common case cheap.
if (abs_a < 2 || abs_b < 2) {
return result;
}
if (sa == sb) {
if (abs_a > MAX / abs_b) {
*overflow = 1;
}
magnitude = abs_a * abs_b;
} else {
if (abs_a > MIN / -abs_b) {
*overflow = 1;
}
unsigned_overflow = __builtin_mul_overflow(abs_a, abs_b, &magnitude);
}
return result;
// Negative products may have magnitude 2^127: (2^126) * (-2) is INT128_MIN.
const __uint128_t limit = (__uint128_t(1) << 127) - !negative;
*overflow = unsigned_overflow || magnitude > limit;
return static_cast<__int128>(negative ? -magnitude : magnitude);
}

template <>
Expand Down
102 changes: 102 additions & 0 deletions be/test/common/arithmetic_overflow_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

#include "exec/common/arithmetic_overflow.h"

#include <gtest/gtest.h>

#include <array>
#include <limits>
#include <random>

namespace doris {
namespace {

void check_int128_product(__int128 lhs, __int128 rhs) {
const wide::Int256 expected = wide::Int256(lhs) * wide::Int256(rhs);
const bool expected_overflow = expected < wide::Int256(std::numeric_limits<__int128>::min()) ||
expected > wide::Int256(std::numeric_limits<__int128>::max());
__int128 result = 0;
EXPECT_EQ(common::mul_overflow(lhs, rhs, result), expected_overflow);
// The low 128 bits must still be the product when the overflow flag is set.
EXPECT_EQ(static_cast<__uint128_t>(result), static_cast<__uint128_t>(expected));
}

} // namespace

TEST(ArithmeticOverflowTest, Int128MultiplyBoundaries) {
constexpr __int128 min = std::numeric_limits<__int128>::min();
constexpr __int128 max = std::numeric_limits<__int128>::max();
constexpr __int128 two63 = __int128(1) << 63;
constexpr __int128 two64 = __int128(1) << 64;
const std::array<__int128, 25> inputs = {
min, min + 1, min / 2 - 1, min / 2, min / 2 + 1, -two64 - 1, -two64,
-two64 + 1, -two63, -3, -2, -1, 0, 1,
2, 3, two63, two64 - 1, two64, two64 + 1, max / 2 - 1,
max / 2, max / 2 + 1, max - 1, max};
for (size_t i = 0; i < inputs.size(); ++i) {
for (size_t j = 0; j < inputs.size(); ++j) {
SCOPED_TRACE(testing::Message() << "i=" << i << ", j=" << j);
check_int128_product(inputs[i], inputs[j]);
}
}
}

TEST(ArithmeticOverflowTest, Int128MultiplyPowersOfTwo) {
for (int lhs_bit = 0; lhs_bit < 127; ++lhs_bit) {
for (int rhs_bit = 0; rhs_bit < 127; ++rhs_bit) {
SCOPED_TRACE(testing::Message() << "lhs_bit=" << lhs_bit << ", rhs_bit=" << rhs_bit);
const __int128 lhs = __int128(1) << lhs_bit;
const __int128 rhs = __int128(1) << rhs_bit;
check_int128_product(lhs, rhs);
check_int128_product(-lhs, rhs);
check_int128_product(lhs, -rhs);
check_int128_product(-lhs, -rhs);
}
}
}

TEST(ArithmeticOverflowTest, Int128MultiplyRandomized) {
std::mt19937_64 rng(0x128dec1a1);
for (size_t i = 0; i < 10000; ++i) {
SCOPED_TRACE(testing::Message() << "iteration=" << i);
const auto lhs = static_cast<__int128>((__uint128_t(rng()) << 64) | rng());
const auto rhs = static_cast<__int128>((__uint128_t(rng()) << 64) | rng());
check_int128_product(lhs, rhs);
check_int128_product(static_cast<int64_t>(lhs), static_cast<int64_t>(rhs));
}
}

TEST(ArithmeticOverflowTest, Int128MultiplyAliasedResult) {
constexpr __int128 min = std::numeric_limits<__int128>::min();
constexpr __int128 max = std::numeric_limits<__int128>::max();
for (const __int128 lhs : {min, min / 2, __int128(-1), __int128(0), __int128(1), max}) {
for (const __int128 rhs :
{__int128(-2), __int128(-1), __int128(0), __int128(1), __int128(2)}) {
__int128 expected;
const bool overflow = common::mul_overflow(lhs, rhs, expected);
__int128 left = lhs;
EXPECT_EQ(common::mul_overflow(left, rhs, left), overflow);
EXPECT_EQ(left, expected);
__int128 right = rhs;
EXPECT_EQ(common::mul_overflow(lhs, right, right), overflow);
EXPECT_EQ(right, expected);
}
}
}

} // namespace doris
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
-- This file is automatically generated. You should know what you did if you want to edit this
-- !vector_vector --
1 0 0
2 99999999999999999999999999999999999999 99999999999999999999999999999999999999
3 -99999999999999999999999999999999999999 -99999999999999999999999999999999999999
4 99999999999999999999999999999999999999 99999999999999999999999999999999999999
5 999999999999999998000000000000000001 999999999999999998000000000000000001
6 -999999999999999998000000000000000001 -999999999999999998000000000000000001
7 85070591730234615865843651857942052864 85070591730234615865843651857942052864
8 -85070591730234615865843651857942052864 -85070591730234615865843651857942052864
9 -85070591730234615865843651857942052864 -85070591730234615865843651857942052864
10 85070591730234615865843651857942052864 85070591730234615865843651857942052864
11 \N \N
12 \N \N

-- !vector_constant --
1 0 0
2 0 -1
3 0 1
4 0 99999999999999999999999999999999999999
5 0 -999999999999999999
6 0 999999999999999999
7 0 -18446744073709551616
8 0 18446744073709551616
9 0 -18446744073709551616
10 0 18446744073709551616
11 \N \N
12 0 -2

-- !constant_vector --
1 0 0
2 0 -1
3 0 1
4 0 99999999999999999999999999999999999999
5 0 -999999999999999999
6 0 999999999999999999
7 0 -18446744073709551616
8 0 18446744073709551616
9 0 -18446744073709551616
10 0 18446744073709551616
11 \N \N
12 0 -2

-- !constant_constant --
-85070591730234615865843651857942052864

-- !scaled_products --
1 11604.9298 12533.324184 -172.557000
2 -11604.9298 -12533.324184 172.557000
3 0.0000 0.000000 172.557000
4 \N \N \N
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

suite("test_decimal128_checked_multiply") {
sql "set check_overflow_for_decimal = true"
sql "set enable_decimal256 = false"
// Keep constant expressions in the BE so constant multiplication paths are exercised.
sql "set debug_skip_fold_constant = true"

sql "drop table if exists test_decimal128_checked_multiply"
sql """
create table test_decimal128_checked_multiply (
id int,
a decimal(38, 0),
b decimal(38, 0)
) distributed by hash(id) buckets 1
properties("replication_num" = "1")
"""
sql """
insert into test_decimal128_checked_multiply values
(1, 0, 99999999999999999999999999999999999999),
(2, 1, 99999999999999999999999999999999999999),
(3, -1, 99999999999999999999999999999999999999),
(4, -99999999999999999999999999999999999999, -1),
(5, 999999999999999999, 999999999999999999),
(6, -999999999999999999, 999999999999999999),
(7, 18446744073709551616, 4611686018427387904),
(8, -18446744073709551616, 4611686018427387904),
(9, 18446744073709551616, -4611686018427387904),
(10, -18446744073709551616, -4611686018427387904),
(11, null, 2),
(12, 2, null)
"""

qt_vector_vector """
select id, a * b, b * a
from test_decimal128_checked_multiply order by id
"""
qt_vector_constant """
select id, a * cast('0' as decimal(1, 0)), a * cast('-1' as decimal(1, 0))
from test_decimal128_checked_multiply order by id
"""
qt_constant_vector """
select id, cast('0' as decimal(1, 0)) * a, cast('-1' as decimal(1, 0)) * a
from test_decimal128_checked_multiply order by id
"""
qt_constant_constant """
select cast('-18446744073709551616' as decimal(20, 0))
* cast('4611686018427387904' as decimal(19, 0))
"""

sql "drop table if exists test_decimal128_checked_multiply_overflow"
sql """
create table test_decimal128_checked_multiply_overflow (
id int,
a decimal(38, 0),
b decimal(38, 0)
) distributed by hash(id) buckets 1
properties("replication_num" = "1")
"""
sql """
insert into test_decimal128_checked_multiply_overflow values
(1, 85070591730234615865843651857942052864, 2),
(2, -85070591730234615865843651857942052864, -2),
(3, -85070591730234615865843651857942052864, 3),
(4, 18446744073709551616, 18446744073709551616),
(5, -18446744073709551616, 18446744073709551616),
(6, -18446744073709551616, -18446744073709551616),
(7, 60000000000000000000000000000000000000, 2)
"""
// Cover signed-range overflow, unsigned-128 overflow and Decimal(38,0) precision overflow.
for (int id = 1; id <= 7; ++id) {
test {
sql "select a * b from test_decimal128_checked_multiply_overflow where id = ${id}"
exception "Arithmetic overflow"
}
}
test {
sql """
select a * cast('2' as decimal(1, 0))
from test_decimal128_checked_multiply_overflow where id = 1
"""
exception "Arithmetic overflow"
}
test {
sql """
select cast('2' as decimal(1, 0)) * a
from test_decimal128_checked_multiply_overflow where id = 1
"""
exception "Arithmetic overflow"
}
test {
sql """
select cast('85070591730234615865843651857942052864' as decimal(38, 0))
* cast('2' as decimal(1, 0))
"""
exception "Arithmetic overflow"
}

sql "drop table if exists test_decimal128_checked_multiply_scaled"
sql """
create table test_decimal128_checked_multiply_scaled (
id int,
price decimal(15, 2),
discount decimal(15, 2),
tax decimal(15, 2),
a decimal(38, 18),
b decimal(38, 18)
) distributed by hash(id) buckets 1
properties("replication_num" = "1")
"""
sql """
insert into test_decimal128_checked_multiply_scaled values
(1, 12345.67, 0.06, 0.08, -15687.000000000000000000, 0.011000000000000000),
(2, -12345.67, 0.06, 0.08, 15687.000000000000000000, 0.011000000000000000),
(3, 0.00, 0.00, 0.00, -15687.000000000000000000, -0.011000000000000000),
(4, null, 0.06, 0.08, null, 0.011000000000000000)
"""
// The scaled products exercise the wider intermediate fallback used after int128 overflow.
qt_scaled_products """
select id, price * (1 - discount), price * (1 - discount) * (1 + tax), a * b
from test_decimal128_checked_multiply_scaled order by id
"""
}
Loading