Make MultiplyWithoutOverflow be a total function.

That is, remove the `CHECK`-fails. Now the function will return a negative result if either of the arguments is negative (new) or if the multiplication overflows (old).

This doesn't change behavior, as all tests are still passing. The function is now slightly faster.

PiperOrigin-RevId: 342279369
Change-Id: Ib6d4cdb038910d8714d09224b2c1bb2b2ab6ee16
This commit is contained in:
Mihai Maruseac 2020-11-13 09:38:59 -08:00 committed by TensorFlower Gardener
parent 3ad7998055
commit 3584f845fb
2 changed files with 10 additions and 9 deletions
tensorflow/core/util

View File

@ -23,7 +23,12 @@ limitations under the License.
namespace tensorflow {
// Multiply two nonnegative int64's, returning negative for overflow
// If any of the arguments is negative, return negative too.
inline int64 MultiplyWithoutOverflow(const int64 x, const int64 y) {
if (TF_PREDICT_FALSE(x < 0)) return -1;
if (TF_PREDICT_FALSE(y < 0)) return -1;
if (TF_PREDICT_FALSE(x == 0)) return 0;
// Multiply in uint64 rather than int64 since signed overflow is undefined.
// Negative values will wrap around to large unsigned values in the casts
// (see section 4.7 [conv.integral] of the C++14 standard).
@ -33,15 +38,11 @@ inline int64 MultiplyWithoutOverflow(const int64 x, const int64 y) {
// Check if we overflow uint64, using a cheap check if both inputs are small
if (TF_PREDICT_FALSE((ux | uy) >> 32 != 0)) {
// Ensure nonnegativity. Note that negative numbers will appear "large"
// to the unsigned comparisons above.
CHECK(x >= 0 && y >= 0);
// Otherwise, detect overflow using a division
if (ux != 0 && uxy / ux != uy) return -1;
if (uxy / ux != uy) return -1;
}
// Cast back to signed. Any negative value will signal an error.
// Cast back to signed. A negative value will signal an error.
return static_cast<int64>(uxy);
}

View File

@ -75,9 +75,9 @@ TEST(OverflowTest, Nonnegative) {
TEST(OverflowTest, Negative) {
const int64 negatives[] = {-1, std::numeric_limits<int64>::min()};
for (const int64 n : negatives) {
EXPECT_DEATH(MultiplyWithoutOverflow(n, 0), "") << n;
EXPECT_DEATH(MultiplyWithoutOverflow(0, n), "") << n;
EXPECT_DEATH(MultiplyWithoutOverflow(n, n), "") << n;
EXPECT_LT(MultiplyWithoutOverflow(n, 0), 0) << n;
EXPECT_LT(MultiplyWithoutOverflow(0, n), 0) << n;
EXPECT_LT(MultiplyWithoutOverflow(n, n), 0) << n;
}
}