1 // This file is dual licensed under the MIT and the University of Illinois Open
2 // Source Licenses. See LICENSE.TXT for details.
4 #include "../assembly.h"
6 // du_int __udivdi3(du_int a, du_int b);
9 // both inputs and the output are 64-bit unsigned integers.
10 // This will do whatever the underlying hardware is set to do on division by zero.
11 // No other exceptions are generated, as the divide cannot overflow.
13 // This is targeted at 32-bit x86 *only*, as this can be done directly in hardware
14 // on x86_64. The performance goal is ~40 cycles per divide, which is faster than
15 // currently possible via simulation of integer divides on the x87 unit.
17 // Stephen Canon, December 2008
23 DEFINE_COMPILERRT_FUNCTION(__udivdi3)
26 movl 20(%esp), %ebx // Find the index i of the leading bit in b.
27 bsrl %ebx, %ecx // If the high word of b is zero, jump to
28 jz 9f // the code to handle that special case [9].
30 /* High word of b is known to be non-zero on this branch */
32 movl 16(%esp), %eax // Construct bhi, containing bits [1+i:32+i] of b
34 shrl %cl, %eax // Practically, this means that bhi is given by:
36 notl %ecx // bhi = (high word of b) << (31 - i) |
37 shll %cl, %ebx // (low word of b) >> (1 + i)
39 movl 12(%esp), %edx // Load the high and low words of a, and jump
40 movl 8(%esp), %eax // to [1] if the high word is larger than bhi
41 cmpl %ebx, %edx // to avoid overflowing the upcoming divide.
44 /* High word of a is greater than or equal to (b >> (1 + i)) on this branch */
46 divl %ebx // eax <-- qs, edx <-- r such that ahi:alo = bs*qs + r
51 shrl %cl, %eax // q = qs >> (1 + i)
53 mull 20(%esp) // q*blo
55 movl 16(%esp), %ecx // ECX:EBX = a
57 sbbl %edx, %ecx // ECX:EBX = a - q*blo
59 imull %edi, %eax // q*bhi
60 subl %eax, %ecx // ECX:EBX = a - q*b
61 sbbl $0, %edi // decrement q if remainder is negative
69 1: /* High word of a is greater than or equal to (b >> (1 + i)) on this branch */
71 subl %ebx, %edx // subtract bhi from ahi so that divide will not
72 divl %ebx // overflow, and find q and r such that
74 // ahi:alo = (1:q)*bhi + r
76 // Note that q is a number in (31-i).(1+i)
83 shrl %cl, %eax // q = (1:qs) >> (1 + i)
85 mull 20(%esp) // q*blo
87 movl 16(%esp), %ecx // ECX:EBX = a
89 sbbl %edx, %ecx // ECX:EBX = a - q*blo
91 imull %edi, %eax // q*bhi
92 subl %eax, %ecx // ECX:EBX = a - q*b
93 sbbl $0, %edi // decrement q if remainder is negative
101 9: /* High word of b is zero on this branch */
103 movl 12(%esp), %eax // Find qhi and rhi such that
104 movl 16(%esp), %ecx //
105 xorl %edx, %edx // ahi = qhi*b + rhi with 0 ≤ rhi < b
108 movl 8(%esp), %eax // Find qlo such that
110 movl %ebx, %edx // rhi:alo = qlo*b + rlo with 0 ≤ rlo < b
112 retl // and return qhi:qlo
113 END_COMPILERRT_FUNCTION(__udivdi3)