muloti4.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*===-- muloti4.c - Implement __muloti4 -----------------------------------===
  2. *
  3. * The LLVM Compiler Infrastructure
  4. *
  5. * This file is dual licensed under the MIT and the University of Illinois Open
  6. * Source Licenses. See LICENSE.TXT for details.
  7. *
  8. * ===----------------------------------------------------------------------===
  9. *
  10. * This file implements __muloti4 for the compiler_rt library.
  11. *
  12. * ===----------------------------------------------------------------------===
  13. */
  14. #include "int_lib.h"
  15. #ifdef CRT_HAS_128BIT
  16. /* Returns: a * b */
  17. /* Effects: sets *overflow to 1 if a * b overflows */
  18. __attribute__((no_sanitize("undefined")))
  19. COMPILER_RT_ABI ti_int
  20. __muloti4(ti_int a, ti_int b, int* overflow)
  21. {
  22. const int N = (int)(sizeof(ti_int) * CHAR_BIT);
  23. const ti_int MIN = (ti_int)1 << (N-1);
  24. const ti_int MAX = ~MIN;
  25. *overflow = 0;
  26. ti_int result = a * b;
  27. if (a == MIN)
  28. {
  29. if (b != 0 && b != 1)
  30. *overflow = 1;
  31. return result;
  32. }
  33. if (b == MIN)
  34. {
  35. if (a != 0 && a != 1)
  36. *overflow = 1;
  37. return result;
  38. }
  39. ti_int sa = a >> (N - 1);
  40. ti_int abs_a = (a ^ sa) - sa;
  41. ti_int sb = b >> (N - 1);
  42. ti_int abs_b = (b ^ sb) - sb;
  43. if (abs_a < 2 || abs_b < 2)
  44. return result;
  45. if (sa == sb)
  46. {
  47. if (abs_a > MAX / abs_b)
  48. *overflow = 1;
  49. }
  50. else
  51. {
  52. if (abs_a > MIN / -abs_b)
  53. *overflow = 1;
  54. }
  55. return result;
  56. }
  57. #endif /* CRT_HAS_128BIT */