mulodi4.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*===-- mulodi4.c - Implement __mulodi4 -----------------------------------===
  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 __mulodi4 for the compiler_rt library.
  11. *
  12. * ===----------------------------------------------------------------------===
  13. */
  14. #if 0
  15. #include "int_lib.h"
  16. #else
  17. #define COMPILER_RT_ABI
  18. #define di_int int64_t
  19. #include "torint.h"
  20. di_int __mulodi4(di_int a, di_int b, int* overflow);
  21. #endif
  22. /* Returns: a * b */
  23. /* Effects: sets *overflow to 1 if a * b overflows */
  24. COMPILER_RT_ABI di_int
  25. __mulodi4(di_int a, di_int b, int* overflow)
  26. {
  27. const int N = (int)(sizeof(di_int) * CHAR_BIT);
  28. const di_int MIN = (di_int)1 << (N-1);
  29. const di_int MAX = ~MIN;
  30. *overflow = 0;
  31. di_int result = a * b;
  32. if (a == MIN)
  33. {
  34. if (b != 0 && b != 1)
  35. *overflow = 1;
  36. return result;
  37. }
  38. if (b == MIN)
  39. {
  40. if (a != 0 && a != 1)
  41. *overflow = 1;
  42. return result;
  43. }
  44. di_int sa = a >> (N - 1);
  45. di_int abs_a = (a ^ sa) - sa;
  46. di_int sb = b >> (N - 1);
  47. di_int abs_b = (b ^ sb) - sb;
  48. if (abs_a < 2 || abs_b < 2)
  49. return result;
  50. if (sa == sb)
  51. {
  52. if (abs_a > MAX / abs_b)
  53. *overflow = 1;
  54. }
  55. else
  56. {
  57. if (abs_a > MIN / -abs_b)
  58. *overflow = 1;
  59. }
  60. return result;
  61. }