1/* Generic signed 32 bit division implementation.
2   Copyright (C) 2009-2020 Free Software Foundation, Inc.
3   Contributed by Embecosm on behalf of Adapteva, Inc.
4
5This file is part of GCC.
6
7This file is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
9Free Software Foundation; either version 3, or (at your option) any
10later version.
11
12This file is distributed in the hope that it will be useful, but
13WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15General Public License for more details.
16
17Under Section 7 of GPL version 3, you are granted additional
18permissions described in the GCC Runtime Library Exception, version
193.1, as published by the Free Software Foundation.
20
21You should have received a copy of the GNU General Public License and
22a copy of the GCC Runtime Library Exception along with this program;
23see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
24<http://www.gnu.org/licenses/>.  */
25
26typedef union { unsigned int i; float f; } fu;
27
28/* Although the semantics of the function ask for signed / unsigned inputs,
29   for the actual implementation we use unsigned numbers.  */
30unsigned int __divsi3 (unsigned int a, unsigned int b);
31
32unsigned int
33__divsi3 (unsigned int a, unsigned int b)
34{
35  unsigned int sign = (int) (a ^ b) >> 31;
36  unsigned int d, t, s0, s1, s2, r0, r1;
37  fu u0, u1, u2, u1b, u2b;
38
39  a = abs (a);
40  b = abs (b);
41
42  if (b > a)
43    return 0;
44
45  /* Compute difference in number of bits in S0.  */
46  u0.i = 0x40000000;
47  u1b.i = u2b.i = u0.i;
48  u1.i = a;
49  u2.i = b;
50  u1.i = a | u0.i;
51  t = 0x4b800000 | ((a >> 23) & 0xffff);
52  if (a >> 23)
53    {
54      u1.i = t;
55      u1b.i = 0x4b800000;
56    }
57  u2.i = b | u0.i;
58  t = 0x4b800000 | ((b >> 23) & 0xffff);
59  if (b >> 23)
60    {
61      u2.i = t;
62      u2b.i = 0x4b800000;
63    }
64  u1.f = u1.f - u1b.f;
65  u2.f = u2.f - u2b.f;
66  s1 = u1.i >> 23;
67  s2 = u2.i >> 23;
68  s0 = s1 - s2;
69
70  b <<= s0;
71  d = b - 1;
72
73  r0 = 1 << s0;
74  r1 = 0;
75  t = a - b;
76  if (t <= a)
77    {
78      a = t;
79      r1 = r0;
80    }
81
82#define STEP(n) case n: a += a; t = a - d; if (t <= a) a = t;
83  switch (s0)
84    {
85    STEP (31)
86    STEP (30)
87    STEP (29)
88    STEP (28)
89    STEP (27)
90    STEP (26)
91    STEP (25)
92    STEP (24)
93    STEP (23)
94    STEP (22)
95    STEP (21)
96    STEP (20)
97    STEP (19)
98    STEP (18)
99    STEP (17)
100    STEP (16)
101    STEP (15)
102    STEP (14)
103    STEP (13)
104    STEP (12)
105    STEP (11)
106    STEP (10)
107    STEP (9)
108    STEP (8)
109    STEP (7)
110    STEP (6)
111    STEP (5)
112    STEP (4)
113    STEP (3)
114    STEP (2)
115    STEP (1)
116    case 0: ;
117    }
118  r0 = r1 | (r0-1 & a);
119  return (r0 ^ sign) - sign;
120}
121