Eric Christopher | 1d18094 | 2011-06-17 20:17:05 +0000 | [diff] [blame^] | 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 | |
| 15 | #include "int_lib.h" |
| 16 | #include <stdlib.h> |
| 17 | |
| 18 | /* Returns: a * b */ |
| 19 | |
| 20 | /* Effects: sets *overflow to 1 if a * b overflows */ |
| 21 | |
| 22 | di_int |
| 23 | __mulodi4(di_int a, di_int b, int* overflow) |
| 24 | { |
| 25 | const int N = (int)(sizeof(di_int) * CHAR_BIT); |
| 26 | const di_int MIN = (di_int)1 << (N-1); |
| 27 | const di_int MAX = ~MIN; |
| 28 | *overflow = 0; |
| 29 | di_int result = a * b; |
| 30 | if (a == MIN) |
| 31 | { |
| 32 | if (b != 0 && b != 1) |
| 33 | *overflow = 1; |
| 34 | return result; |
| 35 | } |
| 36 | if (b == MIN) |
| 37 | { |
| 38 | if (a != 0 && a != 1) |
| 39 | *overflow = 1; |
| 40 | return result; |
| 41 | } |
| 42 | di_int sa = a >> (N - 1); |
| 43 | di_int abs_a = (a ^ sa) - sa; |
| 44 | di_int sb = b >> (N - 1); |
| 45 | di_int abs_b = (b ^ sb) - sb; |
| 46 | if (abs_a < 2 || abs_b < 2) |
| 47 | return result; |
| 48 | if (sa == sb) |
| 49 | { |
| 50 | if (abs_a > MAX / abs_b) |
| 51 | *overflow = 1; |
| 52 | } |
| 53 | else |
| 54 | { |
| 55 | if (abs_a > MIN / -abs_b) |
| 56 | *overflow = 1; |
| 57 | } |
| 58 | return result; |
| 59 | } |