blob: a1717d81f287997939fc19944cc31d53c9ba7e5f [file] [log] [blame]
Eric Christopher1ace4052011-06-17 20:17:05 +00001/*===-- mulosi4.c - Implement __mulosi4 -----------------------------------===
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 __mulosi4 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
22si_int
23__mulosi4(si_int a, si_int b, int* overflow)
24{
25 const int N = (int)(sizeof(si_int) * CHAR_BIT);
26 const si_int MIN = (si_int)1 << (N-1);
27 const si_int MAX = ~MIN;
28 *overflow = 0;
29 si_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 si_int sa = a >> (N - 1);
43 si_int abs_a = (a ^ sa) - sa;
44 si_int sb = b >> (N - 1);
45 si_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}