1/*===-- int128_builtins.cpp - Implement __muloti4 --------------------------===
2 *
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
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
19_LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Wmissing-prototypes") // See the FIXME above
20
21#if _LIBCPP_HAS_INT128
22
23extern "C" __attribute__((no_sanitize("undefined"))) _LIBCPP_EXPORTED_FROM_ABI __int128_t
24__muloti4(__int128_t a, __int128_t b, int* overflow) {
25 const int N = (int)(sizeof(__int128_t) * CHAR_BIT);
26 const __int128_t MIN = (__int128_t)1 << (N - 1);
27 const __int128_t MAX = ~MIN;
28 *overflow = 0;
29 __int128_t result = a * b;
30 if (a == MIN) {
31 if (b != 0 && b != 1)
32 *overflow = 1;
33 return result;
34 }
35 if (b == MIN) {
36 if (a != 0 && a != 1)
37 *overflow = 1;
38 return result;
39 }
40 __int128_t sa = a >> (N - 1);
41 __int128_t abs_a = (a ^ sa) - sa;
42 __int128_t sb = b >> (N - 1);
43 __int128_t abs_b = (b ^ sb) - sb;
44 if (abs_a < 2 || abs_b < 2)
45 return result;
46 if (sa == sb) {
47 if (abs_a > MAX / abs_b)
48 *overflow = 1;
49 } else {
50 if (abs_a > MIN / -abs_b)
51 *overflow = 1;
52 }
53 return result;
54}
55
56#endif
57