1/* Copyright (C) 2012-2022 Free Software Foundation, Inc.
2   Contributed by Altera and Mentor Graphics, Inc.
3
4This file is free software; you can redistribute it and/or modify it
5under the terms of the GNU General Public License as published by the
6Free Software Foundation; either version 3, or (at your option) any
7later version.
8
9This file is distributed in the hope that it will be useful, but
10WITHOUT ANY WARRANTY; without even the implied warranty of
11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12General Public License for more details.
13
14Under Section 7 of GPL version 3, you are granted additional
15permissions described in the GCC Runtime Library Exception, version
163.1, as published by the Free Software Foundation.
17
18You should have received a copy of the GNU General Public License and
19a copy of the GCC Runtime Library Exception along with this program;
20see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
21<http://www.gnu.org/licenses/>.  */
22
23#include "lib2-nios2.h"
24
25/* 16-bit HI divide and modulo as used in Nios II.  */
26
27static UHItype
28udivmodhi4 (UHItype num, UHItype den, word_type modwanted)
29{
30  UHItype bit = 1;
31  UHItype res = 0;
32
33  while (den < num && bit && !(den & (1L<<15)))
34    {
35      den <<=1;
36      bit <<=1;
37    }
38  while (bit)
39    {
40      if (num >= den)
41	{
42	  num -= den;
43	  res |= bit;
44	}
45      bit >>=1;
46      den >>=1;
47    }
48  if (modwanted)
49    return num;
50  return res;
51}
52
53
54HItype
55__divhi3 (HItype a, HItype b)
56{
57  word_type neg = 0;
58  HItype res;
59
60  if (a < 0)
61    {
62      a = -a;
63      neg = !neg;
64    }
65
66  if (b < 0)
67    {
68      b = -b;
69      neg = !neg;
70    }
71
72  res = udivmodhi4 (a, b, 0);
73
74  if (neg)
75    res = -res;
76
77  return res;
78}
79
80
81HItype
82__modhi3 (HItype a, HItype b)
83{
84  word_type neg = 0;
85  HItype res;
86
87  if (a < 0)
88    {
89      a = -a;
90      neg = 1;
91    }
92
93  if (b < 0)
94    b = -b;
95
96  res = udivmodhi4 (a, b, 1);
97
98  if (neg)
99    res = -res;
100
101  return res;
102}
103
104
105UHItype
106__udivhi3 (UHItype a, UHItype b)
107{
108  return udivmodhi4 (a, b, 0);
109}
110
111
112UHItype
113__umodhi3 (UHItype a, UHItype b)
114{
115  return udivmodhi4 (a, b, 1);
116}
117
118