Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 1 | /*===-- int128_builtins.cpp - Implement __muloti4 --------------------------=== |
| 2 | * |
Chandler Carruth | 57b08b0 | 2019-01-19 10:56:40 +0000 | [diff] [blame] | 3 | * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | * See https://llvm.org/LICENSE.txt for license information. |
| 5 | * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 6 | * |
| 7 | * ===----------------------------------------------------------------------=== |
| 8 | * |
| 9 | * This file implements __muloti4, and is stolen from the compiler_rt library. |
| 10 | * |
| 11 | * FIXME: we steal and re-compile it into filesystem, which uses __int128_t, |
| 12 | * and requires this builtin when sanitized. See llvm.org/PR30643 |
| 13 | * |
| 14 | * ===----------------------------------------------------------------------=== |
| 15 | */ |
| 16 | #include "__config" |
| 17 | #include "climits" |
| 18 | |
Eric Fiselier | 998a5c8 | 2018-07-27 03:07:09 +0000 | [diff] [blame] | 19 | #if !defined(_LIBCPP_HAS_NO_INT128) |
Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 20 | |
Eric Fiselier | 5b59295 | 2019-08-21 00:16:33 +0000 | [diff] [blame] | 21 | extern "C" __attribute__((no_sanitize("undefined"))) _LIBCPP_FUNC_VIS |
Eric Fiselier | f74c546 | 2018-07-26 03:36:37 +0000 | [diff] [blame] | 22 | __int128_t __muloti4(__int128_t a, __int128_t b, int* overflow) { |
Eric Fiselier | 1e1f8ec | 2018-07-26 00:34:50 +0000 | [diff] [blame] | 23 | const int N = (int)(sizeof(__int128_t) * CHAR_BIT); |
| 24 | const __int128_t MIN = (__int128_t)1 << (N - 1); |
| 25 | const __int128_t MAX = ~MIN; |
| 26 | *overflow = 0; |
| 27 | __int128_t result = a * b; |
| 28 | if (a == MIN) { |
| 29 | if (b != 0 && b != 1) |
| 30 | *overflow = 1; |
| 31 | return result; |
| 32 | } |
| 33 | if (b == MIN) { |
| 34 | if (a != 0 && a != 1) |
| 35 | *overflow = 1; |
| 36 | return result; |
| 37 | } |
| 38 | __int128_t sa = a >> (N - 1); |
| 39 | __int128_t abs_a = (a ^ sa) - sa; |
| 40 | __int128_t sb = b >> (N - 1); |
| 41 | __int128_t abs_b = (b ^ sb) - sb; |
| 42 | if (abs_a < 2 || abs_b < 2) |
| 43 | return result; |
| 44 | if (sa == sb) { |
| 45 | if (abs_a > MAX / abs_b) |
| 46 | *overflow = 1; |
| 47 | } else { |
| 48 | if (abs_a > MIN / -abs_b) |
| 49 | *overflow = 1; |
| 50 | } |
| 51 | return result; |
| 52 | } |
| 53 | |
| 54 | #endif |